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