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