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