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