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