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