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