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