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