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