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