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