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