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