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