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