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