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