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