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