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