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 IsInit information 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 { 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 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 bool progress; 2895 do { 2896 ConnectionGraph::do_analysis(this, &igvn); 2897 2898 if (failing()) return; 2899 2900 int mcount = macro_count(); // Record number of allocations and locks before IGVN 2901 2902 // Optimize out fields loads from scalar replaceable allocations. 2903 igvn.optimize(); 2904 print_method(PHASE_ITER_GVN_AFTER_EA, 2); 2905 2906 if (failing()) return; 2907 2908 if (congraph() != nullptr && macro_count() > 0) { 2909 TracePhase tp(_t_macroEliminate); 2910 PhaseMacroExpand mexp(igvn); 2911 mexp.eliminate_macro_nodes(); 2912 if (failing()) { 2913 return; 2914 } 2915 igvn.set_delay_transform(false); 2916 print_method(PHASE_ITER_GVN_AFTER_ELIMINATION, 2); 2917 } 2918 2919 ConnectionGraph::verify_ram_nodes(this, root()); 2920 if (failing()) return; 2921 2922 progress = do_iterative_escape_analysis() && 2923 (macro_count() < mcount) && 2924 ConnectionGraph::has_candidates(this); 2925 // Try again if candidates exist and made progress 2926 // by removing some allocations and/or locks. 2927 } while (progress); 2928 } 2929 2930 // Loop transforms on the ideal graph. Range Check Elimination, 2931 // peeling, unrolling, etc. 2932 2933 // Set loop opts counter 2934 if((_loop_opts_cnt > 0) && (has_loops() || has_split_ifs())) { 2935 { 2936 TracePhase tp(_t_idealLoop); 2937 PhaseIdealLoop::optimize(igvn, LoopOptsDefault); 2938 _loop_opts_cnt--; 2939 if (major_progress()) print_method(PHASE_PHASEIDEALLOOP1, 2); 2940 if (failing()) return; 2941 } 2942 // Loop opts pass if partial peeling occurred in previous pass 2943 if(PartialPeelLoop && major_progress() && (_loop_opts_cnt > 0)) { 2944 TracePhase tp(_t_idealLoop); 2945 PhaseIdealLoop::optimize(igvn, LoopOptsSkipSplitIf); 2946 _loop_opts_cnt--; 2947 if (major_progress()) print_method(PHASE_PHASEIDEALLOOP2, 2); 2948 if (failing()) return; 2949 } 2950 // Loop opts pass for loop-unrolling before CCP 2951 if(major_progress() && (_loop_opts_cnt > 0)) { 2952 TracePhase tp(_t_idealLoop); 2953 PhaseIdealLoop::optimize(igvn, LoopOptsSkipSplitIf); 2954 _loop_opts_cnt--; 2955 if (major_progress()) print_method(PHASE_PHASEIDEALLOOP3, 2); 2956 } 2957 if (!failing()) { 2958 // Verify that last round of loop opts produced a valid graph 2959 PhaseIdealLoop::verify(igvn); 2960 } 2961 } 2962 if (failing()) return; 2963 2964 // Conditional Constant Propagation; 2965 print_method(PHASE_BEFORE_CCP1, 2); 2966 PhaseCCP ccp( &igvn ); 2967 assert( true, "Break here to ccp.dump_nodes_and_types(_root,999,1)"); 2968 { 2969 TracePhase tp(_t_ccp); 2970 ccp.do_transform(); 2971 } 2972 print_method(PHASE_CCP1, 2); 2973 2974 assert( true, "Break here to ccp.dump_old2new_map()"); 2975 2976 // Iterative Global Value Numbering, including ideal transforms 2977 { 2978 TracePhase tp(_t_iterGVN2); 2979 igvn.reset_from_igvn(&ccp); 2980 igvn.optimize(); 2981 } 2982 print_method(PHASE_ITER_GVN2, 2); 2983 2984 if (failing()) return; 2985 2986 // Loop transforms on the ideal graph. Range Check Elimination, 2987 // peeling, unrolling, etc. 2988 if (!optimize_loops(igvn, LoopOptsDefault)) { 2989 return; 2990 } 2991 2992 if (failing()) return; 2993 2994 C->clear_major_progress(); // ensure that major progress is now clear 2995 2996 process_for_post_loop_opts_igvn(igvn); 2997 2998 process_for_merge_stores_igvn(igvn); 2999 3000 if (failing()) return; 3001 3002 #ifdef ASSERT 3003 bs->verify_gc_barriers(this, BarrierSetC2::BeforeMacroExpand); 3004 #endif 3005 3006 assert(_late_inlines.length() == 0 || IncrementalInlineMH || IncrementalInlineVirtual, "not empty"); 3007 3008 if (_late_inlines.length() > 0) { 3009 // More opportunities to optimize virtual and MH calls. 3010 // Though it's maybe too late to perform inlining, strength-reducing them to direct calls is still an option. 3011 process_late_inline_calls_no_inline(igvn); 3012 } 3013 3014 { 3015 TracePhase tp(_t_macroExpand); 3016 PhaseMacroExpand mex(igvn); 3017 // Last attempt to eliminate macro nodes. 3018 mex.eliminate_macro_nodes(); 3019 if (failing()) { 3020 return; 3021 } 3022 3023 print_method(PHASE_BEFORE_MACRO_EXPANSION, 3); 3024 if (mex.expand_macro_nodes()) { 3025 assert(failing(), "must bail out w/ explicit message"); 3026 return; 3027 } 3028 print_method(PHASE_AFTER_MACRO_EXPANSION, 2); 3029 } 3030 3031 // Process inline type nodes again and remove them. From here 3032 // on we don't need to keep track of field values anymore. 3033 process_inline_types(igvn, /* remove= */ true); 3034 3035 { 3036 TracePhase tp(_t_barrierExpand); 3037 if (bs->expand_barriers(this, igvn)) { 3038 assert(failing(), "must bail out w/ explicit message"); 3039 return; 3040 } 3041 print_method(PHASE_BARRIER_EXPANSION, 2); 3042 } 3043 3044 if (C->max_vector_size() > 0) { 3045 C->optimize_logic_cones(igvn); 3046 igvn.optimize(); 3047 if (failing()) return; 3048 } 3049 3050 DEBUG_ONLY( _modified_nodes = nullptr; ) 3051 DEBUG_ONLY( _late_inlines.clear(); ) 3052 3053 assert(igvn._worklist.size() == 0, "not empty"); 3054 } // (End scope of igvn; run destructor if necessary for asserts.) 3055 3056 check_no_dead_use(); 3057 3058 // We will never use the NodeHash table any more. Clear it so that final_graph_reshaping does not have 3059 // to remove hashes to unlock nodes for modifications. 3060 C->node_hash()->clear(); 3061 3062 // A method with only infinite loops has no edges entering loops from root 3063 { 3064 TracePhase tp(_t_graphReshaping); 3065 if (final_graph_reshaping()) { 3066 assert(failing(), "must bail out w/ explicit message"); 3067 return; 3068 } 3069 } 3070 3071 print_method(PHASE_OPTIMIZE_FINISHED, 2); 3072 DEBUG_ONLY(set_phase_optimize_finished();) 3073 } 3074 3075 #ifdef ASSERT 3076 void Compile::check_no_dead_use() const { 3077 ResourceMark rm; 3078 Unique_Node_List wq; 3079 wq.push(root()); 3080 for (uint i = 0; i < wq.size(); ++i) { 3081 Node* n = wq.at(i); 3082 for (DUIterator_Fast jmax, j = n->fast_outs(jmax); j < jmax; j++) { 3083 Node* u = n->fast_out(j); 3084 if (u->outcnt() == 0 && !u->is_Con()) { 3085 u->dump(); 3086 fatal("no reachable node should have no use"); 3087 } 3088 wq.push(u); 3089 } 3090 } 3091 } 3092 #endif 3093 3094 void Compile::inline_vector_reboxing_calls() { 3095 if (C->_vector_reboxing_late_inlines.length() > 0) { 3096 _late_inlines_pos = C->_late_inlines.length(); 3097 while (_vector_reboxing_late_inlines.length() > 0) { 3098 CallGenerator* cg = _vector_reboxing_late_inlines.pop(); 3099 cg->do_late_inline(); 3100 if (failing()) return; 3101 print_method(PHASE_INLINE_VECTOR_REBOX, 3, cg->call_node()); 3102 } 3103 _vector_reboxing_late_inlines.trunc_to(0); 3104 } 3105 } 3106 3107 bool Compile::has_vbox_nodes() { 3108 if (C->_vector_reboxing_late_inlines.length() > 0) { 3109 return true; 3110 } 3111 for (int macro_idx = C->macro_count() - 1; macro_idx >= 0; macro_idx--) { 3112 Node * n = C->macro_node(macro_idx); 3113 assert(n->is_macro(), "only macro nodes expected here"); 3114 if (n->Opcode() == Op_VectorUnbox || n->Opcode() == Op_VectorBox || n->Opcode() == Op_VectorBoxAllocate) { 3115 return true; 3116 } 3117 } 3118 return false; 3119 } 3120 3121 //---------------------------- Bitwise operation packing optimization --------------------------- 3122 3123 static bool is_vector_unary_bitwise_op(Node* n) { 3124 return n->Opcode() == Op_XorV && 3125 VectorNode::is_vector_bitwise_not_pattern(n); 3126 } 3127 3128 static bool is_vector_binary_bitwise_op(Node* n) { 3129 switch (n->Opcode()) { 3130 case Op_AndV: 3131 case Op_OrV: 3132 return true; 3133 3134 case Op_XorV: 3135 return !is_vector_unary_bitwise_op(n); 3136 3137 default: 3138 return false; 3139 } 3140 } 3141 3142 static bool is_vector_ternary_bitwise_op(Node* n) { 3143 return n->Opcode() == Op_MacroLogicV; 3144 } 3145 3146 static bool is_vector_bitwise_op(Node* n) { 3147 return is_vector_unary_bitwise_op(n) || 3148 is_vector_binary_bitwise_op(n) || 3149 is_vector_ternary_bitwise_op(n); 3150 } 3151 3152 static bool is_vector_bitwise_cone_root(Node* n) { 3153 if (n->bottom_type()->isa_vectmask() || !is_vector_bitwise_op(n)) { 3154 return false; 3155 } 3156 for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) { 3157 if (is_vector_bitwise_op(n->fast_out(i))) { 3158 return false; 3159 } 3160 } 3161 return true; 3162 } 3163 3164 static uint collect_unique_inputs(Node* n, Unique_Node_List& inputs) { 3165 uint cnt = 0; 3166 if (is_vector_bitwise_op(n)) { 3167 uint inp_cnt = n->is_predicated_vector() ? n->req()-1 : n->req(); 3168 if (VectorNode::is_vector_bitwise_not_pattern(n)) { 3169 for (uint i = 1; i < inp_cnt; i++) { 3170 Node* in = n->in(i); 3171 bool skip = VectorNode::is_all_ones_vector(in); 3172 if (!skip && !inputs.member(in)) { 3173 inputs.push(in); 3174 cnt++; 3175 } 3176 } 3177 assert(cnt <= 1, "not unary"); 3178 } else { 3179 uint last_req = inp_cnt; 3180 if (is_vector_ternary_bitwise_op(n)) { 3181 last_req = inp_cnt - 1; // skip last input 3182 } 3183 for (uint i = 1; i < last_req; i++) { 3184 Node* def = n->in(i); 3185 if (!inputs.member(def)) { 3186 inputs.push(def); 3187 cnt++; 3188 } 3189 } 3190 } 3191 } else { // not a bitwise operations 3192 if (!inputs.member(n)) { 3193 inputs.push(n); 3194 cnt++; 3195 } 3196 } 3197 return cnt; 3198 } 3199 3200 void Compile::collect_logic_cone_roots(Unique_Node_List& list) { 3201 Unique_Node_List useful_nodes; 3202 C->identify_useful_nodes(useful_nodes); 3203 3204 for (uint i = 0; i < useful_nodes.size(); i++) { 3205 Node* n = useful_nodes.at(i); 3206 if (is_vector_bitwise_cone_root(n)) { 3207 list.push(n); 3208 } 3209 } 3210 } 3211 3212 Node* Compile::xform_to_MacroLogicV(PhaseIterGVN& igvn, 3213 const TypeVect* vt, 3214 Unique_Node_List& partition, 3215 Unique_Node_List& inputs) { 3216 assert(partition.size() == 2 || partition.size() == 3, "not supported"); 3217 assert(inputs.size() == 2 || inputs.size() == 3, "not supported"); 3218 assert(Matcher::match_rule_supported_vector(Op_MacroLogicV, vt->length(), vt->element_basic_type()), "not supported"); 3219 3220 Node* in1 = inputs.at(0); 3221 Node* in2 = inputs.at(1); 3222 Node* in3 = (inputs.size() == 3 ? inputs.at(2) : in2); 3223 3224 uint func = compute_truth_table(partition, inputs); 3225 3226 Node* pn = partition.at(partition.size() - 1); 3227 Node* mask = pn->is_predicated_vector() ? pn->in(pn->req()-1) : nullptr; 3228 return igvn.transform(MacroLogicVNode::make(igvn, in1, in2, in3, mask, func, vt)); 3229 } 3230 3231 static uint extract_bit(uint func, uint pos) { 3232 return (func & (1 << pos)) >> pos; 3233 } 3234 3235 // 3236 // A macro logic node represents a truth table. It has 4 inputs, 3237 // First three inputs corresponds to 3 columns of a truth table 3238 // and fourth input captures the logic function. 3239 // 3240 // eg. fn = (in1 AND in2) OR in3; 3241 // 3242 // MacroNode(in1,in2,in3,fn) 3243 // 3244 // ----------------- 3245 // in1 in2 in3 fn 3246 // ----------------- 3247 // 0 0 0 0 3248 // 0 0 1 1 3249 // 0 1 0 0 3250 // 0 1 1 1 3251 // 1 0 0 0 3252 // 1 0 1 1 3253 // 1 1 0 1 3254 // 1 1 1 1 3255 // 3256 3257 uint Compile::eval_macro_logic_op(uint func, uint in1 , uint in2, uint in3) { 3258 int res = 0; 3259 for (int i = 0; i < 8; i++) { 3260 int bit1 = extract_bit(in1, i); 3261 int bit2 = extract_bit(in2, i); 3262 int bit3 = extract_bit(in3, i); 3263 3264 int func_bit_pos = (bit1 << 2 | bit2 << 1 | bit3); 3265 int func_bit = extract_bit(func, func_bit_pos); 3266 3267 res |= func_bit << i; 3268 } 3269 return res; 3270 } 3271 3272 static uint eval_operand(Node* n, ResourceHashtable<Node*,uint>& eval_map) { 3273 assert(n != nullptr, ""); 3274 assert(eval_map.contains(n), "absent"); 3275 return *(eval_map.get(n)); 3276 } 3277 3278 static void eval_operands(Node* n, 3279 uint& func1, uint& func2, uint& func3, 3280 ResourceHashtable<Node*,uint>& eval_map) { 3281 assert(is_vector_bitwise_op(n), ""); 3282 3283 if (is_vector_unary_bitwise_op(n)) { 3284 Node* opnd = n->in(1); 3285 if (VectorNode::is_vector_bitwise_not_pattern(n) && VectorNode::is_all_ones_vector(opnd)) { 3286 opnd = n->in(2); 3287 } 3288 func1 = eval_operand(opnd, eval_map); 3289 } else if (is_vector_binary_bitwise_op(n)) { 3290 func1 = eval_operand(n->in(1), eval_map); 3291 func2 = eval_operand(n->in(2), eval_map); 3292 } else { 3293 assert(is_vector_ternary_bitwise_op(n), "unknown operation"); 3294 func1 = eval_operand(n->in(1), eval_map); 3295 func2 = eval_operand(n->in(2), eval_map); 3296 func3 = eval_operand(n->in(3), eval_map); 3297 } 3298 } 3299 3300 uint Compile::compute_truth_table(Unique_Node_List& partition, Unique_Node_List& inputs) { 3301 assert(inputs.size() <= 3, "sanity"); 3302 ResourceMark rm; 3303 uint res = 0; 3304 ResourceHashtable<Node*,uint> eval_map; 3305 3306 // Populate precomputed functions for inputs. 3307 // Each input corresponds to one column of 3 input truth-table. 3308 uint input_funcs[] = { 0xAA, // (_, _, c) -> c 3309 0xCC, // (_, b, _) -> b 3310 0xF0 }; // (a, _, _) -> a 3311 for (uint i = 0; i < inputs.size(); i++) { 3312 eval_map.put(inputs.at(i), input_funcs[2-i]); 3313 } 3314 3315 for (uint i = 0; i < partition.size(); i++) { 3316 Node* n = partition.at(i); 3317 3318 uint func1 = 0, func2 = 0, func3 = 0; 3319 eval_operands(n, func1, func2, func3, eval_map); 3320 3321 switch (n->Opcode()) { 3322 case Op_OrV: 3323 assert(func3 == 0, "not binary"); 3324 res = func1 | func2; 3325 break; 3326 case Op_AndV: 3327 assert(func3 == 0, "not binary"); 3328 res = func1 & func2; 3329 break; 3330 case Op_XorV: 3331 if (VectorNode::is_vector_bitwise_not_pattern(n)) { 3332 assert(func2 == 0 && func3 == 0, "not unary"); 3333 res = (~func1) & 0xFF; 3334 } else { 3335 assert(func3 == 0, "not binary"); 3336 res = func1 ^ func2; 3337 } 3338 break; 3339 case Op_MacroLogicV: 3340 // Ordering of inputs may change during evaluation of sub-tree 3341 // containing MacroLogic node as a child node, thus a re-evaluation 3342 // makes sure that function is evaluated in context of current 3343 // inputs. 3344 res = eval_macro_logic_op(n->in(4)->get_int(), func1, func2, func3); 3345 break; 3346 3347 default: assert(false, "not supported: %s", n->Name()); 3348 } 3349 assert(res <= 0xFF, "invalid"); 3350 eval_map.put(n, res); 3351 } 3352 return res; 3353 } 3354 3355 // Criteria under which nodes gets packed into a macro logic node:- 3356 // 1) Parent and both child nodes are all unmasked or masked with 3357 // same predicates. 3358 // 2) Masked parent can be packed with left child if it is predicated 3359 // and both have same predicates. 3360 // 3) Masked parent can be packed with right child if its un-predicated 3361 // or has matching predication condition. 3362 // 4) An unmasked parent can be packed with an unmasked child. 3363 bool Compile::compute_logic_cone(Node* n, Unique_Node_List& partition, Unique_Node_List& inputs) { 3364 assert(partition.size() == 0, "not empty"); 3365 assert(inputs.size() == 0, "not empty"); 3366 if (is_vector_ternary_bitwise_op(n)) { 3367 return false; 3368 } 3369 3370 bool is_unary_op = is_vector_unary_bitwise_op(n); 3371 if (is_unary_op) { 3372 assert(collect_unique_inputs(n, inputs) == 1, "not unary"); 3373 return false; // too few inputs 3374 } 3375 3376 bool pack_left_child = true; 3377 bool pack_right_child = true; 3378 3379 bool left_child_LOP = is_vector_bitwise_op(n->in(1)); 3380 bool right_child_LOP = is_vector_bitwise_op(n->in(2)); 3381 3382 int left_child_input_cnt = 0; 3383 int right_child_input_cnt = 0; 3384 3385 bool parent_is_predicated = n->is_predicated_vector(); 3386 bool left_child_predicated = n->in(1)->is_predicated_vector(); 3387 bool right_child_predicated = n->in(2)->is_predicated_vector(); 3388 3389 Node* parent_pred = parent_is_predicated ? n->in(n->req()-1) : nullptr; 3390 Node* left_child_pred = left_child_predicated ? n->in(1)->in(n->in(1)->req()-1) : nullptr; 3391 Node* right_child_pred = right_child_predicated ? n->in(1)->in(n->in(1)->req()-1) : nullptr; 3392 3393 do { 3394 if (pack_left_child && left_child_LOP && 3395 ((!parent_is_predicated && !left_child_predicated) || 3396 ((parent_is_predicated && left_child_predicated && 3397 parent_pred == left_child_pred)))) { 3398 partition.push(n->in(1)); 3399 left_child_input_cnt = collect_unique_inputs(n->in(1), inputs); 3400 } else { 3401 inputs.push(n->in(1)); 3402 left_child_input_cnt = 1; 3403 } 3404 3405 if (pack_right_child && right_child_LOP && 3406 (!right_child_predicated || 3407 (right_child_predicated && parent_is_predicated && 3408 parent_pred == right_child_pred))) { 3409 partition.push(n->in(2)); 3410 right_child_input_cnt = collect_unique_inputs(n->in(2), inputs); 3411 } else { 3412 inputs.push(n->in(2)); 3413 right_child_input_cnt = 1; 3414 } 3415 3416 if (inputs.size() > 3) { 3417 assert(partition.size() > 0, ""); 3418 inputs.clear(); 3419 partition.clear(); 3420 if (left_child_input_cnt > right_child_input_cnt) { 3421 pack_left_child = false; 3422 } else { 3423 pack_right_child = false; 3424 } 3425 } else { 3426 break; 3427 } 3428 } while(true); 3429 3430 if(partition.size()) { 3431 partition.push(n); 3432 } 3433 3434 return (partition.size() == 2 || partition.size() == 3) && 3435 (inputs.size() == 2 || inputs.size() == 3); 3436 } 3437 3438 void Compile::process_logic_cone_root(PhaseIterGVN &igvn, Node *n, VectorSet &visited) { 3439 assert(is_vector_bitwise_op(n), "not a root"); 3440 3441 visited.set(n->_idx); 3442 3443 // 1) Do a DFS walk over the logic cone. 3444 for (uint i = 1; i < n->req(); i++) { 3445 Node* in = n->in(i); 3446 if (!visited.test(in->_idx) && is_vector_bitwise_op(in)) { 3447 process_logic_cone_root(igvn, in, visited); 3448 } 3449 } 3450 3451 // 2) Bottom up traversal: Merge node[s] with 3452 // the parent to form macro logic node. 3453 Unique_Node_List partition; 3454 Unique_Node_List inputs; 3455 if (compute_logic_cone(n, partition, inputs)) { 3456 const TypeVect* vt = n->bottom_type()->is_vect(); 3457 Node* pn = partition.at(partition.size() - 1); 3458 Node* mask = pn->is_predicated_vector() ? pn->in(pn->req()-1) : nullptr; 3459 if (mask == nullptr || 3460 Matcher::match_rule_supported_vector_masked(Op_MacroLogicV, vt->length(), vt->element_basic_type())) { 3461 Node* macro_logic = xform_to_MacroLogicV(igvn, vt, partition, inputs); 3462 VectorNode::trace_new_vector(macro_logic, "MacroLogic"); 3463 igvn.replace_node(n, macro_logic); 3464 } 3465 } 3466 } 3467 3468 void Compile::optimize_logic_cones(PhaseIterGVN &igvn) { 3469 ResourceMark rm; 3470 if (Matcher::match_rule_supported(Op_MacroLogicV)) { 3471 Unique_Node_List list; 3472 collect_logic_cone_roots(list); 3473 3474 while (list.size() > 0) { 3475 Node* n = list.pop(); 3476 const TypeVect* vt = n->bottom_type()->is_vect(); 3477 bool supported = Matcher::match_rule_supported_vector(Op_MacroLogicV, vt->length(), vt->element_basic_type()); 3478 if (supported) { 3479 VectorSet visited(comp_arena()); 3480 process_logic_cone_root(igvn, n, visited); 3481 } 3482 } 3483 } 3484 } 3485 3486 //------------------------------Code_Gen--------------------------------------- 3487 // Given a graph, generate code for it 3488 void Compile::Code_Gen() { 3489 if (failing()) { 3490 return; 3491 } 3492 3493 // Perform instruction selection. You might think we could reclaim Matcher 3494 // memory PDQ, but actually the Matcher is used in generating spill code. 3495 // Internals of the Matcher (including some VectorSets) must remain live 3496 // for awhile - thus I cannot reclaim Matcher memory lest a VectorSet usage 3497 // set a bit in reclaimed memory. 3498 3499 // In debug mode can dump m._nodes.dump() for mapping of ideal to machine 3500 // nodes. Mapping is only valid at the root of each matched subtree. 3501 NOT_PRODUCT( verify_graph_edges(); ) 3502 3503 Matcher matcher; 3504 _matcher = &matcher; 3505 { 3506 TracePhase tp(_t_matcher); 3507 matcher.match(); 3508 if (failing()) { 3509 return; 3510 } 3511 } 3512 // In debug mode can dump m._nodes.dump() for mapping of ideal to machine 3513 // nodes. Mapping is only valid at the root of each matched subtree. 3514 NOT_PRODUCT( verify_graph_edges(); ) 3515 3516 // If you have too many nodes, or if matching has failed, bail out 3517 check_node_count(0, "out of nodes matching instructions"); 3518 if (failing()) { 3519 return; 3520 } 3521 3522 print_method(PHASE_MATCHING, 2); 3523 3524 // Build a proper-looking CFG 3525 PhaseCFG cfg(node_arena(), root(), matcher); 3526 if (failing()) { 3527 return; 3528 } 3529 _cfg = &cfg; 3530 { 3531 TracePhase tp(_t_scheduler); 3532 bool success = cfg.do_global_code_motion(); 3533 if (!success) { 3534 return; 3535 } 3536 3537 print_method(PHASE_GLOBAL_CODE_MOTION, 2); 3538 NOT_PRODUCT( verify_graph_edges(); ) 3539 cfg.verify(); 3540 if (failing()) { 3541 return; 3542 } 3543 } 3544 3545 PhaseChaitin regalloc(unique(), cfg, matcher, false); 3546 _regalloc = ®alloc; 3547 { 3548 TracePhase tp(_t_registerAllocation); 3549 // Perform register allocation. After Chaitin, use-def chains are 3550 // no longer accurate (at spill code) and so must be ignored. 3551 // Node->LRG->reg mappings are still accurate. 3552 _regalloc->Register_Allocate(); 3553 3554 // Bail out if the allocator builds too many nodes 3555 if (failing()) { 3556 return; 3557 } 3558 3559 print_method(PHASE_REGISTER_ALLOCATION, 2); 3560 } 3561 3562 // Prior to register allocation we kept empty basic blocks in case the 3563 // the allocator needed a place to spill. After register allocation we 3564 // are not adding any new instructions. If any basic block is empty, we 3565 // can now safely remove it. 3566 { 3567 TracePhase tp(_t_blockOrdering); 3568 cfg.remove_empty_blocks(); 3569 if (do_freq_based_layout()) { 3570 PhaseBlockLayout layout(cfg); 3571 } else { 3572 cfg.set_loop_alignment(); 3573 } 3574 cfg.fixup_flow(); 3575 cfg.remove_unreachable_blocks(); 3576 cfg.verify_dominator_tree(); 3577 print_method(PHASE_BLOCK_ORDERING, 3); 3578 } 3579 3580 // Apply peephole optimizations 3581 if( OptoPeephole ) { 3582 TracePhase tp(_t_peephole); 3583 PhasePeephole peep( _regalloc, cfg); 3584 peep.do_transform(); 3585 print_method(PHASE_PEEPHOLE, 3); 3586 } 3587 3588 // Do late expand if CPU requires this. 3589 if (Matcher::require_postalloc_expand) { 3590 TracePhase tp(_t_postalloc_expand); 3591 cfg.postalloc_expand(_regalloc); 3592 print_method(PHASE_POSTALLOC_EXPAND, 3); 3593 } 3594 3595 #ifdef ASSERT 3596 { 3597 CompilationMemoryStatistic::do_test_allocations(); 3598 if (failing()) return; 3599 } 3600 #endif 3601 3602 // Convert Nodes to instruction bits in a buffer 3603 { 3604 TracePhase tp(_t_output); 3605 PhaseOutput output; 3606 output.Output(); 3607 if (failing()) return; 3608 output.install(); 3609 print_method(PHASE_FINAL_CODE, 1); // Compile::_output is not null here 3610 } 3611 3612 // He's dead, Jim. 3613 _cfg = (PhaseCFG*)((intptr_t)0xdeadbeef); 3614 _regalloc = (PhaseChaitin*)((intptr_t)0xdeadbeef); 3615 } 3616 3617 //------------------------------Final_Reshape_Counts--------------------------- 3618 // This class defines counters to help identify when a method 3619 // may/must be executed using hardware with only 24-bit precision. 3620 struct Final_Reshape_Counts : public StackObj { 3621 int _call_count; // count non-inlined 'common' calls 3622 int _float_count; // count float ops requiring 24-bit precision 3623 int _double_count; // count double ops requiring more precision 3624 int _java_call_count; // count non-inlined 'java' calls 3625 int _inner_loop_count; // count loops which need alignment 3626 VectorSet _visited; // Visitation flags 3627 Node_List _tests; // Set of IfNodes & PCTableNodes 3628 3629 Final_Reshape_Counts() : 3630 _call_count(0), _float_count(0), _double_count(0), 3631 _java_call_count(0), _inner_loop_count(0) { } 3632 3633 void inc_call_count () { _call_count ++; } 3634 void inc_float_count () { _float_count ++; } 3635 void inc_double_count() { _double_count++; } 3636 void inc_java_call_count() { _java_call_count++; } 3637 void inc_inner_loop_count() { _inner_loop_count++; } 3638 3639 int get_call_count () const { return _call_count ; } 3640 int get_float_count () const { return _float_count ; } 3641 int get_double_count() const { return _double_count; } 3642 int get_java_call_count() const { return _java_call_count; } 3643 int get_inner_loop_count() const { return _inner_loop_count; } 3644 }; 3645 3646 //------------------------------final_graph_reshaping_impl---------------------- 3647 // Implement items 1-5 from final_graph_reshaping below. 3648 void Compile::final_graph_reshaping_impl(Node *n, Final_Reshape_Counts& frc, Unique_Node_List& dead_nodes) { 3649 3650 if ( n->outcnt() == 0 ) return; // dead node 3651 uint nop = n->Opcode(); 3652 3653 // Check for 2-input instruction with "last use" on right input. 3654 // Swap to left input. Implements item (2). 3655 if( n->req() == 3 && // two-input instruction 3656 n->in(1)->outcnt() > 1 && // left use is NOT a last use 3657 (!n->in(1)->is_Phi() || n->in(1)->in(2) != n) && // it is not data loop 3658 n->in(2)->outcnt() == 1 &&// right use IS a last use 3659 !n->in(2)->is_Con() ) { // right use is not a constant 3660 // Check for commutative opcode 3661 switch( nop ) { 3662 case Op_AddI: case Op_AddF: case Op_AddD: case Op_AddL: 3663 case Op_MaxI: case Op_MaxL: case Op_MaxF: case Op_MaxD: 3664 case Op_MinI: case Op_MinL: case Op_MinF: case Op_MinD: 3665 case Op_MulI: case Op_MulF: case Op_MulD: case Op_MulL: 3666 case Op_AndL: case Op_XorL: case Op_OrL: 3667 case Op_AndI: case Op_XorI: case Op_OrI: { 3668 // Move "last use" input to left by swapping inputs 3669 n->swap_edges(1, 2); 3670 break; 3671 } 3672 default: 3673 break; 3674 } 3675 } 3676 3677 #ifdef ASSERT 3678 if( n->is_Mem() ) { 3679 int alias_idx = get_alias_index(n->as_Mem()->adr_type()); 3680 assert( n->in(0) != nullptr || alias_idx != Compile::AliasIdxRaw || 3681 // oop will be recorded in oop map if load crosses safepoint 3682 (n->is_Load() && (n->as_Load()->bottom_type()->isa_oopptr() || 3683 LoadNode::is_immutable_value(n->in(MemNode::Address)))), 3684 "raw memory operations should have control edge"); 3685 } 3686 if (n->is_MemBar()) { 3687 MemBarNode* mb = n->as_MemBar(); 3688 if (mb->trailing_store() || mb->trailing_load_store()) { 3689 assert(mb->leading_membar()->trailing_membar() == mb, "bad membar pair"); 3690 Node* mem = BarrierSet::barrier_set()->barrier_set_c2()->step_over_gc_barrier(mb->in(MemBarNode::Precedent)); 3691 assert((mb->trailing_store() && mem->is_Store() && mem->as_Store()->is_release()) || 3692 (mb->trailing_load_store() && mem->is_LoadStore()), "missing mem op"); 3693 } else if (mb->leading()) { 3694 assert(mb->trailing_membar()->leading_membar() == mb, "bad membar pair"); 3695 } 3696 } 3697 #endif 3698 // Count FPU ops and common calls, implements item (3) 3699 bool gc_handled = BarrierSet::barrier_set()->barrier_set_c2()->final_graph_reshaping(this, n, nop, dead_nodes); 3700 if (!gc_handled) { 3701 final_graph_reshaping_main_switch(n, frc, nop, dead_nodes); 3702 } 3703 3704 // Collect CFG split points 3705 if (n->is_MultiBranch() && !n->is_RangeCheck()) { 3706 frc._tests.push(n); 3707 } 3708 } 3709 3710 void Compile::handle_div_mod_op(Node* n, BasicType bt, bool is_unsigned) { 3711 if (!UseDivMod) { 3712 return; 3713 } 3714 3715 // Check if "a % b" and "a / b" both exist 3716 Node* d = n->find_similar(Op_DivIL(bt, is_unsigned)); 3717 if (d == nullptr) { 3718 return; 3719 } 3720 3721 // Replace them with a fused divmod if supported 3722 if (Matcher::has_match_rule(Op_DivModIL(bt, is_unsigned))) { 3723 DivModNode* divmod = DivModNode::make(n, bt, is_unsigned); 3724 // If the divisor input for a Div (or Mod etc.) is not zero, then the control input of the Div is set to zero. 3725 // It could be that the divisor input is found not zero because its type is narrowed down by a CastII in the 3726 // subgraph for that input. Range check CastIIs are removed during final graph reshape. To preserve the dependency 3727 // carried by a CastII, precedence edges are added to the Div node. We need to transfer the precedence edges to the 3728 // DivMod node so the dependency is not lost. 3729 divmod->add_prec_from(n); 3730 divmod->add_prec_from(d); 3731 d->subsume_by(divmod->div_proj(), this); 3732 n->subsume_by(divmod->mod_proj(), this); 3733 } else { 3734 // Replace "a % b" with "a - ((a / b) * b)" 3735 Node* mult = MulNode::make(d, d->in(2), bt); 3736 Node* sub = SubNode::make(d->in(1), mult, bt); 3737 n->subsume_by(sub, this); 3738 } 3739 } 3740 3741 void Compile::final_graph_reshaping_main_switch(Node* n, Final_Reshape_Counts& frc, uint nop, Unique_Node_List& dead_nodes) { 3742 switch( nop ) { 3743 // Count all float operations that may use FPU 3744 case Op_AddF: 3745 case Op_SubF: 3746 case Op_MulF: 3747 case Op_DivF: 3748 case Op_NegF: 3749 case Op_ModF: 3750 case Op_ConvI2F: 3751 case Op_ConF: 3752 case Op_CmpF: 3753 case Op_CmpF3: 3754 case Op_StoreF: 3755 case Op_LoadF: 3756 // case Op_ConvL2F: // longs are split into 32-bit halves 3757 frc.inc_float_count(); 3758 break; 3759 3760 case Op_ConvF2D: 3761 case Op_ConvD2F: 3762 frc.inc_float_count(); 3763 frc.inc_double_count(); 3764 break; 3765 3766 // Count all double operations that may use FPU 3767 case Op_AddD: 3768 case Op_SubD: 3769 case Op_MulD: 3770 case Op_DivD: 3771 case Op_NegD: 3772 case Op_ModD: 3773 case Op_ConvI2D: 3774 case Op_ConvD2I: 3775 // case Op_ConvL2D: // handled by leaf call 3776 // case Op_ConvD2L: // handled by leaf call 3777 case Op_ConD: 3778 case Op_CmpD: 3779 case Op_CmpD3: 3780 case Op_StoreD: 3781 case Op_LoadD: 3782 case Op_LoadD_unaligned: 3783 frc.inc_double_count(); 3784 break; 3785 case Op_Opaque1: // Remove Opaque Nodes before matching 3786 n->subsume_by(n->in(1), this); 3787 break; 3788 case Op_CallStaticJava: 3789 case Op_CallJava: 3790 case Op_CallDynamicJava: 3791 frc.inc_java_call_count(); // Count java call site; 3792 case Op_CallRuntime: 3793 case Op_CallLeaf: 3794 case Op_CallLeafVector: 3795 case Op_CallLeafNoFP: { 3796 assert (n->is_Call(), ""); 3797 CallNode *call = n->as_Call(); 3798 // Count call sites where the FP mode bit would have to be flipped. 3799 // Do not count uncommon runtime calls: 3800 // uncommon_trap, _complete_monitor_locking, _complete_monitor_unlocking, 3801 // _new_Java, _new_typeArray, _new_objArray, _rethrow_Java, ... 3802 if (!call->is_CallStaticJava() || !call->as_CallStaticJava()->_name) { 3803 frc.inc_call_count(); // Count the call site 3804 } else { // See if uncommon argument is shared 3805 Node *n = call->in(TypeFunc::Parms); 3806 int nop = n->Opcode(); 3807 // Clone shared simple arguments to uncommon calls, item (1). 3808 if (n->outcnt() > 1 && 3809 !n->is_Proj() && 3810 nop != Op_CreateEx && 3811 nop != Op_CheckCastPP && 3812 nop != Op_DecodeN && 3813 nop != Op_DecodeNKlass && 3814 !n->is_Mem() && 3815 !n->is_Phi()) { 3816 Node *x = n->clone(); 3817 call->set_req(TypeFunc::Parms, x); 3818 } 3819 } 3820 break; 3821 } 3822 case Op_StoreB: 3823 case Op_StoreC: 3824 case Op_StoreI: 3825 case Op_StoreL: 3826 case Op_StoreLSpecial: 3827 case Op_CompareAndSwapB: 3828 case Op_CompareAndSwapS: 3829 case Op_CompareAndSwapI: 3830 case Op_CompareAndSwapL: 3831 case Op_CompareAndSwapP: 3832 case Op_CompareAndSwapN: 3833 case Op_WeakCompareAndSwapB: 3834 case Op_WeakCompareAndSwapS: 3835 case Op_WeakCompareAndSwapI: 3836 case Op_WeakCompareAndSwapL: 3837 case Op_WeakCompareAndSwapP: 3838 case Op_WeakCompareAndSwapN: 3839 case Op_CompareAndExchangeB: 3840 case Op_CompareAndExchangeS: 3841 case Op_CompareAndExchangeI: 3842 case Op_CompareAndExchangeL: 3843 case Op_CompareAndExchangeP: 3844 case Op_CompareAndExchangeN: 3845 case Op_GetAndAddS: 3846 case Op_GetAndAddB: 3847 case Op_GetAndAddI: 3848 case Op_GetAndAddL: 3849 case Op_GetAndSetS: 3850 case Op_GetAndSetB: 3851 case Op_GetAndSetI: 3852 case Op_GetAndSetL: 3853 case Op_GetAndSetP: 3854 case Op_GetAndSetN: 3855 case Op_StoreP: 3856 case Op_StoreN: 3857 case Op_StoreNKlass: 3858 case Op_LoadB: 3859 case Op_LoadUB: 3860 case Op_LoadUS: 3861 case Op_LoadI: 3862 case Op_LoadKlass: 3863 case Op_LoadNKlass: 3864 case Op_LoadL: 3865 case Op_LoadL_unaligned: 3866 case Op_LoadP: 3867 case Op_LoadN: 3868 case Op_LoadRange: 3869 case Op_LoadS: 3870 break; 3871 3872 case Op_AddP: { // Assert sane base pointers 3873 Node *addp = n->in(AddPNode::Address); 3874 assert( !addp->is_AddP() || 3875 addp->in(AddPNode::Base)->is_top() || // Top OK for allocation 3876 addp->in(AddPNode::Base) == n->in(AddPNode::Base), 3877 "Base pointers must match (addp %u)", addp->_idx ); 3878 #ifdef _LP64 3879 if ((UseCompressedOops || UseCompressedClassPointers) && 3880 addp->Opcode() == Op_ConP && 3881 addp == n->in(AddPNode::Base) && 3882 n->in(AddPNode::Offset)->is_Con()) { 3883 // If the transformation of ConP to ConN+DecodeN is beneficial depends 3884 // on the platform and on the compressed oops mode. 3885 // Use addressing with narrow klass to load with offset on x86. 3886 // Some platforms can use the constant pool to load ConP. 3887 // Do this transformation here since IGVN will convert ConN back to ConP. 3888 const Type* t = addp->bottom_type(); 3889 bool is_oop = t->isa_oopptr() != nullptr; 3890 bool is_klass = t->isa_klassptr() != nullptr; 3891 3892 if ((is_oop && UseCompressedOops && Matcher::const_oop_prefer_decode() ) || 3893 (is_klass && UseCompressedClassPointers && Matcher::const_klass_prefer_decode() && 3894 t->isa_klassptr()->exact_klass()->is_in_encoding_range())) { 3895 Node* nn = nullptr; 3896 3897 int op = is_oop ? Op_ConN : Op_ConNKlass; 3898 3899 // Look for existing ConN node of the same exact type. 3900 Node* r = root(); 3901 uint cnt = r->outcnt(); 3902 for (uint i = 0; i < cnt; i++) { 3903 Node* m = r->raw_out(i); 3904 if (m!= nullptr && m->Opcode() == op && 3905 m->bottom_type()->make_ptr() == t) { 3906 nn = m; 3907 break; 3908 } 3909 } 3910 if (nn != nullptr) { 3911 // Decode a narrow oop to match address 3912 // [R12 + narrow_oop_reg<<3 + offset] 3913 if (is_oop) { 3914 nn = new DecodeNNode(nn, t); 3915 } else { 3916 nn = new DecodeNKlassNode(nn, t); 3917 } 3918 // Check for succeeding AddP which uses the same Base. 3919 // Otherwise we will run into the assertion above when visiting that guy. 3920 for (uint i = 0; i < n->outcnt(); ++i) { 3921 Node *out_i = n->raw_out(i); 3922 if (out_i && out_i->is_AddP() && out_i->in(AddPNode::Base) == addp) { 3923 out_i->set_req(AddPNode::Base, nn); 3924 #ifdef ASSERT 3925 for (uint j = 0; j < out_i->outcnt(); ++j) { 3926 Node *out_j = out_i->raw_out(j); 3927 assert(out_j == nullptr || !out_j->is_AddP() || out_j->in(AddPNode::Base) != addp, 3928 "more than 2 AddP nodes in a chain (out_j %u)", out_j->_idx); 3929 } 3930 #endif 3931 } 3932 } 3933 n->set_req(AddPNode::Base, nn); 3934 n->set_req(AddPNode::Address, nn); 3935 if (addp->outcnt() == 0) { 3936 addp->disconnect_inputs(this); 3937 } 3938 } 3939 } 3940 } 3941 #endif 3942 break; 3943 } 3944 3945 case Op_CastPP: { 3946 // Remove CastPP nodes to gain more freedom during scheduling but 3947 // keep the dependency they encode as control or precedence edges 3948 // (if control is set already) on memory operations. Some CastPP 3949 // nodes don't have a control (don't carry a dependency): skip 3950 // those. 3951 if (n->in(0) != nullptr) { 3952 ResourceMark rm; 3953 Unique_Node_List wq; 3954 wq.push(n); 3955 for (uint next = 0; next < wq.size(); ++next) { 3956 Node *m = wq.at(next); 3957 for (DUIterator_Fast imax, i = m->fast_outs(imax); i < imax; i++) { 3958 Node* use = m->fast_out(i); 3959 if (use->is_Mem() || use->is_EncodeNarrowPtr()) { 3960 use->ensure_control_or_add_prec(n->in(0)); 3961 } else { 3962 switch(use->Opcode()) { 3963 case Op_AddP: 3964 case Op_DecodeN: 3965 case Op_DecodeNKlass: 3966 case Op_CheckCastPP: 3967 case Op_CastPP: 3968 wq.push(use); 3969 break; 3970 } 3971 } 3972 } 3973 } 3974 } 3975 const bool is_LP64 = LP64_ONLY(true) NOT_LP64(false); 3976 if (is_LP64 && n->in(1)->is_DecodeN() && Matcher::gen_narrow_oop_implicit_null_checks()) { 3977 Node* in1 = n->in(1); 3978 const Type* t = n->bottom_type(); 3979 Node* new_in1 = in1->clone(); 3980 new_in1->as_DecodeN()->set_type(t); 3981 3982 if (!Matcher::narrow_oop_use_complex_address()) { 3983 // 3984 // x86, ARM and friends can handle 2 adds in addressing mode 3985 // and Matcher can fold a DecodeN node into address by using 3986 // a narrow oop directly and do implicit null check in address: 3987 // 3988 // [R12 + narrow_oop_reg<<3 + offset] 3989 // NullCheck narrow_oop_reg 3990 // 3991 // On other platforms (Sparc) we have to keep new DecodeN node and 3992 // use it to do implicit null check in address: 3993 // 3994 // decode_not_null narrow_oop_reg, base_reg 3995 // [base_reg + offset] 3996 // NullCheck base_reg 3997 // 3998 // Pin the new DecodeN node to non-null path on these platform (Sparc) 3999 // to keep the information to which null check the new DecodeN node 4000 // corresponds to use it as value in implicit_null_check(). 4001 // 4002 new_in1->set_req(0, n->in(0)); 4003 } 4004 4005 n->subsume_by(new_in1, this); 4006 if (in1->outcnt() == 0) { 4007 in1->disconnect_inputs(this); 4008 } 4009 } else { 4010 n->subsume_by(n->in(1), this); 4011 if (n->outcnt() == 0) { 4012 n->disconnect_inputs(this); 4013 } 4014 } 4015 break; 4016 } 4017 case Op_CastII: { 4018 n->as_CastII()->remove_range_check_cast(this); 4019 break; 4020 } 4021 #ifdef _LP64 4022 case Op_CmpP: 4023 // Do this transformation here to preserve CmpPNode::sub() and 4024 // other TypePtr related Ideal optimizations (for example, ptr nullness). 4025 if (n->in(1)->is_DecodeNarrowPtr() || n->in(2)->is_DecodeNarrowPtr()) { 4026 Node* in1 = n->in(1); 4027 Node* in2 = n->in(2); 4028 if (!in1->is_DecodeNarrowPtr()) { 4029 in2 = in1; 4030 in1 = n->in(2); 4031 } 4032 assert(in1->is_DecodeNarrowPtr(), "sanity"); 4033 4034 Node* new_in2 = nullptr; 4035 if (in2->is_DecodeNarrowPtr()) { 4036 assert(in2->Opcode() == in1->Opcode(), "must be same node type"); 4037 new_in2 = in2->in(1); 4038 } else if (in2->Opcode() == Op_ConP) { 4039 const Type* t = in2->bottom_type(); 4040 if (t == TypePtr::NULL_PTR) { 4041 assert(in1->is_DecodeN(), "compare klass to null?"); 4042 // Don't convert CmpP null check into CmpN if compressed 4043 // oops implicit null check is not generated. 4044 // This will allow to generate normal oop implicit null check. 4045 if (Matcher::gen_narrow_oop_implicit_null_checks()) 4046 new_in2 = ConNode::make(TypeNarrowOop::NULL_PTR); 4047 // 4048 // This transformation together with CastPP transformation above 4049 // will generated code for implicit null checks for compressed oops. 4050 // 4051 // The original code after Optimize() 4052 // 4053 // LoadN memory, narrow_oop_reg 4054 // decode narrow_oop_reg, base_reg 4055 // CmpP base_reg, nullptr 4056 // CastPP base_reg // NotNull 4057 // Load [base_reg + offset], val_reg 4058 // 4059 // after these transformations will be 4060 // 4061 // LoadN memory, narrow_oop_reg 4062 // CmpN narrow_oop_reg, nullptr 4063 // decode_not_null narrow_oop_reg, base_reg 4064 // Load [base_reg + offset], val_reg 4065 // 4066 // and the uncommon path (== nullptr) will use narrow_oop_reg directly 4067 // since narrow oops can be used in debug info now (see the code in 4068 // final_graph_reshaping_walk()). 4069 // 4070 // At the end the code will be matched to 4071 // on x86: 4072 // 4073 // Load_narrow_oop memory, narrow_oop_reg 4074 // Load [R12 + narrow_oop_reg<<3 + offset], val_reg 4075 // NullCheck narrow_oop_reg 4076 // 4077 // and on sparc: 4078 // 4079 // Load_narrow_oop memory, narrow_oop_reg 4080 // decode_not_null narrow_oop_reg, base_reg 4081 // Load [base_reg + offset], val_reg 4082 // NullCheck base_reg 4083 // 4084 } else if (t->isa_oopptr()) { 4085 new_in2 = ConNode::make(t->make_narrowoop()); 4086 } else if (t->isa_klassptr()) { 4087 new_in2 = ConNode::make(t->make_narrowklass()); 4088 } 4089 } 4090 if (new_in2 != nullptr) { 4091 Node* cmpN = new CmpNNode(in1->in(1), new_in2); 4092 n->subsume_by(cmpN, this); 4093 if (in1->outcnt() == 0) { 4094 in1->disconnect_inputs(this); 4095 } 4096 if (in2->outcnt() == 0) { 4097 in2->disconnect_inputs(this); 4098 } 4099 } 4100 } 4101 break; 4102 4103 case Op_DecodeN: 4104 case Op_DecodeNKlass: 4105 assert(!n->in(1)->is_EncodeNarrowPtr(), "should be optimized out"); 4106 // DecodeN could be pinned when it can't be fold into 4107 // an address expression, see the code for Op_CastPP above. 4108 assert(n->in(0) == nullptr || (UseCompressedOops && !Matcher::narrow_oop_use_complex_address()), "no control"); 4109 break; 4110 4111 case Op_EncodeP: 4112 case Op_EncodePKlass: { 4113 Node* in1 = n->in(1); 4114 if (in1->is_DecodeNarrowPtr()) { 4115 n->subsume_by(in1->in(1), this); 4116 } else if (in1->Opcode() == Op_ConP) { 4117 const Type* t = in1->bottom_type(); 4118 if (t == TypePtr::NULL_PTR) { 4119 assert(t->isa_oopptr(), "null klass?"); 4120 n->subsume_by(ConNode::make(TypeNarrowOop::NULL_PTR), this); 4121 } else if (t->isa_oopptr()) { 4122 n->subsume_by(ConNode::make(t->make_narrowoop()), this); 4123 } else if (t->isa_klassptr()) { 4124 n->subsume_by(ConNode::make(t->make_narrowklass()), this); 4125 } 4126 } 4127 if (in1->outcnt() == 0) { 4128 in1->disconnect_inputs(this); 4129 } 4130 break; 4131 } 4132 4133 case Op_Proj: { 4134 if (OptimizeStringConcat || IncrementalInline) { 4135 ProjNode* proj = n->as_Proj(); 4136 if (proj->_is_io_use) { 4137 assert(proj->_con == TypeFunc::I_O || proj->_con == TypeFunc::Memory, ""); 4138 // Separate projections were used for the exception path which 4139 // are normally removed by a late inline. If it wasn't inlined 4140 // then they will hang around and should just be replaced with 4141 // the original one. Merge them. 4142 Node* non_io_proj = proj->in(0)->as_Multi()->proj_out_or_null(proj->_con, false /*is_io_use*/); 4143 if (non_io_proj != nullptr) { 4144 proj->subsume_by(non_io_proj , this); 4145 } 4146 } 4147 } 4148 break; 4149 } 4150 4151 case Op_Phi: 4152 if (n->as_Phi()->bottom_type()->isa_narrowoop() || n->as_Phi()->bottom_type()->isa_narrowklass()) { 4153 // The EncodeP optimization may create Phi with the same edges 4154 // for all paths. It is not handled well by Register Allocator. 4155 Node* unique_in = n->in(1); 4156 assert(unique_in != nullptr, ""); 4157 uint cnt = n->req(); 4158 for (uint i = 2; i < cnt; i++) { 4159 Node* m = n->in(i); 4160 assert(m != nullptr, ""); 4161 if (unique_in != m) 4162 unique_in = nullptr; 4163 } 4164 if (unique_in != nullptr) { 4165 n->subsume_by(unique_in, this); 4166 } 4167 } 4168 break; 4169 4170 #endif 4171 4172 case Op_ModI: 4173 handle_div_mod_op(n, T_INT, false); 4174 break; 4175 4176 case Op_ModL: 4177 handle_div_mod_op(n, T_LONG, false); 4178 break; 4179 4180 case Op_UModI: 4181 handle_div_mod_op(n, T_INT, true); 4182 break; 4183 4184 case Op_UModL: 4185 handle_div_mod_op(n, T_LONG, true); 4186 break; 4187 4188 case Op_LoadVector: 4189 case Op_StoreVector: 4190 #ifdef ASSERT 4191 // Add VerifyVectorAlignment node between adr and load / store. 4192 if (VerifyAlignVector && Matcher::has_match_rule(Op_VerifyVectorAlignment)) { 4193 bool must_verify_alignment = n->is_LoadVector() ? n->as_LoadVector()->must_verify_alignment() : 4194 n->as_StoreVector()->must_verify_alignment(); 4195 if (must_verify_alignment) { 4196 jlong vector_width = n->is_LoadVector() ? n->as_LoadVector()->memory_size() : 4197 n->as_StoreVector()->memory_size(); 4198 // The memory access should be aligned to the vector width in bytes. 4199 // However, the underlying array is possibly less well aligned, but at least 4200 // to ObjectAlignmentInBytes. Hence, even if multiple arrays are accessed in 4201 // a loop we can expect at least the following alignment: 4202 jlong guaranteed_alignment = MIN2(vector_width, (jlong)ObjectAlignmentInBytes); 4203 assert(2 <= guaranteed_alignment && guaranteed_alignment <= 64, "alignment must be in range"); 4204 assert(is_power_of_2(guaranteed_alignment), "alignment must be power of 2"); 4205 // Create mask from alignment. e.g. 0b1000 -> 0b0111 4206 jlong mask = guaranteed_alignment - 1; 4207 Node* mask_con = ConLNode::make(mask); 4208 VerifyVectorAlignmentNode* va = new VerifyVectorAlignmentNode(n->in(MemNode::Address), mask_con); 4209 n->set_req(MemNode::Address, va); 4210 } 4211 } 4212 #endif 4213 break; 4214 4215 case Op_LoadVectorGather: 4216 case Op_StoreVectorScatter: 4217 case Op_LoadVectorGatherMasked: 4218 case Op_StoreVectorScatterMasked: 4219 case Op_VectorCmpMasked: 4220 case Op_VectorMaskGen: 4221 case Op_LoadVectorMasked: 4222 case Op_StoreVectorMasked: 4223 break; 4224 4225 case Op_AddReductionVI: 4226 case Op_AddReductionVL: 4227 case Op_AddReductionVF: 4228 case Op_AddReductionVD: 4229 case Op_MulReductionVI: 4230 case Op_MulReductionVL: 4231 case Op_MulReductionVF: 4232 case Op_MulReductionVD: 4233 case Op_MinReductionV: 4234 case Op_MaxReductionV: 4235 case Op_AndReductionV: 4236 case Op_OrReductionV: 4237 case Op_XorReductionV: 4238 break; 4239 4240 case Op_PackB: 4241 case Op_PackS: 4242 case Op_PackI: 4243 case Op_PackF: 4244 case Op_PackL: 4245 case Op_PackD: 4246 if (n->req()-1 > 2) { 4247 // Replace many operand PackNodes with a binary tree for matching 4248 PackNode* p = (PackNode*) n; 4249 Node* btp = p->binary_tree_pack(1, n->req()); 4250 n->subsume_by(btp, this); 4251 } 4252 break; 4253 case Op_Loop: 4254 assert(!n->as_Loop()->is_loop_nest_inner_loop() || _loop_opts_cnt == 0, "should have been turned into a counted loop"); 4255 case Op_CountedLoop: 4256 case Op_LongCountedLoop: 4257 case Op_OuterStripMinedLoop: 4258 if (n->as_Loop()->is_inner_loop()) { 4259 frc.inc_inner_loop_count(); 4260 } 4261 n->as_Loop()->verify_strip_mined(0); 4262 break; 4263 case Op_LShiftI: 4264 case Op_RShiftI: 4265 case Op_URShiftI: 4266 case Op_LShiftL: 4267 case Op_RShiftL: 4268 case Op_URShiftL: 4269 if (Matcher::need_masked_shift_count) { 4270 // The cpu's shift instructions don't restrict the count to the 4271 // lower 5/6 bits. We need to do the masking ourselves. 4272 Node* in2 = n->in(2); 4273 juint mask = (n->bottom_type() == TypeInt::INT) ? (BitsPerInt - 1) : (BitsPerLong - 1); 4274 const TypeInt* t = in2->find_int_type(); 4275 if (t != nullptr && t->is_con()) { 4276 juint shift = t->get_con(); 4277 if (shift > mask) { // Unsigned cmp 4278 n->set_req(2, ConNode::make(TypeInt::make(shift & mask))); 4279 } 4280 } else { 4281 if (t == nullptr || t->_lo < 0 || t->_hi > (int)mask) { 4282 Node* shift = new AndINode(in2, ConNode::make(TypeInt::make(mask))); 4283 n->set_req(2, shift); 4284 } 4285 } 4286 if (in2->outcnt() == 0) { // Remove dead node 4287 in2->disconnect_inputs(this); 4288 } 4289 } 4290 break; 4291 case Op_MemBarStoreStore: 4292 case Op_MemBarRelease: 4293 // Break the link with AllocateNode: it is no longer useful and 4294 // confuses register allocation. 4295 if (n->req() > MemBarNode::Precedent) { 4296 n->set_req(MemBarNode::Precedent, top()); 4297 } 4298 break; 4299 case Op_MemBarAcquire: { 4300 if (n->as_MemBar()->trailing_load() && n->req() > MemBarNode::Precedent) { 4301 // At parse time, the trailing MemBarAcquire for a volatile load 4302 // is created with an edge to the load. After optimizations, 4303 // that input may be a chain of Phis. If those phis have no 4304 // other use, then the MemBarAcquire keeps them alive and 4305 // register allocation can be confused. 4306 dead_nodes.push(n->in(MemBarNode::Precedent)); 4307 n->set_req(MemBarNode::Precedent, top()); 4308 } 4309 break; 4310 } 4311 case Op_Blackhole: 4312 break; 4313 case Op_RangeCheck: { 4314 RangeCheckNode* rc = n->as_RangeCheck(); 4315 Node* iff = new IfNode(rc->in(0), rc->in(1), rc->_prob, rc->_fcnt); 4316 n->subsume_by(iff, this); 4317 frc._tests.push(iff); 4318 break; 4319 } 4320 case Op_ConvI2L: { 4321 if (!Matcher::convi2l_type_required) { 4322 // Code generation on some platforms doesn't need accurate 4323 // ConvI2L types. Widening the type can help remove redundant 4324 // address computations. 4325 n->as_Type()->set_type(TypeLong::INT); 4326 ResourceMark rm; 4327 Unique_Node_List wq; 4328 wq.push(n); 4329 for (uint next = 0; next < wq.size(); next++) { 4330 Node *m = wq.at(next); 4331 4332 for(;;) { 4333 // Loop over all nodes with identical inputs edges as m 4334 Node* k = m->find_similar(m->Opcode()); 4335 if (k == nullptr) { 4336 break; 4337 } 4338 // Push their uses so we get a chance to remove node made 4339 // redundant 4340 for (DUIterator_Fast imax, i = k->fast_outs(imax); i < imax; i++) { 4341 Node* u = k->fast_out(i); 4342 if (u->Opcode() == Op_LShiftL || 4343 u->Opcode() == Op_AddL || 4344 u->Opcode() == Op_SubL || 4345 u->Opcode() == Op_AddP) { 4346 wq.push(u); 4347 } 4348 } 4349 // Replace all nodes with identical edges as m with m 4350 k->subsume_by(m, this); 4351 } 4352 } 4353 } 4354 break; 4355 } 4356 case Op_CmpUL: { 4357 if (!Matcher::has_match_rule(Op_CmpUL)) { 4358 // No support for unsigned long comparisons 4359 ConINode* sign_pos = new ConINode(TypeInt::make(BitsPerLong - 1)); 4360 Node* sign_bit_mask = new RShiftLNode(n->in(1), sign_pos); 4361 Node* orl = new OrLNode(n->in(1), sign_bit_mask); 4362 ConLNode* remove_sign_mask = new ConLNode(TypeLong::make(max_jlong)); 4363 Node* andl = new AndLNode(orl, remove_sign_mask); 4364 Node* cmp = new CmpLNode(andl, n->in(2)); 4365 n->subsume_by(cmp, this); 4366 } 4367 break; 4368 } 4369 #ifdef ASSERT 4370 case Op_InlineType: { 4371 n->dump(-1); 4372 assert(false, "inline type node was not removed"); 4373 break; 4374 } 4375 case Op_ConNKlass: { 4376 const TypePtr* tp = n->as_Type()->type()->make_ptr(); 4377 ciKlass* klass = tp->is_klassptr()->exact_klass(); 4378 assert(klass->is_in_encoding_range(), "klass cannot be compressed"); 4379 break; 4380 } 4381 #endif 4382 default: 4383 assert(!n->is_Call(), ""); 4384 assert(!n->is_Mem(), ""); 4385 assert(nop != Op_ProfileBoolean, "should be eliminated during IGVN"); 4386 break; 4387 } 4388 } 4389 4390 //------------------------------final_graph_reshaping_walk--------------------- 4391 // Replacing Opaque nodes with their input in final_graph_reshaping_impl(), 4392 // requires that the walk visits a node's inputs before visiting the node. 4393 void Compile::final_graph_reshaping_walk(Node_Stack& nstack, Node* root, Final_Reshape_Counts& frc, Unique_Node_List& dead_nodes) { 4394 Unique_Node_List sfpt; 4395 4396 frc._visited.set(root->_idx); // first, mark node as visited 4397 uint cnt = root->req(); 4398 Node *n = root; 4399 uint i = 0; 4400 while (true) { 4401 if (i < cnt) { 4402 // Place all non-visited non-null inputs onto stack 4403 Node* m = n->in(i); 4404 ++i; 4405 if (m != nullptr && !frc._visited.test_set(m->_idx)) { 4406 if (m->is_SafePoint() && m->as_SafePoint()->jvms() != nullptr) { 4407 // compute worst case interpreter size in case of a deoptimization 4408 update_interpreter_frame_size(m->as_SafePoint()->jvms()->interpreter_frame_size()); 4409 4410 sfpt.push(m); 4411 } 4412 cnt = m->req(); 4413 nstack.push(n, i); // put on stack parent and next input's index 4414 n = m; 4415 i = 0; 4416 } 4417 } else { 4418 // Now do post-visit work 4419 final_graph_reshaping_impl(n, frc, dead_nodes); 4420 if (nstack.is_empty()) 4421 break; // finished 4422 n = nstack.node(); // Get node from stack 4423 cnt = n->req(); 4424 i = nstack.index(); 4425 nstack.pop(); // Shift to the next node on stack 4426 } 4427 } 4428 4429 // Skip next transformation if compressed oops are not used. 4430 if ((UseCompressedOops && !Matcher::gen_narrow_oop_implicit_null_checks()) || 4431 (!UseCompressedOops && !UseCompressedClassPointers)) 4432 return; 4433 4434 // Go over safepoints nodes to skip DecodeN/DecodeNKlass nodes for debug edges. 4435 // It could be done for an uncommon traps or any safepoints/calls 4436 // if the DecodeN/DecodeNKlass node is referenced only in a debug info. 4437 while (sfpt.size() > 0) { 4438 n = sfpt.pop(); 4439 JVMState *jvms = n->as_SafePoint()->jvms(); 4440 assert(jvms != nullptr, "sanity"); 4441 int start = jvms->debug_start(); 4442 int end = n->req(); 4443 bool is_uncommon = (n->is_CallStaticJava() && 4444 n->as_CallStaticJava()->uncommon_trap_request() != 0); 4445 for (int j = start; j < end; j++) { 4446 Node* in = n->in(j); 4447 if (in->is_DecodeNarrowPtr()) { 4448 bool safe_to_skip = true; 4449 if (!is_uncommon ) { 4450 // Is it safe to skip? 4451 for (uint i = 0; i < in->outcnt(); i++) { 4452 Node* u = in->raw_out(i); 4453 if (!u->is_SafePoint() || 4454 (u->is_Call() && u->as_Call()->has_non_debug_use(n))) { 4455 safe_to_skip = false; 4456 } 4457 } 4458 } 4459 if (safe_to_skip) { 4460 n->set_req(j, in->in(1)); 4461 } 4462 if (in->outcnt() == 0) { 4463 in->disconnect_inputs(this); 4464 } 4465 } 4466 } 4467 } 4468 } 4469 4470 //------------------------------final_graph_reshaping-------------------------- 4471 // Final Graph Reshaping. 4472 // 4473 // (1) Clone simple inputs to uncommon calls, so they can be scheduled late 4474 // and not commoned up and forced early. Must come after regular 4475 // optimizations to avoid GVN undoing the cloning. Clone constant 4476 // inputs to Loop Phis; these will be split by the allocator anyways. 4477 // Remove Opaque nodes. 4478 // (2) Move last-uses by commutative operations to the left input to encourage 4479 // Intel update-in-place two-address operations and better register usage 4480 // on RISCs. Must come after regular optimizations to avoid GVN Ideal 4481 // calls canonicalizing them back. 4482 // (3) Count the number of double-precision FP ops, single-precision FP ops 4483 // and call sites. On Intel, we can get correct rounding either by 4484 // forcing singles to memory (requires extra stores and loads after each 4485 // FP bytecode) or we can set a rounding mode bit (requires setting and 4486 // clearing the mode bit around call sites). The mode bit is only used 4487 // if the relative frequency of single FP ops to calls is low enough. 4488 // This is a key transform for SPEC mpeg_audio. 4489 // (4) Detect infinite loops; blobs of code reachable from above but not 4490 // below. Several of the Code_Gen algorithms fail on such code shapes, 4491 // so we simply bail out. Happens a lot in ZKM.jar, but also happens 4492 // from time to time in other codes (such as -Xcomp finalizer loops, etc). 4493 // Detection is by looking for IfNodes where only 1 projection is 4494 // reachable from below or CatchNodes missing some targets. 4495 // (5) Assert for insane oop offsets in debug mode. 4496 4497 bool Compile::final_graph_reshaping() { 4498 // an infinite loop may have been eliminated by the optimizer, 4499 // in which case the graph will be empty. 4500 if (root()->req() == 1) { 4501 // Do not compile method that is only a trivial infinite loop, 4502 // since the content of the loop may have been eliminated. 4503 record_method_not_compilable("trivial infinite loop"); 4504 return true; 4505 } 4506 4507 // Expensive nodes have their control input set to prevent the GVN 4508 // from freely commoning them. There's no GVN beyond this point so 4509 // no need to keep the control input. We want the expensive nodes to 4510 // be freely moved to the least frequent code path by gcm. 4511 assert(OptimizeExpensiveOps || expensive_count() == 0, "optimization off but list non empty?"); 4512 for (int i = 0; i < expensive_count(); i++) { 4513 _expensive_nodes.at(i)->set_req(0, nullptr); 4514 } 4515 4516 Final_Reshape_Counts frc; 4517 4518 // Visit everybody reachable! 4519 // Allocate stack of size C->live_nodes()/2 to avoid frequent realloc 4520 Node_Stack nstack(live_nodes() >> 1); 4521 Unique_Node_List dead_nodes; 4522 final_graph_reshaping_walk(nstack, root(), frc, dead_nodes); 4523 4524 // Check for unreachable (from below) code (i.e., infinite loops). 4525 for( uint i = 0; i < frc._tests.size(); i++ ) { 4526 MultiBranchNode *n = frc._tests[i]->as_MultiBranch(); 4527 // Get number of CFG targets. 4528 // Note that PCTables include exception targets after calls. 4529 uint required_outcnt = n->required_outcnt(); 4530 if (n->outcnt() != required_outcnt) { 4531 // Check for a few special cases. Rethrow Nodes never take the 4532 // 'fall-thru' path, so expected kids is 1 less. 4533 if (n->is_PCTable() && n->in(0) && n->in(0)->in(0)) { 4534 if (n->in(0)->in(0)->is_Call()) { 4535 CallNode* call = n->in(0)->in(0)->as_Call(); 4536 if (call->entry_point() == OptoRuntime::rethrow_stub()) { 4537 required_outcnt--; // Rethrow always has 1 less kid 4538 } else if (call->req() > TypeFunc::Parms && 4539 call->is_CallDynamicJava()) { 4540 // Check for null receiver. In such case, the optimizer has 4541 // detected that the virtual call will always result in a null 4542 // pointer exception. The fall-through projection of this CatchNode 4543 // will not be populated. 4544 Node* arg0 = call->in(TypeFunc::Parms); 4545 if (arg0->is_Type() && 4546 arg0->as_Type()->type()->higher_equal(TypePtr::NULL_PTR)) { 4547 required_outcnt--; 4548 } 4549 } else if (call->entry_point() == OptoRuntime::new_array_Java() || 4550 call->entry_point() == OptoRuntime::new_array_nozero_Java()) { 4551 // Check for illegal array length. In such case, the optimizer has 4552 // detected that the allocation attempt will always result in an 4553 // exception. There is no fall-through projection of this CatchNode . 4554 assert(call->is_CallStaticJava(), "static call expected"); 4555 assert(call->req() == call->jvms()->endoff() + 1, "missing extra input"); 4556 uint valid_length_test_input = call->req() - 1; 4557 Node* valid_length_test = call->in(valid_length_test_input); 4558 call->del_req(valid_length_test_input); 4559 if (valid_length_test->find_int_con(1) == 0) { 4560 required_outcnt--; 4561 } 4562 dead_nodes.push(valid_length_test); 4563 assert(n->outcnt() == required_outcnt, "malformed control flow"); 4564 continue; 4565 } 4566 } 4567 } 4568 4569 // Recheck with a better notion of 'required_outcnt' 4570 if (n->outcnt() != required_outcnt) { 4571 record_method_not_compilable("malformed control flow"); 4572 return true; // Not all targets reachable! 4573 } 4574 } else if (n->is_PCTable() && n->in(0) && n->in(0)->in(0) && n->in(0)->in(0)->is_Call()) { 4575 CallNode* call = n->in(0)->in(0)->as_Call(); 4576 if (call->entry_point() == OptoRuntime::new_array_Java() || 4577 call->entry_point() == OptoRuntime::new_array_nozero_Java()) { 4578 assert(call->is_CallStaticJava(), "static call expected"); 4579 assert(call->req() == call->jvms()->endoff() + 1, "missing extra input"); 4580 uint valid_length_test_input = call->req() - 1; 4581 dead_nodes.push(call->in(valid_length_test_input)); 4582 call->del_req(valid_length_test_input); // valid length test useless now 4583 } 4584 } 4585 // Check that I actually visited all kids. Unreached kids 4586 // must be infinite loops. 4587 for (DUIterator_Fast jmax, j = n->fast_outs(jmax); j < jmax; j++) 4588 if (!frc._visited.test(n->fast_out(j)->_idx)) { 4589 record_method_not_compilable("infinite loop"); 4590 return true; // Found unvisited kid; must be unreach 4591 } 4592 4593 // Here so verification code in final_graph_reshaping_walk() 4594 // always see an OuterStripMinedLoopEnd 4595 if (n->is_OuterStripMinedLoopEnd() || n->is_LongCountedLoopEnd()) { 4596 IfNode* init_iff = n->as_If(); 4597 Node* iff = new IfNode(init_iff->in(0), init_iff->in(1), init_iff->_prob, init_iff->_fcnt); 4598 n->subsume_by(iff, this); 4599 } 4600 } 4601 4602 while (dead_nodes.size() > 0) { 4603 Node* m = dead_nodes.pop(); 4604 if (m->outcnt() == 0 && m != top()) { 4605 for (uint j = 0; j < m->req(); j++) { 4606 Node* in = m->in(j); 4607 if (in != nullptr) { 4608 dead_nodes.push(in); 4609 } 4610 } 4611 m->disconnect_inputs(this); 4612 } 4613 } 4614 4615 set_java_calls(frc.get_java_call_count()); 4616 set_inner_loops(frc.get_inner_loop_count()); 4617 4618 // No infinite loops, no reason to bail out. 4619 return false; 4620 } 4621 4622 //-----------------------------too_many_traps---------------------------------- 4623 // Report if there are too many traps at the current method and bci. 4624 // Return true if there was a trap, and/or PerMethodTrapLimit is exceeded. 4625 bool Compile::too_many_traps(ciMethod* method, 4626 int bci, 4627 Deoptimization::DeoptReason reason) { 4628 ciMethodData* md = method->method_data(); 4629 if (md->is_empty()) { 4630 // Assume the trap has not occurred, or that it occurred only 4631 // because of a transient condition during start-up in the interpreter. 4632 return false; 4633 } 4634 ciMethod* m = Deoptimization::reason_is_speculate(reason) ? this->method() : nullptr; 4635 if (md->has_trap_at(bci, m, reason) != 0) { 4636 // Assume PerBytecodeTrapLimit==0, for a more conservative heuristic. 4637 // Also, if there are multiple reasons, or if there is no per-BCI record, 4638 // assume the worst. 4639 if (log()) 4640 log()->elem("observe trap='%s' count='%d'", 4641 Deoptimization::trap_reason_name(reason), 4642 md->trap_count(reason)); 4643 return true; 4644 } else { 4645 // Ignore method/bci and see if there have been too many globally. 4646 return too_many_traps(reason, md); 4647 } 4648 } 4649 4650 // Less-accurate variant which does not require a method and bci. 4651 bool Compile::too_many_traps(Deoptimization::DeoptReason reason, 4652 ciMethodData* logmd) { 4653 if (trap_count(reason) >= Deoptimization::per_method_trap_limit(reason)) { 4654 // Too many traps globally. 4655 // Note that we use cumulative trap_count, not just md->trap_count. 4656 if (log()) { 4657 int mcount = (logmd == nullptr)? -1: (int)logmd->trap_count(reason); 4658 log()->elem("observe trap='%s' count='0' mcount='%d' ccount='%d'", 4659 Deoptimization::trap_reason_name(reason), 4660 mcount, trap_count(reason)); 4661 } 4662 return true; 4663 } else { 4664 // The coast is clear. 4665 return false; 4666 } 4667 } 4668 4669 //--------------------------too_many_recompiles-------------------------------- 4670 // Report if there are too many recompiles at the current method and bci. 4671 // Consults PerBytecodeRecompilationCutoff and PerMethodRecompilationCutoff. 4672 // Is not eager to return true, since this will cause the compiler to use 4673 // Action_none for a trap point, to avoid too many recompilations. 4674 bool Compile::too_many_recompiles(ciMethod* method, 4675 int bci, 4676 Deoptimization::DeoptReason reason) { 4677 ciMethodData* md = method->method_data(); 4678 if (md->is_empty()) { 4679 // Assume the trap has not occurred, or that it occurred only 4680 // because of a transient condition during start-up in the interpreter. 4681 return false; 4682 } 4683 // Pick a cutoff point well within PerBytecodeRecompilationCutoff. 4684 uint bc_cutoff = (uint) PerBytecodeRecompilationCutoff / 8; 4685 uint m_cutoff = (uint) PerMethodRecompilationCutoff / 2 + 1; // not zero 4686 Deoptimization::DeoptReason per_bc_reason 4687 = Deoptimization::reason_recorded_per_bytecode_if_any(reason); 4688 ciMethod* m = Deoptimization::reason_is_speculate(reason) ? this->method() : nullptr; 4689 if ((per_bc_reason == Deoptimization::Reason_none 4690 || md->has_trap_at(bci, m, reason) != 0) 4691 // The trap frequency measure we care about is the recompile count: 4692 && md->trap_recompiled_at(bci, m) 4693 && md->overflow_recompile_count() >= bc_cutoff) { 4694 // Do not emit a trap here if it has already caused recompilations. 4695 // Also, if there are multiple reasons, or if there is no per-BCI record, 4696 // assume the worst. 4697 if (log()) 4698 log()->elem("observe trap='%s recompiled' count='%d' recompiles2='%d'", 4699 Deoptimization::trap_reason_name(reason), 4700 md->trap_count(reason), 4701 md->overflow_recompile_count()); 4702 return true; 4703 } else if (trap_count(reason) != 0 4704 && decompile_count() >= m_cutoff) { 4705 // Too many recompiles globally, and we have seen this sort of trap. 4706 // Use cumulative decompile_count, not just md->decompile_count. 4707 if (log()) 4708 log()->elem("observe trap='%s' count='%d' mcount='%d' decompiles='%d' mdecompiles='%d'", 4709 Deoptimization::trap_reason_name(reason), 4710 md->trap_count(reason), trap_count(reason), 4711 md->decompile_count(), decompile_count()); 4712 return true; 4713 } else { 4714 // The coast is clear. 4715 return false; 4716 } 4717 } 4718 4719 // Compute when not to trap. Used by matching trap based nodes and 4720 // NullCheck optimization. 4721 void Compile::set_allowed_deopt_reasons() { 4722 _allowed_reasons = 0; 4723 if (is_method_compilation()) { 4724 for (int rs = (int)Deoptimization::Reason_none+1; rs < Compile::trapHistLength; rs++) { 4725 assert(rs < BitsPerInt, "recode bit map"); 4726 if (!too_many_traps((Deoptimization::DeoptReason) rs)) { 4727 _allowed_reasons |= nth_bit(rs); 4728 } 4729 } 4730 } 4731 } 4732 4733 bool Compile::needs_clinit_barrier(ciMethod* method, ciMethod* accessing_method) { 4734 return method->is_static() && needs_clinit_barrier(method->holder(), accessing_method); 4735 } 4736 4737 bool Compile::needs_clinit_barrier(ciField* field, ciMethod* accessing_method) { 4738 return field->is_static() && needs_clinit_barrier(field->holder(), accessing_method); 4739 } 4740 4741 bool Compile::needs_clinit_barrier(ciInstanceKlass* holder, ciMethod* accessing_method) { 4742 if (holder->is_initialized()) { 4743 return false; 4744 } 4745 if (holder->is_being_initialized()) { 4746 if (accessing_method->holder() == holder) { 4747 // Access inside a class. The barrier can be elided when access happens in <clinit>, 4748 // <init>, or a static method. In all those cases, there was an initialization 4749 // barrier on the holder klass passed. 4750 if (accessing_method->is_class_initializer() || 4751 accessing_method->is_object_constructor() || 4752 accessing_method->is_static()) { 4753 return false; 4754 } 4755 } else if (accessing_method->holder()->is_subclass_of(holder)) { 4756 // Access from a subclass. The barrier can be elided only when access happens in <clinit>. 4757 // In case of <init> or a static method, the barrier is on the subclass is not enough: 4758 // child class can become fully initialized while its parent class is still being initialized. 4759 if (accessing_method->is_class_initializer()) { 4760 return false; 4761 } 4762 } 4763 ciMethod* root = method(); // the root method of compilation 4764 if (root != accessing_method) { 4765 return needs_clinit_barrier(holder, root); // check access in the context of compilation root 4766 } 4767 } 4768 return true; 4769 } 4770 4771 #ifndef PRODUCT 4772 //------------------------------verify_bidirectional_edges--------------------- 4773 // For each input edge to a node (ie - for each Use-Def edge), verify that 4774 // there is a corresponding Def-Use edge. 4775 void Compile::verify_bidirectional_edges(Unique_Node_List& visited, const Unique_Node_List* root_and_safepoints) const { 4776 // Allocate stack of size C->live_nodes()/16 to avoid frequent realloc 4777 uint stack_size = live_nodes() >> 4; 4778 Node_List nstack(MAX2(stack_size, (uint) OptoNodeListSize)); 4779 if (root_and_safepoints != nullptr) { 4780 assert(root_and_safepoints->member(_root), "root is not in root_and_safepoints"); 4781 for (uint i = 0, limit = root_and_safepoints->size(); i < limit; i++) { 4782 Node* root_or_safepoint = root_and_safepoints->at(i); 4783 // If the node is a safepoint, let's check if it still has a control input 4784 // Lack of control input signifies that this node was killed by CCP or 4785 // recursively by remove_globally_dead_node and it shouldn't be a starting 4786 // point. 4787 if (!root_or_safepoint->is_SafePoint() || root_or_safepoint->in(0) != nullptr) { 4788 nstack.push(root_or_safepoint); 4789 } 4790 } 4791 } else { 4792 nstack.push(_root); 4793 } 4794 4795 while (nstack.size() > 0) { 4796 Node* n = nstack.pop(); 4797 if (visited.member(n)) { 4798 continue; 4799 } 4800 visited.push(n); 4801 4802 // Walk over all input edges, checking for correspondence 4803 uint length = n->len(); 4804 for (uint i = 0; i < length; i++) { 4805 Node* in = n->in(i); 4806 if (in != nullptr && !visited.member(in)) { 4807 nstack.push(in); // Put it on stack 4808 } 4809 if (in != nullptr && !in->is_top()) { 4810 // Count instances of `next` 4811 int cnt = 0; 4812 for (uint idx = 0; idx < in->_outcnt; idx++) { 4813 if (in->_out[idx] == n) { 4814 cnt++; 4815 } 4816 } 4817 assert(cnt > 0, "Failed to find Def-Use edge."); 4818 // Check for duplicate edges 4819 // walk the input array downcounting the input edges to n 4820 for (uint j = 0; j < length; j++) { 4821 if (n->in(j) == in) { 4822 cnt--; 4823 } 4824 } 4825 assert(cnt == 0, "Mismatched edge count."); 4826 } else if (in == nullptr) { 4827 assert(i == 0 || i >= n->req() || 4828 n->is_Region() || n->is_Phi() || n->is_ArrayCopy() || 4829 (n->is_Allocate() && i >= AllocateNode::InlineType) || 4830 (n->is_Unlock() && i == (n->req() - 1)) || 4831 (n->is_MemBar() && i == 5), // the precedence edge to a membar can be removed during macro node expansion 4832 "only region, phi, arraycopy, allocate, unlock or membar nodes have null data edges"); 4833 } else { 4834 assert(in->is_top(), "sanity"); 4835 // Nothing to check. 4836 } 4837 } 4838 } 4839 } 4840 4841 //------------------------------verify_graph_edges--------------------------- 4842 // Walk the Graph and verify that there is a one-to-one correspondence 4843 // between Use-Def edges and Def-Use edges in the graph. 4844 void Compile::verify_graph_edges(bool no_dead_code, const Unique_Node_List* root_and_safepoints) const { 4845 if (VerifyGraphEdges) { 4846 Unique_Node_List visited; 4847 4848 // Call graph walk to check edges 4849 verify_bidirectional_edges(visited, root_and_safepoints); 4850 if (no_dead_code) { 4851 // Now make sure that no visited node is used by an unvisited node. 4852 bool dead_nodes = false; 4853 Unique_Node_List checked; 4854 while (visited.size() > 0) { 4855 Node* n = visited.pop(); 4856 checked.push(n); 4857 for (uint i = 0; i < n->outcnt(); i++) { 4858 Node* use = n->raw_out(i); 4859 if (checked.member(use)) continue; // already checked 4860 if (visited.member(use)) continue; // already in the graph 4861 if (use->is_Con()) continue; // a dead ConNode is OK 4862 // At this point, we have found a dead node which is DU-reachable. 4863 if (!dead_nodes) { 4864 tty->print_cr("*** Dead nodes reachable via DU edges:"); 4865 dead_nodes = true; 4866 } 4867 use->dump(2); 4868 tty->print_cr("---"); 4869 checked.push(use); // No repeats; pretend it is now checked. 4870 } 4871 } 4872 assert(!dead_nodes, "using nodes must be reachable from root"); 4873 } 4874 } 4875 } 4876 #endif 4877 4878 // The Compile object keeps track of failure reasons separately from the ciEnv. 4879 // This is required because there is not quite a 1-1 relation between the 4880 // ciEnv and its compilation task and the Compile object. Note that one 4881 // ciEnv might use two Compile objects, if C2Compiler::compile_method decides 4882 // to backtrack and retry without subsuming loads. Other than this backtracking 4883 // behavior, the Compile's failure reason is quietly copied up to the ciEnv 4884 // by the logic in C2Compiler. 4885 void Compile::record_failure(const char* reason DEBUG_ONLY(COMMA bool allow_multiple_failures)) { 4886 if (log() != nullptr) { 4887 log()->elem("failure reason='%s' phase='compile'", reason); 4888 } 4889 if (_failure_reason.get() == nullptr) { 4890 // Record the first failure reason. 4891 _failure_reason.set(reason); 4892 if (CaptureBailoutInformation) { 4893 _first_failure_details = new CompilationFailureInfo(reason); 4894 } 4895 } else { 4896 assert(!StressBailout || allow_multiple_failures, "should have handled previous failure."); 4897 } 4898 4899 if (!C->failure_reason_is(C2Compiler::retry_no_subsuming_loads())) { 4900 C->print_method(PHASE_FAILURE, 1); 4901 } 4902 _root = nullptr; // flush the graph, too 4903 } 4904 4905 Compile::TracePhase::TracePhase(const char* name, PhaseTraceId id) 4906 : TraceTime(name, &Phase::timers[id], CITime, CITimeVerbose), 4907 _compile(Compile::current()), 4908 _log(nullptr), 4909 _dolog(CITimeVerbose) 4910 { 4911 assert(_compile != nullptr, "sanity check"); 4912 assert(id != PhaseTraceId::_t_none, "Don't use none"); 4913 if (_dolog) { 4914 _log = _compile->log(); 4915 } 4916 if (_log != nullptr) { 4917 _log->begin_head("phase name='%s' nodes='%d' live='%d'", phase_name(), _compile->unique(), _compile->live_nodes()); 4918 _log->stamp(); 4919 _log->end_head(); 4920 } 4921 4922 // Inform memory statistic, if enabled 4923 if (CompilationMemoryStatistic::enabled()) { 4924 CompilationMemoryStatistic::on_phase_start((int)id, name); 4925 } 4926 } 4927 4928 Compile::TracePhase::TracePhase(PhaseTraceId id) 4929 : TracePhase(Phase::get_phase_trace_id_text(id), id) {} 4930 4931 Compile::TracePhase::~TracePhase() { 4932 4933 // Inform memory statistic, if enabled 4934 if (CompilationMemoryStatistic::enabled()) { 4935 CompilationMemoryStatistic::on_phase_end(); 4936 } 4937 4938 if (_compile->failing_internal()) { 4939 if (_log != nullptr) { 4940 _log->done("phase"); 4941 } 4942 return; // timing code, not stressing bailouts. 4943 } 4944 #ifdef ASSERT 4945 if (PrintIdealNodeCount) { 4946 tty->print_cr("phase name='%s' nodes='%d' live='%d' live_graph_walk='%d'", 4947 phase_name(), _compile->unique(), _compile->live_nodes(), _compile->count_live_nodes_by_graph_walk()); 4948 } 4949 4950 if (VerifyIdealNodeCount) { 4951 _compile->print_missing_nodes(); 4952 } 4953 #endif 4954 4955 if (_log != nullptr) { 4956 _log->done("phase name='%s' nodes='%d' live='%d'", phase_name(), _compile->unique(), _compile->live_nodes()); 4957 } 4958 } 4959 4960 //----------------------------static_subtype_check----------------------------- 4961 // Shortcut important common cases when superklass is exact: 4962 // (0) superklass is java.lang.Object (can occur in reflective code) 4963 // (1) subklass is already limited to a subtype of superklass => always ok 4964 // (2) subklass does not overlap with superklass => always fail 4965 // (3) superklass has NO subtypes and we can check with a simple compare. 4966 Compile::SubTypeCheckResult Compile::static_subtype_check(const TypeKlassPtr* superk, const TypeKlassPtr* subk, bool skip) { 4967 if (skip) { 4968 return SSC_full_test; // Let caller generate the general case. 4969 } 4970 4971 if (subk->is_java_subtype_of(superk)) { 4972 return SSC_always_true; // (0) and (1) this test cannot fail 4973 } 4974 4975 if (!subk->maybe_java_subtype_of(superk)) { 4976 return SSC_always_false; // (2) true path dead; no dynamic test needed 4977 } 4978 4979 const Type* superelem = superk; 4980 if (superk->isa_aryklassptr()) { 4981 int ignored; 4982 superelem = superk->is_aryklassptr()->base_element_type(ignored); 4983 4984 // Do not fold the subtype check to an array klass pointer comparison for null-able inline type arrays 4985 // because null-free [LMyValue <: null-able [LMyValue but the klasses are different. Perform a full test. 4986 if (!superk->is_aryklassptr()->is_null_free() && superk->is_aryklassptr()->elem()->isa_instklassptr() && 4987 superk->is_aryklassptr()->elem()->is_instklassptr()->instance_klass()->is_inlinetype()) { 4988 return SSC_full_test; 4989 } 4990 } 4991 4992 if (superelem->isa_instklassptr()) { 4993 ciInstanceKlass* ik = superelem->is_instklassptr()->instance_klass(); 4994 if (!ik->has_subklass()) { 4995 if (!ik->is_final()) { 4996 // Add a dependency if there is a chance of a later subclass. 4997 dependencies()->assert_leaf_type(ik); 4998 } 4999 if (!superk->maybe_java_subtype_of(subk)) { 5000 return SSC_always_false; 5001 } 5002 return SSC_easy_test; // (3) caller can do a simple ptr comparison 5003 } 5004 } else { 5005 // A primitive array type has no subtypes. 5006 return SSC_easy_test; // (3) caller can do a simple ptr comparison 5007 } 5008 5009 return SSC_full_test; 5010 } 5011 5012 Node* Compile::conv_I2X_index(PhaseGVN* phase, Node* idx, const TypeInt* sizetype, Node* ctrl) { 5013 #ifdef _LP64 5014 // The scaled index operand to AddP must be a clean 64-bit value. 5015 // Java allows a 32-bit int to be incremented to a negative 5016 // value, which appears in a 64-bit register as a large 5017 // positive number. Using that large positive number as an 5018 // operand in pointer arithmetic has bad consequences. 5019 // On the other hand, 32-bit overflow is rare, and the possibility 5020 // can often be excluded, if we annotate the ConvI2L node with 5021 // a type assertion that its value is known to be a small positive 5022 // number. (The prior range check has ensured this.) 5023 // This assertion is used by ConvI2LNode::Ideal. 5024 int index_max = max_jint - 1; // array size is max_jint, index is one less 5025 if (sizetype != nullptr) index_max = sizetype->_hi - 1; 5026 const TypeInt* iidxtype = TypeInt::make(0, index_max, Type::WidenMax); 5027 idx = constrained_convI2L(phase, idx, iidxtype, ctrl); 5028 #endif 5029 return idx; 5030 } 5031 5032 // Convert integer value to a narrowed long type dependent on ctrl (for example, a range check) 5033 Node* Compile::constrained_convI2L(PhaseGVN* phase, Node* value, const TypeInt* itype, Node* ctrl, bool carry_dependency) { 5034 if (ctrl != nullptr) { 5035 // Express control dependency by a CastII node with a narrow type. 5036 // Make the CastII node dependent on the control input to prevent the narrowed ConvI2L 5037 // node from floating above the range check during loop optimizations. Otherwise, the 5038 // ConvI2L node may be eliminated independently of the range check, causing the data path 5039 // to become TOP while the control path is still there (although it's unreachable). 5040 value = new CastIINode(ctrl, value, itype, carry_dependency ? ConstraintCastNode::StrongDependency : ConstraintCastNode::RegularDependency, true /* range check dependency */); 5041 value = phase->transform(value); 5042 } 5043 const TypeLong* ltype = TypeLong::make(itype->_lo, itype->_hi, itype->_widen); 5044 return phase->transform(new ConvI2LNode(value, ltype)); 5045 } 5046 5047 void Compile::dump_print_inlining() { 5048 inline_printer()->print_on(tty); 5049 } 5050 5051 void Compile::log_late_inline(CallGenerator* cg) { 5052 if (log() != nullptr) { 5053 log()->head("late_inline method='%d' inline_id='" JLONG_FORMAT "'", log()->identify(cg->method()), 5054 cg->unique_id()); 5055 JVMState* p = cg->call_node()->jvms(); 5056 while (p != nullptr) { 5057 log()->elem("jvms bci='%d' method='%d'", p->bci(), log()->identify(p->method())); 5058 p = p->caller(); 5059 } 5060 log()->tail("late_inline"); 5061 } 5062 } 5063 5064 void Compile::log_late_inline_failure(CallGenerator* cg, const char* msg) { 5065 log_late_inline(cg); 5066 if (log() != nullptr) { 5067 log()->inline_fail(msg); 5068 } 5069 } 5070 5071 void Compile::log_inline_id(CallGenerator* cg) { 5072 if (log() != nullptr) { 5073 // The LogCompilation tool needs a unique way to identify late 5074 // inline call sites. This id must be unique for this call site in 5075 // this compilation. Try to have it unique across compilations as 5076 // well because it can be convenient when grepping through the log 5077 // file. 5078 // Distinguish OSR compilations from others in case CICountOSR is 5079 // on. 5080 jlong id = ((jlong)unique()) + (((jlong)compile_id()) << 33) + (CICountOSR && is_osr_compilation() ? ((jlong)1) << 32 : 0); 5081 cg->set_unique_id(id); 5082 log()->elem("inline_id id='" JLONG_FORMAT "'", id); 5083 } 5084 } 5085 5086 void Compile::log_inline_failure(const char* msg) { 5087 if (C->log() != nullptr) { 5088 C->log()->inline_fail(msg); 5089 } 5090 } 5091 5092 5093 // Dump inlining replay data to the stream. 5094 // Don't change thread state and acquire any locks. 5095 void Compile::dump_inline_data(outputStream* out) { 5096 InlineTree* inl_tree = ilt(); 5097 if (inl_tree != nullptr) { 5098 out->print(" inline %d", inl_tree->count()); 5099 inl_tree->dump_replay_data(out); 5100 } 5101 } 5102 5103 void Compile::dump_inline_data_reduced(outputStream* out) { 5104 assert(ReplayReduce, ""); 5105 5106 InlineTree* inl_tree = ilt(); 5107 if (inl_tree == nullptr) { 5108 return; 5109 } 5110 // Enable iterative replay file reduction 5111 // Output "compile" lines for depth 1 subtrees, 5112 // simulating that those trees were compiled 5113 // instead of inlined. 5114 for (int i = 0; i < inl_tree->subtrees().length(); ++i) { 5115 InlineTree* sub = inl_tree->subtrees().at(i); 5116 if (sub->inline_level() != 1) { 5117 continue; 5118 } 5119 5120 ciMethod* method = sub->method(); 5121 int entry_bci = -1; 5122 int comp_level = env()->task()->comp_level(); 5123 out->print("compile "); 5124 method->dump_name_as_ascii(out); 5125 out->print(" %d %d", entry_bci, comp_level); 5126 out->print(" inline %d", sub->count()); 5127 sub->dump_replay_data(out, -1); 5128 out->cr(); 5129 } 5130 } 5131 5132 int Compile::cmp_expensive_nodes(Node* n1, Node* n2) { 5133 if (n1->Opcode() < n2->Opcode()) return -1; 5134 else if (n1->Opcode() > n2->Opcode()) return 1; 5135 5136 assert(n1->req() == n2->req(), "can't compare %s nodes: n1->req() = %d, n2->req() = %d", NodeClassNames[n1->Opcode()], n1->req(), n2->req()); 5137 for (uint i = 1; i < n1->req(); i++) { 5138 if (n1->in(i) < n2->in(i)) return -1; 5139 else if (n1->in(i) > n2->in(i)) return 1; 5140 } 5141 5142 return 0; 5143 } 5144 5145 int Compile::cmp_expensive_nodes(Node** n1p, Node** n2p) { 5146 Node* n1 = *n1p; 5147 Node* n2 = *n2p; 5148 5149 return cmp_expensive_nodes(n1, n2); 5150 } 5151 5152 void Compile::sort_expensive_nodes() { 5153 if (!expensive_nodes_sorted()) { 5154 _expensive_nodes.sort(cmp_expensive_nodes); 5155 } 5156 } 5157 5158 bool Compile::expensive_nodes_sorted() const { 5159 for (int i = 1; i < _expensive_nodes.length(); i++) { 5160 if (cmp_expensive_nodes(_expensive_nodes.adr_at(i), _expensive_nodes.adr_at(i-1)) < 0) { 5161 return false; 5162 } 5163 } 5164 return true; 5165 } 5166 5167 bool Compile::should_optimize_expensive_nodes(PhaseIterGVN &igvn) { 5168 if (_expensive_nodes.length() == 0) { 5169 return false; 5170 } 5171 5172 assert(OptimizeExpensiveOps, "optimization off?"); 5173 5174 // Take this opportunity to remove dead nodes from the list 5175 int j = 0; 5176 for (int i = 0; i < _expensive_nodes.length(); i++) { 5177 Node* n = _expensive_nodes.at(i); 5178 if (!n->is_unreachable(igvn)) { 5179 assert(n->is_expensive(), "should be expensive"); 5180 _expensive_nodes.at_put(j, n); 5181 j++; 5182 } 5183 } 5184 _expensive_nodes.trunc_to(j); 5185 5186 // Then sort the list so that similar nodes are next to each other 5187 // and check for at least two nodes of identical kind with same data 5188 // inputs. 5189 sort_expensive_nodes(); 5190 5191 for (int i = 0; i < _expensive_nodes.length()-1; i++) { 5192 if (cmp_expensive_nodes(_expensive_nodes.adr_at(i), _expensive_nodes.adr_at(i+1)) == 0) { 5193 return true; 5194 } 5195 } 5196 5197 return false; 5198 } 5199 5200 void Compile::cleanup_expensive_nodes(PhaseIterGVN &igvn) { 5201 if (_expensive_nodes.length() == 0) { 5202 return; 5203 } 5204 5205 assert(OptimizeExpensiveOps, "optimization off?"); 5206 5207 // Sort to bring similar nodes next to each other and clear the 5208 // control input of nodes for which there's only a single copy. 5209 sort_expensive_nodes(); 5210 5211 int j = 0; 5212 int identical = 0; 5213 int i = 0; 5214 bool modified = false; 5215 for (; i < _expensive_nodes.length()-1; i++) { 5216 assert(j <= i, "can't write beyond current index"); 5217 if (_expensive_nodes.at(i)->Opcode() == _expensive_nodes.at(i+1)->Opcode()) { 5218 identical++; 5219 _expensive_nodes.at_put(j++, _expensive_nodes.at(i)); 5220 continue; 5221 } 5222 if (identical > 0) { 5223 _expensive_nodes.at_put(j++, _expensive_nodes.at(i)); 5224 identical = 0; 5225 } else { 5226 Node* n = _expensive_nodes.at(i); 5227 igvn.replace_input_of(n, 0, nullptr); 5228 igvn.hash_insert(n); 5229 modified = true; 5230 } 5231 } 5232 if (identical > 0) { 5233 _expensive_nodes.at_put(j++, _expensive_nodes.at(i)); 5234 } else if (_expensive_nodes.length() >= 1) { 5235 Node* n = _expensive_nodes.at(i); 5236 igvn.replace_input_of(n, 0, nullptr); 5237 igvn.hash_insert(n); 5238 modified = true; 5239 } 5240 _expensive_nodes.trunc_to(j); 5241 if (modified) { 5242 igvn.optimize(); 5243 } 5244 } 5245 5246 void Compile::add_expensive_node(Node * n) { 5247 assert(!_expensive_nodes.contains(n), "duplicate entry in expensive list"); 5248 assert(n->is_expensive(), "expensive nodes with non-null control here only"); 5249 assert(!n->is_CFG() && !n->is_Mem(), "no cfg or memory nodes here"); 5250 if (OptimizeExpensiveOps) { 5251 _expensive_nodes.append(n); 5252 } else { 5253 // Clear control input and let IGVN optimize expensive nodes if 5254 // OptimizeExpensiveOps is off. 5255 n->set_req(0, nullptr); 5256 } 5257 } 5258 5259 /** 5260 * Track coarsened Lock and Unlock nodes. 5261 */ 5262 5263 class Lock_List : public Node_List { 5264 uint _origin_cnt; 5265 public: 5266 Lock_List(Arena *a, uint cnt) : Node_List(a), _origin_cnt(cnt) {} 5267 uint origin_cnt() const { return _origin_cnt; } 5268 }; 5269 5270 void Compile::add_coarsened_locks(GrowableArray<AbstractLockNode*>& locks) { 5271 int length = locks.length(); 5272 if (length > 0) { 5273 // Have to keep this list until locks elimination during Macro nodes elimination. 5274 Lock_List* locks_list = new (comp_arena()) Lock_List(comp_arena(), length); 5275 AbstractLockNode* alock = locks.at(0); 5276 BoxLockNode* box = alock->box_node()->as_BoxLock(); 5277 for (int i = 0; i < length; i++) { 5278 AbstractLockNode* lock = locks.at(i); 5279 assert(lock->is_coarsened(), "expecting only coarsened AbstractLock nodes, but got '%s'[%d] node", lock->Name(), lock->_idx); 5280 locks_list->push(lock); 5281 BoxLockNode* this_box = lock->box_node()->as_BoxLock(); 5282 if (this_box != box) { 5283 // Locking regions (BoxLock) could be Unbalanced here: 5284 // - its coarsened locks were eliminated in earlier 5285 // macro nodes elimination followed by loop unroll 5286 // - it is OSR locking region (no Lock node) 5287 // Preserve Unbalanced status in such cases. 5288 if (!this_box->is_unbalanced()) { 5289 this_box->set_coarsened(); 5290 } 5291 if (!box->is_unbalanced()) { 5292 box->set_coarsened(); 5293 } 5294 } 5295 } 5296 _coarsened_locks.append(locks_list); 5297 } 5298 } 5299 5300 void Compile::remove_useless_coarsened_locks(Unique_Node_List& useful) { 5301 int count = coarsened_count(); 5302 for (int i = 0; i < count; i++) { 5303 Node_List* locks_list = _coarsened_locks.at(i); 5304 for (uint j = 0; j < locks_list->size(); j++) { 5305 Node* lock = locks_list->at(j); 5306 assert(lock->is_AbstractLock(), "sanity"); 5307 if (!useful.member(lock)) { 5308 locks_list->yank(lock); 5309 } 5310 } 5311 } 5312 } 5313 5314 void Compile::remove_coarsened_lock(Node* n) { 5315 if (n->is_AbstractLock()) { 5316 int count = coarsened_count(); 5317 for (int i = 0; i < count; i++) { 5318 Node_List* locks_list = _coarsened_locks.at(i); 5319 locks_list->yank(n); 5320 } 5321 } 5322 } 5323 5324 bool Compile::coarsened_locks_consistent() { 5325 int count = coarsened_count(); 5326 for (int i = 0; i < count; i++) { 5327 bool unbalanced = false; 5328 bool modified = false; // track locks kind modifications 5329 Lock_List* locks_list = (Lock_List*)_coarsened_locks.at(i); 5330 uint size = locks_list->size(); 5331 if (size == 0) { 5332 unbalanced = false; // All locks were eliminated - good 5333 } else if (size != locks_list->origin_cnt()) { 5334 unbalanced = true; // Some locks were removed from list 5335 } else { 5336 for (uint j = 0; j < size; j++) { 5337 Node* lock = locks_list->at(j); 5338 // All nodes in group should have the same state (modified or not) 5339 if (!lock->as_AbstractLock()->is_coarsened()) { 5340 if (j == 0) { 5341 // first on list was modified, the rest should be too for consistency 5342 modified = true; 5343 } else if (!modified) { 5344 // this lock was modified but previous locks on the list were not 5345 unbalanced = true; 5346 break; 5347 } 5348 } else if (modified) { 5349 // previous locks on list were modified but not this lock 5350 unbalanced = true; 5351 break; 5352 } 5353 } 5354 } 5355 if (unbalanced) { 5356 // unbalanced monitor enter/exit - only some [un]lock nodes were removed or modified 5357 #ifdef ASSERT 5358 if (PrintEliminateLocks) { 5359 tty->print_cr("=== unbalanced coarsened locks ==="); 5360 for (uint l = 0; l < size; l++) { 5361 locks_list->at(l)->dump(); 5362 } 5363 } 5364 #endif 5365 record_failure(C2Compiler::retry_no_locks_coarsening()); 5366 return false; 5367 } 5368 } 5369 return true; 5370 } 5371 5372 // Mark locking regions (identified by BoxLockNode) as unbalanced if 5373 // locks coarsening optimization removed Lock/Unlock nodes from them. 5374 // Such regions become unbalanced because coarsening only removes part 5375 // of Lock/Unlock nodes in region. As result we can't execute other 5376 // locks elimination optimizations which assume all code paths have 5377 // corresponding pair of Lock/Unlock nodes - they are balanced. 5378 void Compile::mark_unbalanced_boxes() const { 5379 int count = coarsened_count(); 5380 for (int i = 0; i < count; i++) { 5381 Node_List* locks_list = _coarsened_locks.at(i); 5382 uint size = locks_list->size(); 5383 if (size > 0) { 5384 AbstractLockNode* alock = locks_list->at(0)->as_AbstractLock(); 5385 BoxLockNode* box = alock->box_node()->as_BoxLock(); 5386 if (alock->is_coarsened()) { 5387 // coarsened_locks_consistent(), which is called before this method, verifies 5388 // that the rest of Lock/Unlock nodes on locks_list are also coarsened. 5389 assert(!box->is_eliminated(), "regions with coarsened locks should not be marked as eliminated"); 5390 for (uint j = 1; j < size; j++) { 5391 assert(locks_list->at(j)->as_AbstractLock()->is_coarsened(), "only coarsened locks are expected here"); 5392 BoxLockNode* this_box = locks_list->at(j)->as_AbstractLock()->box_node()->as_BoxLock(); 5393 if (box != this_box) { 5394 assert(!this_box->is_eliminated(), "regions with coarsened locks should not be marked as eliminated"); 5395 box->set_unbalanced(); 5396 this_box->set_unbalanced(); 5397 } 5398 } 5399 } 5400 } 5401 } 5402 } 5403 5404 /** 5405 * Remove the speculative part of types and clean up the graph 5406 */ 5407 void Compile::remove_speculative_types(PhaseIterGVN &igvn) { 5408 if (UseTypeSpeculation) { 5409 Unique_Node_List worklist; 5410 worklist.push(root()); 5411 int modified = 0; 5412 // Go over all type nodes that carry a speculative type, drop the 5413 // speculative part of the type and enqueue the node for an igvn 5414 // which may optimize it out. 5415 for (uint next = 0; next < worklist.size(); ++next) { 5416 Node *n = worklist.at(next); 5417 if (n->is_Type()) { 5418 TypeNode* tn = n->as_Type(); 5419 const Type* t = tn->type(); 5420 const Type* t_no_spec = t->remove_speculative(); 5421 if (t_no_spec != t) { 5422 bool in_hash = igvn.hash_delete(n); 5423 assert(in_hash || n->hash() == Node::NO_HASH, "node should be in igvn hash table"); 5424 tn->set_type(t_no_spec); 5425 igvn.hash_insert(n); 5426 igvn._worklist.push(n); // give it a chance to go away 5427 modified++; 5428 } 5429 } 5430 // Iterate over outs - endless loops is unreachable from below 5431 for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) { 5432 Node *m = n->fast_out(i); 5433 if (not_a_node(m)) { 5434 continue; 5435 } 5436 worklist.push(m); 5437 } 5438 } 5439 // Drop the speculative part of all types in the igvn's type table 5440 igvn.remove_speculative_types(); 5441 if (modified > 0) { 5442 igvn.optimize(); 5443 if (failing()) return; 5444 } 5445 #ifdef ASSERT 5446 // Verify that after the IGVN is over no speculative type has resurfaced 5447 worklist.clear(); 5448 worklist.push(root()); 5449 for (uint next = 0; next < worklist.size(); ++next) { 5450 Node *n = worklist.at(next); 5451 const Type* t = igvn.type_or_null(n); 5452 assert((t == nullptr) || (t == t->remove_speculative()), "no more speculative types"); 5453 if (n->is_Type()) { 5454 t = n->as_Type()->type(); 5455 assert(t == t->remove_speculative(), "no more speculative types"); 5456 } 5457 // Iterate over outs - endless loops is unreachable from below 5458 for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) { 5459 Node *m = n->fast_out(i); 5460 if (not_a_node(m)) { 5461 continue; 5462 } 5463 worklist.push(m); 5464 } 5465 } 5466 igvn.check_no_speculative_types(); 5467 #endif 5468 } 5469 } 5470 5471 Node* Compile::optimize_acmp(PhaseGVN* phase, Node* a, Node* b) { 5472 const TypeInstPtr* ta = phase->type(a)->isa_instptr(); 5473 const TypeInstPtr* tb = phase->type(b)->isa_instptr(); 5474 if (!EnableValhalla || ta == nullptr || tb == nullptr || 5475 ta->is_zero_type() || tb->is_zero_type() || 5476 !ta->can_be_inline_type() || !tb->can_be_inline_type()) { 5477 // Use old acmp if one operand is null or not an inline type 5478 return new CmpPNode(a, b); 5479 } else if (ta->is_inlinetypeptr() || tb->is_inlinetypeptr()) { 5480 // We know that one operand is an inline type. Therefore, 5481 // new acmp will only return true if both operands are nullptr. 5482 // Check if both operands are null by or'ing the oops. 5483 a = phase->transform(new CastP2XNode(nullptr, a)); 5484 b = phase->transform(new CastP2XNode(nullptr, b)); 5485 a = phase->transform(new OrXNode(a, b)); 5486 return new CmpXNode(a, phase->MakeConX(0)); 5487 } 5488 // Use new acmp 5489 return nullptr; 5490 } 5491 5492 // Auxiliary methods to support randomized stressing/fuzzing. 5493 5494 void Compile::initialize_stress_seed(const DirectiveSet* directive) { 5495 if (FLAG_IS_DEFAULT(StressSeed) || (FLAG_IS_ERGO(StressSeed) && directive->RepeatCompilationOption)) { 5496 _stress_seed = static_cast<uint>(Ticks::now().nanoseconds()); 5497 FLAG_SET_ERGO(StressSeed, _stress_seed); 5498 } else { 5499 _stress_seed = StressSeed; 5500 } 5501 if (_log != nullptr) { 5502 _log->elem("stress_test seed='%u'", _stress_seed); 5503 } 5504 } 5505 5506 int Compile::random() { 5507 _stress_seed = os::next_random(_stress_seed); 5508 return static_cast<int>(_stress_seed); 5509 } 5510 5511 // This method can be called the arbitrary number of times, with current count 5512 // as the argument. The logic allows selecting a single candidate from the 5513 // running list of candidates as follows: 5514 // int count = 0; 5515 // Cand* selected = null; 5516 // while(cand = cand->next()) { 5517 // if (randomized_select(++count)) { 5518 // selected = cand; 5519 // } 5520 // } 5521 // 5522 // Including count equalizes the chances any candidate is "selected". 5523 // This is useful when we don't have the complete list of candidates to choose 5524 // from uniformly. In this case, we need to adjust the randomicity of the 5525 // selection, or else we will end up biasing the selection towards the latter 5526 // candidates. 5527 // 5528 // Quick back-envelope calculation shows that for the list of n candidates 5529 // the equal probability for the candidate to persist as "best" can be 5530 // achieved by replacing it with "next" k-th candidate with the probability 5531 // of 1/k. It can be easily shown that by the end of the run, the 5532 // probability for any candidate is converged to 1/n, thus giving the 5533 // uniform distribution among all the candidates. 5534 // 5535 // We don't care about the domain size as long as (RANDOMIZED_DOMAIN / count) is large. 5536 #define RANDOMIZED_DOMAIN_POW 29 5537 #define RANDOMIZED_DOMAIN (1 << RANDOMIZED_DOMAIN_POW) 5538 #define RANDOMIZED_DOMAIN_MASK ((1 << (RANDOMIZED_DOMAIN_POW + 1)) - 1) 5539 bool Compile::randomized_select(int count) { 5540 assert(count > 0, "only positive"); 5541 return (random() & RANDOMIZED_DOMAIN_MASK) < (RANDOMIZED_DOMAIN / count); 5542 } 5543 5544 #ifdef ASSERT 5545 // Failures are geometrically distributed with probability 1/StressBailoutMean. 5546 bool Compile::fail_randomly() { 5547 if ((random() % StressBailoutMean) != 0) { 5548 return false; 5549 } 5550 record_failure("StressBailout"); 5551 return true; 5552 } 5553 5554 bool Compile::failure_is_artificial() { 5555 return C->failure_reason_is("StressBailout"); 5556 } 5557 #endif 5558 5559 CloneMap& Compile::clone_map() { return _clone_map; } 5560 void Compile::set_clone_map(Dict* d) { _clone_map._dict = d; } 5561 5562 void NodeCloneInfo::dump_on(outputStream* st) const { 5563 st->print(" {%d:%d} ", idx(), gen()); 5564 } 5565 5566 void CloneMap::clone(Node* old, Node* nnn, int gen) { 5567 uint64_t val = value(old->_idx); 5568 NodeCloneInfo cio(val); 5569 assert(val != 0, "old node should be in the map"); 5570 NodeCloneInfo cin(cio.idx(), gen + cio.gen()); 5571 insert(nnn->_idx, cin.get()); 5572 #ifndef PRODUCT 5573 if (is_debug()) { 5574 tty->print_cr("CloneMap::clone inserted node %d info {%d:%d} into CloneMap", nnn->_idx, cin.idx(), cin.gen()); 5575 } 5576 #endif 5577 } 5578 5579 void CloneMap::verify_insert_and_clone(Node* old, Node* nnn, int gen) { 5580 NodeCloneInfo cio(value(old->_idx)); 5581 if (cio.get() == 0) { 5582 cio.set(old->_idx, 0); 5583 insert(old->_idx, cio.get()); 5584 #ifndef PRODUCT 5585 if (is_debug()) { 5586 tty->print_cr("CloneMap::verify_insert_and_clone inserted node %d info {%d:%d} into CloneMap", old->_idx, cio.idx(), cio.gen()); 5587 } 5588 #endif 5589 } 5590 clone(old, nnn, gen); 5591 } 5592 5593 int CloneMap::max_gen() const { 5594 int g = 0; 5595 DictI di(_dict); 5596 for(; di.test(); ++di) { 5597 int t = gen(di._key); 5598 if (g < t) { 5599 g = t; 5600 #ifndef PRODUCT 5601 if (is_debug()) { 5602 tty->print_cr("CloneMap::max_gen() update max=%d from %d", g, _2_node_idx_t(di._key)); 5603 } 5604 #endif 5605 } 5606 } 5607 return g; 5608 } 5609 5610 void CloneMap::dump(node_idx_t key, outputStream* st) const { 5611 uint64_t val = value(key); 5612 if (val != 0) { 5613 NodeCloneInfo ni(val); 5614 ni.dump_on(st); 5615 } 5616 } 5617 5618 void Compile::shuffle_macro_nodes() { 5619 if (_macro_nodes.length() < 2) { 5620 return; 5621 } 5622 for (uint i = _macro_nodes.length() - 1; i >= 1; i--) { 5623 uint j = C->random() % (i + 1); 5624 swap(_macro_nodes.at(i), _macro_nodes.at(j)); 5625 } 5626 } 5627 5628 // Move Allocate nodes to the start of the list 5629 void Compile::sort_macro_nodes() { 5630 int count = macro_count(); 5631 int allocates = 0; 5632 for (int i = 0; i < count; i++) { 5633 Node* n = macro_node(i); 5634 if (n->is_Allocate()) { 5635 if (i != allocates) { 5636 Node* tmp = macro_node(allocates); 5637 _macro_nodes.at_put(allocates, n); 5638 _macro_nodes.at_put(i, tmp); 5639 } 5640 allocates++; 5641 } 5642 } 5643 } 5644 5645 void Compile::print_method(CompilerPhaseType cpt, int level, Node* n) { 5646 if (failing_internal()) { return; } // failing_internal to not stress bailouts from printing code. 5647 EventCompilerPhase event(UNTIMED); 5648 if (event.should_commit()) { 5649 CompilerEvent::PhaseEvent::post(event, C->_latest_stage_start_counter, cpt, C->_compile_id, level); 5650 } 5651 #ifndef PRODUCT 5652 ResourceMark rm; 5653 stringStream ss; 5654 ss.print_raw(CompilerPhaseTypeHelper::to_description(cpt)); 5655 int iter = ++_igv_phase_iter[cpt]; 5656 if (iter > 1) { 5657 ss.print(" %d", iter); 5658 } 5659 if (n != nullptr) { 5660 ss.print(": %d %s", n->_idx, NodeClassNames[n->Opcode()]); 5661 if (n->is_Call()) { 5662 CallNode* call = n->as_Call(); 5663 if (call->_name != nullptr) { 5664 // E.g. uncommon traps etc. 5665 ss.print(" - %s", call->_name); 5666 } else if (call->is_CallJava()) { 5667 CallJavaNode* call_java = call->as_CallJava(); 5668 if (call_java->method() != nullptr) { 5669 ss.print(" -"); 5670 call_java->method()->print_short_name(&ss); 5671 } 5672 } 5673 } 5674 } 5675 5676 const char* name = ss.as_string(); 5677 if (should_print_igv(level)) { 5678 _igv_printer->print_graph(name); 5679 } 5680 if (should_print_phase(cpt)) { 5681 print_ideal_ir(CompilerPhaseTypeHelper::to_name(cpt)); 5682 } 5683 #endif 5684 C->_latest_stage_start_counter.stamp(); 5685 } 5686 5687 // Only used from CompileWrapper 5688 void Compile::begin_method() { 5689 #ifndef PRODUCT 5690 if (_method != nullptr && should_print_igv(1)) { 5691 _igv_printer->begin_method(); 5692 } 5693 #endif 5694 C->_latest_stage_start_counter.stamp(); 5695 } 5696 5697 // Only used from CompileWrapper 5698 void Compile::end_method() { 5699 EventCompilerPhase event(UNTIMED); 5700 if (event.should_commit()) { 5701 CompilerEvent::PhaseEvent::post(event, C->_latest_stage_start_counter, PHASE_END, C->_compile_id, 1); 5702 } 5703 5704 #ifndef PRODUCT 5705 if (_method != nullptr && should_print_igv(1)) { 5706 _igv_printer->end_method(); 5707 } 5708 #endif 5709 } 5710 5711 bool Compile::should_print_phase(CompilerPhaseType cpt) { 5712 #ifndef PRODUCT 5713 if (_directive->should_print_phase(cpt)) { 5714 return true; 5715 } 5716 #endif 5717 return false; 5718 } 5719 5720 #ifndef PRODUCT 5721 void Compile::init_igv() { 5722 if (_igv_printer == nullptr) { 5723 _igv_printer = IdealGraphPrinter::printer(); 5724 _igv_printer->set_compile(this); 5725 } 5726 } 5727 #endif 5728 5729 bool Compile::should_print_igv(const int level) { 5730 #ifndef PRODUCT 5731 if (PrintIdealGraphLevel < 0) { // disabled by the user 5732 return false; 5733 } 5734 5735 bool need = directive()->IGVPrintLevelOption >= level; 5736 if (need) { 5737 Compile::init_igv(); 5738 } 5739 return need; 5740 #else 5741 return false; 5742 #endif 5743 } 5744 5745 #ifndef PRODUCT 5746 IdealGraphPrinter* Compile::_debug_file_printer = nullptr; 5747 IdealGraphPrinter* Compile::_debug_network_printer = nullptr; 5748 5749 // Called from debugger. Prints method to the default file with the default phase name. 5750 // This works regardless of any Ideal Graph Visualizer flags set or not. 5751 void igv_print() { 5752 Compile::current()->igv_print_method_to_file(); 5753 } 5754 5755 // Same as igv_print() above but with a specified phase name. 5756 void igv_print(const char* phase_name) { 5757 Compile::current()->igv_print_method_to_file(phase_name); 5758 } 5759 5760 // Called from debugger. Prints method with the default phase name to the default network or the one specified with 5761 // the network flags for the Ideal Graph Visualizer, or to the default file depending on the 'network' argument. 5762 // This works regardless of any Ideal Graph Visualizer flags set or not. 5763 void igv_print(bool network) { 5764 if (network) { 5765 Compile::current()->igv_print_method_to_network(); 5766 } else { 5767 Compile::current()->igv_print_method_to_file(); 5768 } 5769 } 5770 5771 // Same as igv_print(bool network) above but with a specified phase name. 5772 void igv_print(bool network, const char* phase_name) { 5773 if (network) { 5774 Compile::current()->igv_print_method_to_network(phase_name); 5775 } else { 5776 Compile::current()->igv_print_method_to_file(phase_name); 5777 } 5778 } 5779 5780 // Called from debugger. Normal write to the default _printer. Only works if Ideal Graph Visualizer printing flags are set. 5781 void igv_print_default() { 5782 Compile::current()->print_method(PHASE_DEBUG, 0); 5783 } 5784 5785 // Called from debugger, especially when replaying a trace in which the program state cannot be altered like with rr replay. 5786 // A method is appended to an existing default file with the default phase name. This means that igv_append() must follow 5787 // an earlier igv_print(*) call which sets up the file. This works regardless of any Ideal Graph Visualizer flags set or not. 5788 void igv_append() { 5789 Compile::current()->igv_print_method_to_file("Debug", true); 5790 } 5791 5792 // Same as igv_append() above but with a specified phase name. 5793 void igv_append(const char* phase_name) { 5794 Compile::current()->igv_print_method_to_file(phase_name, true); 5795 } 5796 5797 void Compile::igv_print_method_to_file(const char* phase_name, bool append) { 5798 const char* file_name = "custom_debug.xml"; 5799 if (_debug_file_printer == nullptr) { 5800 _debug_file_printer = new IdealGraphPrinter(C, file_name, append); 5801 } else { 5802 _debug_file_printer->update_compiled_method(C->method()); 5803 } 5804 tty->print_cr("Method %s to %s", append ? "appended" : "printed", file_name); 5805 _debug_file_printer->print_graph(phase_name); 5806 } 5807 5808 void Compile::igv_print_method_to_network(const char* phase_name) { 5809 ResourceMark rm; 5810 GrowableArray<const Node*> empty_list; 5811 igv_print_graph_to_network(phase_name, empty_list); 5812 } 5813 5814 void Compile::igv_print_graph_to_network(const char* name, GrowableArray<const Node*>& visible_nodes) { 5815 if (_debug_network_printer == nullptr) { 5816 _debug_network_printer = new IdealGraphPrinter(C); 5817 } else { 5818 _debug_network_printer->update_compiled_method(C->method()); 5819 } 5820 tty->print_cr("Method printed over network stream to IGV"); 5821 _debug_network_printer->print(name, C->root(), visible_nodes); 5822 } 5823 #endif 5824 5825 Node* Compile::narrow_value(BasicType bt, Node* value, const Type* type, PhaseGVN* phase, bool transform_res) { 5826 if (type != nullptr && phase->type(value)->higher_equal(type)) { 5827 return value; 5828 } 5829 Node* result = nullptr; 5830 if (bt == T_BYTE) { 5831 result = phase->transform(new LShiftINode(value, phase->intcon(24))); 5832 result = new RShiftINode(result, phase->intcon(24)); 5833 } else if (bt == T_BOOLEAN) { 5834 result = new AndINode(value, phase->intcon(0xFF)); 5835 } else if (bt == T_CHAR) { 5836 result = new AndINode(value,phase->intcon(0xFFFF)); 5837 } else if (bt == T_FLOAT) { 5838 result = new MoveI2FNode(value); 5839 } else { 5840 assert(bt == T_SHORT, "unexpected narrow type"); 5841 result = phase->transform(new LShiftINode(value, phase->intcon(16))); 5842 result = new RShiftINode(result, phase->intcon(16)); 5843 } 5844 if (transform_res) { 5845 result = phase->transform(result); 5846 } 5847 return result; 5848 } 5849 5850 void Compile::record_method_not_compilable_oom() { 5851 record_method_not_compilable(CompilationMemoryStatistic::failure_reason_memlimit()); 5852 }