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