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     }
2857 
2858     ciField* field = from_kls->get_field_by_name(ciSymbol::make(field_name),
2859       ciSymbol::make(TypeArrayKlass::external_name(bt)), false);
2860 
2861     int offset = field->offset_in_bytes();
2862     Node* vec_adr = kit.basic_plus_adr(obj, offset);
2863 
2864     Node* mem = vec_unbox->mem();
2865     Node* ctrl = vec_unbox->in(0);
2866     Node* vec_field_ld = LoadNode::make(gvn,
2867                                         ctrl,
2868                                         mem,
2869                                         vec_adr,
2870                                         vec_adr->bottom_type()->is_ptr(),
2871                                         TypeOopPtr::make_from_klass(field->type()->as_klass()),
2872                                         T_OBJECT,
2873                                         MemNode::unordered);
2874     vec_field_ld = gvn.transform(vec_field_ld);
2875 
2876     Node* adr = kit.array_element_address(vec_field_ld, gvn.intcon(0), bt);
2877     const TypePtr* adr_type = adr->bottom_type()->is_ptr();
2878     int num_elem = vec_unbox->bottom_type()->is_vect()->length();
2879     Node* vec_val_load = LoadVectorNode::make(0,
2880                                               ctrl,
2881                                               mem,
2882                                               adr,
2883                                               adr_type,
2884                                               num_elem,
2885                                               bt);
2886     vec_val_load = gvn.transform(vec_val_load);
2887 
2888     if (from_kls->is_vectormask() && masktype != T_BOOLEAN) {
2889       assert(vec_unbox->bottom_type()->is_vect()->element_basic_type() == masktype, "expect mask type consistency");
2890       vec_val_load = gvn.transform(new VectorLoadMaskNode(vec_val_load, TypeVect::make(masktype, num_elem)));
2891     }
2892 
2893     gvn.hash_delete(vec_unbox);
2894     vec_unbox->disconnect_inputs(NULL, C);
2895     C->gvn_replace_by(vec_unbox, vec_val_load);
2896   }
2897   C->remove_macro_node(vec_unbox);
2898 }
2899 
2900 void Compile::eliminate_vbox_alloc_node(VectorBoxAllocateNode* vbox_alloc) {
2901   JVMState* jvms = clone_jvms(C, vbox_alloc);
2902   GraphKit kit(jvms);
2903   // FIXME replace VBA with a safepoint. Otherwise, no safepoints left in tight loops.
2904   kit.replace_call(vbox_alloc, kit.top(), true);
2905   C->remove_macro_node(vbox_alloc);
2906 }
2907 
2908 //------------------------------Code_Gen---------------------------------------
2909 // Given a graph, generate code for it
2910 void Compile::Code_Gen() {
2911   if (failing()) {
2912     return;
2913   }
2914 
2915   // Perform instruction selection.  You might think we could reclaim Matcher
2916   // memory PDQ, but actually the Matcher is used in generating spill code.
2917   // Internals of the Matcher (including some VectorSets) must remain live
2918   // for awhile - thus I cannot reclaim Matcher memory lest a VectorSet usage
2919   // set a bit in reclaimed memory.
2920 
2921   // In debug mode can dump m._nodes.dump() for mapping of ideal to machine
2922   // nodes.  Mapping is only valid at the root of each matched subtree.
2923   NOT_PRODUCT( verify_graph_edges(); )
2924 
2925   Matcher matcher;
2926   _matcher = &matcher;
2927   {
2928     TracePhase tp("matcher", &timers[_t_matcher]);
2929     matcher.match();
2930     print_method(PHASE_AFTER_MATCHING, 3);
2931   }
2932   // In debug mode can dump m._nodes.dump() for mapping of ideal to machine
2933   // nodes.  Mapping is only valid at the root of each matched subtree.
2934   NOT_PRODUCT( verify_graph_edges(); )
2935 
2936   // If you have too many nodes, or if matching has failed, bail out
2937   check_node_count(0, "out of nodes matching instructions");
2938   if (failing()) {
2939     return;
2940   }
2941 
2942   print_method(PHASE_MATCHING, 2);
2943 
2944   // Build a proper-looking CFG
2945   PhaseCFG cfg(node_arena(), root(), matcher);
2946   _cfg = &cfg;
2947   {
2948     TracePhase tp("scheduler", &timers[_t_scheduler]);
2949     bool success = cfg.do_global_code_motion();
2950     if (!success) {
2951       return;
2952     }
2953 
2954     print_method(PHASE_GLOBAL_CODE_MOTION, 2);
2955     NOT_PRODUCT( verify_graph_edges(); )
2956     debug_only( cfg.verify(); )
2957   }
2958 
2959   PhaseChaitin regalloc(unique(), cfg, matcher, false);
2960   _regalloc = &regalloc;
2961   {
2962     TracePhase tp("regalloc", &timers[_t_registerAllocation]);
2963     // Perform register allocation.  After Chaitin, use-def chains are
2964     // no longer accurate (at spill code) and so must be ignored.
2965     // Node->LRG->reg mappings are still accurate.
2966     _regalloc->Register_Allocate();
2967 
2968     // Bail out if the allocator builds too many nodes
2969     if (failing()) {
2970       return;
2971     }
2972   }
2973 
2974   // Prior to register allocation we kept empty basic blocks in case the
2975   // the allocator needed a place to spill.  After register allocation we
2976   // are not adding any new instructions.  If any basic block is empty, we
2977   // can now safely remove it.
2978   {
2979     TracePhase tp("blockOrdering", &timers[_t_blockOrdering]);
2980     cfg.remove_empty_blocks();
2981     if (do_freq_based_layout()) {
2982       PhaseBlockLayout layout(cfg);
2983     } else {
2984       cfg.set_loop_alignment();
2985     }
2986     cfg.fixup_flow();
2987   }
2988 
2989   // Apply peephole optimizations
2990   if( OptoPeephole ) {
2991     TracePhase tp("peephole", &timers[_t_peephole]);
2992     PhasePeephole peep( _regalloc, cfg);
2993     peep.do_transform();
2994   }
2995 
2996   // Do late expand if CPU requires this.
2997   if (Matcher::require_postalloc_expand) {
2998     TracePhase tp("postalloc_expand", &timers[_t_postalloc_expand]);
2999     cfg.postalloc_expand(_regalloc);
3000   }
3001 
3002   // Convert Nodes to instruction bits in a buffer
3003   {
3004     TraceTime tp("output", &timers[_t_output], CITime);
3005     Output();
3006   }
3007 
3008   print_method(PHASE_FINAL_CODE);
3009 
3010   // He's dead, Jim.
3011   _cfg     = (PhaseCFG*)((intptr_t)0xdeadbeef);
3012   _regalloc = (PhaseChaitin*)((intptr_t)0xdeadbeef);
3013 }
3014 
3015 
3016 //------------------------------dump_asm---------------------------------------
3017 // Dump formatted assembly
3018 #ifndef PRODUCT
3019 void Compile::dump_asm(int *pcs, uint pc_limit) {
3020   bool cut_short = false;
3021   tty->print_cr("#");
3022   tty->print("#  ");  _tf->dump();  tty->cr();
3023   tty->print_cr("#");
3024 
3025   // For all blocks
3026   int pc = 0x0;                 // Program counter
3027   char starts_bundle = ' ';
3028   _regalloc->dump_frame();
3029 
3030   Node *n = NULL;
3031   for (uint i = 0; i < _cfg->number_of_blocks(); i++) {
3032     if (VMThread::should_terminate()) {
3033       cut_short = true;
3034       break;
3035     }
3036     Block* block = _cfg->get_block(i);
3037     if (block->is_connector() && !Verbose) {
3038       continue;
3039     }
3040     n = block->head();
3041     if (pcs && n->_idx < pc_limit) {
3042       tty->print("%3.3x   ", pcs[n->_idx]);
3043     } else {
3044       tty->print("      ");
3045     }
3046     block->dump_head(_cfg);
3047     if (block->is_connector()) {
3048       tty->print_cr("        # Empty connector block");
3049     } else if (block->num_preds() == 2 && block->pred(1)->is_CatchProj() && block->pred(1)->as_CatchProj()->_con == CatchProjNode::fall_through_index) {
3050       tty->print_cr("        # Block is sole successor of call");
3051     }
3052 
3053     // For all instructions
3054     Node *delay = NULL;
3055     for (uint j = 0; j < block->number_of_nodes(); j++) {
3056       if (VMThread::should_terminate()) {
3057         cut_short = true;
3058         break;
3059       }
3060       n = block->get_node(j);
3061       if (valid_bundle_info(n)) {
3062         Bundle* bundle = node_bundling(n);
3063         if (bundle->used_in_unconditional_delay()) {
3064           delay = n;
3065           continue;
3066         }
3067         if (bundle->starts_bundle()) {
3068           starts_bundle = '+';
3069         }
3070       }
3071 
3072       if (WizardMode) {
3073         n->dump();
3074       }
3075 
3076       if( !n->is_Region() &&    // Dont print in the Assembly
3077           !n->is_Phi() &&       // a few noisely useless nodes
3078           !n->is_Proj() &&
3079           !n->is_MachTemp() &&
3080           !n->is_SafePointScalarObject() &&
3081           !n->is_Catch() &&     // Would be nice to print exception table targets
3082           !n->is_MergeMem() &&  // Not very interesting
3083           !n->is_top() &&       // Debug info table constants
3084           !(n->is_Con() && !n->is_Mach())// Debug info table constants
3085           ) {
3086         if (pcs && n->_idx < pc_limit)
3087           tty->print("%3.3x", pcs[n->_idx]);
3088         else
3089           tty->print("   ");
3090         tty->print(" %c ", starts_bundle);
3091         starts_bundle = ' ';
3092         tty->print("\t");
3093         n->format(_regalloc, tty);
3094         tty->cr();
3095       }
3096 
3097       // If we have an instruction with a delay slot, and have seen a delay,
3098       // then back up and print it
3099       if (valid_bundle_info(n) && node_bundling(n)->use_unconditional_delay()) {
3100         assert(delay != NULL, "no unconditional delay instruction");
3101         if (WizardMode) delay->dump();
3102 
3103         if (node_bundling(delay)->starts_bundle())
3104           starts_bundle = '+';
3105         if (pcs && n->_idx < pc_limit)
3106           tty->print("%3.3x", pcs[n->_idx]);
3107         else
3108           tty->print("   ");
3109         tty->print(" %c ", starts_bundle);
3110         starts_bundle = ' ';
3111         tty->print("\t");
3112         delay->format(_regalloc, tty);
3113         tty->cr();
3114         delay = NULL;
3115       }
3116 
3117       // Dump the exception table as well
3118       if( n->is_Catch() && (Verbose || WizardMode) ) {
3119         // Print the exception table for this offset
3120         _handler_table.print_subtable_for(pc);
3121       }
3122     }
3123 
3124     if (pcs && n->_idx < pc_limit)
3125       tty->print_cr("%3.3x", pcs[n->_idx]);
3126     else
3127       tty->cr();
3128 
3129     assert(cut_short || delay == NULL, "no unconditional delay branch");
3130 
3131   } // End of per-block dump
3132   tty->cr();
3133 
3134   if (cut_short)  tty->print_cr("*** disassembly is cut short ***");
3135 }
3136 #endif
3137 
3138 //------------------------------Final_Reshape_Counts---------------------------
3139 // This class defines counters to help identify when a method
3140 // may/must be executed using hardware with only 24-bit precision.
3141 struct Final_Reshape_Counts : public StackObj {
3142   int  _call_count;             // count non-inlined 'common' calls
3143   int  _float_count;            // count float ops requiring 24-bit precision
3144   int  _double_count;           // count double ops requiring more precision
3145   int  _java_call_count;        // count non-inlined 'java' calls
3146   int  _inner_loop_count;       // count loops which need alignment
3147   VectorSet _visited;           // Visitation flags
3148   Node_List _tests;             // Set of IfNodes & PCTableNodes
3149 
3150   Final_Reshape_Counts() :
3151     _call_count(0), _float_count(0), _double_count(0),
3152     _java_call_count(0), _inner_loop_count(0),
3153     _visited( Thread::current()->resource_area() ) { }
3154 
3155   void inc_call_count  () { _call_count  ++; }
3156   void inc_float_count () { _float_count ++; }
3157   void inc_double_count() { _double_count++; }
3158   void inc_java_call_count() { _java_call_count++; }
3159   void inc_inner_loop_count() { _inner_loop_count++; }
3160 
3161   int  get_call_count  () const { return _call_count  ; }
3162   int  get_float_count () const { return _float_count ; }
3163   int  get_double_count() const { return _double_count; }
3164   int  get_java_call_count() const { return _java_call_count; }
3165   int  get_inner_loop_count() const { return _inner_loop_count; }
3166 };
3167 
3168 #ifdef ASSERT
3169 static bool oop_offset_is_sane(const TypeInstPtr* tp) {
3170   ciInstanceKlass *k = tp->klass()->as_instance_klass();
3171   // Make sure the offset goes inside the instance layout.
3172   return k->contains_field_offset(tp->offset());
3173   // Note that OffsetBot and OffsetTop are very negative.
3174 }
3175 #endif
3176 
3177 // Eliminate trivially redundant StoreCMs and accumulate their
3178 // precedence edges.
3179 void Compile::eliminate_redundant_card_marks(Node* n) {
3180   assert(n->Opcode() == Op_StoreCM, "expected StoreCM");
3181   if (n->in(MemNode::Address)->outcnt() > 1) {
3182     // There are multiple users of the same address so it might be
3183     // possible to eliminate some of the StoreCMs
3184     Node* mem = n->in(MemNode::Memory);
3185     Node* adr = n->in(MemNode::Address);
3186     Node* val = n->in(MemNode::ValueIn);
3187     Node* prev = n;
3188     bool done = false;
3189     // Walk the chain of StoreCMs eliminating ones that match.  As
3190     // long as it's a chain of single users then the optimization is
3191     // safe.  Eliminating partially redundant StoreCMs would require
3192     // cloning copies down the other paths.
3193     while (mem->Opcode() == Op_StoreCM && mem->outcnt() == 1 && !done) {
3194       if (adr == mem->in(MemNode::Address) &&
3195           val == mem->in(MemNode::ValueIn)) {
3196         // redundant StoreCM
3197         if (mem->req() > MemNode::OopStore) {
3198           // Hasn't been processed by this code yet.
3199           n->add_prec(mem->in(MemNode::OopStore));
3200         } else {
3201           // Already converted to precedence edge
3202           for (uint i = mem->req(); i < mem->len(); i++) {
3203             // Accumulate any precedence edges
3204             if (mem->in(i) != NULL) {
3205               n->add_prec(mem->in(i));
3206             }
3207           }
3208           // Everything above this point has been processed.
3209           done = true;
3210         }
3211         // Eliminate the previous StoreCM
3212         prev->set_req(MemNode::Memory, mem->in(MemNode::Memory));
3213         assert(mem->outcnt() == 0, "should be dead");
3214         mem->disconnect_inputs(NULL, this);
3215       } else {
3216         prev = mem;
3217       }
3218       mem = prev->in(MemNode::Memory);
3219     }
3220   }
3221 }
3222 
3223 //------------------------------final_graph_reshaping_impl----------------------
3224 // Implement items 1-5 from final_graph_reshaping below.
3225 void Compile::final_graph_reshaping_impl( Node *n, Final_Reshape_Counts &frc) {
3226 
3227   if ( n->outcnt() == 0 ) return; // dead node
3228   uint nop = n->Opcode();
3229 
3230   // Check for 2-input instruction with "last use" on right input.
3231   // Swap to left input.  Implements item (2).
3232   if( n->req() == 3 &&          // two-input instruction
3233       n->in(1)->outcnt() > 1 && // left use is NOT a last use
3234       (!n->in(1)->is_Phi() || n->in(1)->in(2) != n) && // it is not data loop
3235       n->in(2)->outcnt() == 1 &&// right use IS a last use
3236       !n->in(2)->is_Con() ) {   // right use is not a constant
3237     // Check for commutative opcode
3238     switch( nop ) {
3239     case Op_AddI:  case Op_AddF:  case Op_AddD:  case Op_AddL:
3240     case Op_MaxI:  case Op_MaxL:  case Op_MaxF:  case Op_MaxD:
3241     case Op_MinI:  case Op_MinL:  case Op_MinF:  case Op_MinD:
3242     case Op_MulI:  case Op_MulF:  case Op_MulD:  case Op_MulL:
3243     case Op_AndL:  case Op_XorL:  case Op_OrL:
3244     case Op_AndI:  case Op_XorI:  case Op_OrI: {
3245       // Move "last use" input to left by swapping inputs
3246       n->swap_edges(1, 2);
3247       break;
3248     }
3249     default:
3250       break;
3251     }
3252   }
3253 
3254 #ifdef ASSERT
3255   if( n->is_Mem() ) {
3256     int alias_idx = get_alias_index(n->as_Mem()->adr_type());
3257     assert( n->in(0) != NULL || alias_idx != Compile::AliasIdxRaw ||
3258             // oop will be recorded in oop map if load crosses safepoint
3259             n->is_Load() && (n->as_Load()->bottom_type()->isa_oopptr() ||
3260                              LoadNode::is_immutable_value(n->in(MemNode::Address))),
3261             "raw memory operations should have control edge");
3262   }
3263   if (n->is_MemBar()) {
3264     MemBarNode* mb = n->as_MemBar();
3265     if (mb->trailing_store() || mb->trailing_load_store()) {
3266       assert(mb->leading_membar()->trailing_membar() == mb, "bad membar pair");
3267       Node* mem = mb->in(MemBarNode::Precedent);
3268       assert((mb->trailing_store() && mem->is_Store() && mem->as_Store()->is_release()) ||
3269              (mb->trailing_load_store() && mem->is_LoadStore()), "missing mem op");
3270     } else if (mb->leading()) {
3271       assert(mb->trailing_membar()->leading_membar() == mb, "bad membar pair");
3272     }
3273   }
3274 #endif
3275   // Count FPU ops and common calls, implements item (3)
3276   switch( nop ) {
3277   // Count all float operations that may use FPU
3278   case Op_AddF:
3279   case Op_SubF:
3280   case Op_MulF:
3281   case Op_DivF:
3282   case Op_NegF:
3283   case Op_ModF:
3284   case Op_ConvI2F:
3285   case Op_ConF:
3286   case Op_CmpF:
3287   case Op_CmpF3:
3288   // case Op_ConvL2F: // longs are split into 32-bit halves
3289     frc.inc_float_count();
3290     break;
3291 
3292   case Op_ConvF2D:
3293   case Op_ConvD2F:
3294     frc.inc_float_count();
3295     frc.inc_double_count();
3296     break;
3297 
3298   // Count all double operations that may use FPU
3299   case Op_AddD:
3300   case Op_SubD:
3301   case Op_MulD:
3302   case Op_DivD:
3303   case Op_NegD:
3304   case Op_ModD:
3305   case Op_ConvI2D:
3306   case Op_ConvD2I:
3307   // case Op_ConvL2D: // handled by leaf call
3308   // case Op_ConvD2L: // handled by leaf call
3309   case Op_ConD:
3310   case Op_CmpD:
3311   case Op_CmpD3:
3312     frc.inc_double_count();
3313     break;
3314   case Op_Opaque1:              // Remove Opaque Nodes before matching
3315   case Op_Opaque2:              // Remove Opaque Nodes before matching
3316   case Op_Opaque3:
3317     n->subsume_by(n->in(1), this);
3318     break;
3319   case Op_CallStaticJava:
3320   case Op_CallJava:
3321   case Op_CallDynamicJava:
3322     frc.inc_java_call_count(); // Count java call site;
3323   case Op_CallRuntime:
3324   case Op_CallLeaf:
3325   case Op_CallLeafVector:
3326   case Op_CallLeafNoFP: {
3327     assert (n->is_Call(), "");
3328     CallNode *call = n->as_Call();
3329     // Count call sites where the FP mode bit would have to be flipped.
3330     // Do not count uncommon runtime calls:
3331     // uncommon_trap, _complete_monitor_locking, _complete_monitor_unlocking,
3332     // _new_Java, _new_typeArray, _new_objArray, _rethrow_Java, ...
3333     if (!call->is_CallStaticJava() || !call->as_CallStaticJava()->_name) {
3334       frc.inc_call_count();   // Count the call site
3335     } else {                  // See if uncommon argument is shared
3336       Node *n = call->in(TypeFunc::Parms);
3337       int nop = n->Opcode();
3338       // Clone shared simple arguments to uncommon calls, item (1).
3339       if (n->outcnt() > 1 &&
3340           !n->is_Proj() &&
3341           nop != Op_CreateEx &&
3342           nop != Op_CheckCastPP &&
3343           nop != Op_DecodeN &&
3344           nop != Op_DecodeNKlass &&
3345           !n->is_Mem() &&
3346           !n->is_Phi()) {
3347         Node *x = n->clone();
3348         call->set_req(TypeFunc::Parms, x);
3349       }
3350     }
3351     break;
3352   }
3353 
3354   case Op_StoreD:
3355   case Op_LoadD:
3356   case Op_LoadD_unaligned:
3357     frc.inc_double_count();
3358     goto handle_mem;
3359   case Op_StoreF:
3360   case Op_LoadF:
3361     frc.inc_float_count();
3362     goto handle_mem;
3363 
3364   case Op_StoreCM:
3365     {
3366       // Convert OopStore dependence into precedence edge
3367       Node* prec = n->in(MemNode::OopStore);
3368       n->del_req(MemNode::OopStore);
3369       n->add_prec(prec);
3370       eliminate_redundant_card_marks(n);
3371     }
3372 
3373     // fall through
3374 
3375   case Op_StoreB:
3376   case Op_StoreC:
3377   case Op_StorePConditional:
3378   case Op_StoreI:
3379   case Op_StoreL:
3380   case Op_StoreIConditional:
3381   case Op_StoreLConditional:
3382   case Op_CompareAndSwapB:
3383   case Op_CompareAndSwapS:
3384   case Op_CompareAndSwapI:
3385   case Op_CompareAndSwapL:
3386   case Op_CompareAndSwapP:
3387   case Op_CompareAndSwapN:
3388   case Op_WeakCompareAndSwapB:
3389   case Op_WeakCompareAndSwapS:
3390   case Op_WeakCompareAndSwapI:
3391   case Op_WeakCompareAndSwapL:
3392   case Op_WeakCompareAndSwapP:
3393   case Op_WeakCompareAndSwapN:
3394   case Op_CompareAndExchangeB:
3395   case Op_CompareAndExchangeS:
3396   case Op_CompareAndExchangeI:
3397   case Op_CompareAndExchangeL:
3398   case Op_CompareAndExchangeP:
3399   case Op_CompareAndExchangeN:
3400   case Op_GetAndAddS:
3401   case Op_GetAndAddB:
3402   case Op_GetAndAddI:
3403   case Op_GetAndAddL:
3404   case Op_GetAndSetS:
3405   case Op_GetAndSetB:
3406   case Op_GetAndSetI:
3407   case Op_GetAndSetL:
3408   case Op_GetAndSetP:
3409   case Op_GetAndSetN:
3410   case Op_StoreP:
3411   case Op_StoreN:
3412   case Op_StoreNKlass:
3413   case Op_LoadB:
3414   case Op_LoadUB:
3415   case Op_LoadUS:
3416   case Op_LoadI:
3417   case Op_LoadKlass:
3418   case Op_LoadNKlass:
3419   case Op_LoadL:
3420   case Op_LoadL_unaligned:
3421   case Op_LoadPLocked:
3422   case Op_LoadP:
3423 #if INCLUDE_ZGC
3424   case Op_LoadBarrierSlowReg:
3425   case Op_LoadBarrierWeakSlowReg:
3426 #endif
3427   case Op_LoadN:
3428   case Op_LoadRange:
3429   case Op_LoadS: {
3430   handle_mem:
3431 #ifdef ASSERT
3432     if( VerifyOptoOopOffsets ) {
3433       assert( n->is_Mem(), "" );
3434       MemNode *mem  = (MemNode*)n;
3435       // Check to see if address types have grounded out somehow.
3436       const TypeInstPtr *tp = mem->in(MemNode::Address)->bottom_type()->isa_instptr();
3437       assert( !tp || oop_offset_is_sane(tp), "" );
3438     }
3439 #endif
3440     break;
3441   }
3442 
3443   case Op_AddP: {               // Assert sane base pointers
3444     Node *addp = n->in(AddPNode::Address);
3445     assert( !addp->is_AddP() ||
3446             addp->in(AddPNode::Base)->is_top() || // Top OK for allocation
3447             addp->in(AddPNode::Base) == n->in(AddPNode::Base),
3448             "Base pointers must match (addp %u)", addp->_idx );
3449 #ifdef _LP64
3450     if ((UseCompressedOops || UseCompressedClassPointers) &&
3451         addp->Opcode() == Op_ConP &&
3452         addp == n->in(AddPNode::Base) &&
3453         n->in(AddPNode::Offset)->is_Con()) {
3454       // If the transformation of ConP to ConN+DecodeN is beneficial depends
3455       // on the platform and on the compressed oops mode.
3456       // Use addressing with narrow klass to load with offset on x86.
3457       // Some platforms can use the constant pool to load ConP.
3458       // Do this transformation here since IGVN will convert ConN back to ConP.
3459       const Type* t = addp->bottom_type();
3460       bool is_oop   = t->isa_oopptr() != NULL;
3461       bool is_klass = t->isa_klassptr() != NULL;
3462 
3463       if ((is_oop   && Matcher::const_oop_prefer_decode()  ) ||
3464           (is_klass && Matcher::const_klass_prefer_decode())) {
3465         Node* nn = NULL;
3466 
3467         int op = is_oop ? Op_ConN : Op_ConNKlass;
3468 
3469         // Look for existing ConN node of the same exact type.
3470         Node* r  = root();
3471         uint cnt = r->outcnt();
3472         for (uint i = 0; i < cnt; i++) {
3473           Node* m = r->raw_out(i);
3474           if (m!= NULL && m->Opcode() == op &&
3475               m->bottom_type()->make_ptr() == t) {
3476             nn = m;
3477             break;
3478           }
3479         }
3480         if (nn != NULL) {
3481           // Decode a narrow oop to match address
3482           // [R12 + narrow_oop_reg<<3 + offset]
3483           if (is_oop) {
3484             nn = new DecodeNNode(nn, t);
3485           } else {
3486             nn = new DecodeNKlassNode(nn, t);
3487           }
3488           // Check for succeeding AddP which uses the same Base.
3489           // Otherwise we will run into the assertion above when visiting that guy.
3490           for (uint i = 0; i < n->outcnt(); ++i) {
3491             Node *out_i = n->raw_out(i);
3492             if (out_i && out_i->is_AddP() && out_i->in(AddPNode::Base) == addp) {
3493               out_i->set_req(AddPNode::Base, nn);
3494 #ifdef ASSERT
3495               for (uint j = 0; j < out_i->outcnt(); ++j) {
3496                 Node *out_j = out_i->raw_out(j);
3497                 assert(out_j == NULL || !out_j->is_AddP() || out_j->in(AddPNode::Base) != addp,
3498                        "more than 2 AddP nodes in a chain (out_j %u)", out_j->_idx);
3499               }
3500 #endif
3501             }
3502           }
3503           n->set_req(AddPNode::Base, nn);
3504           n->set_req(AddPNode::Address, nn);
3505           if (addp->outcnt() == 0) {
3506             addp->disconnect_inputs(NULL, this);
3507           }
3508         }
3509       }
3510     }
3511 #endif
3512     // platform dependent reshaping of the address expression
3513     reshape_address(n->as_AddP());
3514     break;
3515   }
3516 
3517   case Op_CastPP: {
3518     // Remove CastPP nodes to gain more freedom during scheduling but
3519     // keep the dependency they encode as control or precedence edges
3520     // (if control is set already) on memory operations. Some CastPP
3521     // nodes don't have a control (don't carry a dependency): skip
3522     // those.
3523     if (n->in(0) != NULL) {
3524       ResourceMark rm;
3525       Unique_Node_List wq;
3526       wq.push(n);
3527       for (uint next = 0; next < wq.size(); ++next) {
3528         Node *m = wq.at(next);
3529         for (DUIterator_Fast imax, i = m->fast_outs(imax); i < imax; i++) {
3530           Node* use = m->fast_out(i);
3531           if (use->is_Mem() || use->is_EncodeNarrowPtr()) {
3532             use->ensure_control_or_add_prec(n->in(0));
3533           } else {
3534             switch(use->Opcode()) {
3535             case Op_AddP:
3536             case Op_DecodeN:
3537             case Op_DecodeNKlass:
3538             case Op_CheckCastPP:
3539             case Op_CastPP:
3540               wq.push(use);
3541               break;
3542             }
3543           }
3544         }
3545       }
3546     }
3547     const bool is_LP64 = LP64_ONLY(true) NOT_LP64(false);
3548     if (is_LP64 && n->in(1)->is_DecodeN() && Matcher::gen_narrow_oop_implicit_null_checks()) {
3549       Node* in1 = n->in(1);
3550       const Type* t = n->bottom_type();
3551       Node* new_in1 = in1->clone();
3552       new_in1->as_DecodeN()->set_type(t);
3553 
3554       if (!Matcher::narrow_oop_use_complex_address()) {
3555         //
3556         // x86, ARM and friends can handle 2 adds in addressing mode
3557         // and Matcher can fold a DecodeN node into address by using
3558         // a narrow oop directly and do implicit NULL check in address:
3559         //
3560         // [R12 + narrow_oop_reg<<3 + offset]
3561         // NullCheck narrow_oop_reg
3562         //
3563         // On other platforms (Sparc) we have to keep new DecodeN node and
3564         // use it to do implicit NULL check in address:
3565         //
3566         // decode_not_null narrow_oop_reg, base_reg
3567         // [base_reg + offset]
3568         // NullCheck base_reg
3569         //
3570         // Pin the new DecodeN node to non-null path on these platform (Sparc)
3571         // to keep the information to which NULL check the new DecodeN node
3572         // corresponds to use it as value in implicit_null_check().
3573         //
3574         new_in1->set_req(0, n->in(0));
3575       }
3576 
3577       n->subsume_by(new_in1, this);
3578       if (in1->outcnt() == 0) {
3579         in1->disconnect_inputs(NULL, this);
3580       }
3581     } else {
3582       n->subsume_by(n->in(1), this);
3583       if (n->outcnt() == 0) {
3584         n->disconnect_inputs(NULL, this);
3585       }
3586     }
3587     break;
3588   }
3589 #ifdef _LP64
3590   case Op_CmpP:
3591     // Do this transformation here to preserve CmpPNode::sub() and
3592     // other TypePtr related Ideal optimizations (for example, ptr nullness).
3593     if (n->in(1)->is_DecodeNarrowPtr() || n->in(2)->is_DecodeNarrowPtr()) {
3594       Node* in1 = n->in(1);
3595       Node* in2 = n->in(2);
3596       if (!in1->is_DecodeNarrowPtr()) {
3597         in2 = in1;
3598         in1 = n->in(2);
3599       }
3600       assert(in1->is_DecodeNarrowPtr(), "sanity");
3601 
3602       Node* new_in2 = NULL;
3603       if (in2->is_DecodeNarrowPtr()) {
3604         assert(in2->Opcode() == in1->Opcode(), "must be same node type");
3605         new_in2 = in2->in(1);
3606       } else if (in2->Opcode() == Op_ConP) {
3607         const Type* t = in2->bottom_type();
3608         if (t == TypePtr::NULL_PTR) {
3609           assert(in1->is_DecodeN(), "compare klass to null?");
3610           // Don't convert CmpP null check into CmpN if compressed
3611           // oops implicit null check is not generated.
3612           // This will allow to generate normal oop implicit null check.
3613           if (Matcher::gen_narrow_oop_implicit_null_checks())
3614             new_in2 = ConNode::make(TypeNarrowOop::NULL_PTR);
3615           //
3616           // This transformation together with CastPP transformation above
3617           // will generated code for implicit NULL checks for compressed oops.
3618           //
3619           // The original code after Optimize()
3620           //
3621           //    LoadN memory, narrow_oop_reg
3622           //    decode narrow_oop_reg, base_reg
3623           //    CmpP base_reg, NULL
3624           //    CastPP base_reg // NotNull
3625           //    Load [base_reg + offset], val_reg
3626           //
3627           // after these transformations will be
3628           //
3629           //    LoadN memory, narrow_oop_reg
3630           //    CmpN narrow_oop_reg, NULL
3631           //    decode_not_null narrow_oop_reg, base_reg
3632           //    Load [base_reg + offset], val_reg
3633           //
3634           // and the uncommon path (== NULL) will use narrow_oop_reg directly
3635           // since narrow oops can be used in debug info now (see the code in
3636           // final_graph_reshaping_walk()).
3637           //
3638           // At the end the code will be matched to
3639           // on x86:
3640           //
3641           //    Load_narrow_oop memory, narrow_oop_reg
3642           //    Load [R12 + narrow_oop_reg<<3 + offset], val_reg
3643           //    NullCheck narrow_oop_reg
3644           //
3645           // and on sparc:
3646           //
3647           //    Load_narrow_oop memory, narrow_oop_reg
3648           //    decode_not_null narrow_oop_reg, base_reg
3649           //    Load [base_reg + offset], val_reg
3650           //    NullCheck base_reg
3651           //
3652         } else if (t->isa_oopptr()) {
3653           new_in2 = ConNode::make(t->make_narrowoop());
3654         } else if (t->isa_klassptr()) {
3655           new_in2 = ConNode::make(t->make_narrowklass());
3656         }
3657       }
3658       if (new_in2 != NULL) {
3659         Node* cmpN = new CmpNNode(in1->in(1), new_in2);
3660         n->subsume_by(cmpN, this);
3661         if (in1->outcnt() == 0) {
3662           in1->disconnect_inputs(NULL, this);
3663         }
3664         if (in2->outcnt() == 0) {
3665           in2->disconnect_inputs(NULL, this);
3666         }
3667       }
3668     }
3669     break;
3670 
3671   case Op_DecodeN:
3672   case Op_DecodeNKlass:
3673     assert(!n->in(1)->is_EncodeNarrowPtr(), "should be optimized out");
3674     // DecodeN could be pinned when it can't be fold into
3675     // an address expression, see the code for Op_CastPP above.
3676     assert(n->in(0) == NULL || (UseCompressedOops && !Matcher::narrow_oop_use_complex_address()), "no control");
3677     break;
3678 
3679   case Op_EncodeP:
3680   case Op_EncodePKlass: {
3681     Node* in1 = n->in(1);
3682     if (in1->is_DecodeNarrowPtr()) {
3683       n->subsume_by(in1->in(1), this);
3684     } else if (in1->Opcode() == Op_ConP) {
3685       const Type* t = in1->bottom_type();
3686       if (t == TypePtr::NULL_PTR) {
3687         assert(t->isa_oopptr(), "null klass?");
3688         n->subsume_by(ConNode::make(TypeNarrowOop::NULL_PTR), this);
3689       } else if (t->isa_oopptr()) {
3690         n->subsume_by(ConNode::make(t->make_narrowoop()), this);
3691       } else if (t->isa_klassptr()) {
3692         n->subsume_by(ConNode::make(t->make_narrowklass()), this);
3693       }
3694     }
3695     if (in1->outcnt() == 0) {
3696       in1->disconnect_inputs(NULL, this);
3697     }
3698     break;
3699   }
3700 
3701   case Op_Proj: {
3702     if (OptimizeStringConcat) {
3703       ProjNode* p = n->as_Proj();
3704       if (p->_is_io_use) {
3705         // Separate projections were used for the exception path which
3706         // are normally removed by a late inline.  If it wasn't inlined
3707         // then they will hang around and should just be replaced with
3708         // the original one.
3709         Node* proj = NULL;
3710         // Replace with just one
3711         for (SimpleDUIterator i(p->in(0)); i.has_next(); i.next()) {
3712           Node *use = i.get();
3713           if (use->is_Proj() && p != use && use->as_Proj()->_con == p->_con) {
3714             proj = use;
3715             break;
3716           }
3717         }
3718         assert(proj != NULL, "must be found");
3719         p->subsume_by(proj, this);
3720       }
3721     }
3722     break;
3723   }
3724 
3725   case Op_Phi:
3726     if (n->as_Phi()->bottom_type()->isa_narrowoop() || n->as_Phi()->bottom_type()->isa_narrowklass()) {
3727       // The EncodeP optimization may create Phi with the same edges
3728       // for all paths. It is not handled well by Register Allocator.
3729       Node* unique_in = n->in(1);
3730       assert(unique_in != NULL, "");
3731       uint cnt = n->req();
3732       for (uint i = 2; i < cnt; i++) {
3733         Node* m = n->in(i);
3734         assert(m != NULL, "");
3735         if (unique_in != m)
3736           unique_in = NULL;
3737       }
3738       if (unique_in != NULL) {
3739         n->subsume_by(unique_in, this);
3740       }
3741     }
3742     break;
3743 
3744 #endif
3745 
3746 #ifdef ASSERT
3747   case Op_CastII:
3748     // Verify that all range check dependent CastII nodes were removed.
3749     if (n->isa_CastII()->has_range_check()) {
3750       n->dump(3);
3751       assert(false, "Range check dependent CastII node was not removed");
3752     }
3753     break;
3754 #endif
3755 
3756   case Op_ModI:
3757     if (UseDivMod) {
3758       // Check if a%b and a/b both exist
3759       Node* d = n->find_similar(Op_DivI);
3760       if (d) {
3761         // Replace them with a fused divmod if supported
3762         if (Matcher::has_match_rule(Op_DivModI)) {
3763           DivModINode* divmod = DivModINode::make(n);
3764           d->subsume_by(divmod->div_proj(), this);
3765           n->subsume_by(divmod->mod_proj(), this);
3766         } else {
3767           // replace a%b with a-((a/b)*b)
3768           Node* mult = new MulINode(d, d->in(2));
3769           Node* sub  = new SubINode(d->in(1), mult);
3770           n->subsume_by(sub, this);
3771         }
3772       }
3773     }
3774     break;
3775 
3776   case Op_ModL:
3777     if (UseDivMod) {
3778       // Check if a%b and a/b both exist
3779       Node* d = n->find_similar(Op_DivL);
3780       if (d) {
3781         // Replace them with a fused divmod if supported
3782         if (Matcher::has_match_rule(Op_DivModL)) {
3783           DivModLNode* divmod = DivModLNode::make(n);
3784           d->subsume_by(divmod->div_proj(), this);
3785           n->subsume_by(divmod->mod_proj(), this);
3786         } else {
3787           // replace a%b with a-((a/b)*b)
3788           Node* mult = new MulLNode(d, d->in(2));
3789           Node* sub  = new SubLNode(d->in(1), mult);
3790           n->subsume_by(sub, this);
3791         }
3792       }
3793     }
3794     break;
3795 
3796   case Op_LoadVector:
3797   case Op_StoreVector:
3798     break;
3799 
3800   case Op_AddReductionVI:
3801   case Op_AddReductionVL:
3802   case Op_AddReductionVF:
3803   case Op_AddReductionVD:
3804   case Op_MulReductionVI:
3805   case Op_MulReductionVL:
3806   case Op_MulReductionVF:
3807   case Op_MulReductionVD:
3808   case Op_MinReductionV:
3809   case Op_MaxReductionV:
3810   case Op_AndReductionV:
3811   case Op_OrReductionV:
3812   case Op_XorReductionV:
3813   case Op_SubReductionV:
3814   case Op_SubReductionVFP:
3815     break;
3816 
3817   case Op_PackB:
3818   case Op_PackS:
3819   case Op_PackI:
3820   case Op_PackF:
3821   case Op_PackL:
3822   case Op_PackD:
3823     if (n->req()-1 > 2) {
3824       // Replace many operand PackNodes with a binary tree for matching
3825       PackNode* p = (PackNode*) n;
3826       Node* btp = p->binary_tree_pack(1, n->req());
3827       n->subsume_by(btp, this);
3828     }
3829     break;
3830   case Op_Loop:
3831   case Op_CountedLoop:
3832   case Op_OuterStripMinedLoop:
3833     if (n->as_Loop()->is_inner_loop()) {
3834       frc.inc_inner_loop_count();
3835     }
3836     n->as_Loop()->verify_strip_mined(0);
3837     break;
3838   case Op_LShiftI:
3839   case Op_RShiftI:
3840   case Op_URShiftI:
3841   case Op_LShiftL:
3842   case Op_RShiftL:
3843   case Op_URShiftL:
3844     if (Matcher::need_masked_shift_count) {
3845       // The cpu's shift instructions don't restrict the count to the
3846       // lower 5/6 bits. We need to do the masking ourselves.
3847       Node* in2 = n->in(2);
3848       juint mask = (n->bottom_type() == TypeInt::INT) ? (BitsPerInt - 1) : (BitsPerLong - 1);
3849       const TypeInt* t = in2->find_int_type();
3850       if (t != NULL && t->is_con()) {
3851         juint shift = t->get_con();
3852         if (shift > mask) { // Unsigned cmp
3853           n->set_req(2, ConNode::make(TypeInt::make(shift & mask)));
3854         }
3855       } else {
3856         if (t == NULL || t->_lo < 0 || t->_hi > (int)mask) {
3857           Node* shift = new AndINode(in2, ConNode::make(TypeInt::make(mask)));
3858           n->set_req(2, shift);
3859         }
3860       }
3861       if (in2->outcnt() == 0) { // Remove dead node
3862         in2->disconnect_inputs(NULL, this);
3863       }
3864     }
3865     break;
3866   case Op_MemBarStoreStore:
3867   case Op_MemBarRelease:
3868     // Break the link with AllocateNode: it is no longer useful and
3869     // confuses register allocation.
3870     if (n->req() > MemBarNode::Precedent) {
3871       n->set_req(MemBarNode::Precedent, top());
3872     }
3873     break;
3874   case Op_RangeCheck: {
3875     RangeCheckNode* rc = n->as_RangeCheck();
3876     Node* iff = new IfNode(rc->in(0), rc->in(1), rc->_prob, rc->_fcnt);
3877     n->subsume_by(iff, this);
3878     frc._tests.push(iff);
3879     break;
3880   }
3881   case Op_ConvI2L: {
3882     if (!Matcher::convi2l_type_required) {
3883       // Code generation on some platforms doesn't need accurate
3884       // ConvI2L types. Widening the type can help remove redundant
3885       // address computations.
3886       n->as_Type()->set_type(TypeLong::INT);
3887       ResourceMark rm;
3888       Node_List wq;
3889       wq.push(n);
3890       for (uint next = 0; next < wq.size(); next++) {
3891         Node *m = wq.at(next);
3892 
3893         for(;;) {
3894           // Loop over all nodes with identical inputs edges as m
3895           Node* k = m->find_similar(m->Opcode());
3896           if (k == NULL) {
3897             break;
3898           }
3899           // Push their uses so we get a chance to remove node made
3900           // redundant
3901           for (DUIterator_Fast imax, i = k->fast_outs(imax); i < imax; i++) {
3902             Node* u = k->fast_out(i);
3903             assert(!wq.contains(u), "shouldn't process one node several times");
3904             if (u->Opcode() == Op_LShiftL ||
3905                 u->Opcode() == Op_AddL ||
3906                 u->Opcode() == Op_SubL ||
3907                 u->Opcode() == Op_AddP) {
3908               wq.push(u);
3909             }
3910           }
3911           // Replace all nodes with identical edges as m with m
3912           k->subsume_by(m, this);
3913         }
3914       }
3915     }
3916     break;
3917   }
3918   case Op_CmpUL: {
3919     if (!Matcher::has_match_rule(Op_CmpUL)) {
3920       // We don't support unsigned long comparisons. Set 'max_idx_expr'
3921       // to max_julong if < 0 to make the signed comparison fail.
3922       ConINode* sign_pos = new ConINode(TypeInt::make(BitsPerLong - 1));
3923       Node* sign_bit_mask = new RShiftLNode(n->in(1), sign_pos);
3924       Node* orl = new OrLNode(n->in(1), sign_bit_mask);
3925       ConLNode* remove_sign_mask = new ConLNode(TypeLong::make(max_jlong));
3926       Node* andl = new AndLNode(orl, remove_sign_mask);
3927       Node* cmp = new CmpLNode(andl, n->in(2));
3928       n->subsume_by(cmp, this);
3929     }
3930     break;
3931   }
3932   default:
3933     assert( !n->is_Call(), "" );
3934     assert( !n->is_Mem(), "" );
3935     assert( nop != Op_ProfileBoolean, "should be eliminated during IGVN");
3936     break;
3937   }
3938 
3939   // Collect CFG split points
3940   if (n->is_MultiBranch() && !n->is_RangeCheck()) {
3941     frc._tests.push(n);
3942   }
3943 }
3944 
3945 //------------------------------final_graph_reshaping_walk---------------------
3946 // Replacing Opaque nodes with their input in final_graph_reshaping_impl(),
3947 // requires that the walk visits a node's inputs before visiting the node.
3948 void Compile::final_graph_reshaping_walk( Node_Stack &nstack, Node *root, Final_Reshape_Counts &frc ) {
3949   ResourceArea *area = Thread::current()->resource_area();
3950   Unique_Node_List sfpt(area);
3951 
3952   frc._visited.set(root->_idx); // first, mark node as visited
3953   uint cnt = root->req();
3954   Node *n = root;
3955   uint  i = 0;
3956   while (true) {
3957     if (i < cnt) {
3958       // Place all non-visited non-null inputs onto stack
3959       Node* m = n->in(i);
3960       ++i;
3961       if (m != NULL && !frc._visited.test_set(m->_idx)) {
3962         if (m->is_SafePoint() && m->as_SafePoint()->jvms() != NULL) {
3963           // compute worst case interpreter size in case of a deoptimization
3964           update_interpreter_frame_size(m->as_SafePoint()->jvms()->interpreter_frame_size());
3965 
3966           sfpt.push(m);
3967         }
3968         cnt = m->req();
3969         nstack.push(n, i); // put on stack parent and next input's index
3970         n = m;
3971         i = 0;
3972       }
3973     } else {
3974       // Now do post-visit work
3975       final_graph_reshaping_impl( n, frc );
3976       if (nstack.is_empty())
3977         break;             // finished
3978       n = nstack.node();   // Get node from stack
3979       cnt = n->req();
3980       i = nstack.index();
3981       nstack.pop();        // Shift to the next node on stack
3982     }
3983   }
3984 
3985   // Skip next transformation if compressed oops are not used.
3986   if ((UseCompressedOops && !Matcher::gen_narrow_oop_implicit_null_checks()) ||
3987       (!UseCompressedOops && !UseCompressedClassPointers))
3988     return;
3989 
3990   // Go over safepoints nodes to skip DecodeN/DecodeNKlass nodes for debug edges.
3991   // It could be done for an uncommon traps or any safepoints/calls
3992   // if the DecodeN/DecodeNKlass node is referenced only in a debug info.
3993   while (sfpt.size() > 0) {
3994     n = sfpt.pop();
3995     JVMState *jvms = n->as_SafePoint()->jvms();
3996     assert(jvms != NULL, "sanity");
3997     int start = jvms->debug_start();
3998     int end   = n->req();
3999     bool is_uncommon = (n->is_CallStaticJava() &&
4000                         n->as_CallStaticJava()->uncommon_trap_request() != 0);
4001     for (int j = start; j < end; j++) {
4002       Node* in = n->in(j);
4003       if (in->is_DecodeNarrowPtr()) {
4004         bool safe_to_skip = true;
4005         if (!is_uncommon ) {
4006           // Is it safe to skip?
4007           for (uint i = 0; i < in->outcnt(); i++) {
4008             Node* u = in->raw_out(i);
4009             if (!u->is_SafePoint() ||
4010                 (u->is_Call() && u->as_Call()->has_non_debug_use(n))) {
4011               safe_to_skip = false;
4012             }
4013           }
4014         }
4015         if (safe_to_skip) {
4016           n->set_req(j, in->in(1));
4017         }
4018         if (in->outcnt() == 0) {
4019           in->disconnect_inputs(NULL, this);
4020         }
4021       }
4022     }
4023   }
4024 }
4025 
4026 //------------------------------final_graph_reshaping--------------------------
4027 // Final Graph Reshaping.
4028 //
4029 // (1) Clone simple inputs to uncommon calls, so they can be scheduled late
4030 //     and not commoned up and forced early.  Must come after regular
4031 //     optimizations to avoid GVN undoing the cloning.  Clone constant
4032 //     inputs to Loop Phis; these will be split by the allocator anyways.
4033 //     Remove Opaque nodes.
4034 // (2) Move last-uses by commutative operations to the left input to encourage
4035 //     Intel update-in-place two-address operations and better register usage
4036 //     on RISCs.  Must come after regular optimizations to avoid GVN Ideal
4037 //     calls canonicalizing them back.
4038 // (3) Count the number of double-precision FP ops, single-precision FP ops
4039 //     and call sites.  On Intel, we can get correct rounding either by
4040 //     forcing singles to memory (requires extra stores and loads after each
4041 //     FP bytecode) or we can set a rounding mode bit (requires setting and
4042 //     clearing the mode bit around call sites).  The mode bit is only used
4043 //     if the relative frequency of single FP ops to calls is low enough.
4044 //     This is a key transform for SPEC mpeg_audio.
4045 // (4) Detect infinite loops; blobs of code reachable from above but not
4046 //     below.  Several of the Code_Gen algorithms fail on such code shapes,
4047 //     so we simply bail out.  Happens a lot in ZKM.jar, but also happens
4048 //     from time to time in other codes (such as -Xcomp finalizer loops, etc).
4049 //     Detection is by looking for IfNodes where only 1 projection is
4050 //     reachable from below or CatchNodes missing some targets.
4051 // (5) Assert for insane oop offsets in debug mode.
4052 
4053 bool Compile::final_graph_reshaping() {
4054   // an infinite loop may have been eliminated by the optimizer,
4055   // in which case the graph will be empty.
4056   if (root()->req() == 1) {
4057     record_method_not_compilable("trivial infinite loop");
4058     return true;
4059   }
4060 
4061   // Expensive nodes have their control input set to prevent the GVN
4062   // from freely commoning them. There's no GVN beyond this point so
4063   // no need to keep the control input. We want the expensive nodes to
4064   // be freely moved to the least frequent code path by gcm.
4065   assert(OptimizeExpensiveOps || expensive_count() == 0, "optimization off but list non empty?");
4066   for (int i = 0; i < expensive_count(); i++) {
4067     _expensive_nodes->at(i)->set_req(0, NULL);
4068   }
4069 
4070   Final_Reshape_Counts frc;
4071 
4072   // Visit everybody reachable!
4073   // Allocate stack of size C->live_nodes()/2 to avoid frequent realloc
4074   Node_Stack nstack(live_nodes() >> 1);
4075   final_graph_reshaping_walk(nstack, root(), frc);
4076 
4077   // Check for unreachable (from below) code (i.e., infinite loops).
4078   for( uint i = 0; i < frc._tests.size(); i++ ) {
4079     MultiBranchNode *n = frc._tests[i]->as_MultiBranch();
4080     // Get number of CFG targets.
4081     // Note that PCTables include exception targets after calls.
4082     uint required_outcnt = n->required_outcnt();
4083     if (n->outcnt() != required_outcnt) {
4084       // Check for a few special cases.  Rethrow Nodes never take the
4085       // 'fall-thru' path, so expected kids is 1 less.
4086       if (n->is_PCTable() && n->in(0) && n->in(0)->in(0)) {
4087         if (n->in(0)->in(0)->is_Call()) {
4088           CallNode *call = n->in(0)->in(0)->as_Call();
4089           if (call->entry_point() == OptoRuntime::rethrow_stub()) {
4090             required_outcnt--;      // Rethrow always has 1 less kid
4091           } else if (call->req() > TypeFunc::Parms &&
4092                      call->is_CallDynamicJava()) {
4093             // Check for null receiver. In such case, the optimizer has
4094             // detected that the virtual call will always result in a null
4095             // pointer exception. The fall-through projection of this CatchNode
4096             // will not be populated.
4097             Node *arg0 = call->in(TypeFunc::Parms);
4098             if (arg0->is_Type() &&
4099                 arg0->as_Type()->type()->higher_equal(TypePtr::NULL_PTR)) {
4100               required_outcnt--;
4101             }
4102           } else if (call->entry_point() == OptoRuntime::new_array_Java() &&
4103                      call->req() > TypeFunc::Parms+1 &&
4104                      call->is_CallStaticJava()) {
4105             // Check for negative array length. In such case, the optimizer has
4106             // detected that the allocation attempt will always result in an
4107             // exception. There is no fall-through projection of this CatchNode .
4108             Node *arg1 = call->in(TypeFunc::Parms+1);
4109             if (arg1->is_Type() &&
4110                 arg1->as_Type()->type()->join(TypeInt::POS)->empty()) {
4111               required_outcnt--;
4112             }
4113           }
4114         }
4115       }
4116       // Recheck with a better notion of 'required_outcnt'
4117       if (n->outcnt() != required_outcnt) {
4118         record_method_not_compilable("malformed control flow");
4119         return true;            // Not all targets reachable!
4120       }
4121     }
4122     // Check that I actually visited all kids.  Unreached kids
4123     // must be infinite loops.
4124     for (DUIterator_Fast jmax, j = n->fast_outs(jmax); j < jmax; j++)
4125       if (!frc._visited.test(n->fast_out(j)->_idx)) {
4126         record_method_not_compilable("infinite loop");
4127         return true;            // Found unvisited kid; must be unreach
4128       }
4129 
4130     // Here so verification code in final_graph_reshaping_walk()
4131     // always see an OuterStripMinedLoopEnd
4132     if (n->is_OuterStripMinedLoopEnd()) {
4133       IfNode* init_iff = n->as_If();
4134       Node* iff = new IfNode(init_iff->in(0), init_iff->in(1), init_iff->_prob, init_iff->_fcnt);
4135       n->subsume_by(iff, this);
4136     }
4137   }
4138 
4139   // If original bytecodes contained a mixture of floats and doubles
4140   // check if the optimizer has made it homogenous, item (3).
4141   if( Use24BitFPMode && Use24BitFP && UseSSE == 0 &&
4142       frc.get_float_count() > 32 &&
4143       frc.get_double_count() == 0 &&
4144       (10 * frc.get_call_count() < frc.get_float_count()) ) {
4145     set_24_bit_selection_and_mode( false,  true );
4146   }
4147 
4148   set_java_calls(frc.get_java_call_count());
4149   set_inner_loops(frc.get_inner_loop_count());
4150 
4151   // No infinite loops, no reason to bail out.
4152   return false;
4153 }
4154 
4155 //-----------------------------too_many_traps----------------------------------
4156 // Report if there are too many traps at the current method and bci.
4157 // Return true if there was a trap, and/or PerMethodTrapLimit is exceeded.
4158 bool Compile::too_many_traps(ciMethod* method,
4159                              int bci,
4160                              Deoptimization::DeoptReason reason) {
4161   ciMethodData* md = method->method_data();
4162   if (md->is_empty()) {
4163     // Assume the trap has not occurred, or that it occurred only
4164     // because of a transient condition during start-up in the interpreter.
4165     return false;
4166   }
4167   ciMethod* m = Deoptimization::reason_is_speculate(reason) ? this->method() : NULL;
4168   if (md->has_trap_at(bci, m, reason) != 0) {
4169     // Assume PerBytecodeTrapLimit==0, for a more conservative heuristic.
4170     // Also, if there are multiple reasons, or if there is no per-BCI record,
4171     // assume the worst.
4172     if (log())
4173       log()->elem("observe trap='%s' count='%d'",
4174                   Deoptimization::trap_reason_name(reason),
4175                   md->trap_count(reason));
4176     return true;
4177   } else {
4178     // Ignore method/bci and see if there have been too many globally.
4179     return too_many_traps(reason, md);
4180   }
4181 }
4182 
4183 // Less-accurate variant which does not require a method and bci.
4184 bool Compile::too_many_traps(Deoptimization::DeoptReason reason,
4185                              ciMethodData* logmd) {
4186   if (trap_count(reason) >= Deoptimization::per_method_trap_limit(reason)) {
4187     // Too many traps globally.
4188     // Note that we use cumulative trap_count, not just md->trap_count.
4189     if (log()) {
4190       int mcount = (logmd == NULL)? -1: (int)logmd->trap_count(reason);
4191       log()->elem("observe trap='%s' count='0' mcount='%d' ccount='%d'",
4192                   Deoptimization::trap_reason_name(reason),
4193                   mcount, trap_count(reason));
4194     }
4195     return true;
4196   } else {
4197     // The coast is clear.
4198     return false;
4199   }
4200 }
4201 
4202 //--------------------------too_many_recompiles--------------------------------
4203 // Report if there are too many recompiles at the current method and bci.
4204 // Consults PerBytecodeRecompilationCutoff and PerMethodRecompilationCutoff.
4205 // Is not eager to return true, since this will cause the compiler to use
4206 // Action_none for a trap point, to avoid too many recompilations.
4207 bool Compile::too_many_recompiles(ciMethod* method,
4208                                   int bci,
4209                                   Deoptimization::DeoptReason reason) {
4210   ciMethodData* md = method->method_data();
4211   if (md->is_empty()) {
4212     // Assume the trap has not occurred, or that it occurred only
4213     // because of a transient condition during start-up in the interpreter.
4214     return false;
4215   }
4216   // Pick a cutoff point well within PerBytecodeRecompilationCutoff.
4217   uint bc_cutoff = (uint) PerBytecodeRecompilationCutoff / 8;
4218   uint m_cutoff  = (uint) PerMethodRecompilationCutoff / 2 + 1;  // not zero
4219   Deoptimization::DeoptReason per_bc_reason
4220     = Deoptimization::reason_recorded_per_bytecode_if_any(reason);
4221   ciMethod* m = Deoptimization::reason_is_speculate(reason) ? this->method() : NULL;
4222   if ((per_bc_reason == Deoptimization::Reason_none
4223        || md->has_trap_at(bci, m, reason) != 0)
4224       // The trap frequency measure we care about is the recompile count:
4225       && md->trap_recompiled_at(bci, m)
4226       && md->overflow_recompile_count() >= bc_cutoff) {
4227     // Do not emit a trap here if it has already caused recompilations.
4228     // Also, if there are multiple reasons, or if there is no per-BCI record,
4229     // assume the worst.
4230     if (log())
4231       log()->elem("observe trap='%s recompiled' count='%d' recompiles2='%d'",
4232                   Deoptimization::trap_reason_name(reason),
4233                   md->trap_count(reason),
4234                   md->overflow_recompile_count());
4235     return true;
4236   } else if (trap_count(reason) != 0
4237              && decompile_count() >= m_cutoff) {
4238     // Too many recompiles globally, and we have seen this sort of trap.
4239     // Use cumulative decompile_count, not just md->decompile_count.
4240     if (log())
4241       log()->elem("observe trap='%s' count='%d' mcount='%d' decompiles='%d' mdecompiles='%d'",
4242                   Deoptimization::trap_reason_name(reason),
4243                   md->trap_count(reason), trap_count(reason),
4244                   md->decompile_count(), decompile_count());
4245     return true;
4246   } else {
4247     // The coast is clear.
4248     return false;
4249   }
4250 }
4251 
4252 // Compute when not to trap. Used by matching trap based nodes and
4253 // NullCheck optimization.
4254 void Compile::set_allowed_deopt_reasons() {
4255   _allowed_reasons = 0;
4256   if (is_method_compilation()) {
4257     for (int rs = (int)Deoptimization::Reason_none+1; rs < Compile::trapHistLength; rs++) {
4258       assert(rs < BitsPerInt, "recode bit map");
4259       if (!too_many_traps((Deoptimization::DeoptReason) rs)) {
4260         _allowed_reasons |= nth_bit(rs);
4261       }
4262     }
4263   }
4264 }
4265 
4266 #ifndef PRODUCT
4267 //------------------------------verify_graph_edges---------------------------
4268 // Walk the Graph and verify that there is a one-to-one correspondence
4269 // between Use-Def edges and Def-Use edges in the graph.
4270 void Compile::verify_graph_edges(bool no_dead_code) {
4271   if (VerifyGraphEdges) {
4272     ResourceArea *area = Thread::current()->resource_area();
4273     Unique_Node_List visited(area);
4274     // Call recursive graph walk to check edges
4275     _root->verify_edges(visited);
4276     if (no_dead_code) {
4277       // Now make sure that no visited node is used by an unvisited node.
4278       bool dead_nodes = false;
4279       Unique_Node_List checked(area);
4280       while (visited.size() > 0) {
4281         Node* n = visited.pop();
4282         checked.push(n);
4283         for (uint i = 0; i < n->outcnt(); i++) {
4284           Node* use = n->raw_out(i);
4285           if (checked.member(use))  continue;  // already checked
4286           if (visited.member(use))  continue;  // already in the graph
4287           if (use->is_Con())        continue;  // a dead ConNode is OK
4288           // At this point, we have found a dead node which is DU-reachable.
4289           if (!dead_nodes) {
4290             tty->print_cr("*** Dead nodes reachable via DU edges:");
4291             dead_nodes = true;
4292           }
4293           use->dump(2);
4294           tty->print_cr("---");
4295           checked.push(use);  // No repeats; pretend it is now checked.
4296         }
4297       }
4298       assert(!dead_nodes, "using nodes must be reachable from root");
4299     }
4300   }
4301 }
4302 
4303 // Verify GC barriers consistency
4304 // Currently supported:
4305 // - G1 pre-barriers (see GraphKit::g1_write_barrier_pre())
4306 void Compile::verify_barriers() {
4307 #if INCLUDE_G1GC
4308   if (UseG1GC) {
4309     // Verify G1 pre-barriers
4310     const int marking_offset = in_bytes(G1ThreadLocalData::satb_mark_queue_active_offset());
4311 
4312     ResourceArea *area = Thread::current()->resource_area();
4313     Unique_Node_List visited(area);
4314     Node_List worklist(area);
4315     // We're going to walk control flow backwards starting from the Root
4316     worklist.push(_root);
4317     while (worklist.size() > 0) {
4318       Node* x = worklist.pop();
4319       if (x == NULL || x == top()) continue;
4320       if (visited.member(x)) {
4321         continue;
4322       } else {
4323         visited.push(x);
4324       }
4325 
4326       if (x->is_Region()) {
4327         for (uint i = 1; i < x->req(); i++) {
4328           worklist.push(x->in(i));
4329         }
4330       } else {
4331         worklist.push(x->in(0));
4332         // We are looking for the pattern:
4333         //                            /->ThreadLocal
4334         // If->Bool->CmpI->LoadB->AddP->ConL(marking_offset)
4335         //              \->ConI(0)
4336         // We want to verify that the If and the LoadB have the same control
4337         // See GraphKit::g1_write_barrier_pre()
4338         if (x->is_If()) {
4339           IfNode *iff = x->as_If();
4340           if (iff->in(1)->is_Bool() && iff->in(1)->in(1)->is_Cmp()) {
4341             CmpNode *cmp = iff->in(1)->in(1)->as_Cmp();
4342             if (cmp->Opcode() == Op_CmpI && cmp->in(2)->is_Con() && cmp->in(2)->bottom_type()->is_int()->get_con() == 0
4343                 && cmp->in(1)->is_Load()) {
4344               LoadNode* load = cmp->in(1)->as_Load();
4345               if (load->Opcode() == Op_LoadB && load->in(2)->is_AddP() && load->in(2)->in(2)->Opcode() == Op_ThreadLocal
4346                   && load->in(2)->in(3)->is_Con()
4347                   && load->in(2)->in(3)->bottom_type()->is_intptr_t()->get_con() == marking_offset) {
4348 
4349                 Node* if_ctrl = iff->in(0);
4350                 Node* load_ctrl = load->in(0);
4351 
4352                 if (if_ctrl != load_ctrl) {
4353                   // Skip possible CProj->NeverBranch in infinite loops
4354                   if ((if_ctrl->is_Proj() && if_ctrl->Opcode() == Op_CProj)
4355                       && (if_ctrl->in(0)->is_MultiBranch() && if_ctrl->in(0)->Opcode() == Op_NeverBranch)) {
4356                     if_ctrl = if_ctrl->in(0)->in(0);
4357                   }
4358                 }
4359                 assert(load_ctrl != NULL && if_ctrl == load_ctrl, "controls must match");
4360               }
4361             }
4362           }
4363         }
4364       }
4365     }
4366   }
4367 #endif
4368 }
4369 
4370 #endif
4371 
4372 // The Compile object keeps track of failure reasons separately from the ciEnv.
4373 // This is required because there is not quite a 1-1 relation between the
4374 // ciEnv and its compilation task and the Compile object.  Note that one
4375 // ciEnv might use two Compile objects, if C2Compiler::compile_method decides
4376 // to backtrack and retry without subsuming loads.  Other than this backtracking
4377 // behavior, the Compile's failure reason is quietly copied up to the ciEnv
4378 // by the logic in C2Compiler.
4379 void Compile::record_failure(const char* reason) {
4380   if (log() != NULL) {
4381     log()->elem("failure reason='%s' phase='compile'", reason);
4382   }
4383   if (_failure_reason == NULL) {
4384     // Record the first failure reason.
4385     _failure_reason = reason;
4386   }
4387 
4388   if (!C->failure_reason_is(C2Compiler::retry_no_subsuming_loads())) {
4389     C->print_method(PHASE_FAILURE);
4390   }
4391   _root = NULL;  // flush the graph, too
4392 }
4393 
4394 Compile::TracePhase::TracePhase(const char* name, elapsedTimer* accumulator)
4395   : TraceTime(name, accumulator, CITime, CITimeVerbose),
4396     _phase_name(name), _dolog(CITimeVerbose)
4397 {
4398   if (_dolog) {
4399     C = Compile::current();
4400     _log = C->log();
4401   } else {
4402     C = NULL;
4403     _log = NULL;
4404   }
4405   if (_log != NULL) {
4406     _log->begin_head("phase name='%s' nodes='%d' live='%d'", _phase_name, C->unique(), C->live_nodes());
4407     _log->stamp();
4408     _log->end_head();
4409   }
4410 }
4411 
4412 Compile::TracePhase::~TracePhase() {
4413 
4414   C = Compile::current();
4415   if (_dolog) {
4416     _log = C->log();
4417   } else {
4418     _log = NULL;
4419   }
4420 
4421 #ifdef ASSERT
4422   if (PrintIdealNodeCount) {
4423     tty->print_cr("phase name='%s' nodes='%d' live='%d' live_graph_walk='%d'",
4424                   _phase_name, C->unique(), C->live_nodes(), C->count_live_nodes_by_graph_walk());
4425   }
4426 
4427   if (VerifyIdealNodeCount) {
4428     Compile::current()->print_missing_nodes();
4429   }
4430 #endif
4431 
4432   if (_log != NULL) {
4433     _log->done("phase name='%s' nodes='%d' live='%d'", _phase_name, C->unique(), C->live_nodes());
4434   }
4435 }
4436 
4437 //=============================================================================
4438 // Two Constant's are equal when the type and the value are equal.
4439 bool Compile::Constant::operator==(const Constant& other) {
4440   if (type()          != other.type()         )  return false;
4441   if (can_be_reused() != other.can_be_reused())  return false;
4442   // For floating point values we compare the bit pattern.
4443   switch (type()) {
4444   case T_INT:
4445   case T_FLOAT:   return (_v._value.i == other._v._value.i);
4446   case T_LONG:
4447   case T_DOUBLE:  return (_v._value.j == other._v._value.j);
4448   case T_OBJECT:
4449   case T_ADDRESS: return (_v._value.l == other._v._value.l);
4450   case T_VOID:    return (_v._value.l == other._v._value.l);  // jump-table entries
4451   case T_METADATA: return (_v._metadata == other._v._metadata);
4452   default: ShouldNotReachHere(); return false;
4453   }
4454 }
4455 
4456 static int type_to_size_in_bytes(BasicType t) {
4457   switch (t) {
4458   case T_INT:     return sizeof(jint   );
4459   case T_LONG:    return sizeof(jlong  );
4460   case T_FLOAT:   return sizeof(jfloat );
4461   case T_DOUBLE:  return sizeof(jdouble);
4462   case T_METADATA: return sizeof(Metadata*);
4463     // We use T_VOID as marker for jump-table entries (labels) which
4464     // need an internal word relocation.
4465   case T_VOID:
4466   case T_ADDRESS:
4467   case T_OBJECT:  return sizeof(jobject);
4468   default:
4469     ShouldNotReachHere();
4470     return -1;
4471   }
4472 }
4473 
4474 int Compile::ConstantTable::qsort_comparator(Constant* a, Constant* b) {
4475   // sort descending
4476   if (a->freq() > b->freq())  return -1;
4477   if (a->freq() < b->freq())  return  1;
4478   return 0;
4479 }
4480 
4481 void Compile::ConstantTable::calculate_offsets_and_size() {
4482   // First, sort the array by frequencies.
4483   _constants.sort(qsort_comparator);
4484 
4485 #ifdef ASSERT
4486   // Make sure all jump-table entries were sorted to the end of the
4487   // array (they have a negative frequency).
4488   bool found_void = false;
4489   for (int i = 0; i < _constants.length(); i++) {
4490     Constant con = _constants.at(i);
4491     if (con.type() == T_VOID)
4492       found_void = true;  // jump-tables
4493     else
4494       assert(!found_void, "wrong sorting");
4495   }
4496 #endif
4497 
4498   int offset = 0;
4499   for (int i = 0; i < _constants.length(); i++) {
4500     Constant* con = _constants.adr_at(i);
4501 
4502     // Align offset for type.
4503     int typesize = type_to_size_in_bytes(con->type());
4504     offset = align_up(offset, typesize);
4505     con->set_offset(offset);   // set constant's offset
4506 
4507     if (con->type() == T_VOID) {
4508       MachConstantNode* n = (MachConstantNode*) con->get_jobject();
4509       offset = offset + typesize * n->outcnt();  // expand jump-table
4510     } else {
4511       offset = offset + typesize;
4512     }
4513   }
4514 
4515   // Align size up to the next section start (which is insts; see
4516   // CodeBuffer::align_at_start).
4517   assert(_size == -1, "already set?");
4518   _size = align_up(offset, (int)CodeEntryAlignment);
4519 }
4520 
4521 void Compile::ConstantTable::emit(CodeBuffer& cb) {
4522   MacroAssembler _masm(&cb);
4523   for (int i = 0; i < _constants.length(); i++) {
4524     Constant con = _constants.at(i);
4525     address constant_addr = NULL;
4526     switch (con.type()) {
4527     case T_INT:    constant_addr = _masm.int_constant(   con.get_jint()   ); break;
4528     case T_LONG:   constant_addr = _masm.long_constant(  con.get_jlong()  ); break;
4529     case T_FLOAT:  constant_addr = _masm.float_constant( con.get_jfloat() ); break;
4530     case T_DOUBLE: constant_addr = _masm.double_constant(con.get_jdouble()); break;
4531     case T_OBJECT: {
4532       jobject obj = con.get_jobject();
4533       int oop_index = _masm.oop_recorder()->find_index(obj);
4534       constant_addr = _masm.address_constant((address) obj, oop_Relocation::spec(oop_index));
4535       break;
4536     }
4537     case T_ADDRESS: {
4538       address addr = (address) con.get_jobject();
4539       constant_addr = _masm.address_constant(addr);
4540       break;
4541     }
4542     // We use T_VOID as marker for jump-table entries (labels) which
4543     // need an internal word relocation.
4544     case T_VOID: {
4545       MachConstantNode* n = (MachConstantNode*) con.get_jobject();
4546       // Fill the jump-table with a dummy word.  The real value is
4547       // filled in later in fill_jump_table.
4548       address dummy = (address) n;
4549       constant_addr = _masm.address_constant(dummy);
4550       // Expand jump-table
4551       for (uint i = 1; i < n->outcnt(); i++) {
4552         address temp_addr = _masm.address_constant(dummy + i);
4553         assert(temp_addr, "consts section too small");
4554       }
4555       break;
4556     }
4557     case T_METADATA: {
4558       Metadata* obj = con.get_metadata();
4559       int metadata_index = _masm.oop_recorder()->find_index(obj);
4560       constant_addr = _masm.address_constant((address) obj, metadata_Relocation::spec(metadata_index));
4561       break;
4562     }
4563     default: ShouldNotReachHere();
4564     }
4565     assert(constant_addr, "consts section too small");
4566     assert((constant_addr - _masm.code()->consts()->start()) == con.offset(),
4567             "must be: %d == %d", (int) (constant_addr - _masm.code()->consts()->start()), (int)(con.offset()));
4568   }
4569 }
4570 
4571 int Compile::ConstantTable::find_offset(Constant& con) const {
4572   int idx = _constants.find(con);
4573   guarantee(idx != -1, "constant must be in constant table");
4574   int offset = _constants.at(idx).offset();
4575   guarantee(offset != -1, "constant table not emitted yet?");
4576   return offset;
4577 }
4578 
4579 void Compile::ConstantTable::add(Constant& con) {
4580   if (con.can_be_reused()) {
4581     int idx = _constants.find(con);
4582     if (idx != -1 && _constants.at(idx).can_be_reused()) {
4583       _constants.adr_at(idx)->inc_freq(con.freq());  // increase the frequency by the current value
4584       return;
4585     }
4586   }
4587   (void) _constants.append(con);
4588 }
4589 
4590 Compile::Constant Compile::ConstantTable::add(MachConstantNode* n, BasicType type, jvalue value) {
4591   Block* b = Compile::current()->cfg()->get_block_for_node(n);
4592   Constant con(type, value, b->_freq);
4593   add(con);
4594   return con;
4595 }
4596 
4597 Compile::Constant Compile::ConstantTable::add(Metadata* metadata) {
4598   Constant con(metadata);
4599   add(con);
4600   return con;
4601 }
4602 
4603 Compile::Constant Compile::ConstantTable::add(MachConstantNode* n, MachOper* oper) {
4604   jvalue value;
4605   BasicType type = oper->type()->basic_type();
4606   switch (type) {
4607   case T_LONG:    value.j = oper->constantL(); break;
4608   case T_FLOAT:   value.f = oper->constantF(); break;
4609   case T_DOUBLE:  value.d = oper->constantD(); break;
4610   case T_OBJECT:
4611   case T_ADDRESS: value.l = (jobject) oper->constant(); break;
4612   case T_METADATA: return add((Metadata*)oper->constant()); break;
4613   default: guarantee(false, "unhandled type: %s", type2name(type));
4614   }
4615   return add(n, type, value);
4616 }
4617 
4618 Compile::Constant Compile::ConstantTable::add_jump_table(MachConstantNode* n) {
4619   jvalue value;
4620   // We can use the node pointer here to identify the right jump-table
4621   // as this method is called from Compile::Fill_buffer right before
4622   // the MachNodes are emitted and the jump-table is filled (means the
4623   // MachNode pointers do not change anymore).
4624   value.l = (jobject) n;
4625   Constant con(T_VOID, value, next_jump_table_freq(), false);  // Labels of a jump-table cannot be reused.
4626   add(con);
4627   return con;
4628 }
4629 
4630 void Compile::ConstantTable::fill_jump_table(CodeBuffer& cb, MachConstantNode* n, GrowableArray<Label*> labels) const {
4631   // If called from Compile::scratch_emit_size do nothing.
4632   if (Compile::current()->in_scratch_emit_size())  return;
4633 
4634   assert(labels.is_nonempty(), "must be");
4635   assert((uint) labels.length() == n->outcnt(), "must be equal: %d == %d", labels.length(), n->outcnt());
4636 
4637   // Since MachConstantNode::constant_offset() also contains
4638   // table_base_offset() we need to subtract the table_base_offset()
4639   // to get the plain offset into the constant table.
4640   int offset = n->constant_offset() - table_base_offset();
4641 
4642   MacroAssembler _masm(&cb);
4643   address* jump_table_base = (address*) (_masm.code()->consts()->start() + offset);
4644 
4645   for (uint i = 0; i < n->outcnt(); i++) {
4646     address* constant_addr = &jump_table_base[i];
4647     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));
4648     *constant_addr = cb.consts()->target(*labels.at(i), (address) constant_addr);
4649     cb.consts()->relocate((address) constant_addr, relocInfo::internal_word_type);
4650   }
4651 }
4652 
4653 //----------------------------static_subtype_check-----------------------------
4654 // Shortcut important common cases when superklass is exact:
4655 // (0) superklass is java.lang.Object (can occur in reflective code)
4656 // (1) subklass is already limited to a subtype of superklass => always ok
4657 // (2) subklass does not overlap with superklass => always fail
4658 // (3) superklass has NO subtypes and we can check with a simple compare.
4659 int Compile::static_subtype_check(ciKlass* superk, ciKlass* subk) {
4660   if (StressReflectiveCode) {
4661     return SSC_full_test;       // Let caller generate the general case.
4662   }
4663 
4664   if (superk == env()->Object_klass()) {
4665     return SSC_always_true;     // (0) this test cannot fail
4666   }
4667 
4668   ciType* superelem = superk;
4669   if (superelem->is_array_klass())
4670     superelem = superelem->as_array_klass()->base_element_type();
4671 
4672   if (!subk->is_interface()) {  // cannot trust static interface types yet
4673     if (subk->is_subtype_of(superk)) {
4674       return SSC_always_true;   // (1) false path dead; no dynamic test needed
4675     }
4676     if (!(superelem->is_klass() && superelem->as_klass()->is_interface()) &&
4677         !superk->is_subtype_of(subk)) {
4678       return SSC_always_false;
4679     }
4680   }
4681 
4682   // If casting to an instance klass, it must have no subtypes
4683   if (superk->is_interface()) {
4684     // Cannot trust interfaces yet.
4685     // %%% S.B. superk->nof_implementors() == 1
4686   } else if (superelem->is_instance_klass()) {
4687     ciInstanceKlass* ik = superelem->as_instance_klass();
4688     if (!ik->has_subklass() && !ik->is_interface()) {
4689       if (!ik->is_final()) {
4690         // Add a dependency if there is a chance of a later subclass.
4691         dependencies()->assert_leaf_type(ik);
4692       }
4693       return SSC_easy_test;     // (3) caller can do a simple ptr comparison
4694     }
4695   } else {
4696     // A primitive array type has no subtypes.
4697     return SSC_easy_test;       // (3) caller can do a simple ptr comparison
4698   }
4699 
4700   return SSC_full_test;
4701 }
4702 
4703 Node* Compile::conv_I2X_index(PhaseGVN* phase, Node* idx, const TypeInt* sizetype, Node* ctrl) {
4704 #ifdef _LP64
4705   // The scaled index operand to AddP must be a clean 64-bit value.
4706   // Java allows a 32-bit int to be incremented to a negative
4707   // value, which appears in a 64-bit register as a large
4708   // positive number.  Using that large positive number as an
4709   // operand in pointer arithmetic has bad consequences.
4710   // On the other hand, 32-bit overflow is rare, and the possibility
4711   // can often be excluded, if we annotate the ConvI2L node with
4712   // a type assertion that its value is known to be a small positive
4713   // number.  (The prior range check has ensured this.)
4714   // This assertion is used by ConvI2LNode::Ideal.
4715   int index_max = max_jint - 1;  // array size is max_jint, index is one less
4716   if (sizetype != NULL) index_max = sizetype->_hi - 1;
4717   const TypeInt* iidxtype = TypeInt::make(0, index_max, Type::WidenMax);
4718   idx = constrained_convI2L(phase, idx, iidxtype, ctrl);
4719 #endif
4720   return idx;
4721 }
4722 
4723 // Convert integer value to a narrowed long type dependent on ctrl (for example, a range check)
4724 Node* Compile::constrained_convI2L(PhaseGVN* phase, Node* value, const TypeInt* itype, Node* ctrl) {
4725   if (ctrl != NULL) {
4726     // Express control dependency by a CastII node with a narrow type.
4727     value = new CastIINode(value, itype, false, true /* range check dependency */);
4728     // Make the CastII node dependent on the control input to prevent the narrowed ConvI2L
4729     // node from floating above the range check during loop optimizations. Otherwise, the
4730     // ConvI2L node may be eliminated independently of the range check, causing the data path
4731     // to become TOP while the control path is still there (although it's unreachable).
4732     value->set_req(0, ctrl);
4733     // Save CastII node to remove it after loop optimizations.
4734     phase->C->add_range_check_cast(value);
4735     value = phase->transform(value);
4736   }
4737   const TypeLong* ltype = TypeLong::make(itype->_lo, itype->_hi, itype->_widen);
4738   return phase->transform(new ConvI2LNode(value, ltype));
4739 }
4740 
4741 // The message about the current inlining is accumulated in
4742 // _print_inlining_stream and transfered into the _print_inlining_list
4743 // once we know whether inlining succeeds or not. For regular
4744 // inlining, messages are appended to the buffer pointed by
4745 // _print_inlining_idx in the _print_inlining_list. For late inlining,
4746 // a new buffer is added after _print_inlining_idx in the list. This
4747 // way we can update the inlining message for late inlining call site
4748 // when the inlining is attempted again.
4749 void Compile::print_inlining_init() {
4750   if (print_inlining() || print_intrinsics()) {
4751     _print_inlining_stream = new stringStream();
4752     _print_inlining_list = new (comp_arena())GrowableArray<PrintInliningBuffer>(comp_arena(), 1, 1, PrintInliningBuffer());
4753   }
4754 }
4755 
4756 void Compile::print_inlining_reinit() {
4757   if (print_inlining() || print_intrinsics()) {
4758     // Re allocate buffer when we change ResourceMark
4759     _print_inlining_stream = new stringStream();
4760   }
4761 }
4762 
4763 void Compile::print_inlining_reset() {
4764   _print_inlining_stream->reset();
4765 }
4766 
4767 void Compile::print_inlining_commit() {
4768   assert(print_inlining() || print_intrinsics(), "PrintInlining off?");
4769   // Transfer the message from _print_inlining_stream to the current
4770   // _print_inlining_list buffer and clear _print_inlining_stream.
4771   _print_inlining_list->at(_print_inlining_idx).ss()->write(_print_inlining_stream->as_string(), _print_inlining_stream->size());
4772   print_inlining_reset();
4773 }
4774 
4775 void Compile::print_inlining_push() {
4776   // Add new buffer to the _print_inlining_list at current position
4777   _print_inlining_idx++;
4778   _print_inlining_list->insert_before(_print_inlining_idx, PrintInliningBuffer());
4779 }
4780 
4781 Compile::PrintInliningBuffer& Compile::print_inlining_current() {
4782   return _print_inlining_list->at(_print_inlining_idx);
4783 }
4784 
4785 void Compile::print_inlining_update(CallGenerator* cg) {
4786   if (print_inlining() || print_intrinsics()) {
4787     if (!cg->is_late_inline()) {
4788       if (print_inlining_current().cg() != NULL) {
4789         print_inlining_push();
4790       }
4791       print_inlining_commit();
4792     } else {
4793       if (print_inlining_current().cg() != cg &&
4794           (print_inlining_current().cg() != NULL ||
4795            print_inlining_current().ss()->size() != 0)) {
4796         print_inlining_push();
4797       }
4798       print_inlining_commit();
4799       print_inlining_current().set_cg(cg);
4800     }
4801   }
4802 }
4803 
4804 void Compile::print_inlining_move_to(CallGenerator* cg) {
4805   // We resume inlining at a late inlining call site. Locate the
4806   // corresponding inlining buffer so that we can update it.
4807   if (print_inlining()) {
4808     for (int i = 0; i < _print_inlining_list->length(); i++) {
4809       if (_print_inlining_list->adr_at(i)->cg() == cg) {
4810         _print_inlining_idx = i;
4811         return;
4812       }
4813     }
4814     ShouldNotReachHere();
4815   }
4816 }
4817 
4818 void Compile::print_inlining_update_delayed(CallGenerator* cg) {
4819   if (print_inlining()) {
4820     assert(_print_inlining_stream->size() > 0, "missing inlining msg");
4821     assert(print_inlining_current().cg() == cg, "wrong entry");
4822     // replace message with new message
4823     _print_inlining_list->at_put(_print_inlining_idx, PrintInliningBuffer());
4824     print_inlining_commit();
4825     print_inlining_current().set_cg(cg);
4826   }
4827 }
4828 
4829 void Compile::print_inlining_assert_ready() {
4830   assert(!_print_inlining || _print_inlining_stream->size() == 0, "loosing data");
4831 }
4832 
4833 void Compile::process_print_inlining() {
4834   bool do_print_inlining = print_inlining() || print_intrinsics();
4835   if (do_print_inlining || log() != NULL) {
4836     // Print inlining message for candidates that we couldn't inline
4837     // for lack of space
4838     for (int i = 0; i < _late_inlines.length(); i++) {
4839       CallGenerator* cg = _late_inlines.at(i);
4840       if (!cg->is_mh_late_inline()) {
4841         const char* msg = "live nodes > LiveNodeCountInliningCutoff";
4842         if (do_print_inlining) {
4843           cg->print_inlining_late(msg);
4844         }
4845         log_late_inline_failure(cg, msg);
4846       }
4847     }
4848   }
4849   if (do_print_inlining) {
4850     ResourceMark rm;
4851     stringStream ss;
4852     for (int i = 0; i < _print_inlining_list->length(); i++) {
4853       ss.print("%s", _print_inlining_list->adr_at(i)->ss()->as_string());
4854     }
4855     size_t end = ss.size();
4856     _print_inlining_output = NEW_ARENA_ARRAY(comp_arena(), char, end+1);
4857     strncpy(_print_inlining_output, ss.base(), end+1);
4858     _print_inlining_output[end] = 0;
4859   }
4860 }
4861 
4862 void Compile::dump_print_inlining() {
4863   if (_print_inlining_output != NULL) {
4864     tty->print_raw(_print_inlining_output);
4865   }
4866 }
4867 
4868 void Compile::log_late_inline(CallGenerator* cg) {
4869   if (log() != NULL) {
4870     log()->head("late_inline method='%d'  inline_id='" JLONG_FORMAT "'", log()->identify(cg->method()),
4871                 cg->unique_id());
4872     JVMState* p = cg->call_node()->jvms();
4873     while (p != NULL) {
4874       log()->elem("jvms bci='%d' method='%d'", p->bci(), log()->identify(p->method()));
4875       p = p->caller();
4876     }
4877     log()->tail("late_inline");
4878   }
4879 }
4880 
4881 void Compile::log_late_inline_failure(CallGenerator* cg, const char* msg) {
4882   log_late_inline(cg);
4883   if (log() != NULL) {
4884     log()->inline_fail(msg);
4885   }
4886 }
4887 
4888 void Compile::log_inline_id(CallGenerator* cg) {
4889   if (log() != NULL) {
4890     // The LogCompilation tool needs a unique way to identify late
4891     // inline call sites. This id must be unique for this call site in
4892     // this compilation. Try to have it unique across compilations as
4893     // well because it can be convenient when grepping through the log
4894     // file.
4895     // Distinguish OSR compilations from others in case CICountOSR is
4896     // on.
4897     jlong id = ((jlong)unique()) + (((jlong)compile_id()) << 33) + (CICountOSR && is_osr_compilation() ? ((jlong)1) << 32 : 0);
4898     cg->set_unique_id(id);
4899     log()->elem("inline_id id='" JLONG_FORMAT "'", id);
4900   }
4901 }
4902 
4903 void Compile::log_inline_failure(const char* msg) {
4904   if (C->log() != NULL) {
4905     C->log()->inline_fail(msg);
4906   }
4907 }
4908 
4909 
4910 // Dump inlining replay data to the stream.
4911 // Don't change thread state and acquire any locks.
4912 void Compile::dump_inline_data(outputStream* out) {
4913   InlineTree* inl_tree = ilt();
4914   if (inl_tree != NULL) {
4915     out->print(" inline %d", inl_tree->count());
4916     inl_tree->dump_replay_data(out);
4917   }
4918 }
4919 
4920 int Compile::cmp_expensive_nodes(Node* n1, Node* n2) {
4921   if (n1->Opcode() < n2->Opcode())      return -1;
4922   else if (n1->Opcode() > n2->Opcode()) return 1;
4923 
4924   assert(n1->req() == n2->req(), "can't compare %s nodes: n1->req() = %d, n2->req() = %d", NodeClassNames[n1->Opcode()], n1->req(), n2->req());
4925   for (uint i = 1; i < n1->req(); i++) {
4926     if (n1->in(i) < n2->in(i))      return -1;
4927     else if (n1->in(i) > n2->in(i)) return 1;
4928   }
4929 
4930   return 0;
4931 }
4932 
4933 int Compile::cmp_expensive_nodes(Node** n1p, Node** n2p) {
4934   Node* n1 = *n1p;
4935   Node* n2 = *n2p;
4936 
4937   return cmp_expensive_nodes(n1, n2);
4938 }
4939 
4940 void Compile::sort_expensive_nodes() {
4941   if (!expensive_nodes_sorted()) {
4942     _expensive_nodes->sort(cmp_expensive_nodes);
4943   }
4944 }
4945 
4946 bool Compile::expensive_nodes_sorted() const {
4947   for (int i = 1; i < _expensive_nodes->length(); i++) {
4948     if (cmp_expensive_nodes(_expensive_nodes->adr_at(i), _expensive_nodes->adr_at(i-1)) < 0) {
4949       return false;
4950     }
4951   }
4952   return true;
4953 }
4954 
4955 bool Compile::should_optimize_expensive_nodes(PhaseIterGVN &igvn) {
4956   if (_expensive_nodes->length() == 0) {
4957     return false;
4958   }
4959 
4960   assert(OptimizeExpensiveOps, "optimization off?");
4961 
4962   // Take this opportunity to remove dead nodes from the list
4963   int j = 0;
4964   for (int i = 0; i < _expensive_nodes->length(); i++) {
4965     Node* n = _expensive_nodes->at(i);
4966     if (!n->is_unreachable(igvn)) {
4967       assert(n->is_expensive(), "should be expensive");
4968       _expensive_nodes->at_put(j, n);
4969       j++;
4970     }
4971   }
4972   _expensive_nodes->trunc_to(j);
4973 
4974   // Then sort the list so that similar nodes are next to each other
4975   // and check for at least two nodes of identical kind with same data
4976   // inputs.
4977   sort_expensive_nodes();
4978 
4979   for (int i = 0; i < _expensive_nodes->length()-1; i++) {
4980     if (cmp_expensive_nodes(_expensive_nodes->adr_at(i), _expensive_nodes->adr_at(i+1)) == 0) {
4981       return true;
4982     }
4983   }
4984 
4985   return false;
4986 }
4987 
4988 void Compile::cleanup_expensive_nodes(PhaseIterGVN &igvn) {
4989   if (_expensive_nodes->length() == 0) {
4990     return;
4991   }
4992 
4993   assert(OptimizeExpensiveOps, "optimization off?");
4994 
4995   // Sort to bring similar nodes next to each other and clear the
4996   // control input of nodes for which there's only a single copy.
4997   sort_expensive_nodes();
4998 
4999   int j = 0;
5000   int identical = 0;
5001   int i = 0;
5002   bool modified = false;
5003   for (; i < _expensive_nodes->length()-1; i++) {
5004     assert(j <= i, "can't write beyond current index");
5005     if (_expensive_nodes->at(i)->Opcode() == _expensive_nodes->at(i+1)->Opcode()) {
5006       identical++;
5007       _expensive_nodes->at_put(j++, _expensive_nodes->at(i));
5008       continue;
5009     }
5010     if (identical > 0) {
5011       _expensive_nodes->at_put(j++, _expensive_nodes->at(i));
5012       identical = 0;
5013     } else {
5014       Node* n = _expensive_nodes->at(i);
5015       igvn.replace_input_of(n, 0, NULL);
5016       igvn.hash_insert(n);
5017       modified = true;
5018     }
5019   }
5020   if (identical > 0) {
5021     _expensive_nodes->at_put(j++, _expensive_nodes->at(i));
5022   } else if (_expensive_nodes->length() >= 1) {
5023     Node* n = _expensive_nodes->at(i);
5024     igvn.replace_input_of(n, 0, NULL);
5025     igvn.hash_insert(n);
5026     modified = true;
5027   }
5028   _expensive_nodes->trunc_to(j);
5029   if (modified) {
5030     igvn.optimize();
5031   }
5032 }
5033 
5034 void Compile::add_expensive_node(Node * n) {
5035   assert(!_expensive_nodes->contains(n), "duplicate entry in expensive list");
5036   assert(n->is_expensive(), "expensive nodes with non-null control here only");
5037   assert(!n->is_CFG() && !n->is_Mem(), "no cfg or memory nodes here");
5038   if (OptimizeExpensiveOps) {
5039     _expensive_nodes->append(n);
5040   } else {
5041     // Clear control input and let IGVN optimize expensive nodes if
5042     // OptimizeExpensiveOps is off.
5043     n->set_req(0, NULL);
5044   }
5045 }
5046 
5047 /**
5048  * Remove the speculative part of types and clean up the graph
5049  */
5050 void Compile::remove_speculative_types(PhaseIterGVN &igvn) {
5051   if (UseTypeSpeculation) {
5052     Unique_Node_List worklist;
5053     worklist.push(root());
5054     int modified = 0;
5055     // Go over all type nodes that carry a speculative type, drop the
5056     // speculative part of the type and enqueue the node for an igvn
5057     // which may optimize it out.
5058     for (uint next = 0; next < worklist.size(); ++next) {
5059       Node *n  = worklist.at(next);
5060       if (n->is_Type()) {
5061         TypeNode* tn = n->as_Type();
5062         const Type* t = tn->type();
5063         const Type* t_no_spec = t->remove_speculative();
5064         if (t_no_spec != t) {
5065           bool in_hash = igvn.hash_delete(n);
5066           assert(in_hash, "node should be in igvn hash table");
5067           tn->set_type(t_no_spec);
5068           igvn.hash_insert(n);
5069           igvn._worklist.push(n); // give it a chance to go away
5070           modified++;
5071         }
5072       }
5073       uint max = n->len();
5074       for( uint i = 0; i < max; ++i ) {
5075         Node *m = n->in(i);
5076         if (not_a_node(m))  continue;
5077         worklist.push(m);
5078       }
5079     }
5080     // Drop the speculative part of all types in the igvn's type table
5081     igvn.remove_speculative_types();
5082     if (modified > 0) {
5083       igvn.optimize();
5084     }
5085 #ifdef ASSERT
5086     // Verify that after the IGVN is over no speculative type has resurfaced
5087     worklist.clear();
5088     worklist.push(root());
5089     for (uint next = 0; next < worklist.size(); ++next) {
5090       Node *n  = worklist.at(next);
5091       const Type* t = igvn.type_or_null(n);
5092       assert((t == NULL) || (t == t->remove_speculative()), "no more speculative types");
5093       if (n->is_Type()) {
5094         t = n->as_Type()->type();
5095         assert(t == t->remove_speculative(), "no more speculative types");
5096       }
5097       uint max = n->len();
5098       for( uint i = 0; i < max; ++i ) {
5099         Node *m = n->in(i);
5100         if (not_a_node(m))  continue;
5101         worklist.push(m);
5102       }
5103     }
5104     igvn.check_no_speculative_types();
5105 #endif
5106   }
5107 }
5108 
5109 // Auxiliary method to support randomized stressing/fuzzing.
5110 //
5111 // This method can be called the arbitrary number of times, with current count
5112 // as the argument. The logic allows selecting a single candidate from the
5113 // running list of candidates as follows:
5114 //    int count = 0;
5115 //    Cand* selected = null;
5116 //    while(cand = cand->next()) {
5117 //      if (randomized_select(++count)) {
5118 //        selected = cand;
5119 //      }
5120 //    }
5121 //
5122 // Including count equalizes the chances any candidate is "selected".
5123 // This is useful when we don't have the complete list of candidates to choose
5124 // from uniformly. In this case, we need to adjust the randomicity of the
5125 // selection, or else we will end up biasing the selection towards the latter
5126 // candidates.
5127 //
5128 // Quick back-envelope calculation shows that for the list of n candidates
5129 // the equal probability for the candidate to persist as "best" can be
5130 // achieved by replacing it with "next" k-th candidate with the probability
5131 // of 1/k. It can be easily shown that by the end of the run, the
5132 // probability for any candidate is converged to 1/n, thus giving the
5133 // uniform distribution among all the candidates.
5134 //
5135 // We don't care about the domain size as long as (RANDOMIZED_DOMAIN / count) is large.
5136 #define RANDOMIZED_DOMAIN_POW 29
5137 #define RANDOMIZED_DOMAIN (1 << RANDOMIZED_DOMAIN_POW)
5138 #define RANDOMIZED_DOMAIN_MASK ((1 << (RANDOMIZED_DOMAIN_POW + 1)) - 1)
5139 bool Compile::randomized_select(int count) {
5140   assert(count > 0, "only positive");
5141   return (os::random() & RANDOMIZED_DOMAIN_MASK) < (RANDOMIZED_DOMAIN / count);
5142 }
5143 
5144 CloneMap&     Compile::clone_map()                 { return _clone_map; }
5145 void          Compile::set_clone_map(Dict* d)      { _clone_map._dict = d; }
5146 
5147 void NodeCloneInfo::dump() const {
5148   tty->print(" {%d:%d} ", idx(), gen());
5149 }
5150 
5151 void CloneMap::clone(Node* old, Node* nnn, int gen) {
5152   uint64_t val = value(old->_idx);
5153   NodeCloneInfo cio(val);
5154   assert(val != 0, "old node should be in the map");
5155   NodeCloneInfo cin(cio.idx(), gen + cio.gen());
5156   insert(nnn->_idx, cin.get());
5157 #ifndef PRODUCT
5158   if (is_debug()) {
5159     tty->print_cr("CloneMap::clone inserted node %d info {%d:%d} into CloneMap", nnn->_idx, cin.idx(), cin.gen());
5160   }
5161 #endif
5162 }
5163 
5164 void CloneMap::verify_insert_and_clone(Node* old, Node* nnn, int gen) {
5165   NodeCloneInfo cio(value(old->_idx));
5166   if (cio.get() == 0) {
5167     cio.set(old->_idx, 0);
5168     insert(old->_idx, cio.get());
5169 #ifndef PRODUCT
5170     if (is_debug()) {
5171       tty->print_cr("CloneMap::verify_insert_and_clone inserted node %d info {%d:%d} into CloneMap", old->_idx, cio.idx(), cio.gen());
5172     }
5173 #endif
5174   }
5175   clone(old, nnn, gen);
5176 }
5177 
5178 int CloneMap::max_gen() const {
5179   int g = 0;
5180   DictI di(_dict);
5181   for(; di.test(); ++di) {
5182     int t = gen(di._key);
5183     if (g < t) {
5184       g = t;
5185 #ifndef PRODUCT
5186       if (is_debug()) {
5187         tty->print_cr("CloneMap::max_gen() update max=%d from %d", g, _2_node_idx_t(di._key));
5188       }
5189 #endif
5190     }
5191   }
5192   return g;
5193 }
5194 
5195 void CloneMap::dump(node_idx_t key) const {
5196   uint64_t val = value(key);
5197   if (val != 0) {
5198     NodeCloneInfo ni(val);
5199     ni.dump();
5200   }
5201 }