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