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