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