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* phase_name) {
 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", 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                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("print_ideal");
 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 (has_loops() || _loop_opts_cnt > 0) {
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. But if the flattened field being accessed is read-only
2102       // then no concurrent writes can happen and non-atomic loads are fine, allowing better optimizations.
2103       // A way for fields to be read-only is to be stable and already initialized. Here, we check if the
2104       // field being accessed is stable, and if the null marker of the field/array element is non-zero.
2105       // If so, we know that the stable value was initialized away from the default value (null), and
2106       // that we can assume it's read-only, so can the load can be performed non-atomically.
2107       bool non_atomic_is_fine = false;
2108       if (FoldStableValues) {
2109         const TypeOopPtr* base_type = igvn.type(loadn->base())->isa_oopptr();
2110         ciObject* oop = base_type->const_oop();
2111         ciInstance* holder = oop != nullptr && oop->is_instance() ? oop->as_instance() : nullptr;
2112         ciArray* array = oop != nullptr && oop->is_array() ? oop->as_array() : nullptr;
2113         int off = igvn.type(loadn->ptr())->isa_ptr()->offset();
2114 
2115         if (holder != nullptr) {
2116           ciKlass* klass = holder->klass();
2117           ciInstanceKlass* iklass = klass->as_instance_klass();
2118           const ciField* field = iklass->get_non_flat_field_by_offset(off);
2119           ciField* nm_field = iklass->get_field_by_offset(field->null_marker_offset(), false);
2120           ciConstant cst = nm_field != nullptr ? holder->field_value(nm_field) : ciConstant() /* invalid */;
2121           non_atomic_is_fine = field->is_stable() && cst.is_valid() && cst.as_boolean();
2122         } else if (array != nullptr) {
2123           const TypeAryPtr* aryptr = base_type->is_aryptr();
2124           ciConstant elt = ((ciFlatArray*)array)->null_marker_of_element_by_offset(off);
2125           non_atomic_is_fine = aryptr->is_stable() && elt.is_valid() && !elt.is_null_or_zero();
2126         }
2127       }
2128 
2129       if (non_atomic_is_fine) {
2130         loadn->expand_non_atomic(igvn);
2131       } else {
2132         loadn->expand_atomic(igvn);
2133       }
2134     } else {
2135       n->as_StoreFlat()->expand_atomic(igvn);
2136     }
2137   }
2138   _flat_access_nodes.clear_and_deallocate();
2139   igvn.set_delay_transform(false);
2140   igvn.optimize();
2141 }
2142 
2143 void Compile::adjust_flat_array_access_aliases(PhaseIterGVN& igvn) {
2144   DEBUG_ONLY(igvn.verify_empty_worklist(nullptr));
2145   if (!_has_flat_accesses) {
2146     return;
2147   }
2148   // Initially, all flat array accesses share the same slice to
2149   // keep dependencies with Object[] array accesses (that could be
2150   // to a flat array) correct. We're done with parsing so we
2151   // now know all flat array accesses in this compile
2152   // unit. Let's move flat array accesses to their own slice,
2153   // one per element field. This should help memory access
2154   // optimizations.
2155   ResourceMark rm;
2156   Unique_Node_List wq;
2157   wq.push(root());
2158 
2159   Node_List mergememnodes;
2160   Node_List memnodes;
2161 
2162   // Alias index currently shared by all flat memory accesses
2163   int index = get_alias_index(TypeAryPtr::INLINES);
2164 
2165   // Find MergeMem nodes and flat array accesses
2166   for (uint i = 0; i < wq.size(); i++) {
2167     Node* n = wq.at(i);
2168     if (n->is_Mem()) {
2169       const TypePtr* adr_type = nullptr;
2170       adr_type = get_adr_type(get_alias_index(n->adr_type()));
2171       if (adr_type == TypeAryPtr::INLINES) {
2172         memnodes.push(n);
2173       }
2174     } else if (n->is_MergeMem()) {
2175       MergeMemNode* mm = n->as_MergeMem();
2176       if (mm->memory_at(index) != mm->base_memory()) {
2177         mergememnodes.push(n);
2178       }
2179     }
2180     for (uint j = 0; j < n->req(); j++) {
2181       Node* m = n->in(j);
2182       if (m != nullptr) {
2183         wq.push(m);
2184       }
2185     }
2186   }
2187 
2188   _flat_accesses_share_alias = false;
2189 
2190   // We are going to change the slice for the flat array
2191   // accesses so we need to clear the cache entries that refer to
2192   // them.
2193   for (uint i = 0; i < AliasCacheSize; i++) {
2194     AliasCacheEntry* ace = &_alias_cache[i];
2195     if (ace->_adr_type != nullptr &&
2196         ace->_adr_type->is_flat()) {
2197       ace->_adr_type = nullptr;
2198       ace->_index = (i != 0) ? 0 : AliasIdxTop; // Make sure the nullptr adr_type resolves to AliasIdxTop
2199     }
2200   }
2201 
2202 #ifdef ASSERT
2203   for (uint i = 0; i < memnodes.size(); i++) {
2204     Node* m = memnodes.at(i);
2205     const TypePtr* adr_type = m->adr_type();
2206     m->as_Mem()->set_adr_type(adr_type);
2207   }
2208 #endif // ASSERT
2209 
2210   int start_alias = num_alias_types(); // Start of new aliases
2211   Node_Stack stack(0);
2212 #ifdef ASSERT
2213   VectorSet seen(Thread::current()->resource_area());
2214 #endif
2215   // Now let's fix the memory graph so each flat array access
2216   // is moved to the right slice. Start from the MergeMem nodes.
2217   uint last = unique();
2218   for (uint i = 0; i < mergememnodes.size(); i++) {
2219     MergeMemNode* current = mergememnodes.at(i)->as_MergeMem();
2220     if (current->outcnt() == 0) {
2221       // This node is killed by a previous iteration
2222       continue;
2223     }
2224 
2225     Node* n = current->memory_at(index);
2226     MergeMemNode* mm = nullptr;
2227     do {
2228       // Follow memory edges through memory accesses, phis and
2229       // narrow membars and push nodes on the stack. Once we hit
2230       // bottom memory, we pop element off the stack one at a
2231       // time, in reverse order, and move them to the right slice
2232       // by changing their memory edges.
2233       if ((n->is_Phi() && n->adr_type() != TypePtr::BOTTOM) || n->is_Mem() ||
2234           (n->adr_type() == TypeAryPtr::INLINES && !n->is_NarrowMemProj())) {
2235         assert(!seen.test_set(n->_idx), "");
2236         // Uses (a load for instance) will need to be moved to the
2237         // right slice as well and will get a new memory state
2238         // that we don't know yet. The use could also be the
2239         // backedge of a loop. We put a place holder node between
2240         // the memory node and its uses. We replace that place
2241         // holder with the correct memory state once we know it,
2242         // i.e. when nodes are popped off the stack. Using the
2243         // place holder make the logic work in the presence of
2244         // loops.
2245         if (n->outcnt() > 1) {
2246           Node* place_holder = nullptr;
2247           assert(!n->has_out_with(Op_Node), "");
2248           for (DUIterator k = n->outs(); n->has_out(k); k++) {
2249             Node* u = n->out(k);
2250             if (u != current && u->_idx < last) {
2251               bool success = false;
2252               for (uint l = 0; l < u->req(); l++) {
2253                 if (!stack.is_empty() && u == stack.node() && l == stack.index()) {
2254                   continue;
2255                 }
2256                 Node* in = u->in(l);
2257                 if (in == n) {
2258                   if (place_holder == nullptr) {
2259                     place_holder = new Node(1);
2260                     place_holder->init_req(0, n);
2261                   }
2262                   igvn.replace_input_of(u, l, place_holder);
2263                   success = true;
2264                 }
2265               }
2266               if (success) {
2267                 --k;
2268               }
2269             }
2270           }
2271         }
2272         if (n->is_Phi()) {
2273           stack.push(n, 1);
2274           n = n->in(1);
2275         } else if (n->is_Mem()) {
2276           stack.push(n, n->req());
2277           n = n->in(MemNode::Memory);
2278         } else {
2279           assert(n->is_Proj() && n->in(0)->Opcode() == Op_MemBarCPUOrder, "");
2280           stack.push(n, n->req());
2281           n = n->in(0)->in(TypeFunc::Memory);
2282         }
2283       } else {
2284         assert(n->adr_type() == TypePtr::BOTTOM || (n->Opcode() == Op_Node && n->_idx >= last) || n->is_NarrowMemProj(), "");
2285         // Build a new MergeMem node to carry the new memory state
2286         // as we build it. IGVN should fold extraneous MergeMem
2287         // nodes.
2288         if (n->is_NarrowMemProj()) {
2289           // We need 1 NarrowMemProj for each slice of this array
2290           InitializeNode* init = n->in(0)->as_Initialize();
2291           AllocateNode* alloc = init->allocation();
2292           Node* klass_node = alloc->in(AllocateNode::KlassNode);
2293           const TypeAryKlassPtr* klass_type = klass_node->bottom_type()->isa_aryklassptr();
2294           assert(klass_type != nullptr, "must be an array");
2295           assert(klass_type->klass_is_exact(), "must be an exact klass");
2296           ciArrayKlass* klass = klass_type->exact_klass()->as_array_klass();
2297           assert(klass->is_flat_array_klass(), "must be a flat array");
2298           ciInlineKlass* elem_klass = klass->element_klass()->as_inline_klass();
2299           const TypeAryPtr* oop_type = klass_type->as_instance_type()->is_aryptr();
2300           assert(oop_type->klass_is_exact(), "must be an exact klass");
2301 
2302           Node* base = alloc->in(TypeFunc::Memory);
2303           assert(base->bottom_type() == Type::MEMORY, "the memory input of AllocateNode must be a memory");
2304           assert(base->adr_type() == TypePtr::BOTTOM, "the memory input of AllocateNode must be a bottom memory");
2305           // Must create a MergeMem with base as the base memory, do not clone if base is a
2306           // MergeMem because it may not be processed yet
2307           mm = MergeMemNode::make(nullptr);
2308           mm->set_base_memory(base);
2309           for (int j = 0; j < elem_klass->nof_nonstatic_fields(); j++) {
2310             int field_offset = elem_klass->nonstatic_field_at(j)->offset_in_bytes() - elem_klass->payload_offset();
2311             const TypeAryPtr* field_ptr = oop_type->with_offset(Type::OffsetBot)->with_field_offset(field_offset);
2312             int field_alias_idx = get_alias_index(field_ptr);
2313             assert(field_ptr == get_adr_type(field_alias_idx), "must match");
2314             Node* new_proj = new NarrowMemProjNode(init, field_ptr);
2315             igvn.register_new_node_with_optimizer(new_proj);
2316             mm->set_memory_at(field_alias_idx, new_proj);
2317           }
2318           if (!klass->is_elem_null_free()) {
2319             int nm_offset = elem_klass->null_marker_offset_in_payload();
2320             const TypeAryPtr* nm_ptr = oop_type->with_offset(Type::OffsetBot)->with_field_offset(nm_offset);
2321             int nm_alias_idx = get_alias_index(nm_ptr);
2322             assert(nm_ptr == get_adr_type(nm_alias_idx), "must match");
2323             Node* new_proj = new NarrowMemProjNode(init, nm_ptr);
2324             igvn.register_new_node_with_optimizer(new_proj);
2325             mm->set_memory_at(nm_alias_idx, new_proj);
2326           }
2327 
2328           // Replace all uses of the old NarrowMemProj with the correct state
2329           MergeMemNode* new_n = MergeMemNode::make(mm);
2330           igvn.register_new_node_with_optimizer(new_n);
2331           igvn.replace_node(n, new_n);
2332         } else {
2333           // Must create a MergeMem with n as the base memory, do not clone if n is a MergeMem
2334           // because it may not be processed yet
2335           mm = MergeMemNode::make(nullptr);
2336           mm->set_base_memory(n);
2337         }
2338 
2339         igvn.register_new_node_with_optimizer(mm);
2340         while (stack.size() > 0) {
2341           Node* m = stack.node();
2342           uint idx = stack.index();
2343           if (m->is_Mem()) {
2344             // Move memory node to its new slice
2345             const TypePtr* adr_type = m->adr_type();
2346             int alias = get_alias_index(adr_type);
2347             Node* prev = mm->memory_at(alias);
2348             igvn.replace_input_of(m, MemNode::Memory, prev);
2349             mm->set_memory_at(alias, m);
2350           } else if (m->is_Phi()) {
2351             // We need as many new phis as there are new aliases
2352             Node* new_phi_in = MergeMemNode::make(mm);
2353             igvn.register_new_node_with_optimizer(new_phi_in);
2354             igvn.replace_input_of(m, idx, new_phi_in);
2355             if (idx == m->req()-1) {
2356               Node* r = m->in(0);
2357               for (int j = start_alias; j < num_alias_types(); j++) {
2358                 const TypePtr* adr_type = get_adr_type(j);
2359                 if (!adr_type->isa_aryptr() || !adr_type->is_flat()) {
2360                   continue;
2361                 }
2362                 Node* phi = new PhiNode(r, Type::MEMORY, get_adr_type(j));
2363                 igvn.register_new_node_with_optimizer(phi);
2364                 for (uint k = 1; k < m->req(); k++) {
2365                   phi->init_req(k, m->in(k)->as_MergeMem()->memory_at(j));
2366                 }
2367                 mm->set_memory_at(j, phi);
2368               }
2369               Node* base_phi = new PhiNode(r, Type::MEMORY, TypePtr::BOTTOM);
2370               igvn.register_new_node_with_optimizer(base_phi);
2371               for (uint k = 1; k < m->req(); k++) {
2372                 base_phi->init_req(k, m->in(k)->as_MergeMem()->base_memory());
2373               }
2374               mm->set_base_memory(base_phi);
2375             }
2376           } else {
2377             // This is a MemBarCPUOrder node from
2378             // Parse::array_load()/Parse::array_store(), in the
2379             // branch that handles flat arrays hidden under
2380             // an Object[] array. We also need one new membar per
2381             // new alias to keep the unknown access that the
2382             // membars protect properly ordered with accesses to
2383             // known flat array.
2384             assert(m->is_Proj(), "projection expected");
2385             Node* ctrl = m->in(0)->in(TypeFunc::Control);
2386             igvn.replace_input_of(m->in(0), TypeFunc::Control, top());
2387             for (int j = start_alias; j < num_alias_types(); j++) {
2388               const TypePtr* adr_type = get_adr_type(j);
2389               if (!adr_type->isa_aryptr() || !adr_type->is_flat()) {
2390                 continue;
2391               }
2392               MemBarNode* mb = new MemBarCPUOrderNode(this, j, nullptr);
2393               igvn.register_new_node_with_optimizer(mb);
2394               Node* mem = mm->memory_at(j);
2395               mb->init_req(TypeFunc::Control, ctrl);
2396               mb->init_req(TypeFunc::Memory, mem);
2397               ctrl = new ProjNode(mb, TypeFunc::Control);
2398               igvn.register_new_node_with_optimizer(ctrl);
2399               mem = new ProjNode(mb, TypeFunc::Memory);
2400               igvn.register_new_node_with_optimizer(mem);
2401               mm->set_memory_at(j, mem);
2402             }
2403             igvn.replace_node(m->in(0)->as_Multi()->proj_out(TypeFunc::Control), ctrl);
2404           }
2405           if (idx < m->req()-1) {
2406             idx += 1;
2407             stack.set_index(idx);
2408             n = m->in(idx);
2409             break;
2410           }
2411           // Take care of place holder nodes
2412           if (m->has_out_with(Op_Node)) {
2413             Node* place_holder = m->find_out_with(Op_Node);
2414             if (place_holder != nullptr) {
2415               Node* mm_clone = mm->clone();
2416               igvn.register_new_node_with_optimizer(mm_clone);
2417               Node* hook = new Node(1);
2418               hook->init_req(0, mm);
2419               igvn.replace_node(place_holder, mm_clone);
2420               hook->destruct(&igvn);
2421             }
2422             assert(!m->has_out_with(Op_Node), "place holder should be gone now");
2423           }
2424           stack.pop();
2425         }
2426       }
2427     } while(stack.size() > 0);
2428     // Fix the memory state at the MergeMem we started from
2429     igvn.rehash_node_delayed(current);
2430     for (int j = start_alias; j < num_alias_types(); j++) {
2431       const TypePtr* adr_type = get_adr_type(j);
2432       if (!adr_type->isa_aryptr() || !adr_type->is_flat()) {
2433         continue;
2434       }
2435       current->set_memory_at(j, mm);
2436     }
2437     current->set_memory_at(index, current->base_memory());
2438   }
2439   igvn.optimize();
2440 
2441 #ifdef ASSERT
2442   wq.clear();
2443   wq.push(root());
2444   for (uint i = 0; i < wq.size(); i++) {
2445     Node* n = wq.at(i);
2446     assert(n->adr_type() != TypeAryPtr::INLINES, "should have been removed from the graph");
2447     for (uint j = 0; j < n->req(); j++) {
2448       Node* m = n->in(j);
2449       if (m != nullptr) {
2450         wq.push(m);
2451       }
2452     }
2453   }
2454 #endif
2455 
2456   print_method(PHASE_SPLIT_INLINES_ARRAY, 2);
2457 }
2458 
2459 void Compile::record_for_merge_stores_igvn(Node* n) {
2460   if (!n->for_merge_stores_igvn()) {
2461     assert(!_for_merge_stores_igvn.contains(n), "duplicate");
2462     n->add_flag(Node::NodeFlags::Flag_for_merge_stores_igvn);
2463     _for_merge_stores_igvn.append(n);
2464   }
2465 }
2466 
2467 void Compile::remove_from_merge_stores_igvn(Node* n) {
2468   n->remove_flag(Node::NodeFlags::Flag_for_merge_stores_igvn);
2469   _for_merge_stores_igvn.remove(n);
2470 }
2471 
2472 // We need to wait with merging stores until RangeCheck smearing has removed the RangeChecks during
2473 // the post loops IGVN phase. If we do it earlier, then there may still be some RangeChecks between
2474 // the stores, and we merge the wrong sequence of stores.
2475 // Example:
2476 //   StoreI RangeCheck StoreI StoreI RangeCheck StoreI
2477 // Apply MergeStores:
2478 //   StoreI RangeCheck [   StoreL  ] RangeCheck StoreI
2479 // Remove more RangeChecks:
2480 //   StoreI            [   StoreL  ]            StoreI
2481 // But now it would have been better to do this instead:
2482 //   [         StoreL       ] [       StoreL         ]
2483 //
2484 // Note: we allow stores to merge in this dedicated IGVN round, and any later IGVN round,
2485 //       since we never unset _merge_stores_phase.
2486 void Compile::process_for_merge_stores_igvn(PhaseIterGVN& igvn) {
2487   C->set_merge_stores_phase();
2488 
2489   if (_for_merge_stores_igvn.length() > 0) {
2490     while (_for_merge_stores_igvn.length() > 0) {
2491       Node* n = _for_merge_stores_igvn.pop();
2492       n->remove_flag(Node::NodeFlags::Flag_for_merge_stores_igvn);
2493       igvn._worklist.push(n);
2494     }
2495     igvn.optimize();
2496     if (failing()) return;
2497     assert(_for_merge_stores_igvn.length() == 0, "no more delayed nodes allowed");
2498     print_method(PHASE_AFTER_MERGE_STORES, 3);
2499   }
2500 }
2501 
2502 void Compile::record_unstable_if_trap(UnstableIfTrap* trap) {
2503   if (OptimizeUnstableIf) {
2504     _unstable_if_traps.append(trap);
2505   }
2506 }
2507 
2508 void Compile::remove_useless_unstable_if_traps(Unique_Node_List& useful) {
2509   for (int i = _unstable_if_traps.length() - 1; i >= 0; i--) {
2510     UnstableIfTrap* trap = _unstable_if_traps.at(i);
2511     Node* n = trap->uncommon_trap();
2512     if (!useful.member(n)) {
2513       _unstable_if_traps.delete_at(i); // replaces i-th with last element which is known to be useful (already processed)
2514     }
2515   }
2516 }
2517 
2518 // Remove the unstable if trap associated with 'unc' from candidates. It is either dead
2519 // or fold-compares case. Return true if succeed or not found.
2520 //
2521 // In rare cases, the found trap has been processed. It is too late to delete it. Return
2522 // false and ask fold-compares to yield.
2523 //
2524 // 'fold-compares' may use the uncommon_trap of the dominating IfNode to cover the fused
2525 // IfNode. This breaks the unstable_if trap invariant: control takes the unstable path
2526 // when deoptimization does happen.
2527 bool Compile::remove_unstable_if_trap(CallStaticJavaNode* unc, bool yield) {
2528   for (int i = 0; i < _unstable_if_traps.length(); ++i) {
2529     UnstableIfTrap* trap = _unstable_if_traps.at(i);
2530     if (trap->uncommon_trap() == unc) {
2531       if (yield && trap->modified()) {
2532         return false;
2533       }
2534       _unstable_if_traps.delete_at(i);
2535       break;
2536     }
2537   }
2538   return true;
2539 }
2540 
2541 // Re-calculate unstable_if traps with the liveness of next_bci, which points to the unlikely path.
2542 // It needs to be done after igvn because fold-compares may fuse uncommon_traps and before renumbering.
2543 void Compile::process_for_unstable_if_traps(PhaseIterGVN& igvn) {
2544   for (int i = _unstable_if_traps.length() - 1; i >= 0; --i) {
2545     UnstableIfTrap* trap = _unstable_if_traps.at(i);
2546     CallStaticJavaNode* unc = trap->uncommon_trap();
2547     int next_bci = trap->next_bci();
2548     bool modified = trap->modified();
2549 
2550     if (next_bci != -1 && !modified) {
2551       assert(!_dead_node_list.test(unc->_idx), "changing a dead node!");
2552       JVMState* jvms = unc->jvms();
2553       ciMethod* method = jvms->method();
2554       ciBytecodeStream iter(method);
2555 
2556       iter.force_bci(jvms->bci());
2557       assert(next_bci == iter.next_bci() || next_bci == iter.get_dest(), "wrong next_bci at unstable_if");
2558       Bytecodes::Code c = iter.cur_bc();
2559       Node* lhs = nullptr;
2560       Node* rhs = nullptr;
2561       if (c == Bytecodes::_if_acmpeq || c == Bytecodes::_if_acmpne) {
2562         lhs = unc->peek_operand(0);
2563         rhs = unc->peek_operand(1);
2564       } else if (c == Bytecodes::_ifnull || c == Bytecodes::_ifnonnull) {
2565         lhs = unc->peek_operand(0);
2566       }
2567 
2568       ResourceMark rm;
2569       const MethodLivenessResult& live_locals = method->liveness_at_bci(next_bci);
2570       assert(live_locals.is_valid(), "broken liveness info");
2571       int len = (int)live_locals.size();
2572 
2573       for (int i = 0; i < len; i++) {
2574         Node* local = unc->local(jvms, i);
2575         // kill local using the liveness of next_bci.
2576         // give up when the local looks like an operand to secure reexecution.
2577         if (!live_locals.at(i) && !local->is_top() && local != lhs && local != rhs) {
2578           uint idx = jvms->locoff() + i;
2579 #ifdef ASSERT
2580           if (PrintOpto && Verbose) {
2581             tty->print("[unstable_if] kill local#%d: ", idx);
2582             local->dump();
2583             tty->cr();
2584           }
2585 #endif
2586           igvn.replace_input_of(unc, idx, top());
2587           modified = true;
2588         }
2589       }
2590     }
2591 
2592     // keep the modified trap for late query
2593     if (modified) {
2594       trap->set_modified();
2595     } else {
2596       _unstable_if_traps.delete_at(i);
2597     }
2598   }
2599   igvn.optimize();
2600 }
2601 
2602 // StringOpts and late inlining of string methods
2603 void Compile::inline_string_calls(bool parse_time) {
2604   {
2605     // remove useless nodes to make the usage analysis simpler
2606     ResourceMark rm;
2607     PhaseRemoveUseless pru(initial_gvn(), *igvn_worklist());
2608   }
2609 
2610   {
2611     ResourceMark rm;
2612     print_method(PHASE_BEFORE_STRINGOPTS, 3);
2613     PhaseStringOpts pso(initial_gvn());
2614     print_method(PHASE_AFTER_STRINGOPTS, 3);
2615   }
2616 
2617   // now inline anything that we skipped the first time around
2618   if (!parse_time) {
2619     _late_inlines_pos = _late_inlines.length();
2620   }
2621 
2622   while (_string_late_inlines.length() > 0) {
2623     CallGenerator* cg = _string_late_inlines.pop();
2624     cg->do_late_inline();
2625     if (failing())  return;
2626   }
2627   _string_late_inlines.trunc_to(0);
2628 }
2629 
2630 // Late inlining of boxing methods
2631 void Compile::inline_boxing_calls(PhaseIterGVN& igvn) {
2632   if (_boxing_late_inlines.length() > 0) {
2633     assert(has_boxed_value(), "inconsistent");
2634 
2635     set_inlining_incrementally(true);
2636 
2637     igvn_worklist()->ensure_empty(); // should be done with igvn
2638 
2639     _late_inlines_pos = _late_inlines.length();
2640 
2641     while (_boxing_late_inlines.length() > 0) {
2642       CallGenerator* cg = _boxing_late_inlines.pop();
2643       cg->do_late_inline();
2644       if (failing())  return;
2645     }
2646     _boxing_late_inlines.trunc_to(0);
2647 
2648     inline_incrementally_cleanup(igvn);
2649 
2650     set_inlining_incrementally(false);
2651   }
2652 }
2653 
2654 bool Compile::inline_incrementally_one() {
2655   assert(IncrementalInline, "incremental inlining should be on");
2656 
2657   TracePhase tp(_t_incrInline_inline);
2658 
2659   set_inlining_progress(false);
2660   set_do_cleanup(false);
2661 
2662   for (int i = 0; i < _late_inlines.length(); i++) {
2663     _late_inlines_pos = i+1;
2664     CallGenerator* cg = _late_inlines.at(i);
2665     bool is_scheduled_for_igvn_before = C->igvn_worklist()->member(cg->call_node());
2666     bool does_dispatch = cg->is_virtual_late_inline() || cg->is_mh_late_inline();
2667     if (inlining_incrementally() || does_dispatch) { // a call can be either inlined or strength-reduced to a direct call
2668       if (should_stress_inlining()) {
2669         // randomly add repeated inline attempt if stress-inlining
2670         cg->call_node()->set_generator(cg);
2671         C->igvn_worklist()->push(cg->call_node());
2672         continue;
2673       }
2674       cg->do_late_inline();
2675       assert(_late_inlines.at(i) == cg, "no insertions before current position allowed");
2676       if (failing()) {
2677         return false;
2678       } else if (inlining_progress()) {
2679         _late_inlines_pos = i+1; // restore the position in case new elements were inserted
2680         print_method(PHASE_INCREMENTAL_INLINE_STEP, 3, cg->call_node());
2681         break; // process one call site at a time
2682       } else {
2683         bool is_scheduled_for_igvn_after = C->igvn_worklist()->member(cg->call_node());
2684         if (!is_scheduled_for_igvn_before && is_scheduled_for_igvn_after) {
2685           // Avoid potential infinite loop if node already in the IGVN list
2686           assert(false, "scheduled for IGVN during inlining attempt");
2687         } else {
2688           // Ensure call node has not disappeared from IGVN worklist during a failed inlining attempt
2689           assert(!is_scheduled_for_igvn_before || is_scheduled_for_igvn_after, "call node removed from IGVN list during inlining pass");
2690           cg->call_node()->set_generator(cg);
2691         }
2692       }
2693     } else {
2694       // Ignore late inline direct calls when inlining is not allowed.
2695       // They are left in the late inline list when node budget is exhausted until the list is fully drained.
2696     }
2697   }
2698   // Remove processed elements.
2699   _late_inlines.remove_till(_late_inlines_pos);
2700   _late_inlines_pos = 0;
2701 
2702   assert(inlining_progress() || _late_inlines.length() == 0, "no progress");
2703 
2704   bool needs_cleanup = do_cleanup() || over_inlining_cutoff();
2705 
2706   set_inlining_progress(false);
2707   set_do_cleanup(false);
2708 
2709   bool force_cleanup = directive()->IncrementalInlineForceCleanupOption;
2710   return (_late_inlines.length() > 0) && !needs_cleanup && !force_cleanup;
2711 }
2712 
2713 void Compile::inline_incrementally_cleanup(PhaseIterGVN& igvn) {
2714   {
2715     TracePhase tp(_t_incrInline_pru);
2716     ResourceMark rm;
2717     PhaseRemoveUseless pru(initial_gvn(), *igvn_worklist());
2718   }
2719   {
2720     TracePhase tp(_t_incrInline_igvn);
2721     igvn.reset();
2722     igvn.optimize();
2723     if (failing()) return;
2724   }
2725   print_method(PHASE_INCREMENTAL_INLINE_CLEANUP, 3);
2726 }
2727 
2728 // Perform incremental inlining until bound on number of live nodes is reached
2729 void Compile::inline_incrementally(PhaseIterGVN& igvn) {
2730   TracePhase tp(_t_incrInline);
2731 
2732   set_inlining_incrementally(true);
2733   uint low_live_nodes = 0;
2734 
2735   while (_late_inlines.length() > 0) {
2736     if (live_nodes() > (uint)LiveNodeCountInliningCutoff) {
2737       if (low_live_nodes < (uint)LiveNodeCountInliningCutoff * 8 / 10) {
2738         TracePhase tp(_t_incrInline_ideal);
2739         // PhaseIdealLoop is expensive so we only try it once we are
2740         // out of live nodes and we only try it again if the previous
2741         // helped got the number of nodes down significantly
2742         PhaseIdealLoop::optimize(igvn, LoopOptsNone);
2743         if (failing())  return;
2744         low_live_nodes = live_nodes();
2745         _major_progress = true;
2746       }
2747 
2748       if (live_nodes() > (uint)LiveNodeCountInliningCutoff) {
2749         bool do_print_inlining = print_inlining() || print_intrinsics();
2750         if (do_print_inlining || log() != nullptr) {
2751           // Print inlining message for candidates that we couldn't inline for lack of space.
2752           for (int i = 0; i < _late_inlines.length(); i++) {
2753             CallGenerator* cg = _late_inlines.at(i);
2754             const char* msg = "live nodes > LiveNodeCountInliningCutoff";
2755             if (do_print_inlining) {
2756               inline_printer()->record(cg->method(), cg->call_node()->jvms(), InliningResult::FAILURE, msg);
2757             }
2758             log_late_inline_failure(cg, msg);
2759           }
2760         }
2761         break; // finish
2762       }
2763     }
2764 
2765     igvn_worklist()->ensure_empty(); // should be done with igvn
2766 
2767     while (inline_incrementally_one()) {
2768       assert(!failing_internal() || failure_is_artificial(), "inconsistent");
2769     }
2770     if (failing())  return;
2771 
2772     inline_incrementally_cleanup(igvn);
2773 
2774     print_method(PHASE_INCREMENTAL_INLINE_STEP, 3);
2775 
2776     if (failing())  return;
2777 
2778     if (_late_inlines.length() == 0) {
2779       break; // no more progress
2780     }
2781   }
2782 
2783   igvn_worklist()->ensure_empty(); // should be done with igvn
2784 
2785   if (_string_late_inlines.length() > 0) {
2786     assert(has_stringbuilder(), "inconsistent");
2787 
2788     inline_string_calls(false);
2789 
2790     if (failing())  return;
2791 
2792     inline_incrementally_cleanup(igvn);
2793   }
2794 
2795   set_inlining_incrementally(false);
2796 }
2797 
2798 void Compile::process_late_inline_calls_no_inline(PhaseIterGVN& igvn) {
2799   // "inlining_incrementally() == false" is used to signal that no inlining is allowed
2800   // (see LateInlineVirtualCallGenerator::do_late_inline_check() for details).
2801   // Tracking and verification of modified nodes is disabled by setting "_modified_nodes == nullptr"
2802   // as if "inlining_incrementally() == true" were set.
2803   assert(inlining_incrementally() == false, "not allowed");
2804   set_strength_reduction(true);
2805 #ifdef ASSERT
2806   Unique_Node_List* modified_nodes = _modified_nodes;
2807   _modified_nodes = nullptr;
2808 #endif
2809   assert(_late_inlines.length() > 0, "sanity");
2810 
2811   while (_late_inlines.length() > 0) {
2812     igvn_worklist()->ensure_empty(); // should be done with igvn
2813 
2814     while (inline_incrementally_one()) {
2815       assert(!failing_internal() || failure_is_artificial(), "inconsistent");
2816     }
2817     if (failing())  return;
2818 
2819     inline_incrementally_cleanup(igvn);
2820   }
2821   DEBUG_ONLY( _modified_nodes = modified_nodes; )
2822   set_strength_reduction(false);
2823 }
2824 
2825 bool Compile::optimize_loops(PhaseIterGVN& igvn, LoopOptsMode mode) {
2826   if (_loop_opts_cnt > 0) {
2827     while (major_progress() && (_loop_opts_cnt > 0)) {
2828       TracePhase tp(_t_idealLoop);
2829       PhaseIdealLoop::optimize(igvn, mode);
2830       _loop_opts_cnt--;
2831       if (failing())  return false;
2832       if (major_progress()) print_method(PHASE_PHASEIDEALLOOP_ITERATIONS, 2);
2833     }
2834   }
2835   return true;
2836 }
2837 
2838 // Remove edges from "root" to each SafePoint at a backward branch.
2839 // They were inserted during parsing (see add_safepoint()) to make
2840 // infinite loops without calls or exceptions visible to root, i.e.,
2841 // useful.
2842 void Compile::remove_root_to_sfpts_edges(PhaseIterGVN& igvn) {
2843   Node *r = root();
2844   if (r != nullptr) {
2845     for (uint i = r->req(); i < r->len(); ++i) {
2846       Node *n = r->in(i);
2847       if (n != nullptr && n->is_SafePoint()) {
2848         r->rm_prec(i);
2849         if (n->outcnt() == 0) {
2850           igvn.remove_dead_node(n);
2851         }
2852         --i;
2853       }
2854     }
2855     // Parsing may have added top inputs to the root node (Path
2856     // leading to the Halt node proven dead). Make sure we get a
2857     // chance to clean them up.
2858     igvn._worklist.push(r);
2859     igvn.optimize();
2860   }
2861 }
2862 
2863 //------------------------------Optimize---------------------------------------
2864 // Given a graph, optimize it.
2865 void Compile::Optimize() {
2866   TracePhase tp(_t_optimizer);
2867 
2868 #ifndef PRODUCT
2869   if (env()->break_at_compile()) {
2870     BREAKPOINT;
2871   }
2872 
2873 #endif
2874 
2875   BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
2876 #ifdef ASSERT
2877   bs->verify_gc_barriers(this, BarrierSetC2::BeforeOptimize);
2878 #endif
2879 
2880   ResourceMark rm;
2881 
2882   NOT_PRODUCT( verify_graph_edges(); )
2883 
2884   print_method(PHASE_AFTER_PARSING, 1);
2885 
2886  {
2887   // Iterative Global Value Numbering, including ideal transforms
2888   PhaseIterGVN igvn;
2889 #ifdef ASSERT
2890   _modified_nodes = new (comp_arena()) Unique_Node_List(comp_arena());
2891 #endif
2892   {
2893     TracePhase tp(_t_iterGVN);
2894     igvn.optimize();
2895   }
2896 
2897   if (failing())  return;
2898 
2899   print_method(PHASE_ITER_GVN1, 2);
2900 
2901   process_for_unstable_if_traps(igvn);
2902 
2903   if (failing())  return;
2904 
2905   inline_incrementally(igvn);
2906 
2907   print_method(PHASE_INCREMENTAL_INLINE, 2);
2908 
2909   if (failing())  return;
2910 
2911   if (eliminate_boxing()) {
2912     // Inline valueOf() methods now.
2913     inline_boxing_calls(igvn);
2914 
2915     if (failing())  return;
2916 
2917     if (AlwaysIncrementalInline || StressIncrementalInlining) {
2918       inline_incrementally(igvn);
2919     }
2920 
2921     print_method(PHASE_INCREMENTAL_BOXING_INLINE, 2);
2922 
2923     if (failing())  return;
2924   }
2925 
2926   // Remove the speculative part of types and clean up the graph from
2927   // the extra CastPP nodes whose only purpose is to carry them. Do
2928   // that early so that optimizations are not disrupted by the extra
2929   // CastPP nodes.
2930   remove_speculative_types(igvn);
2931 
2932   if (failing())  return;
2933 
2934   // No more new expensive nodes will be added to the list from here
2935   // so keep only the actual candidates for optimizations.
2936   cleanup_expensive_nodes(igvn);
2937 
2938   if (failing())  return;
2939 
2940   assert(EnableVectorSupport || !has_vbox_nodes(), "sanity");
2941   if (EnableVectorSupport && has_vbox_nodes()) {
2942     TracePhase tp(_t_vector);
2943     PhaseVector pv(igvn);
2944     pv.optimize_vector_boxes();
2945     if (failing())  return;
2946     print_method(PHASE_ITER_GVN_AFTER_VECTOR, 2);
2947   }
2948   assert(!has_vbox_nodes(), "sanity");
2949 
2950   if (!failing() && RenumberLiveNodes && live_nodes() + NodeLimitFudgeFactor < unique()) {
2951     Compile::TracePhase tp(_t_renumberLive);
2952     igvn_worklist()->ensure_empty(); // should be done with igvn
2953     {
2954       ResourceMark rm;
2955       PhaseRenumberLive prl(initial_gvn(), *igvn_worklist());
2956     }
2957     igvn.reset();
2958     igvn.optimize();
2959     if (failing()) return;
2960   }
2961 
2962   // Now that all inlining is over and no PhaseRemoveUseless will run, cut edge from root to loop
2963   // safepoints
2964   remove_root_to_sfpts_edges(igvn);
2965 
2966   // Process inline type nodes now that all inlining is over
2967   process_inline_types(igvn);
2968 
2969   adjust_flat_array_access_aliases(igvn);
2970 
2971   if (failing())  return;
2972 
2973   if (C->macro_count() > 0) {
2974     // Eliminate some macro nodes before EA to reduce analysis pressure
2975     PhaseMacroExpand mexp(igvn);
2976     mexp.eliminate_macro_nodes(/* eliminate_locks= */ false);
2977     if (failing()) {
2978       return;
2979     }
2980     igvn.set_delay_transform(false);
2981     print_method(PHASE_ITER_GVN_AFTER_ELIMINATION, 2);
2982   }
2983 
2984   if (has_loops()) {
2985     print_method(PHASE_BEFORE_LOOP_OPTS, 2);
2986   }
2987 
2988   // Perform escape analysis
2989   if (do_escape_analysis() && ConnectionGraph::has_candidates(this)) {
2990     if (has_loops()) {
2991       // Cleanup graph (remove dead nodes).
2992       TracePhase tp(_t_idealLoop);
2993       PhaseIdealLoop::optimize(igvn, LoopOptsMaxUnroll);
2994       if (failing()) {
2995         return;
2996       }
2997       print_method(PHASE_PHASEIDEAL_BEFORE_EA, 2);
2998       if (C->macro_count() > 0) {
2999         // Eliminate some macro nodes before EA to reduce analysis pressure
3000         PhaseMacroExpand mexp(igvn);
3001         mexp.eliminate_macro_nodes(/* eliminate_locks= */ false);
3002         if (failing()) {
3003           return;
3004         }
3005         igvn.set_delay_transform(false);
3006         print_method(PHASE_ITER_GVN_AFTER_ELIMINATION, 2);
3007       }
3008     }
3009 
3010     bool progress;
3011     do {
3012       ConnectionGraph::do_analysis(this, &igvn);
3013 
3014       if (failing())  return;
3015 
3016       int mcount = macro_count(); // Record number of allocations and locks before IGVN
3017 
3018       // Optimize out fields loads from scalar replaceable allocations.
3019       igvn.optimize();
3020       print_method(PHASE_ITER_GVN_AFTER_EA, 2);
3021 
3022       if (failing()) return;
3023 
3024       if (congraph() != nullptr && macro_count() > 0) {
3025         TracePhase tp(_t_macroEliminate);
3026         PhaseMacroExpand mexp(igvn);
3027         mexp.eliminate_macro_nodes();
3028         if (failing()) {
3029           return;
3030         }
3031         print_method(PHASE_AFTER_MACRO_ELIMINATION, 2);
3032 
3033         igvn.set_delay_transform(false);
3034         print_method(PHASE_ITER_GVN_AFTER_ELIMINATION, 2);
3035       }
3036 
3037       ConnectionGraph::verify_ram_nodes(this, root());
3038       if (failing())  return;
3039 
3040       progress = do_iterative_escape_analysis() &&
3041                  (macro_count() < mcount) &&
3042                  ConnectionGraph::has_candidates(this);
3043       // Try again if candidates exist and made progress
3044       // by removing some allocations and/or locks.
3045     } while (progress);
3046   }
3047 
3048   process_flat_accesses(igvn);
3049   if (failing()) {
3050     return;
3051   }
3052 
3053   // Loop transforms on the ideal graph.  Range Check Elimination,
3054   // peeling, unrolling, etc.
3055 
3056   // Set loop opts counter
3057   if((_loop_opts_cnt > 0) && (has_loops() || has_split_ifs())) {
3058     {
3059       TracePhase tp(_t_idealLoop);
3060       PhaseIdealLoop::optimize(igvn, LoopOptsDefault);
3061       _loop_opts_cnt--;
3062       if (major_progress()) print_method(PHASE_PHASEIDEALLOOP1, 2);
3063       if (failing())  return;
3064     }
3065     // Loop opts pass if partial peeling occurred in previous pass
3066     if(PartialPeelLoop && major_progress() && (_loop_opts_cnt > 0)) {
3067       TracePhase tp(_t_idealLoop);
3068       PhaseIdealLoop::optimize(igvn, LoopOptsSkipSplitIf);
3069       _loop_opts_cnt--;
3070       if (major_progress()) print_method(PHASE_PHASEIDEALLOOP2, 2);
3071       if (failing())  return;
3072     }
3073     // Loop opts pass for loop-unrolling before CCP
3074     if(major_progress() && (_loop_opts_cnt > 0)) {
3075       TracePhase tp(_t_idealLoop);
3076       PhaseIdealLoop::optimize(igvn, LoopOptsSkipSplitIf);
3077       _loop_opts_cnt--;
3078       if (major_progress()) print_method(PHASE_PHASEIDEALLOOP3, 2);
3079     }
3080     if (!failing()) {
3081       // Verify that last round of loop opts produced a valid graph
3082       PhaseIdealLoop::verify(igvn);
3083     }
3084   }
3085   if (failing())  return;
3086 
3087   // Conditional Constant Propagation;
3088   print_method(PHASE_BEFORE_CCP1, 2);
3089   PhaseCCP ccp( &igvn );
3090   assert( true, "Break here to ccp.dump_nodes_and_types(_root,999,1)");
3091   {
3092     TracePhase tp(_t_ccp);
3093     ccp.do_transform();
3094   }
3095   print_method(PHASE_CCP1, 2);
3096 
3097   assert( true, "Break here to ccp.dump_old2new_map()");
3098 
3099   // Iterative Global Value Numbering, including ideal transforms
3100   {
3101     TracePhase tp(_t_iterGVN2);
3102     igvn.reset_from_igvn(&ccp);
3103     igvn.optimize();
3104   }
3105   print_method(PHASE_ITER_GVN2, 2);
3106 
3107   if (failing())  return;
3108 
3109   // Loop transforms on the ideal graph.  Range Check Elimination,
3110   // peeling, unrolling, etc.
3111   if (!optimize_loops(igvn, LoopOptsDefault)) {
3112     return;
3113   }
3114 
3115   if (failing())  return;
3116 
3117   C->clear_major_progress(); // ensure that major progress is now clear
3118 
3119   process_for_post_loop_opts_igvn(igvn);
3120 
3121   process_for_merge_stores_igvn(igvn);
3122 
3123   if (failing())  return;
3124 
3125 #ifdef ASSERT
3126   bs->verify_gc_barriers(this, BarrierSetC2::BeforeMacroExpand);
3127 #endif
3128 
3129   assert(_late_inlines.length() == 0 || IncrementalInlineMH || IncrementalInlineVirtual, "not empty");
3130 
3131   if (_late_inlines.length() > 0) {
3132     // More opportunities to optimize virtual and MH calls.
3133     // Though it's maybe too late to perform inlining, strength-reducing them to direct calls is still an option.
3134     process_late_inline_calls_no_inline(igvn);
3135   }
3136 
3137   {
3138     TracePhase tp(_t_macroExpand);
3139     PhaseMacroExpand mex(igvn);
3140     // Last attempt to eliminate macro nodes.
3141     mex.eliminate_macro_nodes();
3142     if (failing()) {
3143       return;
3144     }
3145 
3146     print_method(PHASE_BEFORE_MACRO_EXPANSION, 3);
3147     // Do not allow new macro nodes once we start to eliminate and expand
3148     C->reset_allow_macro_nodes();
3149     // Last attempt to eliminate macro nodes before expand
3150     mex.eliminate_macro_nodes();
3151     if (failing()) {
3152       return;
3153     }
3154     mex.eliminate_opaque_looplimit_macro_nodes();
3155     if (failing()) {
3156       return;
3157     }
3158     print_method(PHASE_AFTER_MACRO_ELIMINATION, 2);
3159     if (mex.expand_macro_nodes()) {
3160       assert(failing(), "must bail out w/ explicit message");
3161       return;
3162     }
3163     print_method(PHASE_AFTER_MACRO_EXPANSION, 2);
3164   }
3165 
3166   // Process inline type nodes again and remove them. From here
3167   // on we don't need to keep track of field values anymore.
3168   process_inline_types(igvn, /* remove= */ true);
3169 
3170   {
3171     TracePhase tp(_t_barrierExpand);
3172     if (bs->expand_barriers(this, igvn)) {
3173       assert(failing(), "must bail out w/ explicit message");
3174       return;
3175     }
3176     print_method(PHASE_BARRIER_EXPANSION, 2);
3177   }
3178 
3179   if (C->max_vector_size() > 0) {
3180     C->optimize_logic_cones(igvn);
3181     igvn.optimize();
3182     if (failing()) return;
3183   }
3184 
3185   DEBUG_ONLY( _modified_nodes = nullptr; )
3186   DEBUG_ONLY( _late_inlines.clear(); )
3187 
3188   assert(igvn._worklist.size() == 0, "not empty");
3189  } // (End scope of igvn; run destructor if necessary for asserts.)
3190 
3191  check_no_dead_use();
3192 
3193  // We will never use the NodeHash table any more. Clear it so that final_graph_reshaping does not have
3194  // to remove hashes to unlock nodes for modifications.
3195  C->node_hash()->clear();
3196 
3197  // A method with only infinite loops has no edges entering loops from root
3198  {
3199    TracePhase tp(_t_graphReshaping);
3200    if (final_graph_reshaping()) {
3201      assert(failing(), "must bail out w/ explicit message");
3202      return;
3203    }
3204  }
3205 
3206  print_method(PHASE_OPTIMIZE_FINISHED, 2);
3207  DEBUG_ONLY(set_phase_optimize_finished();)
3208 }
3209 
3210 #ifdef ASSERT
3211 void Compile::check_no_dead_use() const {
3212   ResourceMark rm;
3213   Unique_Node_List wq;
3214   wq.push(root());
3215   for (uint i = 0; i < wq.size(); ++i) {
3216     Node* n = wq.at(i);
3217     for (DUIterator_Fast jmax, j = n->fast_outs(jmax); j < jmax; j++) {
3218       Node* u = n->fast_out(j);
3219       if (u->outcnt() == 0 && !u->is_Con()) {
3220         u->dump();
3221         fatal("no reachable node should have no use");
3222       }
3223       wq.push(u);
3224     }
3225   }
3226 }
3227 #endif
3228 
3229 void Compile::inline_vector_reboxing_calls() {
3230   if (C->_vector_reboxing_late_inlines.length() > 0) {
3231     _late_inlines_pos = C->_late_inlines.length();
3232     while (_vector_reboxing_late_inlines.length() > 0) {
3233       CallGenerator* cg = _vector_reboxing_late_inlines.pop();
3234       cg->do_late_inline();
3235       if (failing())  return;
3236       print_method(PHASE_INLINE_VECTOR_REBOX, 3, cg->call_node());
3237     }
3238     _vector_reboxing_late_inlines.trunc_to(0);
3239   }
3240 }
3241 
3242 bool Compile::has_vbox_nodes() {
3243   if (C->_vector_reboxing_late_inlines.length() > 0) {
3244     return true;
3245   }
3246   for (int macro_idx = C->macro_count() - 1; macro_idx >= 0; macro_idx--) {
3247     Node * n = C->macro_node(macro_idx);
3248     assert(n->is_macro(), "only macro nodes expected here");
3249     if (n->Opcode() == Op_VectorUnbox || n->Opcode() == Op_VectorBox || n->Opcode() == Op_VectorBoxAllocate) {
3250       return true;
3251     }
3252   }
3253   return false;
3254 }
3255 
3256 //---------------------------- Bitwise operation packing optimization ---------------------------
3257 
3258 static bool is_vector_unary_bitwise_op(Node* n) {
3259   return n->Opcode() == Op_XorV &&
3260          VectorNode::is_vector_bitwise_not_pattern(n);
3261 }
3262 
3263 static bool is_vector_binary_bitwise_op(Node* n) {
3264   switch (n->Opcode()) {
3265     case Op_AndV:
3266     case Op_OrV:
3267       return true;
3268 
3269     case Op_XorV:
3270       return !is_vector_unary_bitwise_op(n);
3271 
3272     default:
3273       return false;
3274   }
3275 }
3276 
3277 static bool is_vector_ternary_bitwise_op(Node* n) {
3278   return n->Opcode() == Op_MacroLogicV;
3279 }
3280 
3281 static bool is_vector_bitwise_op(Node* n) {
3282   return is_vector_unary_bitwise_op(n)  ||
3283          is_vector_binary_bitwise_op(n) ||
3284          is_vector_ternary_bitwise_op(n);
3285 }
3286 
3287 static bool is_vector_bitwise_cone_root(Node* n) {
3288   if (n->bottom_type()->isa_vectmask() || !is_vector_bitwise_op(n)) {
3289     return false;
3290   }
3291   for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
3292     if (is_vector_bitwise_op(n->fast_out(i))) {
3293       return false;
3294     }
3295   }
3296   return true;
3297 }
3298 
3299 static uint collect_unique_inputs(Node* n, Unique_Node_List& inputs) {
3300   uint cnt = 0;
3301   if (is_vector_bitwise_op(n)) {
3302     uint inp_cnt = n->is_predicated_vector() ? n->req()-1 : n->req();
3303     if (VectorNode::is_vector_bitwise_not_pattern(n)) {
3304       for (uint i = 1; i < inp_cnt; i++) {
3305         Node* in = n->in(i);
3306         bool skip = VectorNode::is_all_ones_vector(in);
3307         if (!skip && !inputs.member(in)) {
3308           inputs.push(in);
3309           cnt++;
3310         }
3311       }
3312       assert(cnt <= 1, "not unary");
3313     } else {
3314       uint last_req = inp_cnt;
3315       if (is_vector_ternary_bitwise_op(n)) {
3316         last_req = inp_cnt - 1; // skip last input
3317       }
3318       for (uint i = 1; i < last_req; i++) {
3319         Node* def = n->in(i);
3320         if (!inputs.member(def)) {
3321           inputs.push(def);
3322           cnt++;
3323         }
3324       }
3325     }
3326   } else { // not a bitwise operations
3327     if (!inputs.member(n)) {
3328       inputs.push(n);
3329       cnt++;
3330     }
3331   }
3332   return cnt;
3333 }
3334 
3335 void Compile::collect_logic_cone_roots(Unique_Node_List& list) {
3336   Unique_Node_List useful_nodes;
3337   C->identify_useful_nodes(useful_nodes);
3338 
3339   for (uint i = 0; i < useful_nodes.size(); i++) {
3340     Node* n = useful_nodes.at(i);
3341     if (is_vector_bitwise_cone_root(n)) {
3342       list.push(n);
3343     }
3344   }
3345 }
3346 
3347 Node* Compile::xform_to_MacroLogicV(PhaseIterGVN& igvn,
3348                                     const TypeVect* vt,
3349                                     Unique_Node_List& partition,
3350                                     Unique_Node_List& inputs) {
3351   assert(partition.size() == 2 || partition.size() == 3, "not supported");
3352   assert(inputs.size()    == 2 || inputs.size()    == 3, "not supported");
3353   assert(Matcher::match_rule_supported_vector(Op_MacroLogicV, vt->length(), vt->element_basic_type()), "not supported");
3354 
3355   Node* in1 = inputs.at(0);
3356   Node* in2 = inputs.at(1);
3357   Node* in3 = (inputs.size() == 3 ? inputs.at(2) : in2);
3358 
3359   uint func = compute_truth_table(partition, inputs);
3360 
3361   Node* pn = partition.at(partition.size() - 1);
3362   Node* mask = pn->is_predicated_vector() ? pn->in(pn->req()-1) : nullptr;
3363   return igvn.transform(MacroLogicVNode::make(igvn, in1, in2, in3, mask, func, vt));
3364 }
3365 
3366 static uint extract_bit(uint func, uint pos) {
3367   return (func & (1 << pos)) >> pos;
3368 }
3369 
3370 //
3371 //  A macro logic node represents a truth table. It has 4 inputs,
3372 //  First three inputs corresponds to 3 columns of a truth table
3373 //  and fourth input captures the logic function.
3374 //
3375 //  eg.  fn = (in1 AND in2) OR in3;
3376 //
3377 //      MacroNode(in1,in2,in3,fn)
3378 //
3379 //  -----------------
3380 //  in1 in2 in3  fn
3381 //  -----------------
3382 //  0    0   0    0
3383 //  0    0   1    1
3384 //  0    1   0    0
3385 //  0    1   1    1
3386 //  1    0   0    0
3387 //  1    0   1    1
3388 //  1    1   0    1
3389 //  1    1   1    1
3390 //
3391 
3392 uint Compile::eval_macro_logic_op(uint func, uint in1 , uint in2, uint in3) {
3393   int res = 0;
3394   for (int i = 0; i < 8; i++) {
3395     int bit1 = extract_bit(in1, i);
3396     int bit2 = extract_bit(in2, i);
3397     int bit3 = extract_bit(in3, i);
3398 
3399     int func_bit_pos = (bit1 << 2 | bit2 << 1 | bit3);
3400     int func_bit = extract_bit(func, func_bit_pos);
3401 
3402     res |= func_bit << i;
3403   }
3404   return res;
3405 }
3406 
3407 static uint eval_operand(Node* n, HashTable<Node*,uint>& eval_map) {
3408   assert(n != nullptr, "");
3409   assert(eval_map.contains(n), "absent");
3410   return *(eval_map.get(n));
3411 }
3412 
3413 static void eval_operands(Node* n,
3414                           uint& func1, uint& func2, uint& func3,
3415                           HashTable<Node*,uint>& eval_map) {
3416   assert(is_vector_bitwise_op(n), "");
3417 
3418   if (is_vector_unary_bitwise_op(n)) {
3419     Node* opnd = n->in(1);
3420     if (VectorNode::is_vector_bitwise_not_pattern(n) && VectorNode::is_all_ones_vector(opnd)) {
3421       opnd = n->in(2);
3422     }
3423     func1 = eval_operand(opnd, eval_map);
3424   } else if (is_vector_binary_bitwise_op(n)) {
3425     func1 = eval_operand(n->in(1), eval_map);
3426     func2 = eval_operand(n->in(2), eval_map);
3427   } else {
3428     assert(is_vector_ternary_bitwise_op(n), "unknown operation");
3429     func1 = eval_operand(n->in(1), eval_map);
3430     func2 = eval_operand(n->in(2), eval_map);
3431     func3 = eval_operand(n->in(3), eval_map);
3432   }
3433 }
3434 
3435 uint Compile::compute_truth_table(Unique_Node_List& partition, Unique_Node_List& inputs) {
3436   assert(inputs.size() <= 3, "sanity");
3437   ResourceMark rm;
3438   uint res = 0;
3439   HashTable<Node*,uint> eval_map;
3440 
3441   // Populate precomputed functions for inputs.
3442   // Each input corresponds to one column of 3 input truth-table.
3443   uint input_funcs[] = { 0xAA,   // (_, _, c) -> c
3444                          0xCC,   // (_, b, _) -> b
3445                          0xF0 }; // (a, _, _) -> a
3446   for (uint i = 0; i < inputs.size(); i++) {
3447     eval_map.put(inputs.at(i), input_funcs[2-i]);
3448   }
3449 
3450   for (uint i = 0; i < partition.size(); i++) {
3451     Node* n = partition.at(i);
3452 
3453     uint func1 = 0, func2 = 0, func3 = 0;
3454     eval_operands(n, func1, func2, func3, eval_map);
3455 
3456     switch (n->Opcode()) {
3457       case Op_OrV:
3458         assert(func3 == 0, "not binary");
3459         res = func1 | func2;
3460         break;
3461       case Op_AndV:
3462         assert(func3 == 0, "not binary");
3463         res = func1 & func2;
3464         break;
3465       case Op_XorV:
3466         if (VectorNode::is_vector_bitwise_not_pattern(n)) {
3467           assert(func2 == 0 && func3 == 0, "not unary");
3468           res = (~func1) & 0xFF;
3469         } else {
3470           assert(func3 == 0, "not binary");
3471           res = func1 ^ func2;
3472         }
3473         break;
3474       case Op_MacroLogicV:
3475         // Ordering of inputs may change during evaluation of sub-tree
3476         // containing MacroLogic node as a child node, thus a re-evaluation
3477         // makes sure that function is evaluated in context of current
3478         // inputs.
3479         res = eval_macro_logic_op(n->in(4)->get_int(), func1, func2, func3);
3480         break;
3481 
3482       default: assert(false, "not supported: %s", n->Name());
3483     }
3484     assert(res <= 0xFF, "invalid");
3485     eval_map.put(n, res);
3486   }
3487   return res;
3488 }
3489 
3490 // Criteria under which nodes gets packed into a macro logic node:-
3491 //  1) Parent and both child nodes are all unmasked or masked with
3492 //     same predicates.
3493 //  2) Masked parent can be packed with left child if it is predicated
3494 //     and both have same predicates.
3495 //  3) Masked parent can be packed with right child if its un-predicated
3496 //     or has matching predication condition.
3497 //  4) An unmasked parent can be packed with an unmasked child.
3498 bool Compile::compute_logic_cone(Node* n, Unique_Node_List& partition, Unique_Node_List& inputs) {
3499   assert(partition.size() == 0, "not empty");
3500   assert(inputs.size() == 0, "not empty");
3501   if (is_vector_ternary_bitwise_op(n)) {
3502     return false;
3503   }
3504 
3505   bool is_unary_op = is_vector_unary_bitwise_op(n);
3506   if (is_unary_op) {
3507     assert(collect_unique_inputs(n, inputs) == 1, "not unary");
3508     return false; // too few inputs
3509   }
3510 
3511   bool pack_left_child = true;
3512   bool pack_right_child = true;
3513 
3514   bool left_child_LOP = is_vector_bitwise_op(n->in(1));
3515   bool right_child_LOP = is_vector_bitwise_op(n->in(2));
3516 
3517   int left_child_input_cnt = 0;
3518   int right_child_input_cnt = 0;
3519 
3520   bool parent_is_predicated = n->is_predicated_vector();
3521   bool left_child_predicated = n->in(1)->is_predicated_vector();
3522   bool right_child_predicated = n->in(2)->is_predicated_vector();
3523 
3524   Node* parent_pred = parent_is_predicated ? n->in(n->req()-1) : nullptr;
3525   Node* left_child_pred = left_child_predicated ? n->in(1)->in(n->in(1)->req()-1) : nullptr;
3526   Node* right_child_pred = right_child_predicated ? n->in(1)->in(n->in(1)->req()-1) : nullptr;
3527 
3528   do {
3529     if (pack_left_child && left_child_LOP &&
3530         ((!parent_is_predicated && !left_child_predicated) ||
3531         ((parent_is_predicated && left_child_predicated &&
3532           parent_pred == left_child_pred)))) {
3533        partition.push(n->in(1));
3534        left_child_input_cnt = collect_unique_inputs(n->in(1), inputs);
3535     } else {
3536        inputs.push(n->in(1));
3537        left_child_input_cnt = 1;
3538     }
3539 
3540     if (pack_right_child && right_child_LOP &&
3541         (!right_child_predicated ||
3542          (right_child_predicated && parent_is_predicated &&
3543           parent_pred == right_child_pred))) {
3544        partition.push(n->in(2));
3545        right_child_input_cnt = collect_unique_inputs(n->in(2), inputs);
3546     } else {
3547        inputs.push(n->in(2));
3548        right_child_input_cnt = 1;
3549     }
3550 
3551     if (inputs.size() > 3) {
3552       assert(partition.size() > 0, "");
3553       inputs.clear();
3554       partition.clear();
3555       if (left_child_input_cnt > right_child_input_cnt) {
3556         pack_left_child = false;
3557       } else {
3558         pack_right_child = false;
3559       }
3560     } else {
3561       break;
3562     }
3563   } while(true);
3564 
3565   if(partition.size()) {
3566     partition.push(n);
3567   }
3568 
3569   return (partition.size() == 2 || partition.size() == 3) &&
3570          (inputs.size()    == 2 || inputs.size()    == 3);
3571 }
3572 
3573 void Compile::process_logic_cone_root(PhaseIterGVN &igvn, Node *n, VectorSet &visited) {
3574   assert(is_vector_bitwise_op(n), "not a root");
3575 
3576   visited.set(n->_idx);
3577 
3578   // 1) Do a DFS walk over the logic cone.
3579   for (uint i = 1; i < n->req(); i++) {
3580     Node* in = n->in(i);
3581     if (!visited.test(in->_idx) && is_vector_bitwise_op(in)) {
3582       process_logic_cone_root(igvn, in, visited);
3583     }
3584   }
3585 
3586   // 2) Bottom up traversal: Merge node[s] with
3587   // the parent to form macro logic node.
3588   Unique_Node_List partition;
3589   Unique_Node_List inputs;
3590   if (compute_logic_cone(n, partition, inputs)) {
3591     const TypeVect* vt = n->bottom_type()->is_vect();
3592     Node* pn = partition.at(partition.size() - 1);
3593     Node* mask = pn->is_predicated_vector() ? pn->in(pn->req()-1) : nullptr;
3594     if (mask == nullptr ||
3595         Matcher::match_rule_supported_vector_masked(Op_MacroLogicV, vt->length(), vt->element_basic_type())) {
3596       Node* macro_logic = xform_to_MacroLogicV(igvn, vt, partition, inputs);
3597       VectorNode::trace_new_vector(macro_logic, "MacroLogic");
3598       igvn.replace_node(n, macro_logic);
3599     }
3600   }
3601 }
3602 
3603 void Compile::optimize_logic_cones(PhaseIterGVN &igvn) {
3604   ResourceMark rm;
3605   if (Matcher::match_rule_supported(Op_MacroLogicV)) {
3606     Unique_Node_List list;
3607     collect_logic_cone_roots(list);
3608 
3609     while (list.size() > 0) {
3610       Node* n = list.pop();
3611       const TypeVect* vt = n->bottom_type()->is_vect();
3612       bool supported = Matcher::match_rule_supported_vector(Op_MacroLogicV, vt->length(), vt->element_basic_type());
3613       if (supported) {
3614         VectorSet visited(comp_arena());
3615         process_logic_cone_root(igvn, n, visited);
3616       }
3617     }
3618   }
3619 }
3620 
3621 //------------------------------Code_Gen---------------------------------------
3622 // Given a graph, generate code for it
3623 void Compile::Code_Gen() {
3624   if (failing()) {
3625     return;
3626   }
3627 
3628   // Perform instruction selection.  You might think we could reclaim Matcher
3629   // memory PDQ, but actually the Matcher is used in generating spill code.
3630   // Internals of the Matcher (including some VectorSets) must remain live
3631   // for awhile - thus I cannot reclaim Matcher memory lest a VectorSet usage
3632   // set a bit in reclaimed memory.
3633 
3634   // In debug mode can dump m._nodes.dump() for mapping of ideal to machine
3635   // nodes.  Mapping is only valid at the root of each matched subtree.
3636   NOT_PRODUCT( verify_graph_edges(); )
3637 
3638   Matcher matcher;
3639   _matcher = &matcher;
3640   {
3641     TracePhase tp(_t_matcher);
3642     matcher.match();
3643     if (failing()) {
3644       return;
3645     }
3646   }
3647   // In debug mode can dump m._nodes.dump() for mapping of ideal to machine
3648   // nodes.  Mapping is only valid at the root of each matched subtree.
3649   NOT_PRODUCT( verify_graph_edges(); )
3650 
3651   // If you have too many nodes, or if matching has failed, bail out
3652   check_node_count(0, "out of nodes matching instructions");
3653   if (failing()) {
3654     return;
3655   }
3656 
3657   print_method(PHASE_MATCHING, 2);
3658 
3659   // Build a proper-looking CFG
3660   PhaseCFG cfg(node_arena(), root(), matcher);
3661   if (failing()) {
3662     return;
3663   }
3664   _cfg = &cfg;
3665   {
3666     TracePhase tp(_t_scheduler);
3667     bool success = cfg.do_global_code_motion();
3668     if (!success) {
3669       return;
3670     }
3671 
3672     print_method(PHASE_GLOBAL_CODE_MOTION, 2);
3673     NOT_PRODUCT( verify_graph_edges(); )
3674     cfg.verify();
3675     if (failing()) {
3676       return;
3677     }
3678   }
3679 
3680   PhaseChaitin regalloc(unique(), cfg, matcher, false);
3681   _regalloc = &regalloc;
3682   {
3683     TracePhase tp(_t_registerAllocation);
3684     // Perform register allocation.  After Chaitin, use-def chains are
3685     // no longer accurate (at spill code) and so must be ignored.
3686     // Node->LRG->reg mappings are still accurate.
3687     _regalloc->Register_Allocate();
3688 
3689     // Bail out if the allocator builds too many nodes
3690     if (failing()) {
3691       return;
3692     }
3693 
3694     print_method(PHASE_REGISTER_ALLOCATION, 2);
3695   }
3696 
3697   // Prior to register allocation we kept empty basic blocks in case the
3698   // the allocator needed a place to spill.  After register allocation we
3699   // are not adding any new instructions.  If any basic block is empty, we
3700   // can now safely remove it.
3701   {
3702     TracePhase tp(_t_blockOrdering);
3703     cfg.remove_empty_blocks();
3704     if (do_freq_based_layout()) {
3705       PhaseBlockLayout layout(cfg);
3706     } else {
3707       cfg.set_loop_alignment();
3708     }
3709     cfg.fixup_flow();
3710     cfg.remove_unreachable_blocks();
3711     cfg.verify_dominator_tree();
3712     print_method(PHASE_BLOCK_ORDERING, 3);
3713   }
3714 
3715   // Apply peephole optimizations
3716   if( OptoPeephole ) {
3717     TracePhase tp(_t_peephole);
3718     PhasePeephole peep( _regalloc, cfg);
3719     peep.do_transform();
3720     print_method(PHASE_PEEPHOLE, 3);
3721   }
3722 
3723   // Do late expand if CPU requires this.
3724   if (Matcher::require_postalloc_expand) {
3725     TracePhase tp(_t_postalloc_expand);
3726     cfg.postalloc_expand(_regalloc);
3727     print_method(PHASE_POSTALLOC_EXPAND, 3);
3728   }
3729 
3730 #ifdef ASSERT
3731   {
3732     CompilationMemoryStatistic::do_test_allocations();
3733     if (failing()) return;
3734   }
3735 #endif
3736 
3737   // Convert Nodes to instruction bits in a buffer
3738   {
3739     TracePhase tp(_t_output);
3740     PhaseOutput output;
3741     output.Output();
3742     if (failing())  return;
3743     output.install();
3744     print_method(PHASE_FINAL_CODE, 1); // Compile::_output is not null here
3745   }
3746 
3747   // He's dead, Jim.
3748   _cfg     = (PhaseCFG*)((intptr_t)0xdeadbeef);
3749   _regalloc = (PhaseChaitin*)((intptr_t)0xdeadbeef);
3750 }
3751 
3752 //------------------------------Final_Reshape_Counts---------------------------
3753 // This class defines counters to help identify when a method
3754 // may/must be executed using hardware with only 24-bit precision.
3755 struct Final_Reshape_Counts : public StackObj {
3756   int  _call_count;             // count non-inlined 'common' calls
3757   int  _float_count;            // count float ops requiring 24-bit precision
3758   int  _double_count;           // count double ops requiring more precision
3759   int  _java_call_count;        // count non-inlined 'java' calls
3760   int  _inner_loop_count;       // count loops which need alignment
3761   VectorSet _visited;           // Visitation flags
3762   Node_List _tests;             // Set of IfNodes & PCTableNodes
3763 
3764   Final_Reshape_Counts() :
3765     _call_count(0), _float_count(0), _double_count(0),
3766     _java_call_count(0), _inner_loop_count(0) { }
3767 
3768   void inc_call_count  () { _call_count  ++; }
3769   void inc_float_count () { _float_count ++; }
3770   void inc_double_count() { _double_count++; }
3771   void inc_java_call_count() { _java_call_count++; }
3772   void inc_inner_loop_count() { _inner_loop_count++; }
3773 
3774   int  get_call_count  () const { return _call_count  ; }
3775   int  get_float_count () const { return _float_count ; }
3776   int  get_double_count() const { return _double_count; }
3777   int  get_java_call_count() const { return _java_call_count; }
3778   int  get_inner_loop_count() const { return _inner_loop_count; }
3779 };
3780 
3781 //------------------------------final_graph_reshaping_impl----------------------
3782 // Implement items 1-5 from final_graph_reshaping below.
3783 void Compile::final_graph_reshaping_impl(Node *n, Final_Reshape_Counts& frc, Unique_Node_List& dead_nodes) {
3784 
3785   if ( n->outcnt() == 0 ) return; // dead node
3786   uint nop = n->Opcode();
3787 
3788   // Check for 2-input instruction with "last use" on right input.
3789   // Swap to left input.  Implements item (2).
3790   if( n->req() == 3 &&          // two-input instruction
3791       n->in(1)->outcnt() > 1 && // left use is NOT a last use
3792       (!n->in(1)->is_Phi() || n->in(1)->in(2) != n) && // it is not data loop
3793       n->in(2)->outcnt() == 1 &&// right use IS a last use
3794       !n->in(2)->is_Con() ) {   // right use is not a constant
3795     // Check for commutative opcode
3796     switch( nop ) {
3797     case Op_AddI:  case Op_AddF:  case Op_AddD:  case Op_AddL:
3798     case Op_MaxI:  case Op_MaxL:  case Op_MaxF:  case Op_MaxD:
3799     case Op_MinI:  case Op_MinL:  case Op_MinF:  case Op_MinD:
3800     case Op_MulI:  case Op_MulF:  case Op_MulD:  case Op_MulL:
3801     case Op_AndL:  case Op_XorL:  case Op_OrL:
3802     case Op_AndI:  case Op_XorI:  case Op_OrI: {
3803       // Move "last use" input to left by swapping inputs
3804       n->swap_edges(1, 2);
3805       break;
3806     }
3807     default:
3808       break;
3809     }
3810   }
3811 
3812 #ifdef ASSERT
3813   if( n->is_Mem() ) {
3814     int alias_idx = get_alias_index(n->as_Mem()->adr_type());
3815     assert( n->in(0) != nullptr || alias_idx != Compile::AliasIdxRaw ||
3816             // oop will be recorded in oop map if load crosses safepoint
3817             (n->is_Load() && (n->as_Load()->bottom_type()->isa_oopptr() ||
3818                               LoadNode::is_immutable_value(n->in(MemNode::Address)))),
3819             "raw memory operations should have control edge");
3820   }
3821   if (n->is_MemBar()) {
3822     MemBarNode* mb = n->as_MemBar();
3823     if (mb->trailing_store() || mb->trailing_load_store()) {
3824       assert(mb->leading_membar()->trailing_membar() == mb, "bad membar pair");
3825       Node* mem = BarrierSet::barrier_set()->barrier_set_c2()->step_over_gc_barrier(mb->in(MemBarNode::Precedent));
3826       assert((mb->trailing_store() && mem->is_Store() && mem->as_Store()->is_release()) ||
3827              (mb->trailing_load_store() && mem->is_LoadStore()), "missing mem op");
3828     } else if (mb->leading()) {
3829       assert(mb->trailing_membar()->leading_membar() == mb, "bad membar pair");
3830     }
3831   }
3832 #endif
3833   // Count FPU ops and common calls, implements item (3)
3834   bool gc_handled = BarrierSet::barrier_set()->barrier_set_c2()->final_graph_reshaping(this, n, nop, dead_nodes);
3835   if (!gc_handled) {
3836     final_graph_reshaping_main_switch(n, frc, nop, dead_nodes);
3837   }
3838 
3839   // Collect CFG split points
3840   if (n->is_MultiBranch() && !n->is_RangeCheck()) {
3841     frc._tests.push(n);
3842   }
3843 }
3844 
3845 void Compile::handle_div_mod_op(Node* n, BasicType bt, bool is_unsigned) {
3846   if (!UseDivMod) {
3847     return;
3848   }
3849 
3850   // Check if "a % b" and "a / b" both exist
3851   Node* d = n->find_similar(Op_DivIL(bt, is_unsigned));
3852   if (d == nullptr) {
3853     return;
3854   }
3855 
3856   // Replace them with a fused divmod if supported
3857   if (Matcher::has_match_rule(Op_DivModIL(bt, is_unsigned))) {
3858     DivModNode* divmod = DivModNode::make(n, bt, is_unsigned);
3859     // If the divisor input for a Div (or Mod etc.) is not zero, then the control input of the Div is set to zero.
3860     // It could be that the divisor input is found not zero because its type is narrowed down by a CastII in the
3861     // subgraph for that input. Range check CastIIs are removed during final graph reshape. To preserve the dependency
3862     // carried by a CastII, precedence edges are added to the Div node. We need to transfer the precedence edges to the
3863     // DivMod node so the dependency is not lost.
3864     divmod->add_prec_from(n);
3865     divmod->add_prec_from(d);
3866     d->subsume_by(divmod->div_proj(), this);
3867     n->subsume_by(divmod->mod_proj(), this);
3868   } else {
3869     // Replace "a % b" with "a - ((a / b) * b)"
3870     Node* mult = MulNode::make(d, d->in(2), bt);
3871     Node* sub = SubNode::make(d->in(1), mult, bt);
3872     n->subsume_by(sub, this);
3873   }
3874 }
3875 
3876 void Compile::final_graph_reshaping_main_switch(Node* n, Final_Reshape_Counts& frc, uint nop, Unique_Node_List& dead_nodes) {
3877   switch( nop ) {
3878   // Count all float operations that may use FPU
3879   case Op_AddF:
3880   case Op_SubF:
3881   case Op_MulF:
3882   case Op_DivF:
3883   case Op_NegF:
3884   case Op_ModF:
3885   case Op_ConvI2F:
3886   case Op_ConF:
3887   case Op_CmpF:
3888   case Op_CmpF3:
3889   case Op_StoreF:
3890   case Op_LoadF:
3891   // case Op_ConvL2F: // longs are split into 32-bit halves
3892     frc.inc_float_count();
3893     break;
3894 
3895   case Op_ConvF2D:
3896   case Op_ConvD2F:
3897     frc.inc_float_count();
3898     frc.inc_double_count();
3899     break;
3900 
3901   // Count all double operations that may use FPU
3902   case Op_AddD:
3903   case Op_SubD:
3904   case Op_MulD:
3905   case Op_DivD:
3906   case Op_NegD:
3907   case Op_ModD:
3908   case Op_ConvI2D:
3909   case Op_ConvD2I:
3910   // case Op_ConvL2D: // handled by leaf call
3911   // case Op_ConvD2L: // handled by leaf call
3912   case Op_ConD:
3913   case Op_CmpD:
3914   case Op_CmpD3:
3915   case Op_StoreD:
3916   case Op_LoadD:
3917   case Op_LoadD_unaligned:
3918     frc.inc_double_count();
3919     break;
3920   case Op_Opaque1:              // Remove Opaque Nodes before matching
3921     n->subsume_by(n->in(1), this);
3922     break;
3923   case Op_CallLeafPure: {
3924     // If the pure call is not supported, then lower to a CallLeaf.
3925     if (!Matcher::match_rule_supported(Op_CallLeafPure)) {
3926       CallNode* call = n->as_Call();
3927       CallNode* new_call = new CallLeafNode(call->tf(), call->entry_point(),
3928                                             call->_name, TypeRawPtr::BOTTOM);
3929       new_call->init_req(TypeFunc::Control, call->in(TypeFunc::Control));
3930       new_call->init_req(TypeFunc::I_O, C->top());
3931       new_call->init_req(TypeFunc::Memory, C->top());
3932       new_call->init_req(TypeFunc::ReturnAdr, C->top());
3933       new_call->init_req(TypeFunc::FramePtr, C->top());
3934       for (unsigned int i = TypeFunc::Parms; i < call->tf()->domain_sig()->cnt(); i++) {
3935         new_call->init_req(i, call->in(i));
3936       }
3937       n->subsume_by(new_call, this);
3938     }
3939     frc.inc_call_count();
3940     break;
3941   }
3942   case Op_CallStaticJava:
3943   case Op_CallJava:
3944   case Op_CallDynamicJava:
3945     frc.inc_java_call_count(); // Count java call site;
3946   case Op_CallRuntime:
3947   case Op_CallLeaf:
3948   case Op_CallLeafVector:
3949   case Op_CallLeafNoFP: {
3950     assert (n->is_Call(), "");
3951     CallNode *call = n->as_Call();
3952     // Count call sites where the FP mode bit would have to be flipped.
3953     // Do not count uncommon runtime calls:
3954     // uncommon_trap, _complete_monitor_locking, _complete_monitor_unlocking,
3955     // _new_Java, _new_typeArray, _new_objArray, _rethrow_Java, ...
3956     if (!call->is_CallStaticJava() || !call->as_CallStaticJava()->_name) {
3957       frc.inc_call_count();   // Count the call site
3958     } else {                  // See if uncommon argument is shared
3959       Node *n = call->in(TypeFunc::Parms);
3960       int nop = n->Opcode();
3961       // Clone shared simple arguments to uncommon calls, item (1).
3962       if (n->outcnt() > 1 &&
3963           !n->is_Proj() &&
3964           nop != Op_CreateEx &&
3965           nop != Op_CheckCastPP &&
3966           nop != Op_DecodeN &&
3967           nop != Op_DecodeNKlass &&
3968           !n->is_Mem() &&
3969           !n->is_Phi()) {
3970         Node *x = n->clone();
3971         call->set_req(TypeFunc::Parms, x);
3972       }
3973     }
3974     break;
3975   }
3976   case Op_StoreB:
3977   case Op_StoreC:
3978   case Op_StoreI:
3979   case Op_StoreL:
3980   case Op_StoreLSpecial:
3981   case Op_CompareAndSwapB:
3982   case Op_CompareAndSwapS:
3983   case Op_CompareAndSwapI:
3984   case Op_CompareAndSwapL:
3985   case Op_CompareAndSwapP:
3986   case Op_CompareAndSwapN:
3987   case Op_WeakCompareAndSwapB:
3988   case Op_WeakCompareAndSwapS:
3989   case Op_WeakCompareAndSwapI:
3990   case Op_WeakCompareAndSwapL:
3991   case Op_WeakCompareAndSwapP:
3992   case Op_WeakCompareAndSwapN:
3993   case Op_CompareAndExchangeB:
3994   case Op_CompareAndExchangeS:
3995   case Op_CompareAndExchangeI:
3996   case Op_CompareAndExchangeL:
3997   case Op_CompareAndExchangeP:
3998   case Op_CompareAndExchangeN:
3999   case Op_GetAndAddS:
4000   case Op_GetAndAddB:
4001   case Op_GetAndAddI:
4002   case Op_GetAndAddL:
4003   case Op_GetAndSetS:
4004   case Op_GetAndSetB:
4005   case Op_GetAndSetI:
4006   case Op_GetAndSetL:
4007   case Op_GetAndSetP:
4008   case Op_GetAndSetN:
4009   case Op_StoreP:
4010   case Op_StoreN:
4011   case Op_StoreNKlass:
4012   case Op_LoadB:
4013   case Op_LoadUB:
4014   case Op_LoadUS:
4015   case Op_LoadI:
4016   case Op_LoadKlass:
4017   case Op_LoadNKlass:
4018   case Op_LoadL:
4019   case Op_LoadL_unaligned:
4020   case Op_LoadP:
4021   case Op_LoadN:
4022   case Op_LoadRange:
4023   case Op_LoadS:
4024     break;
4025 
4026   case Op_AddP: {               // Assert sane base pointers
4027     Node *addp = n->in(AddPNode::Address);
4028     assert(n->as_AddP()->address_input_has_same_base(), "Base pointers must match (addp %u)", addp->_idx );
4029 #ifdef _LP64
4030     if ((UseCompressedOops || UseCompressedClassPointers) &&
4031         addp->Opcode() == Op_ConP &&
4032         addp == n->in(AddPNode::Base) &&
4033         n->in(AddPNode::Offset)->is_Con()) {
4034       // If the transformation of ConP to ConN+DecodeN is beneficial depends
4035       // on the platform and on the compressed oops mode.
4036       // Use addressing with narrow klass to load with offset on x86.
4037       // Some platforms can use the constant pool to load ConP.
4038       // Do this transformation here since IGVN will convert ConN back to ConP.
4039       const Type* t = addp->bottom_type();
4040       bool is_oop   = t->isa_oopptr() != nullptr;
4041       bool is_klass = t->isa_klassptr() != nullptr;
4042 
4043       if ((is_oop   && UseCompressedOops          && Matcher::const_oop_prefer_decode()  ) ||
4044           (is_klass && UseCompressedClassPointers && Matcher::const_klass_prefer_decode() &&
4045            t->isa_klassptr()->exact_klass()->is_in_encoding_range())) {
4046         Node* nn = nullptr;
4047 
4048         int op = is_oop ? Op_ConN : Op_ConNKlass;
4049 
4050         // Look for existing ConN node of the same exact type.
4051         Node* r  = root();
4052         uint cnt = r->outcnt();
4053         for (uint i = 0; i < cnt; i++) {
4054           Node* m = r->raw_out(i);
4055           if (m!= nullptr && m->Opcode() == op &&
4056               m->bottom_type()->make_ptr() == t) {
4057             nn = m;
4058             break;
4059           }
4060         }
4061         if (nn != nullptr) {
4062           // Decode a narrow oop to match address
4063           // [R12 + narrow_oop_reg<<3 + offset]
4064           if (is_oop) {
4065             nn = new DecodeNNode(nn, t);
4066           } else {
4067             nn = new DecodeNKlassNode(nn, t);
4068           }
4069           // Check for succeeding AddP which uses the same Base.
4070           // Otherwise we will run into the assertion above when visiting that guy.
4071           for (uint i = 0; i < n->outcnt(); ++i) {
4072             Node *out_i = n->raw_out(i);
4073             if (out_i && out_i->is_AddP() && out_i->in(AddPNode::Base) == addp) {
4074               out_i->set_req(AddPNode::Base, nn);
4075 #ifdef ASSERT
4076               for (uint j = 0; j < out_i->outcnt(); ++j) {
4077                 Node *out_j = out_i->raw_out(j);
4078                 assert(out_j == nullptr || !out_j->is_AddP() || out_j->in(AddPNode::Base) != addp,
4079                        "more than 2 AddP nodes in a chain (out_j %u)", out_j->_idx);
4080               }
4081 #endif
4082             }
4083           }
4084           n->set_req(AddPNode::Base, nn);
4085           n->set_req(AddPNode::Address, nn);
4086           if (addp->outcnt() == 0) {
4087             addp->disconnect_inputs(this);
4088           }
4089         }
4090       }
4091     }
4092 #endif
4093     break;
4094   }
4095 
4096   case Op_CastPP: {
4097     // Remove CastPP nodes to gain more freedom during scheduling but
4098     // keep the dependency they encode as control or precedence edges
4099     // (if control is set already) on memory operations. Some CastPP
4100     // nodes don't have a control (don't carry a dependency): skip
4101     // those.
4102     if (n->in(0) != nullptr) {
4103       ResourceMark rm;
4104       Unique_Node_List wq;
4105       wq.push(n);
4106       for (uint next = 0; next < wq.size(); ++next) {
4107         Node *m = wq.at(next);
4108         for (DUIterator_Fast imax, i = m->fast_outs(imax); i < imax; i++) {
4109           Node* use = m->fast_out(i);
4110           if (use->is_Mem() || use->is_EncodeNarrowPtr()) {
4111             use->ensure_control_or_add_prec(n->in(0));
4112           } else {
4113             switch(use->Opcode()) {
4114             case Op_AddP:
4115             case Op_DecodeN:
4116             case Op_DecodeNKlass:
4117             case Op_CheckCastPP:
4118             case Op_CastPP:
4119               wq.push(use);
4120               break;
4121             }
4122           }
4123         }
4124       }
4125     }
4126     const bool is_LP64 = LP64_ONLY(true) NOT_LP64(false);
4127     if (is_LP64 && n->in(1)->is_DecodeN() && Matcher::gen_narrow_oop_implicit_null_checks()) {
4128       Node* in1 = n->in(1);
4129       const Type* t = n->bottom_type();
4130       Node* new_in1 = in1->clone();
4131       new_in1->as_DecodeN()->set_type(t);
4132 
4133       if (!Matcher::narrow_oop_use_complex_address()) {
4134         //
4135         // x86, ARM and friends can handle 2 adds in addressing mode
4136         // and Matcher can fold a DecodeN node into address by using
4137         // a narrow oop directly and do implicit null check in address:
4138         //
4139         // [R12 + narrow_oop_reg<<3 + offset]
4140         // NullCheck narrow_oop_reg
4141         //
4142         // On other platforms (Sparc) we have to keep new DecodeN node and
4143         // use it to do implicit null check in address:
4144         //
4145         // decode_not_null narrow_oop_reg, base_reg
4146         // [base_reg + offset]
4147         // NullCheck base_reg
4148         //
4149         // Pin the new DecodeN node to non-null path on these platform (Sparc)
4150         // to keep the information to which null check the new DecodeN node
4151         // corresponds to use it as value in implicit_null_check().
4152         //
4153         new_in1->set_req(0, n->in(0));
4154       }
4155 
4156       n->subsume_by(new_in1, this);
4157       if (in1->outcnt() == 0) {
4158         in1->disconnect_inputs(this);
4159       }
4160     } else {
4161       n->subsume_by(n->in(1), this);
4162       if (n->outcnt() == 0) {
4163         n->disconnect_inputs(this);
4164       }
4165     }
4166     break;
4167   }
4168   case Op_CastII: {
4169     n->as_CastII()->remove_range_check_cast(this);
4170     break;
4171   }
4172 #ifdef _LP64
4173   case Op_CmpP:
4174     // Do this transformation here to preserve CmpPNode::sub() and
4175     // other TypePtr related Ideal optimizations (for example, ptr nullness).
4176     if (n->in(1)->is_DecodeNarrowPtr() || n->in(2)->is_DecodeNarrowPtr()) {
4177       Node* in1 = n->in(1);
4178       Node* in2 = n->in(2);
4179       if (!in1->is_DecodeNarrowPtr()) {
4180         in2 = in1;
4181         in1 = n->in(2);
4182       }
4183       assert(in1->is_DecodeNarrowPtr(), "sanity");
4184 
4185       Node* new_in2 = nullptr;
4186       if (in2->is_DecodeNarrowPtr()) {
4187         assert(in2->Opcode() == in1->Opcode(), "must be same node type");
4188         new_in2 = in2->in(1);
4189       } else if (in2->Opcode() == Op_ConP) {
4190         const Type* t = in2->bottom_type();
4191         if (t == TypePtr::NULL_PTR) {
4192           assert(in1->is_DecodeN(), "compare klass to null?");
4193           // Don't convert CmpP null check into CmpN if compressed
4194           // oops implicit null check is not generated.
4195           // This will allow to generate normal oop implicit null check.
4196           if (Matcher::gen_narrow_oop_implicit_null_checks())
4197             new_in2 = ConNode::make(TypeNarrowOop::NULL_PTR);
4198           //
4199           // This transformation together with CastPP transformation above
4200           // will generated code for implicit null checks for compressed oops.
4201           //
4202           // The original code after Optimize()
4203           //
4204           //    LoadN memory, narrow_oop_reg
4205           //    decode narrow_oop_reg, base_reg
4206           //    CmpP base_reg, nullptr
4207           //    CastPP base_reg // NotNull
4208           //    Load [base_reg + offset], val_reg
4209           //
4210           // after these transformations will be
4211           //
4212           //    LoadN memory, narrow_oop_reg
4213           //    CmpN narrow_oop_reg, nullptr
4214           //    decode_not_null narrow_oop_reg, base_reg
4215           //    Load [base_reg + offset], val_reg
4216           //
4217           // and the uncommon path (== nullptr) will use narrow_oop_reg directly
4218           // since narrow oops can be used in debug info now (see the code in
4219           // final_graph_reshaping_walk()).
4220           //
4221           // At the end the code will be matched to
4222           // on x86:
4223           //
4224           //    Load_narrow_oop memory, narrow_oop_reg
4225           //    Load [R12 + narrow_oop_reg<<3 + offset], val_reg
4226           //    NullCheck narrow_oop_reg
4227           //
4228           // and on sparc:
4229           //
4230           //    Load_narrow_oop memory, narrow_oop_reg
4231           //    decode_not_null narrow_oop_reg, base_reg
4232           //    Load [base_reg + offset], val_reg
4233           //    NullCheck base_reg
4234           //
4235         } else if (t->isa_oopptr()) {
4236           new_in2 = ConNode::make(t->make_narrowoop());
4237         } else if (t->isa_klassptr()) {
4238           ciKlass* klass = t->is_klassptr()->exact_klass();
4239           if (klass->is_in_encoding_range()) {
4240             new_in2 = ConNode::make(t->make_narrowklass());
4241           }
4242         }
4243       }
4244       if (new_in2 != nullptr) {
4245         Node* cmpN = new CmpNNode(in1->in(1), new_in2);
4246         n->subsume_by(cmpN, this);
4247         if (in1->outcnt() == 0) {
4248           in1->disconnect_inputs(this);
4249         }
4250         if (in2->outcnt() == 0) {
4251           in2->disconnect_inputs(this);
4252         }
4253       }
4254     }
4255     break;
4256 
4257   case Op_DecodeN:
4258   case Op_DecodeNKlass:
4259     assert(!n->in(1)->is_EncodeNarrowPtr(), "should be optimized out");
4260     // DecodeN could be pinned when it can't be fold into
4261     // an address expression, see the code for Op_CastPP above.
4262     assert(n->in(0) == nullptr || (UseCompressedOops && !Matcher::narrow_oop_use_complex_address()), "no control");
4263     break;
4264 
4265   case Op_EncodeP:
4266   case Op_EncodePKlass: {
4267     Node* in1 = n->in(1);
4268     if (in1->is_DecodeNarrowPtr()) {
4269       n->subsume_by(in1->in(1), this);
4270     } else if (in1->Opcode() == Op_ConP) {
4271       const Type* t = in1->bottom_type();
4272       if (t == TypePtr::NULL_PTR) {
4273         assert(t->isa_oopptr(), "null klass?");
4274         n->subsume_by(ConNode::make(TypeNarrowOop::NULL_PTR), this);
4275       } else if (t->isa_oopptr()) {
4276         n->subsume_by(ConNode::make(t->make_narrowoop()), this);
4277       } else if (t->isa_klassptr()) {
4278         ciKlass* klass = t->is_klassptr()->exact_klass();
4279         if (klass->is_in_encoding_range()) {
4280           n->subsume_by(ConNode::make(t->make_narrowklass()), this);
4281         } else {
4282           assert(false, "unencodable klass in ConP -> EncodeP");
4283           C->record_failure("unencodable klass in ConP -> EncodeP");
4284         }
4285       }
4286     }
4287     if (in1->outcnt() == 0) {
4288       in1->disconnect_inputs(this);
4289     }
4290     break;
4291   }
4292 
4293   case Op_Proj: {
4294     if (OptimizeStringConcat || IncrementalInline) {
4295       ProjNode* proj = n->as_Proj();
4296       if (proj->_is_io_use) {
4297         assert(proj->_con == TypeFunc::I_O || proj->_con == TypeFunc::Memory, "");
4298         // Separate projections were used for the exception path which
4299         // are normally removed by a late inline.  If it wasn't inlined
4300         // then they will hang around and should just be replaced with
4301         // the original one. Merge them.
4302         Node* non_io_proj = proj->in(0)->as_Multi()->proj_out_or_null(proj->_con, false /*is_io_use*/);
4303         if (non_io_proj  != nullptr) {
4304           proj->subsume_by(non_io_proj , this);
4305         }
4306       }
4307     }
4308     break;
4309   }
4310 
4311   case Op_Phi:
4312     if (n->as_Phi()->bottom_type()->isa_narrowoop() || n->as_Phi()->bottom_type()->isa_narrowklass()) {
4313       // The EncodeP optimization may create Phi with the same edges
4314       // for all paths. It is not handled well by Register Allocator.
4315       Node* unique_in = n->in(1);
4316       assert(unique_in != nullptr, "");
4317       uint cnt = n->req();
4318       for (uint i = 2; i < cnt; i++) {
4319         Node* m = n->in(i);
4320         assert(m != nullptr, "");
4321         if (unique_in != m)
4322           unique_in = nullptr;
4323       }
4324       if (unique_in != nullptr) {
4325         n->subsume_by(unique_in, this);
4326       }
4327     }
4328     break;
4329 
4330 #endif
4331 
4332   case Op_ModI:
4333     handle_div_mod_op(n, T_INT, false);
4334     break;
4335 
4336   case Op_ModL:
4337     handle_div_mod_op(n, T_LONG, false);
4338     break;
4339 
4340   case Op_UModI:
4341     handle_div_mod_op(n, T_INT, true);
4342     break;
4343 
4344   case Op_UModL:
4345     handle_div_mod_op(n, T_LONG, true);
4346     break;
4347 
4348   case Op_LoadVector:
4349   case Op_StoreVector:
4350 #ifdef ASSERT
4351     // Add VerifyVectorAlignment node between adr and load / store.
4352     if (VerifyAlignVector && Matcher::has_match_rule(Op_VerifyVectorAlignment)) {
4353       bool must_verify_alignment = n->is_LoadVector() ? n->as_LoadVector()->must_verify_alignment() :
4354                                                         n->as_StoreVector()->must_verify_alignment();
4355       if (must_verify_alignment) {
4356         jlong vector_width = n->is_LoadVector() ? n->as_LoadVector()->memory_size() :
4357                                                   n->as_StoreVector()->memory_size();
4358         // The memory access should be aligned to the vector width in bytes.
4359         // However, the underlying array is possibly less well aligned, but at least
4360         // to ObjectAlignmentInBytes. Hence, even if multiple arrays are accessed in
4361         // a loop we can expect at least the following alignment:
4362         jlong guaranteed_alignment = MIN2(vector_width, (jlong)ObjectAlignmentInBytes);
4363         assert(2 <= guaranteed_alignment && guaranteed_alignment <= 64, "alignment must be in range");
4364         assert(is_power_of_2(guaranteed_alignment), "alignment must be power of 2");
4365         // Create mask from alignment. e.g. 0b1000 -> 0b0111
4366         jlong mask = guaranteed_alignment - 1;
4367         Node* mask_con = ConLNode::make(mask);
4368         VerifyVectorAlignmentNode* va = new VerifyVectorAlignmentNode(n->in(MemNode::Address), mask_con);
4369         n->set_req(MemNode::Address, va);
4370       }
4371     }
4372 #endif
4373     break;
4374 
4375   case Op_LoadVectorGather:
4376   case Op_StoreVectorScatter:
4377   case Op_LoadVectorGatherMasked:
4378   case Op_StoreVectorScatterMasked:
4379   case Op_VectorCmpMasked:
4380   case Op_VectorMaskGen:
4381   case Op_LoadVectorMasked:
4382   case Op_StoreVectorMasked:
4383     break;
4384 
4385   case Op_AddReductionVI:
4386   case Op_AddReductionVL:
4387   case Op_AddReductionVF:
4388   case Op_AddReductionVD:
4389   case Op_MulReductionVI:
4390   case Op_MulReductionVL:
4391   case Op_MulReductionVF:
4392   case Op_MulReductionVD:
4393   case Op_MinReductionV:
4394   case Op_MaxReductionV:
4395   case Op_AndReductionV:
4396   case Op_OrReductionV:
4397   case Op_XorReductionV:
4398     break;
4399 
4400   case Op_PackB:
4401   case Op_PackS:
4402   case Op_PackI:
4403   case Op_PackF:
4404   case Op_PackL:
4405   case Op_PackD:
4406     if (n->req()-1 > 2) {
4407       // Replace many operand PackNodes with a binary tree for matching
4408       PackNode* p = (PackNode*) n;
4409       Node* btp = p->binary_tree_pack(1, n->req());
4410       n->subsume_by(btp, this);
4411     }
4412     break;
4413   case Op_Loop:
4414     assert(!n->as_Loop()->is_loop_nest_inner_loop() || _loop_opts_cnt == 0, "should have been turned into a counted loop");
4415   case Op_CountedLoop:
4416   case Op_LongCountedLoop:
4417   case Op_OuterStripMinedLoop:
4418     if (n->as_Loop()->is_inner_loop()) {
4419       frc.inc_inner_loop_count();
4420     }
4421     n->as_Loop()->verify_strip_mined(0);
4422     break;
4423   case Op_LShiftI:
4424   case Op_RShiftI:
4425   case Op_URShiftI:
4426   case Op_LShiftL:
4427   case Op_RShiftL:
4428   case Op_URShiftL:
4429     if (Matcher::need_masked_shift_count) {
4430       // The cpu's shift instructions don't restrict the count to the
4431       // lower 5/6 bits. We need to do the masking ourselves.
4432       Node* in2 = n->in(2);
4433       juint mask = (n->bottom_type() == TypeInt::INT) ? (BitsPerInt - 1) : (BitsPerLong - 1);
4434       const TypeInt* t = in2->find_int_type();
4435       if (t != nullptr && t->is_con()) {
4436         juint shift = t->get_con();
4437         if (shift > mask) { // Unsigned cmp
4438           n->set_req(2, ConNode::make(TypeInt::make(shift & mask)));
4439         }
4440       } else {
4441         if (t == nullptr || t->_lo < 0 || t->_hi > (int)mask) {
4442           Node* shift = new AndINode(in2, ConNode::make(TypeInt::make(mask)));
4443           n->set_req(2, shift);
4444         }
4445       }
4446       if (in2->outcnt() == 0) { // Remove dead node
4447         in2->disconnect_inputs(this);
4448       }
4449     }
4450     break;
4451   case Op_MemBarStoreStore:
4452   case Op_MemBarRelease:
4453     // Break the link with AllocateNode: it is no longer useful and
4454     // confuses register allocation.
4455     if (n->req() > MemBarNode::Precedent) {
4456       n->set_req(MemBarNode::Precedent, top());
4457     }
4458     break;
4459   case Op_MemBarAcquire: {
4460     if (n->as_MemBar()->trailing_load() && n->req() > MemBarNode::Precedent) {
4461       // At parse time, the trailing MemBarAcquire for a volatile load
4462       // is created with an edge to the load. After optimizations,
4463       // that input may be a chain of Phis. If those phis have no
4464       // other use, then the MemBarAcquire keeps them alive and
4465       // register allocation can be confused.
4466       dead_nodes.push(n->in(MemBarNode::Precedent));
4467       n->set_req(MemBarNode::Precedent, top());
4468     }
4469     break;
4470   }
4471   case Op_Blackhole:
4472     break;
4473   case Op_RangeCheck: {
4474     RangeCheckNode* rc = n->as_RangeCheck();
4475     Node* iff = new IfNode(rc->in(0), rc->in(1), rc->_prob, rc->_fcnt);
4476     n->subsume_by(iff, this);
4477     frc._tests.push(iff);
4478     break;
4479   }
4480   case Op_ConvI2L: {
4481     if (!Matcher::convi2l_type_required) {
4482       // Code generation on some platforms doesn't need accurate
4483       // ConvI2L types. Widening the type can help remove redundant
4484       // address computations.
4485       n->as_Type()->set_type(TypeLong::INT);
4486       ResourceMark rm;
4487       Unique_Node_List wq;
4488       wq.push(n);
4489       for (uint next = 0; next < wq.size(); next++) {
4490         Node *m = wq.at(next);
4491 
4492         for(;;) {
4493           // Loop over all nodes with identical inputs edges as m
4494           Node* k = m->find_similar(m->Opcode());
4495           if (k == nullptr) {
4496             break;
4497           }
4498           // Push their uses so we get a chance to remove node made
4499           // redundant
4500           for (DUIterator_Fast imax, i = k->fast_outs(imax); i < imax; i++) {
4501             Node* u = k->fast_out(i);
4502             if (u->Opcode() == Op_LShiftL ||
4503                 u->Opcode() == Op_AddL ||
4504                 u->Opcode() == Op_SubL ||
4505                 u->Opcode() == Op_AddP) {
4506               wq.push(u);
4507             }
4508           }
4509           // Replace all nodes with identical edges as m with m
4510           k->subsume_by(m, this);
4511         }
4512       }
4513     }
4514     break;
4515   }
4516   case Op_CmpUL: {
4517     if (!Matcher::has_match_rule(Op_CmpUL)) {
4518       // No support for unsigned long comparisons
4519       ConINode* sign_pos = new ConINode(TypeInt::make(BitsPerLong - 1));
4520       Node* sign_bit_mask = new RShiftLNode(n->in(1), sign_pos);
4521       Node* orl = new OrLNode(n->in(1), sign_bit_mask);
4522       ConLNode* remove_sign_mask = new ConLNode(TypeLong::make(max_jlong));
4523       Node* andl = new AndLNode(orl, remove_sign_mask);
4524       Node* cmp = new CmpLNode(andl, n->in(2));
4525       n->subsume_by(cmp, this);
4526     }
4527     break;
4528   }
4529 #ifdef ASSERT
4530   case Op_InlineType: {
4531     n->dump(-1);
4532     assert(false, "inline type node was not removed");
4533     break;
4534   }
4535   case Op_ConNKlass: {
4536     const TypePtr* tp = n->as_Type()->type()->make_ptr();
4537     ciKlass* klass = tp->is_klassptr()->exact_klass();
4538     assert(klass->is_in_encoding_range(), "klass cannot be compressed");
4539     break;
4540   }
4541 #endif
4542   default:
4543     assert(!n->is_Call(), "");
4544     assert(!n->is_Mem(), "");
4545     assert(nop != Op_ProfileBoolean, "should be eliminated during IGVN");
4546     break;
4547   }
4548 }
4549 
4550 //------------------------------final_graph_reshaping_walk---------------------
4551 // Replacing Opaque nodes with their input in final_graph_reshaping_impl(),
4552 // requires that the walk visits a node's inputs before visiting the node.
4553 void Compile::final_graph_reshaping_walk(Node_Stack& nstack, Node* root, Final_Reshape_Counts& frc, Unique_Node_List& dead_nodes) {
4554   Unique_Node_List sfpt;
4555 
4556   frc._visited.set(root->_idx); // first, mark node as visited
4557   uint cnt = root->req();
4558   Node *n = root;
4559   uint  i = 0;
4560   while (true) {
4561     if (i < cnt) {
4562       // Place all non-visited non-null inputs onto stack
4563       Node* m = n->in(i);
4564       ++i;
4565       if (m != nullptr && !frc._visited.test_set(m->_idx)) {
4566         if (m->is_SafePoint() && m->as_SafePoint()->jvms() != nullptr) {
4567           // compute worst case interpreter size in case of a deoptimization
4568           update_interpreter_frame_size(m->as_SafePoint()->jvms()->interpreter_frame_size());
4569 
4570           sfpt.push(m);
4571         }
4572         cnt = m->req();
4573         nstack.push(n, i); // put on stack parent and next input's index
4574         n = m;
4575         i = 0;
4576       }
4577     } else {
4578       // Now do post-visit work
4579       final_graph_reshaping_impl(n, frc, dead_nodes);
4580       if (nstack.is_empty())
4581         break;             // finished
4582       n = nstack.node();   // Get node from stack
4583       cnt = n->req();
4584       i = nstack.index();
4585       nstack.pop();        // Shift to the next node on stack
4586     }
4587   }
4588 
4589   // Skip next transformation if compressed oops are not used.
4590   if ((UseCompressedOops && !Matcher::gen_narrow_oop_implicit_null_checks()) ||
4591       (!UseCompressedOops && !UseCompressedClassPointers))
4592     return;
4593 
4594   // Go over safepoints nodes to skip DecodeN/DecodeNKlass nodes for debug edges.
4595   // It could be done for an uncommon traps or any safepoints/calls
4596   // if the DecodeN/DecodeNKlass node is referenced only in a debug info.
4597   while (sfpt.size() > 0) {
4598     n = sfpt.pop();
4599     JVMState *jvms = n->as_SafePoint()->jvms();
4600     assert(jvms != nullptr, "sanity");
4601     int start = jvms->debug_start();
4602     int end   = n->req();
4603     bool is_uncommon = (n->is_CallStaticJava() &&
4604                         n->as_CallStaticJava()->uncommon_trap_request() != 0);
4605     for (int j = start; j < end; j++) {
4606       Node* in = n->in(j);
4607       if (in->is_DecodeNarrowPtr()) {
4608         bool safe_to_skip = true;
4609         if (!is_uncommon ) {
4610           // Is it safe to skip?
4611           for (uint i = 0; i < in->outcnt(); i++) {
4612             Node* u = in->raw_out(i);
4613             if (!u->is_SafePoint() ||
4614                 (u->is_Call() && u->as_Call()->has_non_debug_use(n))) {
4615               safe_to_skip = false;
4616             }
4617           }
4618         }
4619         if (safe_to_skip) {
4620           n->set_req(j, in->in(1));
4621         }
4622         if (in->outcnt() == 0) {
4623           in->disconnect_inputs(this);
4624         }
4625       }
4626     }
4627   }
4628 }
4629 
4630 //------------------------------final_graph_reshaping--------------------------
4631 // Final Graph Reshaping.
4632 //
4633 // (1) Clone simple inputs to uncommon calls, so they can be scheduled late
4634 //     and not commoned up and forced early.  Must come after regular
4635 //     optimizations to avoid GVN undoing the cloning.  Clone constant
4636 //     inputs to Loop Phis; these will be split by the allocator anyways.
4637 //     Remove Opaque nodes.
4638 // (2) Move last-uses by commutative operations to the left input to encourage
4639 //     Intel update-in-place two-address operations and better register usage
4640 //     on RISCs.  Must come after regular optimizations to avoid GVN Ideal
4641 //     calls canonicalizing them back.
4642 // (3) Count the number of double-precision FP ops, single-precision FP ops
4643 //     and call sites.  On Intel, we can get correct rounding either by
4644 //     forcing singles to memory (requires extra stores and loads after each
4645 //     FP bytecode) or we can set a rounding mode bit (requires setting and
4646 //     clearing the mode bit around call sites).  The mode bit is only used
4647 //     if the relative frequency of single FP ops to calls is low enough.
4648 //     This is a key transform for SPEC mpeg_audio.
4649 // (4) Detect infinite loops; blobs of code reachable from above but not
4650 //     below.  Several of the Code_Gen algorithms fail on such code shapes,
4651 //     so we simply bail out.  Happens a lot in ZKM.jar, but also happens
4652 //     from time to time in other codes (such as -Xcomp finalizer loops, etc).
4653 //     Detection is by looking for IfNodes where only 1 projection is
4654 //     reachable from below or CatchNodes missing some targets.
4655 // (5) Assert for insane oop offsets in debug mode.
4656 
4657 bool Compile::final_graph_reshaping() {
4658   // an infinite loop may have been eliminated by the optimizer,
4659   // in which case the graph will be empty.
4660   if (root()->req() == 1) {
4661     // Do not compile method that is only a trivial infinite loop,
4662     // since the content of the loop may have been eliminated.
4663     record_method_not_compilable("trivial infinite loop");
4664     return true;
4665   }
4666 
4667   // Expensive nodes have their control input set to prevent the GVN
4668   // from freely commoning them. There's no GVN beyond this point so
4669   // no need to keep the control input. We want the expensive nodes to
4670   // be freely moved to the least frequent code path by gcm.
4671   assert(OptimizeExpensiveOps || expensive_count() == 0, "optimization off but list non empty?");
4672   for (int i = 0; i < expensive_count(); i++) {
4673     _expensive_nodes.at(i)->set_req(0, nullptr);
4674   }
4675 
4676   Final_Reshape_Counts frc;
4677 
4678   // Visit everybody reachable!
4679   // Allocate stack of size C->live_nodes()/2 to avoid frequent realloc
4680   Node_Stack nstack(live_nodes() >> 1);
4681   Unique_Node_List dead_nodes;
4682   final_graph_reshaping_walk(nstack, root(), frc, dead_nodes);
4683 
4684   // Check for unreachable (from below) code (i.e., infinite loops).
4685   for( uint i = 0; i < frc._tests.size(); i++ ) {
4686     MultiBranchNode *n = frc._tests[i]->as_MultiBranch();
4687     // Get number of CFG targets.
4688     // Note that PCTables include exception targets after calls.
4689     uint required_outcnt = n->required_outcnt();
4690     if (n->outcnt() != required_outcnt) {
4691       // Check for a few special cases.  Rethrow Nodes never take the
4692       // 'fall-thru' path, so expected kids is 1 less.
4693       if (n->is_PCTable() && n->in(0) && n->in(0)->in(0)) {
4694         if (n->in(0)->in(0)->is_Call()) {
4695           CallNode* call = n->in(0)->in(0)->as_Call();
4696           if (call->entry_point() == OptoRuntime::rethrow_stub()) {
4697             required_outcnt--;      // Rethrow always has 1 less kid
4698           } else if (call->req() > TypeFunc::Parms &&
4699                      call->is_CallDynamicJava()) {
4700             // Check for null receiver. In such case, the optimizer has
4701             // detected that the virtual call will always result in a null
4702             // pointer exception. The fall-through projection of this CatchNode
4703             // will not be populated.
4704             Node* arg0 = call->in(TypeFunc::Parms);
4705             if (arg0->is_Type() &&
4706                 arg0->as_Type()->type()->higher_equal(TypePtr::NULL_PTR)) {
4707               required_outcnt--;
4708             }
4709           } else if (call->entry_point() == OptoRuntime::new_array_Java() ||
4710                      call->entry_point() == OptoRuntime::new_array_nozero_Java()) {
4711             // Check for illegal array length. In such case, the optimizer has
4712             // detected that the allocation attempt will always result in an
4713             // exception. There is no fall-through projection of this CatchNode .
4714             assert(call->is_CallStaticJava(), "static call expected");
4715             assert(call->req() == call->jvms()->endoff() + 1, "missing extra input");
4716             uint valid_length_test_input = call->req() - 1;
4717             Node* valid_length_test = call->in(valid_length_test_input);
4718             call->del_req(valid_length_test_input);
4719             if (valid_length_test->find_int_con(1) == 0) {
4720               required_outcnt--;
4721             }
4722             dead_nodes.push(valid_length_test);
4723             assert(n->outcnt() == required_outcnt, "malformed control flow");
4724             continue;
4725           }
4726         }
4727       }
4728 
4729       // Recheck with a better notion of 'required_outcnt'
4730       if (n->outcnt() != required_outcnt) {
4731         record_method_not_compilable("malformed control flow");
4732         return true;            // Not all targets reachable!
4733       }
4734     } else if (n->is_PCTable() && n->in(0) && n->in(0)->in(0) && n->in(0)->in(0)->is_Call()) {
4735       CallNode* call = n->in(0)->in(0)->as_Call();
4736       if (call->entry_point() == OptoRuntime::new_array_Java() ||
4737           call->entry_point() == OptoRuntime::new_array_nozero_Java()) {
4738         assert(call->is_CallStaticJava(), "static call expected");
4739         assert(call->req() == call->jvms()->endoff() + 1, "missing extra input");
4740         uint valid_length_test_input = call->req() - 1;
4741         dead_nodes.push(call->in(valid_length_test_input));
4742         call->del_req(valid_length_test_input); // valid length test useless now
4743       }
4744     }
4745     // Check that I actually visited all kids.  Unreached kids
4746     // must be infinite loops.
4747     for (DUIterator_Fast jmax, j = n->fast_outs(jmax); j < jmax; j++)
4748       if (!frc._visited.test(n->fast_out(j)->_idx)) {
4749         record_method_not_compilable("infinite loop");
4750         return true;            // Found unvisited kid; must be unreach
4751       }
4752 
4753     // Here so verification code in final_graph_reshaping_walk()
4754     // always see an OuterStripMinedLoopEnd
4755     if (n->is_OuterStripMinedLoopEnd() || n->is_LongCountedLoopEnd()) {
4756       IfNode* init_iff = n->as_If();
4757       Node* iff = new IfNode(init_iff->in(0), init_iff->in(1), init_iff->_prob, init_iff->_fcnt);
4758       n->subsume_by(iff, this);
4759     }
4760   }
4761 
4762   while (dead_nodes.size() > 0) {
4763     Node* m = dead_nodes.pop();
4764     if (m->outcnt() == 0 && m != top()) {
4765       for (uint j = 0; j < m->req(); j++) {
4766         Node* in = m->in(j);
4767         if (in != nullptr) {
4768           dead_nodes.push(in);
4769         }
4770       }
4771       m->disconnect_inputs(this);
4772     }
4773   }
4774 
4775   set_java_calls(frc.get_java_call_count());
4776   set_inner_loops(frc.get_inner_loop_count());
4777 
4778   // No infinite loops, no reason to bail out.
4779   return false;
4780 }
4781 
4782 //-----------------------------too_many_traps----------------------------------
4783 // Report if there are too many traps at the current method and bci.
4784 // Return true if there was a trap, and/or PerMethodTrapLimit is exceeded.
4785 bool Compile::too_many_traps(ciMethod* method,
4786                              int bci,
4787                              Deoptimization::DeoptReason reason) {
4788   ciMethodData* md = method->method_data();
4789   if (md->is_empty()) {
4790     // Assume the trap has not occurred, or that it occurred only
4791     // because of a transient condition during start-up in the interpreter.
4792     return false;
4793   }
4794   ciMethod* m = Deoptimization::reason_is_speculate(reason) ? this->method() : nullptr;
4795   if (md->has_trap_at(bci, m, reason) != 0) {
4796     // Assume PerBytecodeTrapLimit==0, for a more conservative heuristic.
4797     // Also, if there are multiple reasons, or if there is no per-BCI record,
4798     // assume the worst.
4799     if (log())
4800       log()->elem("observe trap='%s' count='%d'",
4801                   Deoptimization::trap_reason_name(reason),
4802                   md->trap_count(reason));
4803     return true;
4804   } else {
4805     // Ignore method/bci and see if there have been too many globally.
4806     return too_many_traps(reason, md);
4807   }
4808 }
4809 
4810 // Less-accurate variant which does not require a method and bci.
4811 bool Compile::too_many_traps(Deoptimization::DeoptReason reason,
4812                              ciMethodData* logmd) {
4813   if (trap_count(reason) >= Deoptimization::per_method_trap_limit(reason)) {
4814     // Too many traps globally.
4815     // Note that we use cumulative trap_count, not just md->trap_count.
4816     if (log()) {
4817       int mcount = (logmd == nullptr)? -1: (int)logmd->trap_count(reason);
4818       log()->elem("observe trap='%s' count='0' mcount='%d' ccount='%d'",
4819                   Deoptimization::trap_reason_name(reason),
4820                   mcount, trap_count(reason));
4821     }
4822     return true;
4823   } else {
4824     // The coast is clear.
4825     return false;
4826   }
4827 }
4828 
4829 //--------------------------too_many_recompiles--------------------------------
4830 // Report if there are too many recompiles at the current method and bci.
4831 // Consults PerBytecodeRecompilationCutoff and PerMethodRecompilationCutoff.
4832 // Is not eager to return true, since this will cause the compiler to use
4833 // Action_none for a trap point, to avoid too many recompilations.
4834 bool Compile::too_many_recompiles(ciMethod* method,
4835                                   int bci,
4836                                   Deoptimization::DeoptReason reason) {
4837   ciMethodData* md = method->method_data();
4838   if (md->is_empty()) {
4839     // Assume the trap has not occurred, or that it occurred only
4840     // because of a transient condition during start-up in the interpreter.
4841     return false;
4842   }
4843   // Pick a cutoff point well within PerBytecodeRecompilationCutoff.
4844   uint bc_cutoff = (uint) PerBytecodeRecompilationCutoff / 8;
4845   uint m_cutoff  = (uint) PerMethodRecompilationCutoff / 2 + 1;  // not zero
4846   Deoptimization::DeoptReason per_bc_reason
4847     = Deoptimization::reason_recorded_per_bytecode_if_any(reason);
4848   ciMethod* m = Deoptimization::reason_is_speculate(reason) ? this->method() : nullptr;
4849   if ((per_bc_reason == Deoptimization::Reason_none
4850        || md->has_trap_at(bci, m, reason) != 0)
4851       // The trap frequency measure we care about is the recompile count:
4852       && md->trap_recompiled_at(bci, m)
4853       && md->overflow_recompile_count() >= bc_cutoff) {
4854     // Do not emit a trap here if it has already caused recompilations.
4855     // Also, if there are multiple reasons, or if there is no per-BCI record,
4856     // assume the worst.
4857     if (log())
4858       log()->elem("observe trap='%s recompiled' count='%d' recompiles2='%d'",
4859                   Deoptimization::trap_reason_name(reason),
4860                   md->trap_count(reason),
4861                   md->overflow_recompile_count());
4862     return true;
4863   } else if (trap_count(reason) != 0
4864              && decompile_count() >= m_cutoff) {
4865     // Too many recompiles globally, and we have seen this sort of trap.
4866     // Use cumulative decompile_count, not just md->decompile_count.
4867     if (log())
4868       log()->elem("observe trap='%s' count='%d' mcount='%d' decompiles='%d' mdecompiles='%d'",
4869                   Deoptimization::trap_reason_name(reason),
4870                   md->trap_count(reason), trap_count(reason),
4871                   md->decompile_count(), decompile_count());
4872     return true;
4873   } else {
4874     // The coast is clear.
4875     return false;
4876   }
4877 }
4878 
4879 // Compute when not to trap. Used by matching trap based nodes and
4880 // NullCheck optimization.
4881 void Compile::set_allowed_deopt_reasons() {
4882   _allowed_reasons = 0;
4883   if (is_method_compilation()) {
4884     for (int rs = (int)Deoptimization::Reason_none+1; rs < Compile::trapHistLength; rs++) {
4885       assert(rs < BitsPerInt, "recode bit map");
4886       if (!too_many_traps((Deoptimization::DeoptReason) rs)) {
4887         _allowed_reasons |= nth_bit(rs);
4888       }
4889     }
4890   }
4891 }
4892 
4893 bool Compile::needs_clinit_barrier(ciMethod* method, ciMethod* accessing_method) {
4894   return method->is_static() && needs_clinit_barrier(method->holder(), accessing_method);
4895 }
4896 
4897 bool Compile::needs_clinit_barrier(ciField* field, ciMethod* accessing_method) {
4898   return field->is_static() && needs_clinit_barrier(field->holder(), accessing_method);
4899 }
4900 
4901 bool Compile::needs_clinit_barrier(ciInstanceKlass* holder, ciMethod* accessing_method) {
4902   if (holder->is_initialized()) {
4903     return false;
4904   }
4905   if (holder->is_being_initialized()) {
4906     if (accessing_method->holder() == holder) {
4907       // Access inside a class. The barrier can be elided when access happens in <clinit>,
4908       // <init>, or a static method. In all those cases, there was an initialization
4909       // barrier on the holder klass passed.
4910       if (accessing_method->is_class_initializer() ||
4911           accessing_method->is_object_constructor() ||
4912           accessing_method->is_static()) {
4913         return false;
4914       }
4915     } else if (accessing_method->holder()->is_subclass_of(holder)) {
4916       // Access from a subclass. The barrier can be elided only when access happens in <clinit>.
4917       // In case of <init> or a static method, the barrier is on the subclass is not enough:
4918       // child class can become fully initialized while its parent class is still being initialized.
4919       if (accessing_method->is_class_initializer()) {
4920         return false;
4921       }
4922     }
4923     ciMethod* root = method(); // the root method of compilation
4924     if (root != accessing_method) {
4925       return needs_clinit_barrier(holder, root); // check access in the context of compilation root
4926     }
4927   }
4928   return true;
4929 }
4930 
4931 #ifndef PRODUCT
4932 //------------------------------verify_bidirectional_edges---------------------
4933 // For each input edge to a node (ie - for each Use-Def edge), verify that
4934 // there is a corresponding Def-Use edge.
4935 void Compile::verify_bidirectional_edges(Unique_Node_List& visited, const Unique_Node_List* root_and_safepoints) const {
4936   // Allocate stack of size C->live_nodes()/16 to avoid frequent realloc
4937   uint stack_size = live_nodes() >> 4;
4938   Node_List nstack(MAX2(stack_size, (uint) OptoNodeListSize));
4939   if (root_and_safepoints != nullptr) {
4940     assert(root_and_safepoints->member(_root), "root is not in root_and_safepoints");
4941     for (uint i = 0, limit = root_and_safepoints->size(); i < limit; i++) {
4942       Node* root_or_safepoint = root_and_safepoints->at(i);
4943       // If the node is a safepoint, let's check if it still has a control input
4944       // Lack of control input signifies that this node was killed by CCP or
4945       // recursively by remove_globally_dead_node and it shouldn't be a starting
4946       // point.
4947       if (!root_or_safepoint->is_SafePoint() || root_or_safepoint->in(0) != nullptr) {
4948         nstack.push(root_or_safepoint);
4949       }
4950     }
4951   } else {
4952     nstack.push(_root);
4953   }
4954 
4955   while (nstack.size() > 0) {
4956     Node* n = nstack.pop();
4957     if (visited.member(n)) {
4958       continue;
4959     }
4960     visited.push(n);
4961 
4962     // Walk over all input edges, checking for correspondence
4963     uint length = n->len();
4964     for (uint i = 0; i < length; i++) {
4965       Node* in = n->in(i);
4966       if (in != nullptr && !visited.member(in)) {
4967         nstack.push(in); // Put it on stack
4968       }
4969       if (in != nullptr && !in->is_top()) {
4970         // Count instances of `next`
4971         int cnt = 0;
4972         for (uint idx = 0; idx < in->_outcnt; idx++) {
4973           if (in->_out[idx] == n) {
4974             cnt++;
4975           }
4976         }
4977         assert(cnt > 0, "Failed to find Def-Use edge.");
4978         // Check for duplicate edges
4979         // walk the input array downcounting the input edges to n
4980         for (uint j = 0; j < length; j++) {
4981           if (n->in(j) == in) {
4982             cnt--;
4983           }
4984         }
4985         assert(cnt == 0, "Mismatched edge count.");
4986       } else if (in == nullptr) {
4987         assert(i == 0 || i >= n->req() ||
4988                n->is_Region() || n->is_Phi() || n->is_ArrayCopy() ||
4989                (n->is_Allocate() && i >= AllocateNode::InlineType) ||
4990                (n->is_Unlock() && i == (n->req() - 1)) ||
4991                (n->is_MemBar() && i == 5), // the precedence edge to a membar can be removed during macro node expansion
4992               "only region, phi, arraycopy, allocate, unlock or membar nodes have null data edges");
4993       } else {
4994         assert(in->is_top(), "sanity");
4995         // Nothing to check.
4996       }
4997     }
4998   }
4999 }
5000 
5001 //------------------------------verify_graph_edges---------------------------
5002 // Walk the Graph and verify that there is a one-to-one correspondence
5003 // between Use-Def edges and Def-Use edges in the graph.
5004 void Compile::verify_graph_edges(bool no_dead_code, const Unique_Node_List* root_and_safepoints) const {
5005   if (VerifyGraphEdges) {
5006     Unique_Node_List visited;
5007 
5008     // Call graph walk to check edges
5009     verify_bidirectional_edges(visited, root_and_safepoints);
5010     if (no_dead_code) {
5011       // Now make sure that no visited node is used by an unvisited node.
5012       bool dead_nodes = false;
5013       Unique_Node_List checked;
5014       while (visited.size() > 0) {
5015         Node* n = visited.pop();
5016         checked.push(n);
5017         for (uint i = 0; i < n->outcnt(); i++) {
5018           Node* use = n->raw_out(i);
5019           if (checked.member(use))  continue;  // already checked
5020           if (visited.member(use))  continue;  // already in the graph
5021           if (use->is_Con())        continue;  // a dead ConNode is OK
5022           // At this point, we have found a dead node which is DU-reachable.
5023           if (!dead_nodes) {
5024             tty->print_cr("*** Dead nodes reachable via DU edges:");
5025             dead_nodes = true;
5026           }
5027           use->dump(2);
5028           tty->print_cr("---");
5029           checked.push(use);  // No repeats; pretend it is now checked.
5030         }
5031       }
5032       assert(!dead_nodes, "using nodes must be reachable from root");
5033     }
5034   }
5035 }
5036 #endif
5037 
5038 // The Compile object keeps track of failure reasons separately from the ciEnv.
5039 // This is required because there is not quite a 1-1 relation between the
5040 // ciEnv and its compilation task and the Compile object.  Note that one
5041 // ciEnv might use two Compile objects, if C2Compiler::compile_method decides
5042 // to backtrack and retry without subsuming loads.  Other than this backtracking
5043 // behavior, the Compile's failure reason is quietly copied up to the ciEnv
5044 // by the logic in C2Compiler.
5045 void Compile::record_failure(const char* reason DEBUG_ONLY(COMMA bool allow_multiple_failures)) {
5046   if (log() != nullptr) {
5047     log()->elem("failure reason='%s' phase='compile'", reason);
5048   }
5049   if (_failure_reason.get() == nullptr) {
5050     // Record the first failure reason.
5051     _failure_reason.set(reason);
5052     if (CaptureBailoutInformation) {
5053       _first_failure_details = new CompilationFailureInfo(reason);
5054     }
5055   } else {
5056     assert(!StressBailout || allow_multiple_failures, "should have handled previous failure.");
5057   }
5058 
5059   if (!C->failure_reason_is(C2Compiler::retry_no_subsuming_loads())) {
5060     C->print_method(PHASE_FAILURE, 1);
5061   }
5062   _root = nullptr;  // flush the graph, too
5063 }
5064 
5065 Compile::TracePhase::TracePhase(const char* name, PhaseTraceId id)
5066   : TraceTime(name, &Phase::timers[id], CITime, CITimeVerbose),
5067     _compile(Compile::current()),
5068     _log(nullptr),
5069     _dolog(CITimeVerbose)
5070 {
5071   assert(_compile != nullptr, "sanity check");
5072   assert(id != PhaseTraceId::_t_none, "Don't use none");
5073   if (_dolog) {
5074     _log = _compile->log();
5075   }
5076   if (_log != nullptr) {
5077     _log->begin_head("phase name='%s' nodes='%d' live='%d'", phase_name(), _compile->unique(), _compile->live_nodes());
5078     _log->stamp();
5079     _log->end_head();
5080   }
5081 
5082   // Inform memory statistic, if enabled
5083   if (CompilationMemoryStatistic::enabled()) {
5084     CompilationMemoryStatistic::on_phase_start((int)id, name);
5085   }
5086 }
5087 
5088 Compile::TracePhase::TracePhase(PhaseTraceId id)
5089   : TracePhase(Phase::get_phase_trace_id_text(id), id) {}
5090 
5091 Compile::TracePhase::~TracePhase() {
5092 
5093   // Inform memory statistic, if enabled
5094   if (CompilationMemoryStatistic::enabled()) {
5095     CompilationMemoryStatistic::on_phase_end();
5096   }
5097 
5098   if (_compile->failing_internal()) {
5099     if (_log != nullptr) {
5100       _log->done("phase");
5101     }
5102     return; // timing code, not stressing bailouts.
5103   }
5104 #ifdef ASSERT
5105   if (PrintIdealNodeCount) {
5106     tty->print_cr("phase name='%s' nodes='%d' live='%d' live_graph_walk='%d'",
5107                   phase_name(), _compile->unique(), _compile->live_nodes(), _compile->count_live_nodes_by_graph_walk());
5108   }
5109 
5110   if (VerifyIdealNodeCount) {
5111     _compile->print_missing_nodes();
5112   }
5113 #endif
5114 
5115   if (_log != nullptr) {
5116     _log->done("phase name='%s' nodes='%d' live='%d'", phase_name(), _compile->unique(), _compile->live_nodes());
5117   }
5118 }
5119 
5120 //----------------------------static_subtype_check-----------------------------
5121 // Shortcut important common cases when superklass is exact:
5122 // (0) superklass is java.lang.Object (can occur in reflective code)
5123 // (1) subklass is already limited to a subtype of superklass => always ok
5124 // (2) subklass does not overlap with superklass => always fail
5125 // (3) superklass has NO subtypes and we can check with a simple compare.
5126 Compile::SubTypeCheckResult Compile::static_subtype_check(const TypeKlassPtr* superk, const TypeKlassPtr* subk, bool skip) {
5127   if (skip) {
5128     return SSC_full_test;       // Let caller generate the general case.
5129   }
5130 
5131   if (subk->is_java_subtype_of(superk)) {
5132     return SSC_always_true; // (0) and (1)  this test cannot fail
5133   }
5134 
5135   if (!subk->maybe_java_subtype_of(superk)) {
5136     return SSC_always_false; // (2) true path dead; no dynamic test needed
5137   }
5138 
5139   const Type* superelem = superk;
5140   if (superk->isa_aryklassptr()) {
5141     int ignored;
5142     superelem = superk->is_aryklassptr()->base_element_type(ignored);
5143 
5144     // Do not fold the subtype check to an array klass pointer comparison for null-able inline type arrays
5145     // because null-free [LMyValue <: null-able [LMyValue but the klasses are different. Perform a full test.
5146     if (!superk->is_aryklassptr()->is_null_free() && superk->is_aryklassptr()->elem()->isa_instklassptr() &&
5147         superk->is_aryklassptr()->elem()->is_instklassptr()->instance_klass()->is_inlinetype()) {
5148       return SSC_full_test;
5149     }
5150   }
5151 
5152   if (superelem->isa_instklassptr()) {
5153     ciInstanceKlass* ik = superelem->is_instklassptr()->instance_klass();
5154     if (!ik->has_subklass()) {
5155       if (!ik->is_final()) {
5156         // Add a dependency if there is a chance of a later subclass.
5157         dependencies()->assert_leaf_type(ik);
5158       }
5159       if (!superk->maybe_java_subtype_of(subk)) {
5160         return SSC_always_false;
5161       }
5162       return SSC_easy_test;     // (3) caller can do a simple ptr comparison
5163     }
5164   } else {
5165     // A primitive array type has no subtypes.
5166     return SSC_easy_test;       // (3) caller can do a simple ptr comparison
5167   }
5168 
5169   return SSC_full_test;
5170 }
5171 
5172 Node* Compile::conv_I2X_index(PhaseGVN* phase, Node* idx, const TypeInt* sizetype, Node* ctrl) {
5173 #ifdef _LP64
5174   // The scaled index operand to AddP must be a clean 64-bit value.
5175   // Java allows a 32-bit int to be incremented to a negative
5176   // value, which appears in a 64-bit register as a large
5177   // positive number.  Using that large positive number as an
5178   // operand in pointer arithmetic has bad consequences.
5179   // On the other hand, 32-bit overflow is rare, and the possibility
5180   // can often be excluded, if we annotate the ConvI2L node with
5181   // a type assertion that its value is known to be a small positive
5182   // number.  (The prior range check has ensured this.)
5183   // This assertion is used by ConvI2LNode::Ideal.
5184   int index_max = max_jint - 1;  // array size is max_jint, index is one less
5185   if (sizetype != nullptr && sizetype->_hi > 0) {
5186     index_max = sizetype->_hi - 1;
5187   }
5188   const TypeInt* iidxtype = TypeInt::make(0, index_max, Type::WidenMax);
5189   idx = constrained_convI2L(phase, idx, iidxtype, ctrl);
5190 #endif
5191   return idx;
5192 }
5193 
5194 // Convert integer value to a narrowed long type dependent on ctrl (for example, a range check)
5195 Node* Compile::constrained_convI2L(PhaseGVN* phase, Node* value, const TypeInt* itype, Node* ctrl, bool carry_dependency) {
5196   if (ctrl != nullptr) {
5197     // Express control dependency by a CastII node with a narrow type.
5198     // Make the CastII node dependent on the control input to prevent the narrowed ConvI2L
5199     // node from floating above the range check during loop optimizations. Otherwise, the
5200     // ConvI2L node may be eliminated independently of the range check, causing the data path
5201     // to become TOP while the control path is still there (although it's unreachable).
5202     value = new CastIINode(ctrl, value, itype, carry_dependency ? ConstraintCastNode::DependencyType::NonFloatingNarrowing : ConstraintCastNode::DependencyType::FloatingNarrowing, true /* range check dependency */);
5203     value = phase->transform(value);
5204   }
5205   const TypeLong* ltype = TypeLong::make(itype->_lo, itype->_hi, itype->_widen);
5206   return phase->transform(new ConvI2LNode(value, ltype));
5207 }
5208 
5209 void Compile::dump_print_inlining() {
5210   inline_printer()->print_on(tty);
5211 }
5212 
5213 void Compile::log_late_inline(CallGenerator* cg) {
5214   if (log() != nullptr) {
5215     log()->head("late_inline method='%d' inline_id='" JLONG_FORMAT "'", log()->identify(cg->method()),
5216                 cg->unique_id());
5217     JVMState* p = cg->call_node()->jvms();
5218     while (p != nullptr) {
5219       log()->elem("jvms bci='%d' method='%d'", p->bci(), log()->identify(p->method()));
5220       p = p->caller();
5221     }
5222     log()->tail("late_inline");
5223   }
5224 }
5225 
5226 void Compile::log_late_inline_failure(CallGenerator* cg, const char* msg) {
5227   log_late_inline(cg);
5228   if (log() != nullptr) {
5229     log()->inline_fail(msg);
5230   }
5231 }
5232 
5233 void Compile::log_inline_id(CallGenerator* cg) {
5234   if (log() != nullptr) {
5235     // The LogCompilation tool needs a unique way to identify late
5236     // inline call sites. This id must be unique for this call site in
5237     // this compilation. Try to have it unique across compilations as
5238     // well because it can be convenient when grepping through the log
5239     // file.
5240     // Distinguish OSR compilations from others in case CICountOSR is
5241     // on.
5242     jlong id = ((jlong)unique()) + (((jlong)compile_id()) << 33) + (CICountOSR && is_osr_compilation() ? ((jlong)1) << 32 : 0);
5243     cg->set_unique_id(id);
5244     log()->elem("inline_id id='" JLONG_FORMAT "'", id);
5245   }
5246 }
5247 
5248 void Compile::log_inline_failure(const char* msg) {
5249   if (C->log() != nullptr) {
5250     C->log()->inline_fail(msg);
5251   }
5252 }
5253 
5254 
5255 // Dump inlining replay data to the stream.
5256 // Don't change thread state and acquire any locks.
5257 void Compile::dump_inline_data(outputStream* out) {
5258   InlineTree* inl_tree = ilt();
5259   if (inl_tree != nullptr) {
5260     out->print(" inline %d", inl_tree->count());
5261     inl_tree->dump_replay_data(out);
5262   }
5263 }
5264 
5265 void Compile::dump_inline_data_reduced(outputStream* out) {
5266   assert(ReplayReduce, "");
5267 
5268   InlineTree* inl_tree = ilt();
5269   if (inl_tree == nullptr) {
5270     return;
5271   }
5272   // Enable iterative replay file reduction
5273   // Output "compile" lines for depth 1 subtrees,
5274   // simulating that those trees were compiled
5275   // instead of inlined.
5276   for (int i = 0; i < inl_tree->subtrees().length(); ++i) {
5277     InlineTree* sub = inl_tree->subtrees().at(i);
5278     if (sub->inline_level() != 1) {
5279       continue;
5280     }
5281 
5282     ciMethod* method = sub->method();
5283     int entry_bci = -1;
5284     int comp_level = env()->task()->comp_level();
5285     out->print("compile ");
5286     method->dump_name_as_ascii(out);
5287     out->print(" %d %d", entry_bci, comp_level);
5288     out->print(" inline %d", sub->count());
5289     sub->dump_replay_data(out, -1);
5290     out->cr();
5291   }
5292 }
5293 
5294 int Compile::cmp_expensive_nodes(Node* n1, Node* n2) {
5295   if (n1->Opcode() < n2->Opcode())      return -1;
5296   else if (n1->Opcode() > n2->Opcode()) return 1;
5297 
5298   assert(n1->req() == n2->req(), "can't compare %s nodes: n1->req() = %d, n2->req() = %d", NodeClassNames[n1->Opcode()], n1->req(), n2->req());
5299   for (uint i = 1; i < n1->req(); i++) {
5300     if (n1->in(i) < n2->in(i))      return -1;
5301     else if (n1->in(i) > n2->in(i)) return 1;
5302   }
5303 
5304   return 0;
5305 }
5306 
5307 int Compile::cmp_expensive_nodes(Node** n1p, Node** n2p) {
5308   Node* n1 = *n1p;
5309   Node* n2 = *n2p;
5310 
5311   return cmp_expensive_nodes(n1, n2);
5312 }
5313 
5314 void Compile::sort_expensive_nodes() {
5315   if (!expensive_nodes_sorted()) {
5316     _expensive_nodes.sort(cmp_expensive_nodes);
5317   }
5318 }
5319 
5320 bool Compile::expensive_nodes_sorted() const {
5321   for (int i = 1; i < _expensive_nodes.length(); i++) {
5322     if (cmp_expensive_nodes(_expensive_nodes.adr_at(i), _expensive_nodes.adr_at(i-1)) < 0) {
5323       return false;
5324     }
5325   }
5326   return true;
5327 }
5328 
5329 bool Compile::should_optimize_expensive_nodes(PhaseIterGVN &igvn) {
5330   if (_expensive_nodes.length() == 0) {
5331     return false;
5332   }
5333 
5334   assert(OptimizeExpensiveOps, "optimization off?");
5335 
5336   // Take this opportunity to remove dead nodes from the list
5337   int j = 0;
5338   for (int i = 0; i < _expensive_nodes.length(); i++) {
5339     Node* n = _expensive_nodes.at(i);
5340     if (!n->is_unreachable(igvn)) {
5341       assert(n->is_expensive(), "should be expensive");
5342       _expensive_nodes.at_put(j, n);
5343       j++;
5344     }
5345   }
5346   _expensive_nodes.trunc_to(j);
5347 
5348   // Then sort the list so that similar nodes are next to each other
5349   // and check for at least two nodes of identical kind with same data
5350   // inputs.
5351   sort_expensive_nodes();
5352 
5353   for (int i = 0; i < _expensive_nodes.length()-1; i++) {
5354     if (cmp_expensive_nodes(_expensive_nodes.adr_at(i), _expensive_nodes.adr_at(i+1)) == 0) {
5355       return true;
5356     }
5357   }
5358 
5359   return false;
5360 }
5361 
5362 void Compile::cleanup_expensive_nodes(PhaseIterGVN &igvn) {
5363   if (_expensive_nodes.length() == 0) {
5364     return;
5365   }
5366 
5367   assert(OptimizeExpensiveOps, "optimization off?");
5368 
5369   // Sort to bring similar nodes next to each other and clear the
5370   // control input of nodes for which there's only a single copy.
5371   sort_expensive_nodes();
5372 
5373   int j = 0;
5374   int identical = 0;
5375   int i = 0;
5376   bool modified = false;
5377   for (; i < _expensive_nodes.length()-1; i++) {
5378     assert(j <= i, "can't write beyond current index");
5379     if (_expensive_nodes.at(i)->Opcode() == _expensive_nodes.at(i+1)->Opcode()) {
5380       identical++;
5381       _expensive_nodes.at_put(j++, _expensive_nodes.at(i));
5382       continue;
5383     }
5384     if (identical > 0) {
5385       _expensive_nodes.at_put(j++, _expensive_nodes.at(i));
5386       identical = 0;
5387     } else {
5388       Node* n = _expensive_nodes.at(i);
5389       igvn.replace_input_of(n, 0, nullptr);
5390       igvn.hash_insert(n);
5391       modified = true;
5392     }
5393   }
5394   if (identical > 0) {
5395     _expensive_nodes.at_put(j++, _expensive_nodes.at(i));
5396   } else if (_expensive_nodes.length() >= 1) {
5397     Node* n = _expensive_nodes.at(i);
5398     igvn.replace_input_of(n, 0, nullptr);
5399     igvn.hash_insert(n);
5400     modified = true;
5401   }
5402   _expensive_nodes.trunc_to(j);
5403   if (modified) {
5404     igvn.optimize();
5405   }
5406 }
5407 
5408 void Compile::add_expensive_node(Node * n) {
5409   assert(!_expensive_nodes.contains(n), "duplicate entry in expensive list");
5410   assert(n->is_expensive(), "expensive nodes with non-null control here only");
5411   assert(!n->is_CFG() && !n->is_Mem(), "no cfg or memory nodes here");
5412   if (OptimizeExpensiveOps) {
5413     _expensive_nodes.append(n);
5414   } else {
5415     // Clear control input and let IGVN optimize expensive nodes if
5416     // OptimizeExpensiveOps is off.
5417     n->set_req(0, nullptr);
5418   }
5419 }
5420 
5421 /**
5422  * Track coarsened Lock and Unlock nodes.
5423  */
5424 
5425 class Lock_List : public Node_List {
5426   uint _origin_cnt;
5427 public:
5428   Lock_List(Arena *a, uint cnt) : Node_List(a), _origin_cnt(cnt) {}
5429   uint origin_cnt() const { return _origin_cnt; }
5430 };
5431 
5432 void Compile::add_coarsened_locks(GrowableArray<AbstractLockNode*>& locks) {
5433   int length = locks.length();
5434   if (length > 0) {
5435     // Have to keep this list until locks elimination during Macro nodes elimination.
5436     Lock_List* locks_list = new (comp_arena()) Lock_List(comp_arena(), length);
5437     AbstractLockNode* alock = locks.at(0);
5438     BoxLockNode* box = alock->box_node()->as_BoxLock();
5439     for (int i = 0; i < length; i++) {
5440       AbstractLockNode* lock = locks.at(i);
5441       assert(lock->is_coarsened(), "expecting only coarsened AbstractLock nodes, but got '%s'[%d] node", lock->Name(), lock->_idx);
5442       locks_list->push(lock);
5443       BoxLockNode* this_box = lock->box_node()->as_BoxLock();
5444       if (this_box != box) {
5445         // Locking regions (BoxLock) could be Unbalanced here:
5446         //  - its coarsened locks were eliminated in earlier
5447         //    macro nodes elimination followed by loop unroll
5448         //  - it is OSR locking region (no Lock node)
5449         // Preserve Unbalanced status in such cases.
5450         if (!this_box->is_unbalanced()) {
5451           this_box->set_coarsened();
5452         }
5453         if (!box->is_unbalanced()) {
5454           box->set_coarsened();
5455         }
5456       }
5457     }
5458     _coarsened_locks.append(locks_list);
5459   }
5460 }
5461 
5462 void Compile::remove_useless_coarsened_locks(Unique_Node_List& useful) {
5463   int count = coarsened_count();
5464   for (int i = 0; i < count; i++) {
5465     Node_List* locks_list = _coarsened_locks.at(i);
5466     for (uint j = 0; j < locks_list->size(); j++) {
5467       Node* lock = locks_list->at(j);
5468       assert(lock->is_AbstractLock(), "sanity");
5469       if (!useful.member(lock)) {
5470         locks_list->yank(lock);
5471       }
5472     }
5473   }
5474 }
5475 
5476 void Compile::remove_coarsened_lock(Node* n) {
5477   if (n->is_AbstractLock()) {
5478     int count = coarsened_count();
5479     for (int i = 0; i < count; i++) {
5480       Node_List* locks_list = _coarsened_locks.at(i);
5481       locks_list->yank(n);
5482     }
5483   }
5484 }
5485 
5486 bool Compile::coarsened_locks_consistent() {
5487   int count = coarsened_count();
5488   for (int i = 0; i < count; i++) {
5489     bool unbalanced = false;
5490     bool modified = false; // track locks kind modifications
5491     Lock_List* locks_list = (Lock_List*)_coarsened_locks.at(i);
5492     uint size = locks_list->size();
5493     if (size == 0) {
5494       unbalanced = false; // All locks were eliminated - good
5495     } else if (size != locks_list->origin_cnt()) {
5496       unbalanced = true; // Some locks were removed from list
5497     } else {
5498       for (uint j = 0; j < size; j++) {
5499         Node* lock = locks_list->at(j);
5500         // All nodes in group should have the same state (modified or not)
5501         if (!lock->as_AbstractLock()->is_coarsened()) {
5502           if (j == 0) {
5503             // first on list was modified, the rest should be too for consistency
5504             modified = true;
5505           } else if (!modified) {
5506             // this lock was modified but previous locks on the list were not
5507             unbalanced = true;
5508             break;
5509           }
5510         } else if (modified) {
5511           // previous locks on list were modified but not this lock
5512           unbalanced = true;
5513           break;
5514         }
5515       }
5516     }
5517     if (unbalanced) {
5518       // unbalanced monitor enter/exit - only some [un]lock nodes were removed or modified
5519 #ifdef ASSERT
5520       if (PrintEliminateLocks) {
5521         tty->print_cr("=== unbalanced coarsened locks ===");
5522         for (uint l = 0; l < size; l++) {
5523           locks_list->at(l)->dump();
5524         }
5525       }
5526 #endif
5527       record_failure(C2Compiler::retry_no_locks_coarsening());
5528       return false;
5529     }
5530   }
5531   return true;
5532 }
5533 
5534 // Mark locking regions (identified by BoxLockNode) as unbalanced if
5535 // locks coarsening optimization removed Lock/Unlock nodes from them.
5536 // Such regions become unbalanced because coarsening only removes part
5537 // of Lock/Unlock nodes in region. As result we can't execute other
5538 // locks elimination optimizations which assume all code paths have
5539 // corresponding pair of Lock/Unlock nodes - they are balanced.
5540 void Compile::mark_unbalanced_boxes() const {
5541   int count = coarsened_count();
5542   for (int i = 0; i < count; i++) {
5543     Node_List* locks_list = _coarsened_locks.at(i);
5544     uint size = locks_list->size();
5545     if (size > 0) {
5546       AbstractLockNode* alock = locks_list->at(0)->as_AbstractLock();
5547       BoxLockNode* box = alock->box_node()->as_BoxLock();
5548       if (alock->is_coarsened()) {
5549         // coarsened_locks_consistent(), which is called before this method, verifies
5550         // that the rest of Lock/Unlock nodes on locks_list are also coarsened.
5551         assert(!box->is_eliminated(), "regions with coarsened locks should not be marked as eliminated");
5552         for (uint j = 1; j < size; j++) {
5553           assert(locks_list->at(j)->as_AbstractLock()->is_coarsened(), "only coarsened locks are expected here");
5554           BoxLockNode* this_box = locks_list->at(j)->as_AbstractLock()->box_node()->as_BoxLock();
5555           if (box != this_box) {
5556             assert(!this_box->is_eliminated(), "regions with coarsened locks should not be marked as eliminated");
5557             box->set_unbalanced();
5558             this_box->set_unbalanced();
5559           }
5560         }
5561       }
5562     }
5563   }
5564 }
5565 
5566 /**
5567  * Remove the speculative part of types and clean up the graph
5568  */
5569 void Compile::remove_speculative_types(PhaseIterGVN &igvn) {
5570   if (UseTypeSpeculation) {
5571     Unique_Node_List worklist;
5572     worklist.push(root());
5573     int modified = 0;
5574     // Go over all type nodes that carry a speculative type, drop the
5575     // speculative part of the type and enqueue the node for an igvn
5576     // which may optimize it out.
5577     for (uint next = 0; next < worklist.size(); ++next) {
5578       Node *n  = worklist.at(next);
5579       if (n->is_Type()) {
5580         TypeNode* tn = n->as_Type();
5581         const Type* t = tn->type();
5582         const Type* t_no_spec = t->remove_speculative();
5583         if (t_no_spec != t) {
5584           bool in_hash = igvn.hash_delete(n);
5585           assert(in_hash || n->hash() == Node::NO_HASH, "node should be in igvn hash table");
5586           tn->set_type(t_no_spec);
5587           igvn.hash_insert(n);
5588           igvn._worklist.push(n); // give it a chance to go away
5589           modified++;
5590         }
5591       }
5592       // Iterate over outs - endless loops is unreachable from below
5593       for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
5594         Node *m = n->fast_out(i);
5595         if (not_a_node(m)) {
5596           continue;
5597         }
5598         worklist.push(m);
5599       }
5600     }
5601     // Drop the speculative part of all types in the igvn's type table
5602     igvn.remove_speculative_types();
5603     if (modified > 0) {
5604       igvn.optimize();
5605       if (failing())  return;
5606     }
5607 #ifdef ASSERT
5608     // Verify that after the IGVN is over no speculative type has resurfaced
5609     worklist.clear();
5610     worklist.push(root());
5611     for (uint next = 0; next < worklist.size(); ++next) {
5612       Node *n  = worklist.at(next);
5613       const Type* t = igvn.type_or_null(n);
5614       assert((t == nullptr) || (t == t->remove_speculative()), "no more speculative types");
5615       if (n->is_Type()) {
5616         t = n->as_Type()->type();
5617         assert(t == t->remove_speculative(), "no more speculative types");
5618       }
5619       // Iterate over outs - endless loops is unreachable from below
5620       for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
5621         Node *m = n->fast_out(i);
5622         if (not_a_node(m)) {
5623           continue;
5624         }
5625         worklist.push(m);
5626       }
5627     }
5628     igvn.check_no_speculative_types();
5629 #endif
5630   }
5631 }
5632 
5633 // Auxiliary methods to support randomized stressing/fuzzing.
5634 
5635 void Compile::initialize_stress_seed(const DirectiveSet* directive) {
5636   if (FLAG_IS_DEFAULT(StressSeed) || (FLAG_IS_ERGO(StressSeed) && directive->RepeatCompilationOption)) {
5637     _stress_seed = static_cast<uint>(Ticks::now().nanoseconds());
5638     FLAG_SET_ERGO(StressSeed, _stress_seed);
5639   } else {
5640     _stress_seed = StressSeed;
5641   }
5642   if (_log != nullptr) {
5643     _log->elem("stress_test seed='%u'", _stress_seed);
5644   }
5645 }
5646 
5647 int Compile::random() {
5648   _stress_seed = os::next_random(_stress_seed);
5649   return static_cast<int>(_stress_seed);
5650 }
5651 
5652 // This method can be called the arbitrary number of times, with current count
5653 // as the argument. The logic allows selecting a single candidate from the
5654 // running list of candidates as follows:
5655 //    int count = 0;
5656 //    Cand* selected = null;
5657 //    while(cand = cand->next()) {
5658 //      if (randomized_select(++count)) {
5659 //        selected = cand;
5660 //      }
5661 //    }
5662 //
5663 // Including count equalizes the chances any candidate is "selected".
5664 // This is useful when we don't have the complete list of candidates to choose
5665 // from uniformly. In this case, we need to adjust the randomicity of the
5666 // selection, or else we will end up biasing the selection towards the latter
5667 // candidates.
5668 //
5669 // Quick back-envelope calculation shows that for the list of n candidates
5670 // the equal probability for the candidate to persist as "best" can be
5671 // achieved by replacing it with "next" k-th candidate with the probability
5672 // of 1/k. It can be easily shown that by the end of the run, the
5673 // probability for any candidate is converged to 1/n, thus giving the
5674 // uniform distribution among all the candidates.
5675 //
5676 // We don't care about the domain size as long as (RANDOMIZED_DOMAIN / count) is large.
5677 #define RANDOMIZED_DOMAIN_POW 29
5678 #define RANDOMIZED_DOMAIN (1 << RANDOMIZED_DOMAIN_POW)
5679 #define RANDOMIZED_DOMAIN_MASK ((1 << (RANDOMIZED_DOMAIN_POW + 1)) - 1)
5680 bool Compile::randomized_select(int count) {
5681   assert(count > 0, "only positive");
5682   return (random() & RANDOMIZED_DOMAIN_MASK) < (RANDOMIZED_DOMAIN / count);
5683 }
5684 
5685 #ifdef ASSERT
5686 // Failures are geometrically distributed with probability 1/StressBailoutMean.
5687 bool Compile::fail_randomly() {
5688   if ((random() % StressBailoutMean) != 0) {
5689     return false;
5690   }
5691   record_failure("StressBailout");
5692   return true;
5693 }
5694 
5695 bool Compile::failure_is_artificial() {
5696   return C->failure_reason_is("StressBailout");
5697 }
5698 #endif
5699 
5700 CloneMap&     Compile::clone_map()                 { return _clone_map; }
5701 void          Compile::set_clone_map(Dict* d)      { _clone_map._dict = d; }
5702 
5703 void NodeCloneInfo::dump_on(outputStream* st) const {
5704   st->print(" {%d:%d} ", idx(), gen());
5705 }
5706 
5707 void CloneMap::clone(Node* old, Node* nnn, int gen) {
5708   uint64_t val = value(old->_idx);
5709   NodeCloneInfo cio(val);
5710   assert(val != 0, "old node should be in the map");
5711   NodeCloneInfo cin(cio.idx(), gen + cio.gen());
5712   insert(nnn->_idx, cin.get());
5713 #ifndef PRODUCT
5714   if (is_debug()) {
5715     tty->print_cr("CloneMap::clone inserted node %d info {%d:%d} into CloneMap", nnn->_idx, cin.idx(), cin.gen());
5716   }
5717 #endif
5718 }
5719 
5720 void CloneMap::verify_insert_and_clone(Node* old, Node* nnn, int gen) {
5721   NodeCloneInfo cio(value(old->_idx));
5722   if (cio.get() == 0) {
5723     cio.set(old->_idx, 0);
5724     insert(old->_idx, cio.get());
5725 #ifndef PRODUCT
5726     if (is_debug()) {
5727       tty->print_cr("CloneMap::verify_insert_and_clone inserted node %d info {%d:%d} into CloneMap", old->_idx, cio.idx(), cio.gen());
5728     }
5729 #endif
5730   }
5731   clone(old, nnn, gen);
5732 }
5733 
5734 int CloneMap::max_gen() const {
5735   int g = 0;
5736   DictI di(_dict);
5737   for(; di.test(); ++di) {
5738     int t = gen(di._key);
5739     if (g < t) {
5740       g = t;
5741 #ifndef PRODUCT
5742       if (is_debug()) {
5743         tty->print_cr("CloneMap::max_gen() update max=%d from %d", g, _2_node_idx_t(di._key));
5744       }
5745 #endif
5746     }
5747   }
5748   return g;
5749 }
5750 
5751 void CloneMap::dump(node_idx_t key, outputStream* st) const {
5752   uint64_t val = value(key);
5753   if (val != 0) {
5754     NodeCloneInfo ni(val);
5755     ni.dump_on(st);
5756   }
5757 }
5758 
5759 void Compile::shuffle_macro_nodes() {
5760   if (_macro_nodes.length() < 2) {
5761     return;
5762   }
5763   for (uint i = _macro_nodes.length() - 1; i >= 1; i--) {
5764     uint j = C->random() % (i + 1);
5765     swap(_macro_nodes.at(i), _macro_nodes.at(j));
5766   }
5767 }
5768 
5769 // Move Allocate nodes to the start of the list
5770 void Compile::sort_macro_nodes() {
5771   int count = macro_count();
5772   int allocates = 0;
5773   for (int i = 0; i < count; i++) {
5774     Node* n = macro_node(i);
5775     if (n->is_Allocate()) {
5776       if (i != allocates) {
5777         Node* tmp = macro_node(allocates);
5778         _macro_nodes.at_put(allocates, n);
5779         _macro_nodes.at_put(i, tmp);
5780       }
5781       allocates++;
5782     }
5783   }
5784 }
5785 
5786 void Compile::print_method(CompilerPhaseType cpt, int level, Node* n) {
5787   if (failing_internal()) { return; } // failing_internal to not stress bailouts from printing code.
5788   EventCompilerPhase event(UNTIMED);
5789   if (event.should_commit()) {
5790     CompilerEvent::PhaseEvent::post(event, C->_latest_stage_start_counter, cpt, C->_compile_id, level);
5791   }
5792 #ifndef PRODUCT
5793   ResourceMark rm;
5794   stringStream ss;
5795   ss.print_raw(CompilerPhaseTypeHelper::to_description(cpt));
5796   int iter = ++_igv_phase_iter[cpt];
5797   if (iter > 1) {
5798     ss.print(" %d", iter);
5799   }
5800   if (n != nullptr) {
5801     ss.print(": %d %s", n->_idx, NodeClassNames[n->Opcode()]);
5802     if (n->is_Call()) {
5803       CallNode* call = n->as_Call();
5804       if (call->_name != nullptr) {
5805         // E.g. uncommon traps etc.
5806         ss.print(" - %s", call->_name);
5807       } else if (call->is_CallJava()) {
5808         CallJavaNode* call_java = call->as_CallJava();
5809         if (call_java->method() != nullptr) {
5810           ss.print(" -");
5811           call_java->method()->print_short_name(&ss);
5812         }
5813       }
5814     }
5815   }
5816 
5817   const char* name = ss.as_string();
5818   if (should_print_igv(level)) {
5819     _igv_printer->print_graph(name);
5820   }
5821   if (should_print_phase(level)) {
5822     print_phase(name);
5823   }
5824   if (should_print_ideal_phase(cpt)) {
5825     print_ideal_ir(CompilerPhaseTypeHelper::to_name(cpt));
5826   }
5827 #endif
5828   C->_latest_stage_start_counter.stamp();
5829 }
5830 
5831 // Only used from CompileWrapper
5832 void Compile::begin_method() {
5833 #ifndef PRODUCT
5834   if (_method != nullptr && should_print_igv(1)) {
5835     _igv_printer->begin_method();
5836   }
5837 #endif
5838   C->_latest_stage_start_counter.stamp();
5839 }
5840 
5841 // Only used from CompileWrapper
5842 void Compile::end_method() {
5843   EventCompilerPhase event(UNTIMED);
5844   if (event.should_commit()) {
5845     CompilerEvent::PhaseEvent::post(event, C->_latest_stage_start_counter, PHASE_END, C->_compile_id, 1);
5846   }
5847 
5848 #ifndef PRODUCT
5849   if (_method != nullptr && should_print_igv(1)) {
5850     _igv_printer->end_method();
5851   }
5852 #endif
5853 }
5854 
5855 #ifndef PRODUCT
5856 bool Compile::should_print_phase(const int level) const {
5857   return PrintPhaseLevel >= 0 && directive()->PhasePrintLevelOption >= level &&
5858          _method != nullptr; // Do not print phases for stubs.
5859 }
5860 
5861 bool Compile::should_print_ideal_phase(CompilerPhaseType cpt) const {
5862   return _directive->should_print_ideal_phase(cpt);
5863 }
5864 
5865 void Compile::init_igv() {
5866   if (_igv_printer == nullptr) {
5867     _igv_printer = IdealGraphPrinter::printer();
5868     _igv_printer->set_compile(this);
5869   }
5870 }
5871 
5872 bool Compile::should_print_igv(const int level) {
5873   PRODUCT_RETURN_(return false;);
5874 
5875   if (PrintIdealGraphLevel < 0) { // disabled by the user
5876     return false;
5877   }
5878 
5879   bool need = directive()->IGVPrintLevelOption >= level;
5880   if (need) {
5881     Compile::init_igv();
5882   }
5883   return need;
5884 }
5885 
5886 IdealGraphPrinter* Compile::_debug_file_printer = nullptr;
5887 IdealGraphPrinter* Compile::_debug_network_printer = nullptr;
5888 
5889 // Called from debugger. Prints method to the default file with the default phase name.
5890 // This works regardless of any Ideal Graph Visualizer flags set or not.
5891 // Use in debugger (gdb/rr): p igv_print($sp, $fp, $pc).
5892 void igv_print(void* sp, void* fp, void* pc) {
5893   frame fr(sp, fp, pc);
5894   Compile::current()->igv_print_method_to_file(nullptr, false, &fr);
5895 }
5896 
5897 // Same as igv_print() above but with a specified phase name.
5898 void igv_print(const char* phase_name, void* sp, void* fp, void* pc) {
5899   frame fr(sp, fp, pc);
5900   Compile::current()->igv_print_method_to_file(phase_name, false, &fr);
5901 }
5902 
5903 // Called from debugger. Prints method with the default phase name to the default network or the one specified with
5904 // the network flags for the Ideal Graph Visualizer, or to the default file depending on the 'network' argument.
5905 // This works regardless of any Ideal Graph Visualizer flags set or not.
5906 // Use in debugger (gdb/rr): p igv_print(true, $sp, $fp, $pc).
5907 void igv_print(bool network, void* sp, void* fp, void* pc) {
5908   frame fr(sp, fp, pc);
5909   if (network) {
5910     Compile::current()->igv_print_method_to_network(nullptr, &fr);
5911   } else {
5912     Compile::current()->igv_print_method_to_file(nullptr, false, &fr);
5913   }
5914 }
5915 
5916 // Same as igv_print(bool network, ...) above but with a specified phase name.
5917 // Use in debugger (gdb/rr): p igv_print(true, "MyPhase", $sp, $fp, $pc).
5918 void igv_print(bool network, const char* phase_name, void* sp, void* fp, void* pc) {
5919   frame fr(sp, fp, pc);
5920   if (network) {
5921     Compile::current()->igv_print_method_to_network(phase_name, &fr);
5922   } else {
5923     Compile::current()->igv_print_method_to_file(phase_name, false, &fr);
5924   }
5925 }
5926 
5927 // Called from debugger. Normal write to the default _printer. Only works if Ideal Graph Visualizer printing flags are set.
5928 void igv_print_default() {
5929   Compile::current()->print_method(PHASE_DEBUG, 0);
5930 }
5931 
5932 // Called from debugger, especially when replaying a trace in which the program state cannot be altered like with rr replay.
5933 // A method is appended to an existing default file with the default phase name. This means that igv_append() must follow
5934 // an earlier igv_print(*) call which sets up the file. This works regardless of any Ideal Graph Visualizer flags set or not.
5935 // Use in debugger (gdb/rr): p igv_append($sp, $fp, $pc).
5936 void igv_append(void* sp, void* fp, void* pc) {
5937   frame fr(sp, fp, pc);
5938   Compile::current()->igv_print_method_to_file(nullptr, true, &fr);
5939 }
5940 
5941 // Same as igv_append(...) above but with a specified phase name.
5942 // Use in debugger (gdb/rr): p igv_append("MyPhase", $sp, $fp, $pc).
5943 void igv_append(const char* phase_name, void* sp, void* fp, void* pc) {
5944   frame fr(sp, fp, pc);
5945   Compile::current()->igv_print_method_to_file(phase_name, true, &fr);
5946 }
5947 
5948 void Compile::igv_print_method_to_file(const char* phase_name, bool append, const frame* fr) {
5949   const char* file_name = "custom_debug.xml";
5950   if (_debug_file_printer == nullptr) {
5951     _debug_file_printer = new IdealGraphPrinter(C, file_name, append);
5952   } else {
5953     _debug_file_printer->update_compiled_method(C->method());
5954   }
5955   tty->print_cr("Method %s to %s", append ? "appended" : "printed", file_name);
5956   _debug_file_printer->print_graph(phase_name, fr);
5957 }
5958 
5959 void Compile::igv_print_method_to_network(const char* phase_name, const frame* fr) {
5960   ResourceMark rm;
5961   GrowableArray<const Node*> empty_list;
5962   igv_print_graph_to_network(phase_name, empty_list, fr);
5963 }
5964 
5965 void Compile::igv_print_graph_to_network(const char* name, GrowableArray<const Node*>& visible_nodes, const frame* fr) {
5966   if (_debug_network_printer == nullptr) {
5967     _debug_network_printer = new IdealGraphPrinter(C);
5968   } else {
5969     _debug_network_printer->update_compiled_method(C->method());
5970   }
5971   tty->print_cr("Method printed over network stream to IGV");
5972   _debug_network_printer->print(name, C->root(), visible_nodes, fr);
5973 }
5974 #endif // !PRODUCT
5975 
5976 Node* Compile::narrow_value(BasicType bt, Node* value, const Type* type, PhaseGVN* phase, bool transform_res) {
5977   if (type != nullptr && phase->type(value)->higher_equal(type)) {
5978     return value;
5979   }
5980   Node* result = nullptr;
5981   if (bt == T_BYTE) {
5982     result = phase->transform(new LShiftINode(value, phase->intcon(24)));
5983     result = new RShiftINode(result, phase->intcon(24));
5984   } else if (bt == T_BOOLEAN) {
5985     result = new AndINode(value, phase->intcon(0xFF));
5986   } else if (bt == T_CHAR) {
5987     result = new AndINode(value,phase->intcon(0xFFFF));
5988   } else if (bt == T_FLOAT) {
5989     result = new MoveI2FNode(value);
5990   } else {
5991     assert(bt == T_SHORT, "unexpected narrow type");
5992     result = phase->transform(new LShiftINode(value, phase->intcon(16)));
5993     result = new RShiftINode(result, phase->intcon(16));
5994   }
5995   if (transform_res) {
5996     result = phase->transform(result);
5997   }
5998   return result;
5999 }
6000 
6001 void Compile::record_method_not_compilable_oom() {
6002   record_method_not_compilable(CompilationMemoryStatistic::failure_reason_memlimit());
6003 }
6004 
6005 #ifndef PRODUCT
6006 // Collects all the control inputs from nodes on the worklist and from their data dependencies
6007 static void find_candidate_control_inputs(Unique_Node_List& worklist, Unique_Node_List& candidates) {
6008   // Follow non-control edges until we reach CFG nodes
6009   for (uint i = 0; i < worklist.size(); i++) {
6010     const Node* n = worklist.at(i);
6011     for (uint j = 0; j < n->req(); j++) {
6012       Node* in = n->in(j);
6013       if (in == nullptr || in->is_Root()) {
6014         continue;
6015       }
6016       if (in->is_CFG()) {
6017         if (in->is_Call()) {
6018           // The return value of a call is only available if the call did not result in an exception
6019           Node* control_proj_use = in->as_Call()->proj_out(TypeFunc::Control)->unique_out();
6020           if (control_proj_use->is_Catch()) {
6021             Node* fall_through = control_proj_use->as_Catch()->proj_out(CatchProjNode::fall_through_index);
6022             candidates.push(fall_through);
6023             continue;
6024           }
6025         }
6026 
6027         if (in->is_Multi()) {
6028           // We got here by following data inputs so we should only have one control use
6029           // (no IfNode, etc)
6030           assert(!n->is_MultiBranch(), "unexpected node type: %s", n->Name());
6031           candidates.push(in->as_Multi()->proj_out(TypeFunc::Control));
6032         } else {
6033           candidates.push(in);
6034         }
6035       } else {
6036         worklist.push(in);
6037       }
6038     }
6039   }
6040 }
6041 
6042 // Returns the candidate node that is a descendant to all the other candidates
6043 static Node* pick_control(Unique_Node_List& candidates) {
6044   Unique_Node_List worklist;
6045   worklist.copy(candidates);
6046 
6047   // Traverse backwards through the CFG
6048   for (uint i = 0; i < worklist.size(); i++) {
6049     const Node* n = worklist.at(i);
6050     if (n->is_Root()) {
6051       continue;
6052     }
6053     for (uint j = 0; j < n->req(); j++) {
6054       // Skip backedge of loops to avoid cycles
6055       if (n->is_Loop() && j == LoopNode::LoopBackControl) {
6056         continue;
6057       }
6058 
6059       Node* pred = n->in(j);
6060       if (pred != nullptr && pred != n && pred->is_CFG()) {
6061         worklist.push(pred);
6062         // if pred is an ancestor of n, then pred is an ancestor to at least one candidate
6063         candidates.remove(pred);
6064       }
6065     }
6066   }
6067 
6068   assert(candidates.size() == 1, "unexpected control flow");
6069   return candidates.at(0);
6070 }
6071 
6072 // Initialize a parameter input for a debug print call, using a placeholder for jlong and jdouble
6073 static void debug_print_init_parm(Node* call, Node* parm, Node* half, int* pos) {
6074   call->init_req((*pos)++, parm);
6075   const BasicType bt = parm->bottom_type()->basic_type();
6076   if (bt == T_LONG || bt == T_DOUBLE) {
6077     call->init_req((*pos)++, half);
6078   }
6079 }
6080 
6081 Node* Compile::make_debug_print_call(const char* str, address call_addr, PhaseGVN* gvn,
6082                               Node* parm0, Node* parm1,
6083                               Node* parm2, Node* parm3,
6084                               Node* parm4, Node* parm5,
6085                               Node* parm6) const {
6086   Node* str_node = gvn->transform(new ConPNode(TypeRawPtr::make(((address) str))));
6087   const TypeFunc* type = OptoRuntime::debug_print_Type(parm0, parm1, parm2, parm3, parm4, parm5, parm6);
6088   Node* call = new CallLeafNode(type, call_addr, "debug_print", TypeRawPtr::BOTTOM);
6089 
6090   // find the most suitable control input
6091   Unique_Node_List worklist, candidates;
6092   if (parm0 != nullptr) { worklist.push(parm0);
6093   if (parm1 != nullptr) { worklist.push(parm1);
6094   if (parm2 != nullptr) { worklist.push(parm2);
6095   if (parm3 != nullptr) { worklist.push(parm3);
6096   if (parm4 != nullptr) { worklist.push(parm4);
6097   if (parm5 != nullptr) { worklist.push(parm5);
6098   if (parm6 != nullptr) { worklist.push(parm6);
6099   /* close each nested if ===> */  } } } } } } }
6100   find_candidate_control_inputs(worklist, candidates);
6101   Node* control = nullptr;
6102   if (candidates.size() == 0) {
6103     control = C->start()->proj_out(TypeFunc::Control);
6104   } else {
6105     control = pick_control(candidates);
6106   }
6107 
6108   // find all the previous users of the control we picked
6109   GrowableArray<Node*> users_of_control;
6110   for (DUIterator_Fast kmax, i = control->fast_outs(kmax); i < kmax; i++) {
6111     Node* use = control->fast_out(i);
6112     if (use->is_CFG() && use != control) {
6113       users_of_control.push(use);
6114     }
6115   }
6116 
6117   // we do not actually care about IO and memory as it uses neither
6118   call->init_req(TypeFunc::Control,   control);
6119   call->init_req(TypeFunc::I_O,       top());
6120   call->init_req(TypeFunc::Memory,    top());
6121   call->init_req(TypeFunc::FramePtr,  C->start()->proj_out(TypeFunc::FramePtr));
6122   call->init_req(TypeFunc::ReturnAdr, top());
6123 
6124   int pos = TypeFunc::Parms;
6125   call->init_req(pos++, str_node);
6126   if (parm0 != nullptr) { debug_print_init_parm(call, parm0, top(), &pos);
6127   if (parm1 != nullptr) { debug_print_init_parm(call, parm1, top(), &pos);
6128   if (parm2 != nullptr) { debug_print_init_parm(call, parm2, top(), &pos);
6129   if (parm3 != nullptr) { debug_print_init_parm(call, parm3, top(), &pos);
6130   if (parm4 != nullptr) { debug_print_init_parm(call, parm4, top(), &pos);
6131   if (parm5 != nullptr) { debug_print_init_parm(call, parm5, top(), &pos);
6132   if (parm6 != nullptr) { debug_print_init_parm(call, parm6, top(), &pos);
6133   /* close each nested if ===> */  } } } } } } }
6134   assert(call->in(call->req()-1) != nullptr, "must initialize all parms");
6135 
6136   call = gvn->transform(call);
6137   Node* call_control_proj = gvn->transform(new ProjNode(call, TypeFunc::Control));
6138 
6139   // rewire previous users to have the new call as control instead
6140   PhaseIterGVN* igvn = gvn->is_IterGVN();
6141   for (int i = 0; i < users_of_control.length(); i++) {
6142     Node* use = users_of_control.at(i);
6143     for (uint j = 0; j < use->req(); j++) {
6144       if (use->in(j) == control) {
6145         if (igvn != nullptr) {
6146           igvn->replace_input_of(use, j, call_control_proj);
6147         } else {
6148           gvn->hash_delete(use);
6149           use->set_req(j, call_control_proj);
6150           gvn->hash_insert(use);
6151         }
6152       }
6153     }
6154   }
6155 
6156   return call;
6157 }
6158 #endif // !PRODUCT