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