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