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