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