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