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