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