1 /*
   2  * Copyright (c) 1997, 2010, 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 "incls/_precompiled.incl"
  26 #include "incls/_compile.cpp.incl"
  27 
  28 
  29 // -------------------- Compile::mach_constant_base_node -----------------------
  30 // Constant table base node singleton.
  31 MachConstantBaseNode* Compile::mach_constant_base_node() {
  32   if (_mach_constant_base_node == NULL) {
  33     _mach_constant_base_node = new (C) MachConstantBaseNode();
  34     _mach_constant_base_node->set_req(0, C->root());
  35   }
  36   return _mach_constant_base_node;
  37 }
  38 
  39 
  40 /// Support for intrinsics.
  41 
  42 // Return the index at which m must be inserted (or already exists).
  43 // The sort order is by the address of the ciMethod, with is_virtual as minor key.
  44 int Compile::intrinsic_insertion_index(ciMethod* m, bool is_virtual) {
  45 #ifdef ASSERT
  46   for (int i = 1; i < _intrinsics->length(); i++) {
  47     CallGenerator* cg1 = _intrinsics->at(i-1);
  48     CallGenerator* cg2 = _intrinsics->at(i);
  49     assert(cg1->method() != cg2->method()
  50            ? cg1->method()     < cg2->method()
  51            : cg1->is_virtual() < cg2->is_virtual(),
  52            "compiler intrinsics list must stay sorted");
  53   }
  54 #endif
  55   // Binary search sorted list, in decreasing intervals [lo, hi].
  56   int lo = 0, hi = _intrinsics->length()-1;
  57   while (lo <= hi) {
  58     int mid = (uint)(hi + lo) / 2;
  59     ciMethod* mid_m = _intrinsics->at(mid)->method();
  60     if (m < mid_m) {
  61       hi = mid-1;
  62     } else if (m > mid_m) {
  63       lo = mid+1;
  64     } else {
  65       // look at minor sort key
  66       bool mid_virt = _intrinsics->at(mid)->is_virtual();
  67       if (is_virtual < mid_virt) {
  68         hi = mid-1;
  69       } else if (is_virtual > mid_virt) {
  70         lo = mid+1;
  71       } else {
  72         return mid;  // exact match
  73       }
  74     }
  75   }
  76   return lo;  // inexact match
  77 }
  78 
  79 void Compile::register_intrinsic(CallGenerator* cg) {
  80   if (_intrinsics == NULL) {
  81     _intrinsics = new GrowableArray<CallGenerator*>(60);
  82   }
  83   // This code is stolen from ciObjectFactory::insert.
  84   // Really, GrowableArray should have methods for
  85   // insert_at, remove_at, and binary_search.
  86   int len = _intrinsics->length();
  87   int index = intrinsic_insertion_index(cg->method(), cg->is_virtual());
  88   if (index == len) {
  89     _intrinsics->append(cg);
  90   } else {
  91 #ifdef ASSERT
  92     CallGenerator* oldcg = _intrinsics->at(index);
  93     assert(oldcg->method() != cg->method() || oldcg->is_virtual() != cg->is_virtual(), "don't register twice");
  94 #endif
  95     _intrinsics->append(_intrinsics->at(len-1));
  96     int pos;
  97     for (pos = len-2; pos >= index; pos--) {
  98       _intrinsics->at_put(pos+1,_intrinsics->at(pos));
  99     }
 100     _intrinsics->at_put(index, cg);
 101   }
 102   assert(find_intrinsic(cg->method(), cg->is_virtual()) == cg, "registration worked");
 103 }
 104 
 105 CallGenerator* Compile::find_intrinsic(ciMethod* m, bool is_virtual) {
 106   assert(m->is_loaded(), "don't try this on unloaded methods");
 107   if (_intrinsics != NULL) {
 108     int index = intrinsic_insertion_index(m, is_virtual);
 109     if (index < _intrinsics->length()
 110         && _intrinsics->at(index)->method() == m
 111         && _intrinsics->at(index)->is_virtual() == is_virtual) {
 112       return _intrinsics->at(index);
 113     }
 114   }
 115   // Lazily create intrinsics for intrinsic IDs well-known in the runtime.
 116   if (m->intrinsic_id() != vmIntrinsics::_none &&
 117       m->intrinsic_id() <= vmIntrinsics::LAST_COMPILER_INLINE) {
 118     CallGenerator* cg = make_vm_intrinsic(m, is_virtual);
 119     if (cg != NULL) {
 120       // Save it for next time:
 121       register_intrinsic(cg);
 122       return cg;
 123     } else {
 124       gather_intrinsic_statistics(m->intrinsic_id(), is_virtual, _intrinsic_disabled);
 125     }
 126   }
 127   return NULL;
 128 }
 129 
 130 // Compile:: register_library_intrinsics and make_vm_intrinsic are defined
 131 // in library_call.cpp.
 132 
 133 
 134 #ifndef PRODUCT
 135 // statistics gathering...
 136 
 137 juint  Compile::_intrinsic_hist_count[vmIntrinsics::ID_LIMIT] = {0};
 138 jubyte Compile::_intrinsic_hist_flags[vmIntrinsics::ID_LIMIT] = {0};
 139 
 140 bool Compile::gather_intrinsic_statistics(vmIntrinsics::ID id, bool is_virtual, int flags) {
 141   assert(id > vmIntrinsics::_none && id < vmIntrinsics::ID_LIMIT, "oob");
 142   int oflags = _intrinsic_hist_flags[id];
 143   assert(flags != 0, "what happened?");
 144   if (is_virtual) {
 145     flags |= _intrinsic_virtual;
 146   }
 147   bool changed = (flags != oflags);
 148   if ((flags & _intrinsic_worked) != 0) {
 149     juint count = (_intrinsic_hist_count[id] += 1);
 150     if (count == 1) {
 151       changed = true;           // first time
 152     }
 153     // increment the overall count also:
 154     _intrinsic_hist_count[vmIntrinsics::_none] += 1;
 155   }
 156   if (changed) {
 157     if (((oflags ^ flags) & _intrinsic_virtual) != 0) {
 158       // Something changed about the intrinsic's virtuality.
 159       if ((flags & _intrinsic_virtual) != 0) {
 160         // This is the first use of this intrinsic as a virtual call.
 161         if (oflags != 0) {
 162           // We already saw it as a non-virtual, so note both cases.
 163           flags |= _intrinsic_both;
 164         }
 165       } else if ((oflags & _intrinsic_both) == 0) {
 166         // This is the first use of this intrinsic as a non-virtual
 167         flags |= _intrinsic_both;
 168       }
 169     }
 170     _intrinsic_hist_flags[id] = (jubyte) (oflags | flags);
 171   }
 172   // update the overall flags also:
 173   _intrinsic_hist_flags[vmIntrinsics::_none] |= (jubyte) flags;
 174   return changed;
 175 }
 176 
 177 static char* format_flags(int flags, char* buf) {
 178   buf[0] = 0;
 179   if ((flags & Compile::_intrinsic_worked) != 0)    strcat(buf, ",worked");
 180   if ((flags & Compile::_intrinsic_failed) != 0)    strcat(buf, ",failed");
 181   if ((flags & Compile::_intrinsic_disabled) != 0)  strcat(buf, ",disabled");
 182   if ((flags & Compile::_intrinsic_virtual) != 0)   strcat(buf, ",virtual");
 183   if ((flags & Compile::_intrinsic_both) != 0)      strcat(buf, ",nonvirtual");
 184   if (buf[0] == 0)  strcat(buf, ",");
 185   assert(buf[0] == ',', "must be");
 186   return &buf[1];
 187 }
 188 
 189 void Compile::print_intrinsic_statistics() {
 190   char flagsbuf[100];
 191   ttyLocker ttyl;
 192   if (xtty != NULL)  xtty->head("statistics type='intrinsic'");
 193   tty->print_cr("Compiler intrinsic usage:");
 194   juint total = _intrinsic_hist_count[vmIntrinsics::_none];
 195   if (total == 0)  total = 1;  // avoid div0 in case of no successes
 196   #define PRINT_STAT_LINE(name, c, f) \
 197     tty->print_cr("  %4d (%4.1f%%) %s (%s)", (int)(c), ((c) * 100.0) / total, name, f);
 198   for (int index = 1 + (int)vmIntrinsics::_none; index < (int)vmIntrinsics::ID_LIMIT; index++) {
 199     vmIntrinsics::ID id = (vmIntrinsics::ID) index;
 200     int   flags = _intrinsic_hist_flags[id];
 201     juint count = _intrinsic_hist_count[id];
 202     if ((flags | count) != 0) {
 203       PRINT_STAT_LINE(vmIntrinsics::name_at(id), count, format_flags(flags, flagsbuf));
 204     }
 205   }
 206   PRINT_STAT_LINE("total", total, format_flags(_intrinsic_hist_flags[vmIntrinsics::_none], flagsbuf));
 207   if (xtty != NULL)  xtty->tail("statistics");
 208 }
 209 
 210 void Compile::print_statistics() {
 211   { ttyLocker ttyl;
 212     if (xtty != NULL)  xtty->head("statistics type='opto'");
 213     Parse::print_statistics();
 214     PhaseCCP::print_statistics();
 215     PhaseRegAlloc::print_statistics();
 216     Scheduling::print_statistics();
 217     PhasePeephole::print_statistics();
 218     PhaseIdealLoop::print_statistics();
 219     if (xtty != NULL)  xtty->tail("statistics");
 220   }
 221   if (_intrinsic_hist_flags[vmIntrinsics::_none] != 0) {
 222     // put this under its own <statistics> element.
 223     print_intrinsic_statistics();
 224   }
 225 }
 226 #endif //PRODUCT
 227 
 228 // Support for bundling info
 229 Bundle* Compile::node_bundling(const Node *n) {
 230   assert(valid_bundle_info(n), "oob");
 231   return &_node_bundling_base[n->_idx];
 232 }
 233 
 234 bool Compile::valid_bundle_info(const Node *n) {
 235   return (_node_bundling_limit > n->_idx);
 236 }
 237 
 238 
 239 void Compile::gvn_replace_by(Node* n, Node* nn) {
 240   for (DUIterator_Last imin, i = n->last_outs(imin); i >= imin; ) {
 241     Node* use = n->last_out(i);
 242     bool is_in_table = initial_gvn()->hash_delete(use);
 243     uint uses_found = 0;
 244     for (uint j = 0; j < use->len(); j++) {
 245       if (use->in(j) == n) {
 246         if (j < use->req())
 247           use->set_req(j, nn);
 248         else
 249           use->set_prec(j, nn);
 250         uses_found++;
 251       }
 252     }
 253     if (is_in_table) {
 254       // reinsert into table
 255       initial_gvn()->hash_find_insert(use);
 256     }
 257     record_for_igvn(use);
 258     i -= uses_found;    // we deleted 1 or more copies of this edge
 259   }
 260 }
 261 
 262 
 263 
 264 
 265 // Identify all nodes that are reachable from below, useful.
 266 // Use breadth-first pass that records state in a Unique_Node_List,
 267 // recursive traversal is slower.
 268 void Compile::identify_useful_nodes(Unique_Node_List &useful) {
 269   int estimated_worklist_size = unique();
 270   useful.map( estimated_worklist_size, NULL );  // preallocate space
 271 
 272   // Initialize worklist
 273   if (root() != NULL)     { useful.push(root()); }
 274   // If 'top' is cached, declare it useful to preserve cached node
 275   if( cached_top_node() ) { useful.push(cached_top_node()); }
 276 
 277   // Push all useful nodes onto the list, breadthfirst
 278   for( uint next = 0; next < useful.size(); ++next ) {
 279     assert( next < unique(), "Unique useful nodes < total nodes");
 280     Node *n  = useful.at(next);
 281     uint max = n->len();
 282     for( uint i = 0; i < max; ++i ) {
 283       Node *m = n->in(i);
 284       if( m == NULL ) continue;
 285       useful.push(m);
 286     }
 287   }
 288 }
 289 
 290 // Disconnect all useless nodes by disconnecting those at the boundary.
 291 void Compile::remove_useless_nodes(Unique_Node_List &useful) {
 292   uint next = 0;
 293   while( next < useful.size() ) {
 294     Node *n = useful.at(next++);
 295     // Use raw traversal of out edges since this code removes out edges
 296     int max = n->outcnt();
 297     for (int j = 0; j < max; ++j ) {
 298       Node* child = n->raw_out(j);
 299       if( ! useful.member(child) ) {
 300         assert( !child->is_top() || child != top(),
 301                 "If top is cached in Compile object it is in useful list");
 302         // Only need to remove this out-edge to the useless node
 303         n->raw_del_out(j);
 304         --j;
 305         --max;
 306       }
 307     }
 308     if (n->outcnt() == 1 && n->has_special_unique_user()) {
 309       record_for_igvn( n->unique_out() );
 310     }
 311   }
 312   debug_only(verify_graph_edges(true/*check for no_dead_code*/);)
 313 }
 314 
 315 //------------------------------frame_size_in_words-----------------------------
 316 // frame_slots in units of words
 317 int Compile::frame_size_in_words() const {
 318   // shift is 0 in LP32 and 1 in LP64
 319   const int shift = (LogBytesPerWord - LogBytesPerInt);
 320   int words = _frame_slots >> shift;
 321   assert( words << shift == _frame_slots, "frame size must be properly aligned in LP64" );
 322   return words;
 323 }
 324 
 325 // ============================================================================
 326 //------------------------------CompileWrapper---------------------------------
 327 class CompileWrapper : public StackObj {
 328   Compile *const _compile;
 329  public:
 330   CompileWrapper(Compile* compile);
 331 
 332   ~CompileWrapper();
 333 };
 334 
 335 CompileWrapper::CompileWrapper(Compile* compile) : _compile(compile) {
 336   // the Compile* pointer is stored in the current ciEnv:
 337   ciEnv* env = compile->env();
 338   assert(env == ciEnv::current(), "must already be a ciEnv active");
 339   assert(env->compiler_data() == NULL, "compile already active?");
 340   env->set_compiler_data(compile);
 341   assert(compile == Compile::current(), "sanity");
 342 
 343   compile->set_type_dict(NULL);
 344   compile->set_type_hwm(NULL);
 345   compile->set_type_last_size(0);
 346   compile->set_last_tf(NULL, NULL);
 347   compile->set_indexSet_arena(NULL);
 348   compile->set_indexSet_free_block_list(NULL);
 349   compile->init_type_arena();
 350   Type::Initialize(compile);
 351   _compile->set_scratch_buffer_blob(NULL);
 352   _compile->begin_method();
 353 }
 354 CompileWrapper::~CompileWrapper() {
 355   _compile->end_method();
 356   if (_compile->scratch_buffer_blob() != NULL)
 357     BufferBlob::free(_compile->scratch_buffer_blob());
 358   _compile->env()->set_compiler_data(NULL);
 359 }
 360 
 361 
 362 //----------------------------print_compile_messages---------------------------
 363 void Compile::print_compile_messages() {
 364 #ifndef PRODUCT
 365   // Check if recompiling
 366   if (_subsume_loads == false && PrintOpto) {
 367     // Recompiling without allowing machine instructions to subsume loads
 368     tty->print_cr("*********************************************************");
 369     tty->print_cr("** Bailout: Recompile without subsuming loads          **");
 370     tty->print_cr("*********************************************************");
 371   }
 372   if (_do_escape_analysis != DoEscapeAnalysis && PrintOpto) {
 373     // Recompiling without escape analysis
 374     tty->print_cr("*********************************************************");
 375     tty->print_cr("** Bailout: Recompile without escape analysis          **");
 376     tty->print_cr("*********************************************************");
 377   }
 378   if (env()->break_at_compile()) {
 379     // Open the debugger when compiling this method.
 380     tty->print("### Breaking when compiling: ");
 381     method()->print_short_name();
 382     tty->cr();
 383     BREAKPOINT;
 384   }
 385 
 386   if( PrintOpto ) {
 387     if (is_osr_compilation()) {
 388       tty->print("[OSR]%3d", _compile_id);
 389     } else {
 390       tty->print("%3d", _compile_id);
 391     }
 392   }
 393 #endif
 394 }
 395 
 396 
 397 void Compile::init_scratch_buffer_blob(int const_size) {
 398   if (scratch_buffer_blob() != NULL)  return;
 399 
 400   // Construct a temporary CodeBuffer to have it construct a BufferBlob
 401   // Cache this BufferBlob for this compile.
 402   ResourceMark rm;
 403   _scratch_const_size = const_size;
 404   int size = (MAX_inst_size + MAX_stubs_size + _scratch_const_size);
 405   BufferBlob* blob = BufferBlob::create("Compile::scratch_buffer", size);
 406   // Record the buffer blob for next time.
 407   set_scratch_buffer_blob(blob);
 408   // Have we run out of code space?
 409   if (scratch_buffer_blob() == NULL) {
 410     // Let CompilerBroker disable further compilations.
 411     record_failure("Not enough space for scratch buffer in CodeCache");
 412     return;
 413   }
 414 
 415   // Initialize the relocation buffers
 416   relocInfo* locs_buf = (relocInfo*) blob->content_end() - MAX_locs_size;
 417   set_scratch_locs_memory(locs_buf);
 418 }
 419 
 420 
 421 void Compile::clear_scratch_buffer_blob() {
 422   assert(scratch_buffer_blob(), "no BufferBlob set");
 423   set_scratch_buffer_blob(NULL);
 424   set_scratch_locs_memory(NULL);
 425 }
 426 
 427 
 428 //-----------------------scratch_emit_size-------------------------------------
 429 // Helper function that computes size by emitting code
 430 uint Compile::scratch_emit_size(const Node* n) {
 431   // Start scratch_emit_size section.
 432   set_in_scratch_emit_size(true);
 433 
 434   // Emit into a trash buffer and count bytes emitted.
 435   // This is a pretty expensive way to compute a size,
 436   // but it works well enough if seldom used.
 437   // All common fixed-size instructions are given a size
 438   // method by the AD file.
 439   // Note that the scratch buffer blob and locs memory are
 440   // allocated at the beginning of the compile task, and
 441   // may be shared by several calls to scratch_emit_size.
 442   // The allocation of the scratch buffer blob is particularly
 443   // expensive, since it has to grab the code cache lock.
 444   BufferBlob* blob = this->scratch_buffer_blob();
 445   assert(blob != NULL, "Initialize BufferBlob at start");
 446   assert(blob->size() > MAX_inst_size, "sanity");
 447   relocInfo* locs_buf = scratch_locs_memory();
 448   address blob_begin = blob->content_begin();
 449   address blob_end   = (address)locs_buf;
 450   assert(blob->content_contains(blob_end), "sanity");
 451   CodeBuffer buf(blob_begin, blob_end - blob_begin);
 452   buf.initialize_consts_size(_scratch_const_size);
 453   buf.initialize_stubs_size(MAX_stubs_size);
 454   assert(locs_buf != NULL, "sanity");
 455   int lsize = MAX_locs_size / 3;
 456   buf.consts()->initialize_shared_locs(&locs_buf[lsize * 0], lsize);
 457   buf.insts()->initialize_shared_locs( &locs_buf[lsize * 1], lsize);
 458   buf.stubs()->initialize_shared_locs( &locs_buf[lsize * 2], lsize);
 459 
 460   // Do the emission.
 461   n->emit(buf, this->regalloc());
 462 
 463   // End scratch_emit_size section.
 464   set_in_scratch_emit_size(false);
 465 
 466   return buf.insts_size();
 467 }
 468 
 469 
 470 // ============================================================================
 471 //------------------------------Compile standard-------------------------------
 472 debug_only( int Compile::_debug_idx = 100000; )
 473 
 474 // Compile a method.  entry_bci is -1 for normal compilations and indicates
 475 // the continuation bci for on stack replacement.
 476 
 477 
 478 Compile::Compile( ciEnv* ci_env, C2Compiler* compiler, ciMethod* target, int osr_bci, bool subsume_loads, bool do_escape_analysis )
 479                 : Phase(Compiler),
 480                   _env(ci_env),
 481                   _log(ci_env->log()),
 482                   _compile_id(ci_env->compile_id()),
 483                   _save_argument_registers(false),
 484                   _stub_name(NULL),
 485                   _stub_function(NULL),
 486                   _stub_entry_point(NULL),
 487                   _method(target),
 488                   _entry_bci(osr_bci),
 489                   _initial_gvn(NULL),
 490                   _for_igvn(NULL),
 491                   _warm_calls(NULL),
 492                   _subsume_loads(subsume_loads),
 493                   _do_escape_analysis(do_escape_analysis),
 494                   _failure_reason(NULL),
 495                   _code_buffer("Compile::Fill_buffer"),
 496                   _orig_pc_slot(0),
 497                   _orig_pc_slot_offset_in_bytes(0),
 498                   _has_method_handle_invokes(false),
 499                   _mach_constant_base_node(NULL),
 500                   _node_bundling_limit(0),
 501                   _node_bundling_base(NULL),
 502                   _java_calls(0),
 503                   _inner_loops(0),
 504                   _scratch_const_size(-1),
 505                   _in_scratch_emit_size(false),
 506 #ifndef PRODUCT
 507                   _trace_opto_output(TraceOptoOutput || method()->has_option("TraceOptoOutput")),
 508                   _printer(IdealGraphPrinter::printer()),
 509 #endif
 510                   _congraph(NULL) {
 511   C = this;
 512 
 513   CompileWrapper cw(this);
 514 #ifndef PRODUCT
 515   if (TimeCompiler2) {
 516     tty->print(" ");
 517     target->holder()->name()->print();
 518     tty->print(".");
 519     target->print_short_name();
 520     tty->print("  ");
 521   }
 522   TraceTime t1("Total compilation time", &_t_totalCompilation, TimeCompiler, TimeCompiler2);
 523   TraceTime t2(NULL, &_t_methodCompilation, TimeCompiler, false);
 524   bool print_opto_assembly = PrintOptoAssembly || _method->has_option("PrintOptoAssembly");
 525   if (!print_opto_assembly) {
 526     bool print_assembly = (PrintAssembly || _method->should_print_assembly());
 527     if (print_assembly && !Disassembler::can_decode()) {
 528       tty->print_cr("PrintAssembly request changed to PrintOptoAssembly");
 529       print_opto_assembly = true;
 530     }
 531   }
 532   set_print_assembly(print_opto_assembly);
 533   set_parsed_irreducible_loop(false);
 534 #endif
 535 
 536   if (ProfileTraps) {
 537     // Make sure the method being compiled gets its own MDO,
 538     // so we can at least track the decompile_count().
 539     method()->build_method_data();
 540   }
 541 
 542   Init(::AliasLevel);
 543 
 544 
 545   print_compile_messages();
 546 
 547   if (UseOldInlining || PrintCompilation NOT_PRODUCT( || PrintOpto) )
 548     _ilt = InlineTree::build_inline_tree_root();
 549   else
 550     _ilt = NULL;
 551 
 552   // Even if NO memory addresses are used, MergeMem nodes must have at least 1 slice
 553   assert(num_alias_types() >= AliasIdxRaw, "");
 554 
 555 #define MINIMUM_NODE_HASH  1023
 556   // Node list that Iterative GVN will start with
 557   Unique_Node_List for_igvn(comp_arena());
 558   set_for_igvn(&for_igvn);
 559 
 560   // GVN that will be run immediately on new nodes
 561   uint estimated_size = method()->code_size()*4+64;
 562   estimated_size = (estimated_size < MINIMUM_NODE_HASH ? MINIMUM_NODE_HASH : estimated_size);
 563   PhaseGVN gvn(node_arena(), estimated_size);
 564   set_initial_gvn(&gvn);
 565 
 566   { // Scope for timing the parser
 567     TracePhase t3("parse", &_t_parser, true);
 568 
 569     // Put top into the hash table ASAP.
 570     initial_gvn()->transform_no_reclaim(top());
 571 
 572     // Set up tf(), start(), and find a CallGenerator.
 573     CallGenerator* cg;
 574     if (is_osr_compilation()) {
 575       const TypeTuple *domain = StartOSRNode::osr_domain();
 576       const TypeTuple *range = TypeTuple::make_range(method()->signature());
 577       init_tf(TypeFunc::make(domain, range));
 578       StartNode* s = new (this, 2) StartOSRNode(root(), domain);
 579       initial_gvn()->set_type_bottom(s);
 580       init_start(s);
 581       cg = CallGenerator::for_osr(method(), entry_bci());
 582     } else {
 583       // Normal case.
 584       init_tf(TypeFunc::make(method()));
 585       StartNode* s = new (this, 2) StartNode(root(), tf()->domain());
 586       initial_gvn()->set_type_bottom(s);
 587       init_start(s);
 588       float past_uses = method()->interpreter_invocation_count();
 589       float expected_uses = past_uses;
 590       cg = CallGenerator::for_inline(method(), expected_uses);
 591     }
 592     if (failing())  return;
 593     if (cg == NULL) {
 594       record_method_not_compilable_all_tiers("cannot parse method");
 595       return;
 596     }
 597     JVMState* jvms = build_start_state(start(), tf());
 598     if ((jvms = cg->generate(jvms)) == NULL) {
 599       record_method_not_compilable("method parse failed");
 600       return;
 601     }
 602     GraphKit kit(jvms);
 603 
 604     if (!kit.stopped()) {
 605       // Accept return values, and transfer control we know not where.
 606       // This is done by a special, unique ReturnNode bound to root.
 607       return_values(kit.jvms());
 608     }
 609 
 610     if (kit.has_exceptions()) {
 611       // Any exceptions that escape from this call must be rethrown
 612       // to whatever caller is dynamically above us on the stack.
 613       // This is done by a special, unique RethrowNode bound to root.
 614       rethrow_exceptions(kit.transfer_exceptions_into_jvms());
 615     }
 616 
 617     if (!failing() && has_stringbuilder()) {
 618       {
 619         // remove useless nodes to make the usage analysis simpler
 620         ResourceMark rm;
 621         PhaseRemoveUseless pru(initial_gvn(), &for_igvn);
 622       }
 623 
 624       {
 625         ResourceMark rm;
 626         print_method("Before StringOpts", 3);
 627         PhaseStringOpts pso(initial_gvn(), &for_igvn);
 628         print_method("After StringOpts", 3);
 629       }
 630 
 631       // now inline anything that we skipped the first time around
 632       while (_late_inlines.length() > 0) {
 633         CallGenerator* cg = _late_inlines.pop();
 634         cg->do_late_inline();
 635       }
 636     }
 637     assert(_late_inlines.length() == 0, "should have been processed");
 638 
 639     print_method("Before RemoveUseless", 3);
 640 
 641     // Remove clutter produced by parsing.
 642     if (!failing()) {
 643       ResourceMark rm;
 644       PhaseRemoveUseless pru(initial_gvn(), &for_igvn);
 645     }
 646   }
 647 
 648   // Note:  Large methods are capped off in do_one_bytecode().
 649   if (failing())  return;
 650 
 651   // After parsing, node notes are no longer automagic.
 652   // They must be propagated by register_new_node_with_optimizer(),
 653   // clone(), or the like.
 654   set_default_node_notes(NULL);
 655 
 656   for (;;) {
 657     int successes = Inline_Warm();
 658     if (failing())  return;
 659     if (successes == 0)  break;
 660   }
 661 
 662   // Drain the list.
 663   Finish_Warm();
 664 #ifndef PRODUCT
 665   if (_printer) {
 666     _printer->print_inlining(this);
 667   }
 668 #endif
 669 
 670   if (failing())  return;
 671   NOT_PRODUCT( verify_graph_edges(); )
 672 
 673   // Now optimize
 674   Optimize();
 675   if (failing())  return;
 676   NOT_PRODUCT( verify_graph_edges(); )
 677 
 678 #ifndef PRODUCT
 679   if (PrintIdeal) {
 680     ttyLocker ttyl;  // keep the following output all in one block
 681     // This output goes directly to the tty, not the compiler log.
 682     // To enable tools to match it up with the compilation activity,
 683     // be sure to tag this tty output with the compile ID.
 684     if (xtty != NULL) {
 685       xtty->head("ideal compile_id='%d'%s", compile_id(),
 686                  is_osr_compilation()    ? " compile_kind='osr'" :
 687                  "");
 688     }
 689     root()->dump(9999);
 690     if (xtty != NULL) {
 691       xtty->tail("ideal");
 692     }
 693   }
 694 #endif
 695 
 696   // Now that we know the size of all the monitors we can add a fixed slot
 697   // for the original deopt pc.
 698 
 699   _orig_pc_slot =  fixed_slots();
 700   int next_slot = _orig_pc_slot + (sizeof(address) / VMRegImpl::stack_slot_size);
 701   set_fixed_slots(next_slot);
 702 
 703   // Now generate code
 704   Code_Gen();
 705   if (failing())  return;
 706 
 707   // Check if we want to skip execution of all compiled code.
 708   {
 709 #ifndef PRODUCT
 710     if (OptoNoExecute) {
 711       record_method_not_compilable("+OptoNoExecute");  // Flag as failed
 712       return;
 713     }
 714     TracePhase t2("install_code", &_t_registerMethod, TimeCompiler);
 715 #endif
 716 
 717     if (is_osr_compilation()) {
 718       _code_offsets.set_value(CodeOffsets::Verified_Entry, 0);
 719       _code_offsets.set_value(CodeOffsets::OSR_Entry, _first_block_size);
 720     } else {
 721       _code_offsets.set_value(CodeOffsets::Verified_Entry, _first_block_size);
 722       _code_offsets.set_value(CodeOffsets::OSR_Entry, 0);
 723     }
 724 
 725     env()->register_method(_method, _entry_bci,
 726                            &_code_offsets,
 727                            _orig_pc_slot_offset_in_bytes,
 728                            code_buffer(),
 729                            frame_size_in_words(), _oop_map_set,
 730                            &_handler_table, &_inc_table,
 731                            compiler,
 732                            env()->comp_level(),
 733                            true, /*has_debug_info*/
 734                            has_unsafe_access()
 735                            );
 736   }
 737 }
 738 
 739 //------------------------------Compile----------------------------------------
 740 // Compile a runtime stub
 741 Compile::Compile( ciEnv* ci_env,
 742                   TypeFunc_generator generator,
 743                   address stub_function,
 744                   const char *stub_name,
 745                   int is_fancy_jump,
 746                   bool pass_tls,
 747                   bool save_arg_registers,
 748                   bool return_pc )
 749   : Phase(Compiler),
 750     _env(ci_env),
 751     _log(ci_env->log()),
 752     _compile_id(-1),
 753     _save_argument_registers(save_arg_registers),
 754     _method(NULL),
 755     _stub_name(stub_name),
 756     _stub_function(stub_function),
 757     _stub_entry_point(NULL),
 758     _entry_bci(InvocationEntryBci),
 759     _initial_gvn(NULL),
 760     _for_igvn(NULL),
 761     _warm_calls(NULL),
 762     _orig_pc_slot(0),
 763     _orig_pc_slot_offset_in_bytes(0),
 764     _subsume_loads(true),
 765     _do_escape_analysis(false),
 766     _failure_reason(NULL),
 767     _code_buffer("Compile::Fill_buffer"),
 768     _has_method_handle_invokes(false),
 769     _mach_constant_base_node(NULL),
 770     _node_bundling_limit(0),
 771     _node_bundling_base(NULL),
 772     _java_calls(0),
 773     _inner_loops(0),
 774 #ifndef PRODUCT
 775     _trace_opto_output(TraceOptoOutput),
 776     _printer(NULL),
 777 #endif
 778     _congraph(NULL) {
 779   C = this;
 780 
 781 #ifndef PRODUCT
 782   TraceTime t1(NULL, &_t_totalCompilation, TimeCompiler, false);
 783   TraceTime t2(NULL, &_t_stubCompilation, TimeCompiler, false);
 784   set_print_assembly(PrintFrameConverterAssembly);
 785   set_parsed_irreducible_loop(false);
 786 #endif
 787   CompileWrapper cw(this);
 788   Init(/*AliasLevel=*/ 0);
 789   init_tf((*generator)());
 790 
 791   {
 792     // The following is a dummy for the sake of GraphKit::gen_stub
 793     Unique_Node_List for_igvn(comp_arena());
 794     set_for_igvn(&for_igvn);  // not used, but some GraphKit guys push on this
 795     PhaseGVN gvn(Thread::current()->resource_area(),255);
 796     set_initial_gvn(&gvn);    // not significant, but GraphKit guys use it pervasively
 797     gvn.transform_no_reclaim(top());
 798 
 799     GraphKit kit;
 800     kit.gen_stub(stub_function, stub_name, is_fancy_jump, pass_tls, return_pc);
 801   }
 802 
 803   NOT_PRODUCT( verify_graph_edges(); )
 804   Code_Gen();
 805   if (failing())  return;
 806 
 807 
 808   // Entry point will be accessed using compile->stub_entry_point();
 809   if (code_buffer() == NULL) {
 810     Matcher::soft_match_failure();
 811   } else {
 812     if (PrintAssembly && (WizardMode || Verbose))
 813       tty->print_cr("### Stub::%s", stub_name);
 814 
 815     if (!failing()) {
 816       assert(_fixed_slots == 0, "no fixed slots used for runtime stubs");
 817 
 818       // Make the NMethod
 819       // For now we mark the frame as never safe for profile stackwalking
 820       RuntimeStub *rs = RuntimeStub::new_runtime_stub(stub_name,
 821                                                       code_buffer(),
 822                                                       CodeOffsets::frame_never_safe,
 823                                                       // _code_offsets.value(CodeOffsets::Frame_Complete),
 824                                                       frame_size_in_words(),
 825                                                       _oop_map_set,
 826                                                       save_arg_registers);
 827       assert(rs != NULL && rs->is_runtime_stub(), "sanity check");
 828 
 829       _stub_entry_point = rs->entry_point();
 830     }
 831   }
 832 }
 833 
 834 #ifndef PRODUCT
 835 void print_opto_verbose_signature( const TypeFunc *j_sig, const char *stub_name ) {
 836   if(PrintOpto && Verbose) {
 837     tty->print("%s   ", stub_name); j_sig->print_flattened(); tty->cr();
 838   }
 839 }
 840 #endif
 841 
 842 void Compile::print_codes() {
 843 }
 844 
 845 //------------------------------Init-------------------------------------------
 846 // Prepare for a single compilation
 847 void Compile::Init(int aliaslevel) {
 848   _unique  = 0;
 849   _regalloc = NULL;
 850 
 851   _tf      = NULL;  // filled in later
 852   _top     = NULL;  // cached later
 853   _matcher = NULL;  // filled in later
 854   _cfg     = NULL;  // filled in later
 855 
 856   set_24_bit_selection_and_mode(Use24BitFP, false);
 857 
 858   _node_note_array = NULL;
 859   _default_node_notes = NULL;
 860 
 861   _immutable_memory = NULL; // filled in at first inquiry
 862 
 863   // Globally visible Nodes
 864   // First set TOP to NULL to give safe behavior during creation of RootNode
 865   set_cached_top_node(NULL);
 866   set_root(new (this, 3) RootNode());
 867   // Now that you have a Root to point to, create the real TOP
 868   set_cached_top_node( new (this, 1) ConNode(Type::TOP) );
 869   set_recent_alloc(NULL, NULL);
 870 
 871   // Create Debug Information Recorder to record scopes, oopmaps, etc.
 872   env()->set_oop_recorder(new OopRecorder(comp_arena()));
 873   env()->set_debug_info(new DebugInformationRecorder(env()->oop_recorder()));
 874   env()->set_dependencies(new Dependencies(env()));
 875 
 876   _fixed_slots = 0;
 877   set_has_split_ifs(false);
 878   set_has_loops(has_method() && method()->has_loops()); // first approximation
 879   set_has_stringbuilder(false);
 880   _trap_can_recompile = false;  // no traps emitted yet
 881   _major_progress = true; // start out assuming good things will happen
 882   set_has_unsafe_access(false);
 883   Copy::zero_to_bytes(_trap_hist, sizeof(_trap_hist));
 884   set_decompile_count(0);
 885 
 886   set_do_freq_based_layout(BlockLayoutByFrequency || method_has_option("BlockLayoutByFrequency"));
 887   set_num_loop_opts(LoopOptsCount);
 888   set_do_inlining(Inline);
 889   set_max_inline_size(MaxInlineSize);
 890   set_freq_inline_size(FreqInlineSize);
 891   set_do_scheduling(OptoScheduling);
 892   set_do_count_invocations(false);
 893   set_do_method_data_update(false);
 894 
 895   if (debug_info()->recording_non_safepoints()) {
 896     set_node_note_array(new(comp_arena()) GrowableArray<Node_Notes*>
 897                         (comp_arena(), 8, 0, NULL));
 898     set_default_node_notes(Node_Notes::make(this));
 899   }
 900 
 901   // // -- Initialize types before each compile --
 902   // // Update cached type information
 903   // if( _method && _method->constants() )
 904   //   Type::update_loaded_types(_method, _method->constants());
 905 
 906   // Init alias_type map.
 907   if (!_do_escape_analysis && aliaslevel == 3)
 908     aliaslevel = 2;  // No unique types without escape analysis
 909   _AliasLevel = aliaslevel;
 910   const int grow_ats = 16;
 911   _max_alias_types = grow_ats;
 912   _alias_types   = NEW_ARENA_ARRAY(comp_arena(), AliasType*, grow_ats);
 913   AliasType* ats = NEW_ARENA_ARRAY(comp_arena(), AliasType,  grow_ats);
 914   Copy::zero_to_bytes(ats, sizeof(AliasType)*grow_ats);
 915   {
 916     for (int i = 0; i < grow_ats; i++)  _alias_types[i] = &ats[i];
 917   }
 918   // Initialize the first few types.
 919   _alias_types[AliasIdxTop]->Init(AliasIdxTop, NULL);
 920   _alias_types[AliasIdxBot]->Init(AliasIdxBot, TypePtr::BOTTOM);
 921   _alias_types[AliasIdxRaw]->Init(AliasIdxRaw, TypeRawPtr::BOTTOM);
 922   _num_alias_types = AliasIdxRaw+1;
 923   // Zero out the alias type cache.
 924   Copy::zero_to_bytes(_alias_cache, sizeof(_alias_cache));
 925   // A NULL adr_type hits in the cache right away.  Preload the right answer.
 926   probe_alias_cache(NULL)->_index = AliasIdxTop;
 927 
 928   _intrinsics = NULL;
 929   _macro_nodes = new(comp_arena()) GrowableArray<Node*>(comp_arena(), 8,  0, NULL);
 930   _predicate_opaqs = new(comp_arena()) GrowableArray<Node*>(comp_arena(), 8,  0, NULL);
 931   register_library_intrinsics();
 932 }
 933 
 934 //---------------------------init_start----------------------------------------
 935 // Install the StartNode on this compile object.
 936 void Compile::init_start(StartNode* s) {
 937   if (failing())
 938     return; // already failing
 939   assert(s == start(), "");
 940 }
 941 
 942 StartNode* Compile::start() const {
 943   assert(!failing(), "");
 944   for (DUIterator_Fast imax, i = root()->fast_outs(imax); i < imax; i++) {
 945     Node* start = root()->fast_out(i);
 946     if( start->is_Start() )
 947       return start->as_Start();
 948   }
 949   ShouldNotReachHere();
 950   return NULL;
 951 }
 952 
 953 //-------------------------------immutable_memory-------------------------------------
 954 // Access immutable memory
 955 Node* Compile::immutable_memory() {
 956   if (_immutable_memory != NULL) {
 957     return _immutable_memory;
 958   }
 959   StartNode* s = start();
 960   for (DUIterator_Fast imax, i = s->fast_outs(imax); true; i++) {
 961     Node *p = s->fast_out(i);
 962     if (p != s && p->as_Proj()->_con == TypeFunc::Memory) {
 963       _immutable_memory = p;
 964       return _immutable_memory;
 965     }
 966   }
 967   ShouldNotReachHere();
 968   return NULL;
 969 }
 970 
 971 //----------------------set_cached_top_node------------------------------------
 972 // Install the cached top node, and make sure Node::is_top works correctly.
 973 void Compile::set_cached_top_node(Node* tn) {
 974   if (tn != NULL)  verify_top(tn);
 975   Node* old_top = _top;
 976   _top = tn;
 977   // Calling Node::setup_is_top allows the nodes the chance to adjust
 978   // their _out arrays.
 979   if (_top != NULL)     _top->setup_is_top();
 980   if (old_top != NULL)  old_top->setup_is_top();
 981   assert(_top == NULL || top()->is_top(), "");
 982 }
 983 
 984 #ifndef PRODUCT
 985 void Compile::verify_top(Node* tn) const {
 986   if (tn != NULL) {
 987     assert(tn->is_Con(), "top node must be a constant");
 988     assert(((ConNode*)tn)->type() == Type::TOP, "top node must have correct type");
 989     assert(tn->in(0) != NULL, "must have live top node");
 990   }
 991 }
 992 #endif
 993 
 994 
 995 ///-------------------Managing Per-Node Debug & Profile Info-------------------
 996 
 997 void Compile::grow_node_notes(GrowableArray<Node_Notes*>* arr, int grow_by) {
 998   guarantee(arr != NULL, "");
 999   int num_blocks = arr->length();
1000   if (grow_by < num_blocks)  grow_by = num_blocks;
1001   int num_notes = grow_by * _node_notes_block_size;
1002   Node_Notes* notes = NEW_ARENA_ARRAY(node_arena(), Node_Notes, num_notes);
1003   Copy::zero_to_bytes(notes, num_notes * sizeof(Node_Notes));
1004   while (num_notes > 0) {
1005     arr->append(notes);
1006     notes     += _node_notes_block_size;
1007     num_notes -= _node_notes_block_size;
1008   }
1009   assert(num_notes == 0, "exact multiple, please");
1010 }
1011 
1012 bool Compile::copy_node_notes_to(Node* dest, Node* source) {
1013   if (source == NULL || dest == NULL)  return false;
1014 
1015   if (dest->is_Con())
1016     return false;               // Do not push debug info onto constants.
1017 
1018 #ifdef ASSERT
1019   // Leave a bread crumb trail pointing to the original node:
1020   if (dest != NULL && dest != source && dest->debug_orig() == NULL) {
1021     dest->set_debug_orig(source);
1022   }
1023 #endif
1024 
1025   if (node_note_array() == NULL)
1026     return false;               // Not collecting any notes now.
1027 
1028   // This is a copy onto a pre-existing node, which may already have notes.
1029   // If both nodes have notes, do not overwrite any pre-existing notes.
1030   Node_Notes* source_notes = node_notes_at(source->_idx);
1031   if (source_notes == NULL || source_notes->is_clear())  return false;
1032   Node_Notes* dest_notes   = node_notes_at(dest->_idx);
1033   if (dest_notes == NULL || dest_notes->is_clear()) {
1034     return set_node_notes_at(dest->_idx, source_notes);
1035   }
1036 
1037   Node_Notes merged_notes = (*source_notes);
1038   // The order of operations here ensures that dest notes will win...
1039   merged_notes.update_from(dest_notes);
1040   return set_node_notes_at(dest->_idx, &merged_notes);
1041 }
1042 
1043 
1044 //--------------------------allow_range_check_smearing-------------------------
1045 // Gating condition for coalescing similar range checks.
1046 // Sometimes we try 'speculatively' replacing a series of a range checks by a
1047 // single covering check that is at least as strong as any of them.
1048 // If the optimization succeeds, the simplified (strengthened) range check
1049 // will always succeed.  If it fails, we will deopt, and then give up
1050 // on the optimization.
1051 bool Compile::allow_range_check_smearing() const {
1052   // If this method has already thrown a range-check,
1053   // assume it was because we already tried range smearing
1054   // and it failed.
1055   uint already_trapped = trap_count(Deoptimization::Reason_range_check);
1056   return !already_trapped;
1057 }
1058 
1059 
1060 //------------------------------flatten_alias_type-----------------------------
1061 const TypePtr *Compile::flatten_alias_type( const TypePtr *tj ) const {
1062   int offset = tj->offset();
1063   TypePtr::PTR ptr = tj->ptr();
1064 
1065   // Known instance (scalarizable allocation) alias only with itself.
1066   bool is_known_inst = tj->isa_oopptr() != NULL &&
1067                        tj->is_oopptr()->is_known_instance();
1068 
1069   // Process weird unsafe references.
1070   if (offset == Type::OffsetBot && (tj->isa_instptr() /*|| tj->isa_klassptr()*/)) {
1071     assert(InlineUnsafeOps, "indeterminate pointers come only from unsafe ops");
1072     assert(!is_known_inst, "scalarizable allocation should not have unsafe references");
1073     tj = TypeOopPtr::BOTTOM;
1074     ptr = tj->ptr();
1075     offset = tj->offset();
1076   }
1077 
1078   // Array pointers need some flattening
1079   const TypeAryPtr *ta = tj->isa_aryptr();
1080   if( ta && is_known_inst ) {
1081     if ( offset != Type::OffsetBot &&
1082          offset > arrayOopDesc::length_offset_in_bytes() ) {
1083       offset = Type::OffsetBot; // Flatten constant access into array body only
1084       tj = ta = TypeAryPtr::make(ptr, ta->ary(), ta->klass(), true, offset, ta->instance_id());
1085     }
1086   } else if( ta && _AliasLevel >= 2 ) {
1087     // For arrays indexed by constant indices, we flatten the alias
1088     // space to include all of the array body.  Only the header, klass
1089     // and array length can be accessed un-aliased.
1090     if( offset != Type::OffsetBot ) {
1091       if( ta->const_oop() ) { // methodDataOop or methodOop
1092         offset = Type::OffsetBot;   // Flatten constant access into array body
1093         tj = ta = TypeAryPtr::make(ptr,ta->const_oop(),ta->ary(),ta->klass(),false,offset);
1094       } else if( offset == arrayOopDesc::length_offset_in_bytes() ) {
1095         // range is OK as-is.
1096         tj = ta = TypeAryPtr::RANGE;
1097       } else if( offset == oopDesc::klass_offset_in_bytes() ) {
1098         tj = TypeInstPtr::KLASS; // all klass loads look alike
1099         ta = TypeAryPtr::RANGE; // generic ignored junk
1100         ptr = TypePtr::BotPTR;
1101       } else if( offset == oopDesc::mark_offset_in_bytes() ) {
1102         tj = TypeInstPtr::MARK;
1103         ta = TypeAryPtr::RANGE; // generic ignored junk
1104         ptr = TypePtr::BotPTR;
1105       } else {                  // Random constant offset into array body
1106         offset = Type::OffsetBot;   // Flatten constant access into array body
1107         tj = ta = TypeAryPtr::make(ptr,ta->ary(),ta->klass(),false,offset);
1108       }
1109     }
1110     // Arrays of fixed size alias with arrays of unknown size.
1111     if (ta->size() != TypeInt::POS) {
1112       const TypeAry *tary = TypeAry::make(ta->elem(), TypeInt::POS);
1113       tj = ta = TypeAryPtr::make(ptr,ta->const_oop(),tary,ta->klass(),false,offset);
1114     }
1115     // Arrays of known objects become arrays of unknown objects.
1116     if (ta->elem()->isa_narrowoop() && ta->elem() != TypeNarrowOop::BOTTOM) {
1117       const TypeAry *tary = TypeAry::make(TypeNarrowOop::BOTTOM, ta->size());
1118       tj = ta = TypeAryPtr::make(ptr,ta->const_oop(),tary,NULL,false,offset);
1119     }
1120     if (ta->elem()->isa_oopptr() && ta->elem() != TypeInstPtr::BOTTOM) {
1121       const TypeAry *tary = TypeAry::make(TypeInstPtr::BOTTOM, ta->size());
1122       tj = ta = TypeAryPtr::make(ptr,ta->const_oop(),tary,NULL,false,offset);
1123     }
1124     // Arrays of bytes and of booleans both use 'bastore' and 'baload' so
1125     // cannot be distinguished by bytecode alone.
1126     if (ta->elem() == TypeInt::BOOL) {
1127       const TypeAry *tary = TypeAry::make(TypeInt::BYTE, ta->size());
1128       ciKlass* aklass = ciTypeArrayKlass::make(T_BYTE);
1129       tj = ta = TypeAryPtr::make(ptr,ta->const_oop(),tary,aklass,false,offset);
1130     }
1131     // During the 2nd round of IterGVN, NotNull castings are removed.
1132     // Make sure the Bottom and NotNull variants alias the same.
1133     // Also, make sure exact and non-exact variants alias the same.
1134     if( ptr == TypePtr::NotNull || ta->klass_is_exact() ) {
1135       if (ta->const_oop()) {
1136         tj = ta = TypeAryPtr::make(TypePtr::Constant,ta->const_oop(),ta->ary(),ta->klass(),false,offset);
1137       } else {
1138         tj = ta = TypeAryPtr::make(TypePtr::BotPTR,ta->ary(),ta->klass(),false,offset);
1139       }
1140     }
1141   }
1142 
1143   // Oop pointers need some flattening
1144   const TypeInstPtr *to = tj->isa_instptr();
1145   if( to && _AliasLevel >= 2 && to != TypeOopPtr::BOTTOM ) {
1146     if( ptr == TypePtr::Constant ) {
1147       // No constant oop pointers (such as Strings); they alias with
1148       // unknown strings.
1149       assert(!is_known_inst, "not scalarizable allocation");
1150       tj = to = TypeInstPtr::make(TypePtr::BotPTR,to->klass(),false,0,offset);
1151     } else if( is_known_inst ) {
1152       tj = to; // Keep NotNull and klass_is_exact for instance type
1153     } else if( ptr == TypePtr::NotNull || to->klass_is_exact() ) {
1154       // During the 2nd round of IterGVN, NotNull castings are removed.
1155       // Make sure the Bottom and NotNull variants alias the same.
1156       // Also, make sure exact and non-exact variants alias the same.
1157       tj = to = TypeInstPtr::make(TypePtr::BotPTR,to->klass(),false,0,offset);
1158     }
1159     // Canonicalize the holder of this field
1160     ciInstanceKlass *k = to->klass()->as_instance_klass();
1161     if (offset >= 0 && offset < instanceOopDesc::base_offset_in_bytes()) {
1162       // First handle header references such as a LoadKlassNode, even if the
1163       // object's klass is unloaded at compile time (4965979).
1164       if (!is_known_inst) { // Do it only for non-instance types
1165         tj = to = TypeInstPtr::make(TypePtr::BotPTR, env()->Object_klass(), false, NULL, offset);
1166       }
1167     } else if (offset < 0 || offset >= k->size_helper() * wordSize) {
1168       to = NULL;
1169       tj = TypeOopPtr::BOTTOM;
1170       offset = tj->offset();
1171     } else {
1172       ciInstanceKlass *canonical_holder = k->get_canonical_holder(offset);
1173       if (!k->equals(canonical_holder) || tj->offset() != offset) {
1174         if( is_known_inst ) {
1175           tj = to = TypeInstPtr::make(to->ptr(), canonical_holder, true, NULL, offset, to->instance_id());
1176         } else {
1177           tj = to = TypeInstPtr::make(to->ptr(), canonical_holder, false, NULL, offset);
1178         }
1179       }
1180     }
1181   }
1182 
1183   // Klass pointers to object array klasses need some flattening
1184   const TypeKlassPtr *tk = tj->isa_klassptr();
1185   if( tk ) {
1186     // If we are referencing a field within a Klass, we need
1187     // to assume the worst case of an Object.  Both exact and
1188     // inexact types must flatten to the same alias class.
1189     // Since the flattened result for a klass is defined to be
1190     // precisely java.lang.Object, use a constant ptr.
1191     if ( offset == Type::OffsetBot || (offset >= 0 && (size_t)offset < sizeof(Klass)) ) {
1192 
1193       tj = tk = TypeKlassPtr::make(TypePtr::Constant,
1194                                    TypeKlassPtr::OBJECT->klass(),
1195                                    offset);
1196     }
1197 
1198     ciKlass* klass = tk->klass();
1199     if( klass->is_obj_array_klass() ) {
1200       ciKlass* k = TypeAryPtr::OOPS->klass();
1201       if( !k || !k->is_loaded() )                  // Only fails for some -Xcomp runs
1202         k = TypeInstPtr::BOTTOM->klass();
1203       tj = tk = TypeKlassPtr::make( TypePtr::NotNull, k, offset );
1204     }
1205 
1206     // Check for precise loads from the primary supertype array and force them
1207     // to the supertype cache alias index.  Check for generic array loads from
1208     // the primary supertype array and also force them to the supertype cache
1209     // alias index.  Since the same load can reach both, we need to merge
1210     // these 2 disparate memories into the same alias class.  Since the
1211     // primary supertype array is read-only, there's no chance of confusion
1212     // where we bypass an array load and an array store.
1213     uint off2 = offset - Klass::primary_supers_offset_in_bytes();
1214     if( offset == Type::OffsetBot ||
1215         off2 < Klass::primary_super_limit()*wordSize ) {
1216       offset = sizeof(oopDesc) +Klass::secondary_super_cache_offset_in_bytes();
1217       tj = tk = TypeKlassPtr::make( TypePtr::NotNull, tk->klass(), offset );
1218     }
1219   }
1220 
1221   // Flatten all Raw pointers together.
1222   if (tj->base() == Type::RawPtr)
1223     tj = TypeRawPtr::BOTTOM;
1224 
1225   if (tj->base() == Type::AnyPtr)
1226     tj = TypePtr::BOTTOM;      // An error, which the caller must check for.
1227 
1228   // Flatten all to bottom for now
1229   switch( _AliasLevel ) {
1230   case 0:
1231     tj = TypePtr::BOTTOM;
1232     break;
1233   case 1:                       // Flatten to: oop, static, field or array
1234     switch (tj->base()) {
1235     //case Type::AryPtr: tj = TypeAryPtr::RANGE;    break;
1236     case Type::RawPtr:   tj = TypeRawPtr::BOTTOM;   break;
1237     case Type::AryPtr:   // do not distinguish arrays at all
1238     case Type::InstPtr:  tj = TypeInstPtr::BOTTOM;  break;
1239     case Type::KlassPtr: tj = TypeKlassPtr::OBJECT; break;
1240     case Type::AnyPtr:   tj = TypePtr::BOTTOM;      break;  // caller checks it
1241     default: ShouldNotReachHere();
1242     }
1243     break;
1244   case 2:                       // No collapsing at level 2; keep all splits
1245   case 3:                       // No collapsing at level 3; keep all splits
1246     break;
1247   default:
1248     Unimplemented();
1249   }
1250 
1251   offset = tj->offset();
1252   assert( offset != Type::OffsetTop, "Offset has fallen from constant" );
1253 
1254   assert( (offset != Type::OffsetBot && tj->base() != Type::AryPtr) ||
1255           (offset == Type::OffsetBot && tj->base() == Type::AryPtr) ||
1256           (offset == Type::OffsetBot && tj == TypeOopPtr::BOTTOM) ||
1257           (offset == Type::OffsetBot && tj == TypePtr::BOTTOM) ||
1258           (offset == oopDesc::mark_offset_in_bytes() && tj->base() == Type::AryPtr) ||
1259           (offset == oopDesc::klass_offset_in_bytes() && tj->base() == Type::AryPtr) ||
1260           (offset == arrayOopDesc::length_offset_in_bytes() && tj->base() == Type::AryPtr)  ,
1261           "For oops, klasses, raw offset must be constant; for arrays the offset is never known" );
1262   assert( tj->ptr() != TypePtr::TopPTR &&
1263           tj->ptr() != TypePtr::AnyNull &&
1264           tj->ptr() != TypePtr::Null, "No imprecise addresses" );
1265 //    assert( tj->ptr() != TypePtr::Constant ||
1266 //            tj->base() == Type::RawPtr ||
1267 //            tj->base() == Type::KlassPtr, "No constant oop addresses" );
1268 
1269   return tj;
1270 }
1271 
1272 void Compile::AliasType::Init(int i, const TypePtr* at) {
1273   _index = i;
1274   _adr_type = at;
1275   _field = NULL;
1276   _is_rewritable = true; // default
1277   const TypeOopPtr *atoop = (at != NULL) ? at->isa_oopptr() : NULL;
1278   if (atoop != NULL && atoop->is_known_instance()) {
1279     const TypeOopPtr *gt = atoop->cast_to_instance_id(TypeOopPtr::InstanceBot);
1280     _general_index = Compile::current()->get_alias_index(gt);
1281   } else {
1282     _general_index = 0;
1283   }
1284 }
1285 
1286 //---------------------------------print_on------------------------------------
1287 #ifndef PRODUCT
1288 void Compile::AliasType::print_on(outputStream* st) {
1289   if (index() < 10)
1290         st->print("@ <%d> ", index());
1291   else  st->print("@ <%d>",  index());
1292   st->print(is_rewritable() ? "   " : " RO");
1293   int offset = adr_type()->offset();
1294   if (offset == Type::OffsetBot)
1295         st->print(" +any");
1296   else  st->print(" +%-3d", offset);
1297   st->print(" in ");
1298   adr_type()->dump_on(st);
1299   const TypeOopPtr* tjp = adr_type()->isa_oopptr();
1300   if (field() != NULL && tjp) {
1301     if (tjp->klass()  != field()->holder() ||
1302         tjp->offset() != field()->offset_in_bytes()) {
1303       st->print(" != ");
1304       field()->print();
1305       st->print(" ***");
1306     }
1307   }
1308 }
1309 
1310 void print_alias_types() {
1311   Compile* C = Compile::current();
1312   tty->print_cr("--- Alias types, AliasIdxBot .. %d", C->num_alias_types()-1);
1313   for (int idx = Compile::AliasIdxBot; idx < C->num_alias_types(); idx++) {
1314     C->alias_type(idx)->print_on(tty);
1315     tty->cr();
1316   }
1317 }
1318 #endif
1319 
1320 
1321 //----------------------------probe_alias_cache--------------------------------
1322 Compile::AliasCacheEntry* Compile::probe_alias_cache(const TypePtr* adr_type) {
1323   intptr_t key = (intptr_t) adr_type;
1324   key ^= key >> logAliasCacheSize;
1325   return &_alias_cache[key & right_n_bits(logAliasCacheSize)];
1326 }
1327 
1328 
1329 //-----------------------------grow_alias_types--------------------------------
1330 void Compile::grow_alias_types() {
1331   const int old_ats  = _max_alias_types; // how many before?
1332   const int new_ats  = old_ats;          // how many more?
1333   const int grow_ats = old_ats+new_ats;  // how many now?
1334   _max_alias_types = grow_ats;
1335   _alias_types =  REALLOC_ARENA_ARRAY(comp_arena(), AliasType*, _alias_types, old_ats, grow_ats);
1336   AliasType* ats =    NEW_ARENA_ARRAY(comp_arena(), AliasType, new_ats);
1337   Copy::zero_to_bytes(ats, sizeof(AliasType)*new_ats);
1338   for (int i = 0; i < new_ats; i++)  _alias_types[old_ats+i] = &ats[i];
1339 }
1340 
1341 
1342 //--------------------------------find_alias_type------------------------------
1343 Compile::AliasType* Compile::find_alias_type(const TypePtr* adr_type, bool no_create) {
1344   if (_AliasLevel == 0)
1345     return alias_type(AliasIdxBot);
1346 
1347   AliasCacheEntry* ace = probe_alias_cache(adr_type);
1348   if (ace->_adr_type == adr_type) {
1349     return alias_type(ace->_index);
1350   }
1351 
1352   // Handle special cases.
1353   if (adr_type == NULL)             return alias_type(AliasIdxTop);
1354   if (adr_type == TypePtr::BOTTOM)  return alias_type(AliasIdxBot);
1355 
1356   // Do it the slow way.
1357   const TypePtr* flat = flatten_alias_type(adr_type);
1358 
1359 #ifdef ASSERT
1360   assert(flat == flatten_alias_type(flat), "idempotent");
1361   assert(flat != TypePtr::BOTTOM,     "cannot alias-analyze an untyped ptr");
1362   if (flat->isa_oopptr() && !flat->isa_klassptr()) {
1363     const TypeOopPtr* foop = flat->is_oopptr();
1364     // Scalarizable allocations have exact klass always.
1365     bool exact = !foop->klass_is_exact() || foop->is_known_instance();
1366     const TypePtr* xoop = foop->cast_to_exactness(exact)->is_ptr();
1367     assert(foop == flatten_alias_type(xoop), "exactness must not affect alias type");
1368   }
1369   assert(flat == flatten_alias_type(flat), "exact bit doesn't matter");
1370 #endif
1371 
1372   int idx = AliasIdxTop;
1373   for (int i = 0; i < num_alias_types(); i++) {
1374     if (alias_type(i)->adr_type() == flat) {
1375       idx = i;
1376       break;
1377     }
1378   }
1379 
1380   if (idx == AliasIdxTop) {
1381     if (no_create)  return NULL;
1382     // Grow the array if necessary.
1383     if (_num_alias_types == _max_alias_types)  grow_alias_types();
1384     // Add a new alias type.
1385     idx = _num_alias_types++;
1386     _alias_types[idx]->Init(idx, flat);
1387     if (flat == TypeInstPtr::KLASS)  alias_type(idx)->set_rewritable(false);
1388     if (flat == TypeAryPtr::RANGE)   alias_type(idx)->set_rewritable(false);
1389     if (flat->isa_instptr()) {
1390       if (flat->offset() == java_lang_Class::klass_offset_in_bytes()
1391           && flat->is_instptr()->klass() == env()->Class_klass())
1392         alias_type(idx)->set_rewritable(false);
1393     }
1394     if (flat->isa_klassptr()) {
1395       if (flat->offset() == Klass::super_check_offset_offset_in_bytes() + (int)sizeof(oopDesc))
1396         alias_type(idx)->set_rewritable(false);
1397       if (flat->offset() == Klass::modifier_flags_offset_in_bytes() + (int)sizeof(oopDesc))
1398         alias_type(idx)->set_rewritable(false);
1399       if (flat->offset() == Klass::access_flags_offset_in_bytes() + (int)sizeof(oopDesc))
1400         alias_type(idx)->set_rewritable(false);
1401       if (flat->offset() == Klass::java_mirror_offset_in_bytes() + (int)sizeof(oopDesc))
1402         alias_type(idx)->set_rewritable(false);
1403     }
1404     // %%% (We would like to finalize JavaThread::threadObj_offset(),
1405     // but the base pointer type is not distinctive enough to identify
1406     // references into JavaThread.)
1407 
1408     // Check for final instance fields.
1409     const TypeInstPtr* tinst = flat->isa_instptr();
1410     if (tinst && tinst->offset() >= instanceOopDesc::base_offset_in_bytes()) {
1411       ciInstanceKlass *k = tinst->klass()->as_instance_klass();
1412       ciField* field = k->get_field_by_offset(tinst->offset(), false);
1413       // Set field() and is_rewritable() attributes.
1414       if (field != NULL)  alias_type(idx)->set_field(field);
1415     }
1416     const TypeKlassPtr* tklass = flat->isa_klassptr();
1417     // Check for final static fields.
1418     if (tklass && tklass->klass()->is_instance_klass()) {
1419       ciInstanceKlass *k = tklass->klass()->as_instance_klass();
1420       ciField* field = k->get_field_by_offset(tklass->offset(), true);
1421       // Set field() and is_rewritable() attributes.
1422       if (field != NULL)   alias_type(idx)->set_field(field);
1423     }
1424   }
1425 
1426   // Fill the cache for next time.
1427   ace->_adr_type = adr_type;
1428   ace->_index    = idx;
1429   assert(alias_type(adr_type) == alias_type(idx),  "type must be installed");
1430 
1431   // Might as well try to fill the cache for the flattened version, too.
1432   AliasCacheEntry* face = probe_alias_cache(flat);
1433   if (face->_adr_type == NULL) {
1434     face->_adr_type = flat;
1435     face->_index    = idx;
1436     assert(alias_type(flat) == alias_type(idx), "flat type must work too");
1437   }
1438 
1439   return alias_type(idx);
1440 }
1441 
1442 
1443 Compile::AliasType* Compile::alias_type(ciField* field) {
1444   const TypeOopPtr* t;
1445   if (field->is_static())
1446     t = TypeKlassPtr::make(field->holder());
1447   else
1448     t = TypeOopPtr::make_from_klass_raw(field->holder());
1449   AliasType* atp = alias_type(t->add_offset(field->offset_in_bytes()));
1450   assert(field->is_final() == !atp->is_rewritable(), "must get the rewritable bits correct");
1451   return atp;
1452 }
1453 
1454 
1455 //------------------------------have_alias_type--------------------------------
1456 bool Compile::have_alias_type(const TypePtr* adr_type) {
1457   AliasCacheEntry* ace = probe_alias_cache(adr_type);
1458   if (ace->_adr_type == adr_type) {
1459     return true;
1460   }
1461 
1462   // Handle special cases.
1463   if (adr_type == NULL)             return true;
1464   if (adr_type == TypePtr::BOTTOM)  return true;
1465 
1466   return find_alias_type(adr_type, true) != NULL;
1467 }
1468 
1469 //-----------------------------must_alias--------------------------------------
1470 // True if all values of the given address type are in the given alias category.
1471 bool Compile::must_alias(const TypePtr* adr_type, int alias_idx) {
1472   if (alias_idx == AliasIdxBot)         return true;  // the universal category
1473   if (adr_type == NULL)                 return true;  // NULL serves as TypePtr::TOP
1474   if (alias_idx == AliasIdxTop)         return false; // the empty category
1475   if (adr_type->base() == Type::AnyPtr) return false; // TypePtr::BOTTOM or its twins
1476 
1477   // the only remaining possible overlap is identity
1478   int adr_idx = get_alias_index(adr_type);
1479   assert(adr_idx != AliasIdxBot && adr_idx != AliasIdxTop, "");
1480   assert(adr_idx == alias_idx ||
1481          (alias_type(alias_idx)->adr_type() != TypeOopPtr::BOTTOM
1482           && adr_type                       != TypeOopPtr::BOTTOM),
1483          "should not be testing for overlap with an unsafe pointer");
1484   return adr_idx == alias_idx;
1485 }
1486 
1487 //------------------------------can_alias--------------------------------------
1488 // True if any values of the given address type are in the given alias category.
1489 bool Compile::can_alias(const TypePtr* adr_type, int alias_idx) {
1490   if (alias_idx == AliasIdxTop)         return false; // the empty category
1491   if (adr_type == NULL)                 return false; // NULL serves as TypePtr::TOP
1492   if (alias_idx == AliasIdxBot)         return true;  // the universal category
1493   if (adr_type->base() == Type::AnyPtr) return true;  // TypePtr::BOTTOM or its twins
1494 
1495   // the only remaining possible overlap is identity
1496   int adr_idx = get_alias_index(adr_type);
1497   assert(adr_idx != AliasIdxBot && adr_idx != AliasIdxTop, "");
1498   return adr_idx == alias_idx;
1499 }
1500 
1501 
1502 
1503 //---------------------------pop_warm_call-------------------------------------
1504 WarmCallInfo* Compile::pop_warm_call() {
1505   WarmCallInfo* wci = _warm_calls;
1506   if (wci != NULL)  _warm_calls = wci->remove_from(wci);
1507   return wci;
1508 }
1509 
1510 //----------------------------Inline_Warm--------------------------------------
1511 int Compile::Inline_Warm() {
1512   // If there is room, try to inline some more warm call sites.
1513   // %%% Do a graph index compaction pass when we think we're out of space?
1514   if (!InlineWarmCalls)  return 0;
1515 
1516   int calls_made_hot = 0;
1517   int room_to_grow   = NodeCountInliningCutoff - unique();
1518   int amount_to_grow = MIN2(room_to_grow, (int)NodeCountInliningStep);
1519   int amount_grown   = 0;
1520   WarmCallInfo* call;
1521   while (amount_to_grow > 0 && (call = pop_warm_call()) != NULL) {
1522     int est_size = (int)call->size();
1523     if (est_size > (room_to_grow - amount_grown)) {
1524       // This one won't fit anyway.  Get rid of it.
1525       call->make_cold();
1526       continue;
1527     }
1528     call->make_hot();
1529     calls_made_hot++;
1530     amount_grown   += est_size;
1531     amount_to_grow -= est_size;
1532   }
1533 
1534   if (calls_made_hot > 0)  set_major_progress();
1535   return calls_made_hot;
1536 }
1537 
1538 
1539 //----------------------------Finish_Warm--------------------------------------
1540 void Compile::Finish_Warm() {
1541   if (!InlineWarmCalls)  return;
1542   if (failing())  return;
1543   if (warm_calls() == NULL)  return;
1544 
1545   // Clean up loose ends, if we are out of space for inlining.
1546   WarmCallInfo* call;
1547   while ((call = pop_warm_call()) != NULL) {
1548     call->make_cold();
1549   }
1550 }
1551 
1552 //---------------------cleanup_loop_predicates-----------------------
1553 // Remove the opaque nodes that protect the predicates so that all unused
1554 // checks and uncommon_traps will be eliminated from the ideal graph
1555 void Compile::cleanup_loop_predicates(PhaseIterGVN &igvn) {
1556   if (predicate_count()==0) return;
1557   for (int i = predicate_count(); i > 0; i--) {
1558     Node * n = predicate_opaque1_node(i-1);
1559     assert(n->Opcode() == Op_Opaque1, "must be");
1560     igvn.replace_node(n, n->in(1));
1561   }
1562   assert(predicate_count()==0, "should be clean!");
1563   igvn.optimize();
1564 }
1565 
1566 //------------------------------Optimize---------------------------------------
1567 // Given a graph, optimize it.
1568 void Compile::Optimize() {
1569   TracePhase t1("optimizer", &_t_optimizer, true);
1570 
1571 #ifndef PRODUCT
1572   if (env()->break_at_compile()) {
1573     BREAKPOINT;
1574   }
1575 
1576 #endif
1577 
1578   ResourceMark rm;
1579   int          loop_opts_cnt;
1580 
1581   NOT_PRODUCT( verify_graph_edges(); )
1582 
1583   print_method("After Parsing");
1584 
1585  {
1586   // Iterative Global Value Numbering, including ideal transforms
1587   // Initialize IterGVN with types and values from parse-time GVN
1588   PhaseIterGVN igvn(initial_gvn());
1589   {
1590     NOT_PRODUCT( TracePhase t2("iterGVN", &_t_iterGVN, TimeCompiler); )
1591     igvn.optimize();
1592   }
1593 
1594   print_method("Iter GVN 1", 2);
1595 
1596   if (failing())  return;
1597 
1598   // Perform escape analysis
1599   if (_do_escape_analysis && ConnectionGraph::has_candidates(this)) {
1600     TracePhase t2("escapeAnalysis", &_t_escapeAnalysis, true);
1601     ConnectionGraph::do_analysis(this, &igvn);
1602 
1603     if (failing())  return;
1604 
1605     igvn.optimize();
1606     print_method("Iter GVN 3", 2);
1607 
1608     if (failing())  return;
1609 
1610   }
1611 
1612   // Loop transforms on the ideal graph.  Range Check Elimination,
1613   // peeling, unrolling, etc.
1614 
1615   // Set loop opts counter
1616   loop_opts_cnt = num_loop_opts();
1617   if((loop_opts_cnt > 0) && (has_loops() || has_split_ifs())) {
1618     {
1619       TracePhase t2("idealLoop", &_t_idealLoop, true);
1620       PhaseIdealLoop ideal_loop( igvn, true, UseLoopPredicate);
1621       loop_opts_cnt--;
1622       if (major_progress()) print_method("PhaseIdealLoop 1", 2);
1623       if (failing())  return;
1624     }
1625     // Loop opts pass if partial peeling occurred in previous pass
1626     if(PartialPeelLoop && major_progress() && (loop_opts_cnt > 0)) {
1627       TracePhase t3("idealLoop", &_t_idealLoop, true);
1628       PhaseIdealLoop ideal_loop( igvn, false, UseLoopPredicate);
1629       loop_opts_cnt--;
1630       if (major_progress()) print_method("PhaseIdealLoop 2", 2);
1631       if (failing())  return;
1632     }
1633     // Loop opts pass for loop-unrolling before CCP
1634     if(major_progress() && (loop_opts_cnt > 0)) {
1635       TracePhase t4("idealLoop", &_t_idealLoop, true);
1636       PhaseIdealLoop ideal_loop( igvn, false, UseLoopPredicate);
1637       loop_opts_cnt--;
1638       if (major_progress()) print_method("PhaseIdealLoop 3", 2);
1639     }
1640     if (!failing()) {
1641       // Verify that last round of loop opts produced a valid graph
1642       NOT_PRODUCT( TracePhase t2("idealLoopVerify", &_t_idealLoopVerify, TimeCompiler); )
1643       PhaseIdealLoop::verify(igvn);
1644     }
1645   }
1646   if (failing())  return;
1647 
1648   // Conditional Constant Propagation;
1649   PhaseCCP ccp( &igvn );
1650   assert( true, "Break here to ccp.dump_nodes_and_types(_root,999,1)");
1651   {
1652     TracePhase t2("ccp", &_t_ccp, true);
1653     ccp.do_transform();
1654   }
1655   print_method("PhaseCPP 1", 2);
1656 
1657   assert( true, "Break here to ccp.dump_old2new_map()");
1658 
1659   // Iterative Global Value Numbering, including ideal transforms
1660   {
1661     NOT_PRODUCT( TracePhase t2("iterGVN2", &_t_iterGVN2, TimeCompiler); )
1662     igvn = ccp;
1663     igvn.optimize();
1664   }
1665 
1666   print_method("Iter GVN 2", 2);
1667 
1668   if (failing())  return;
1669 
1670   // Loop transforms on the ideal graph.  Range Check Elimination,
1671   // peeling, unrolling, etc.
1672   if(loop_opts_cnt > 0) {
1673     debug_only( int cnt = 0; );
1674     bool loop_predication = UseLoopPredicate;
1675     while(major_progress() && (loop_opts_cnt > 0)) {
1676       TracePhase t2("idealLoop", &_t_idealLoop, true);
1677       assert( cnt++ < 40, "infinite cycle in loop optimization" );
1678       PhaseIdealLoop ideal_loop( igvn, true, loop_predication);
1679       loop_opts_cnt--;
1680       if (major_progress()) print_method("PhaseIdealLoop iterations", 2);
1681       if (failing())  return;
1682       // Perform loop predication optimization during first iteration after CCP.
1683       // After that switch it off and cleanup unused loop predicates.
1684       if (loop_predication) {
1685         loop_predication = false;
1686         cleanup_loop_predicates(igvn);
1687         if (failing())  return;
1688       }
1689     }
1690   }
1691 
1692   {
1693     // Verify that all previous optimizations produced a valid graph
1694     // at least to this point, even if no loop optimizations were done.
1695     NOT_PRODUCT( TracePhase t2("idealLoopVerify", &_t_idealLoopVerify, TimeCompiler); )
1696     PhaseIdealLoop::verify(igvn);
1697   }
1698 
1699   {
1700     NOT_PRODUCT( TracePhase t2("macroExpand", &_t_macroExpand, TimeCompiler); )
1701     PhaseMacroExpand  mex(igvn);
1702     if (mex.expand_macro_nodes()) {
1703       assert(failing(), "must bail out w/ explicit message");
1704       return;
1705     }
1706   }
1707 
1708  } // (End scope of igvn; run destructor if necessary for asserts.)
1709 
1710   // A method with only infinite loops has no edges entering loops from root
1711   {
1712     NOT_PRODUCT( TracePhase t2("graphReshape", &_t_graphReshaping, TimeCompiler); )
1713     if (final_graph_reshaping()) {
1714       assert(failing(), "must bail out w/ explicit message");
1715       return;
1716     }
1717   }
1718 
1719   print_method("Optimize finished", 2);
1720 }
1721 
1722 
1723 //------------------------------Code_Gen---------------------------------------
1724 // Given a graph, generate code for it
1725 void Compile::Code_Gen() {
1726   if (failing())  return;
1727 
1728   // Perform instruction selection.  You might think we could reclaim Matcher
1729   // memory PDQ, but actually the Matcher is used in generating spill code.
1730   // Internals of the Matcher (including some VectorSets) must remain live
1731   // for awhile - thus I cannot reclaim Matcher memory lest a VectorSet usage
1732   // set a bit in reclaimed memory.
1733 
1734   // In debug mode can dump m._nodes.dump() for mapping of ideal to machine
1735   // nodes.  Mapping is only valid at the root of each matched subtree.
1736   NOT_PRODUCT( verify_graph_edges(); )
1737 
1738   Node_List proj_list;
1739   Matcher m(proj_list);
1740   _matcher = &m;
1741   {
1742     TracePhase t2("matcher", &_t_matcher, true);
1743     m.match();
1744   }
1745   // In debug mode can dump m._nodes.dump() for mapping of ideal to machine
1746   // nodes.  Mapping is only valid at the root of each matched subtree.
1747   NOT_PRODUCT( verify_graph_edges(); )
1748 
1749   // If you have too many nodes, or if matching has failed, bail out
1750   check_node_count(0, "out of nodes matching instructions");
1751   if (failing())  return;
1752 
1753   // Build a proper-looking CFG
1754   PhaseCFG cfg(node_arena(), root(), m);
1755   _cfg = &cfg;
1756   {
1757     NOT_PRODUCT( TracePhase t2("scheduler", &_t_scheduler, TimeCompiler); )
1758     cfg.Dominators();
1759     if (failing())  return;
1760 
1761     NOT_PRODUCT( verify_graph_edges(); )
1762 
1763     cfg.Estimate_Block_Frequency();
1764     cfg.GlobalCodeMotion(m,unique(),proj_list);
1765 
1766     print_method("Global code motion", 2);
1767 
1768     if (failing())  return;
1769     NOT_PRODUCT( verify_graph_edges(); )
1770 
1771     debug_only( cfg.verify(); )
1772   }
1773   NOT_PRODUCT( verify_graph_edges(); )
1774 
1775   PhaseChaitin regalloc(unique(),cfg,m);
1776   _regalloc = &regalloc;
1777   {
1778     TracePhase t2("regalloc", &_t_registerAllocation, true);
1779     // Perform any platform dependent preallocation actions.  This is used,
1780     // for example, to avoid taking an implicit null pointer exception
1781     // using the frame pointer on win95.
1782     _regalloc->pd_preallocate_hook();
1783 
1784     // Perform register allocation.  After Chaitin, use-def chains are
1785     // no longer accurate (at spill code) and so must be ignored.
1786     // Node->LRG->reg mappings are still accurate.
1787     _regalloc->Register_Allocate();
1788 
1789     // Bail out if the allocator builds too many nodes
1790     if (failing())  return;
1791   }
1792 
1793   // Prior to register allocation we kept empty basic blocks in case the
1794   // the allocator needed a place to spill.  After register allocation we
1795   // are not adding any new instructions.  If any basic block is empty, we
1796   // can now safely remove it.
1797   {
1798     NOT_PRODUCT( TracePhase t2("blockOrdering", &_t_blockOrdering, TimeCompiler); )
1799     cfg.remove_empty();
1800     if (do_freq_based_layout()) {
1801       PhaseBlockLayout layout(cfg);
1802     } else {
1803       cfg.set_loop_alignment();
1804     }
1805     cfg.fixup_flow();
1806   }
1807 
1808   // Perform any platform dependent postallocation verifications.
1809   debug_only( _regalloc->pd_postallocate_verify_hook(); )
1810 
1811   // Apply peephole optimizations
1812   if( OptoPeephole ) {
1813     NOT_PRODUCT( TracePhase t2("peephole", &_t_peephole, TimeCompiler); )
1814     PhasePeephole peep( _regalloc, cfg);
1815     peep.do_transform();
1816   }
1817 
1818   // Convert Nodes to instruction bits in a buffer
1819   {
1820     // %%%% workspace merge brought two timers together for one job
1821     TracePhase t2a("output", &_t_output, true);
1822     NOT_PRODUCT( TraceTime t2b(NULL, &_t_codeGeneration, TimeCompiler, false); )
1823     Output();
1824   }
1825 
1826   print_method("Final Code");
1827 
1828   // He's dead, Jim.
1829   _cfg     = (PhaseCFG*)0xdeadbeef;
1830   _regalloc = (PhaseChaitin*)0xdeadbeef;
1831 }
1832 
1833 
1834 //------------------------------dump_asm---------------------------------------
1835 // Dump formatted assembly
1836 #ifndef PRODUCT
1837 void Compile::dump_asm(int *pcs, uint pc_limit) {
1838   bool cut_short = false;
1839   tty->print_cr("#");
1840   tty->print("#  ");  _tf->dump();  tty->cr();
1841   tty->print_cr("#");
1842 
1843   // For all blocks
1844   int pc = 0x0;                 // Program counter
1845   char starts_bundle = ' ';
1846   _regalloc->dump_frame();
1847 
1848   Node *n = NULL;
1849   for( uint i=0; i<_cfg->_num_blocks; i++ ) {
1850     if (VMThread::should_terminate()) { cut_short = true; break; }
1851     Block *b = _cfg->_blocks[i];
1852     if (b->is_connector() && !Verbose) continue;
1853     n = b->_nodes[0];
1854     if (pcs && n->_idx < pc_limit)
1855       tty->print("%3.3x   ", pcs[n->_idx]);
1856     else
1857       tty->print("      ");
1858     b->dump_head( &_cfg->_bbs );
1859     if (b->is_connector()) {
1860       tty->print_cr("        # Empty connector block");
1861     } else if (b->num_preds() == 2 && b->pred(1)->is_CatchProj() && b->pred(1)->as_CatchProj()->_con == CatchProjNode::fall_through_index) {
1862       tty->print_cr("        # Block is sole successor of call");
1863     }
1864 
1865     // For all instructions
1866     Node *delay = NULL;
1867     for( uint j = 0; j<b->_nodes.size(); j++ ) {
1868       if (VMThread::should_terminate()) { cut_short = true; break; }
1869       n = b->_nodes[j];
1870       if (valid_bundle_info(n)) {
1871         Bundle *bundle = node_bundling(n);
1872         if (bundle->used_in_unconditional_delay()) {
1873           delay = n;
1874           continue;
1875         }
1876         if (bundle->starts_bundle())
1877           starts_bundle = '+';
1878       }
1879 
1880       if (WizardMode) n->dump();
1881 
1882       if( !n->is_Region() &&    // Dont print in the Assembly
1883           !n->is_Phi() &&       // a few noisely useless nodes
1884           !n->is_Proj() &&
1885           !n->is_MachTemp() &&
1886           !n->is_SafePointScalarObject() &&
1887           !n->is_Catch() &&     // Would be nice to print exception table targets
1888           !n->is_MergeMem() &&  // Not very interesting
1889           !n->is_top() &&       // Debug info table constants
1890           !(n->is_Con() && !n->is_Mach())// Debug info table constants
1891           ) {
1892         if (pcs && n->_idx < pc_limit)
1893           tty->print("%3.3x", pcs[n->_idx]);
1894         else
1895           tty->print("   ");
1896         tty->print(" %c ", starts_bundle);
1897         starts_bundle = ' ';
1898         tty->print("\t");
1899         n->format(_regalloc, tty);
1900         tty->cr();
1901       }
1902 
1903       // If we have an instruction with a delay slot, and have seen a delay,
1904       // then back up and print it
1905       if (valid_bundle_info(n) && node_bundling(n)->use_unconditional_delay()) {
1906         assert(delay != NULL, "no unconditional delay instruction");
1907         if (WizardMode) delay->dump();
1908 
1909         if (node_bundling(delay)->starts_bundle())
1910           starts_bundle = '+';
1911         if (pcs && n->_idx < pc_limit)
1912           tty->print("%3.3x", pcs[n->_idx]);
1913         else
1914           tty->print("   ");
1915         tty->print(" %c ", starts_bundle);
1916         starts_bundle = ' ';
1917         tty->print("\t");
1918         delay->format(_regalloc, tty);
1919         tty->print_cr("");
1920         delay = NULL;
1921       }
1922 
1923       // Dump the exception table as well
1924       if( n->is_Catch() && (Verbose || WizardMode) ) {
1925         // Print the exception table for this offset
1926         _handler_table.print_subtable_for(pc);
1927       }
1928     }
1929 
1930     if (pcs && n->_idx < pc_limit)
1931       tty->print_cr("%3.3x", pcs[n->_idx]);
1932     else
1933       tty->print_cr("");
1934 
1935     assert(cut_short || delay == NULL, "no unconditional delay branch");
1936 
1937   } // End of per-block dump
1938   tty->print_cr("");
1939 
1940   if (cut_short)  tty->print_cr("*** disassembly is cut short ***");
1941 }
1942 #endif
1943 
1944 //------------------------------Final_Reshape_Counts---------------------------
1945 // This class defines counters to help identify when a method
1946 // may/must be executed using hardware with only 24-bit precision.
1947 struct Final_Reshape_Counts : public StackObj {
1948   int  _call_count;             // count non-inlined 'common' calls
1949   int  _float_count;            // count float ops requiring 24-bit precision
1950   int  _double_count;           // count double ops requiring more precision
1951   int  _java_call_count;        // count non-inlined 'java' calls
1952   int  _inner_loop_count;       // count loops which need alignment
1953   VectorSet _visited;           // Visitation flags
1954   Node_List _tests;             // Set of IfNodes & PCTableNodes
1955 
1956   Final_Reshape_Counts() :
1957     _call_count(0), _float_count(0), _double_count(0),
1958     _java_call_count(0), _inner_loop_count(0),
1959     _visited( Thread::current()->resource_area() ) { }
1960 
1961   void inc_call_count  () { _call_count  ++; }
1962   void inc_float_count () { _float_count ++; }
1963   void inc_double_count() { _double_count++; }
1964   void inc_java_call_count() { _java_call_count++; }
1965   void inc_inner_loop_count() { _inner_loop_count++; }
1966 
1967   int  get_call_count  () const { return _call_count  ; }
1968   int  get_float_count () const { return _float_count ; }
1969   int  get_double_count() const { return _double_count; }
1970   int  get_java_call_count() const { return _java_call_count; }
1971   int  get_inner_loop_count() const { return _inner_loop_count; }
1972 };
1973 
1974 static bool oop_offset_is_sane(const TypeInstPtr* tp) {
1975   ciInstanceKlass *k = tp->klass()->as_instance_klass();
1976   // Make sure the offset goes inside the instance layout.
1977   return k->contains_field_offset(tp->offset());
1978   // Note that OffsetBot and OffsetTop are very negative.
1979 }
1980 
1981 //------------------------------final_graph_reshaping_impl----------------------
1982 // Implement items 1-5 from final_graph_reshaping below.
1983 static void final_graph_reshaping_impl( Node *n, Final_Reshape_Counts &frc ) {
1984 
1985   if ( n->outcnt() == 0 ) return; // dead node
1986   uint nop = n->Opcode();
1987 
1988   // Check for 2-input instruction with "last use" on right input.
1989   // Swap to left input.  Implements item (2).
1990   if( n->req() == 3 &&          // two-input instruction
1991       n->in(1)->outcnt() > 1 && // left use is NOT a last use
1992       (!n->in(1)->is_Phi() || n->in(1)->in(2) != n) && // it is not data loop
1993       n->in(2)->outcnt() == 1 &&// right use IS a last use
1994       !n->in(2)->is_Con() ) {   // right use is not a constant
1995     // Check for commutative opcode
1996     switch( nop ) {
1997     case Op_AddI:  case Op_AddF:  case Op_AddD:  case Op_AddL:
1998     case Op_MaxI:  case Op_MinI:
1999     case Op_MulI:  case Op_MulF:  case Op_MulD:  case Op_MulL:
2000     case Op_AndL:  case Op_XorL:  case Op_OrL:
2001     case Op_AndI:  case Op_XorI:  case Op_OrI: {
2002       // Move "last use" input to left by swapping inputs
2003       n->swap_edges(1, 2);
2004       break;
2005     }
2006     default:
2007       break;
2008     }
2009   }
2010 
2011 #ifdef ASSERT
2012   if( n->is_Mem() ) {
2013     Compile* C = Compile::current();
2014     int alias_idx = C->get_alias_index(n->as_Mem()->adr_type());
2015     assert( n->in(0) != NULL || alias_idx != Compile::AliasIdxRaw ||
2016             // oop will be recorded in oop map if load crosses safepoint
2017             n->is_Load() && (n->as_Load()->bottom_type()->isa_oopptr() ||
2018                              LoadNode::is_immutable_value(n->in(MemNode::Address))),
2019             "raw memory operations should have control edge");
2020   }
2021 #endif
2022   // Count FPU ops and common calls, implements item (3)
2023   switch( nop ) {
2024   // Count all float operations that may use FPU
2025   case Op_AddF:
2026   case Op_SubF:
2027   case Op_MulF:
2028   case Op_DivF:
2029   case Op_NegF:
2030   case Op_ModF:
2031   case Op_ConvI2F:
2032   case Op_ConF:
2033   case Op_CmpF:
2034   case Op_CmpF3:
2035   // case Op_ConvL2F: // longs are split into 32-bit halves
2036     frc.inc_float_count();
2037     break;
2038 
2039   case Op_ConvF2D:
2040   case Op_ConvD2F:
2041     frc.inc_float_count();
2042     frc.inc_double_count();
2043     break;
2044 
2045   // Count all double operations that may use FPU
2046   case Op_AddD:
2047   case Op_SubD:
2048   case Op_MulD:
2049   case Op_DivD:
2050   case Op_NegD:
2051   case Op_ModD:
2052   case Op_ConvI2D:
2053   case Op_ConvD2I:
2054   // case Op_ConvL2D: // handled by leaf call
2055   // case Op_ConvD2L: // handled by leaf call
2056   case Op_ConD:
2057   case Op_CmpD:
2058   case Op_CmpD3:
2059     frc.inc_double_count();
2060     break;
2061   case Op_Opaque1:              // Remove Opaque Nodes before matching
2062   case Op_Opaque2:              // Remove Opaque Nodes before matching
2063     n->subsume_by(n->in(1));
2064     break;
2065   case Op_CallStaticJava:
2066   case Op_CallJava:
2067   case Op_CallDynamicJava:
2068     frc.inc_java_call_count(); // Count java call site;
2069   case Op_CallRuntime:
2070   case Op_CallLeaf:
2071   case Op_CallLeafNoFP: {
2072     assert( n->is_Call(), "" );
2073     CallNode *call = n->as_Call();
2074     // Count call sites where the FP mode bit would have to be flipped.
2075     // Do not count uncommon runtime calls:
2076     // uncommon_trap, _complete_monitor_locking, _complete_monitor_unlocking,
2077     // _new_Java, _new_typeArray, _new_objArray, _rethrow_Java, ...
2078     if( !call->is_CallStaticJava() || !call->as_CallStaticJava()->_name ) {
2079       frc.inc_call_count();   // Count the call site
2080     } else {                  // See if uncommon argument is shared
2081       Node *n = call->in(TypeFunc::Parms);
2082       int nop = n->Opcode();
2083       // Clone shared simple arguments to uncommon calls, item (1).
2084       if( n->outcnt() > 1 &&
2085           !n->is_Proj() &&
2086           nop != Op_CreateEx &&
2087           nop != Op_CheckCastPP &&
2088           nop != Op_DecodeN &&
2089           !n->is_Mem() ) {
2090         Node *x = n->clone();
2091         call->set_req( TypeFunc::Parms, x );
2092       }
2093     }
2094     break;
2095   }
2096 
2097   case Op_StoreD:
2098   case Op_LoadD:
2099   case Op_LoadD_unaligned:
2100     frc.inc_double_count();
2101     goto handle_mem;
2102   case Op_StoreF:
2103   case Op_LoadF:
2104     frc.inc_float_count();
2105     goto handle_mem;
2106 
2107   case Op_StoreB:
2108   case Op_StoreC:
2109   case Op_StoreCM:
2110   case Op_StorePConditional:
2111   case Op_StoreI:
2112   case Op_StoreL:
2113   case Op_StoreIConditional:
2114   case Op_StoreLConditional:
2115   case Op_CompareAndSwapI:
2116   case Op_CompareAndSwapL:
2117   case Op_CompareAndSwapP:
2118   case Op_CompareAndSwapN:
2119   case Op_StoreP:
2120   case Op_StoreN:
2121   case Op_LoadB:
2122   case Op_LoadUB:
2123   case Op_LoadUS:
2124   case Op_LoadI:
2125   case Op_LoadUI2L:
2126   case Op_LoadKlass:
2127   case Op_LoadNKlass:
2128   case Op_LoadL:
2129   case Op_LoadL_unaligned:
2130   case Op_LoadPLocked:
2131   case Op_LoadLLocked:
2132   case Op_LoadP:
2133   case Op_LoadN:
2134   case Op_LoadRange:
2135   case Op_LoadS: {
2136   handle_mem:
2137 #ifdef ASSERT
2138     if( VerifyOptoOopOffsets ) {
2139       assert( n->is_Mem(), "" );
2140       MemNode *mem  = (MemNode*)n;
2141       // Check to see if address types have grounded out somehow.
2142       const TypeInstPtr *tp = mem->in(MemNode::Address)->bottom_type()->isa_instptr();
2143       assert( !tp || oop_offset_is_sane(tp), "" );
2144     }
2145 #endif
2146     break;
2147   }
2148 
2149   case Op_AddP: {               // Assert sane base pointers
2150     Node *addp = n->in(AddPNode::Address);
2151     assert( !addp->is_AddP() ||
2152             addp->in(AddPNode::Base)->is_top() || // Top OK for allocation
2153             addp->in(AddPNode::Base) == n->in(AddPNode::Base),
2154             "Base pointers must match" );
2155 #ifdef _LP64
2156     if (UseCompressedOops &&
2157         addp->Opcode() == Op_ConP &&
2158         addp == n->in(AddPNode::Base) &&
2159         n->in(AddPNode::Offset)->is_Con()) {
2160       // Use addressing with narrow klass to load with offset on x86.
2161       // On sparc loading 32-bits constant and decoding it have less
2162       // instructions (4) then load 64-bits constant (7).
2163       // Do this transformation here since IGVN will convert ConN back to ConP.
2164       const Type* t = addp->bottom_type();
2165       if (t->isa_oopptr()) {
2166         Node* nn = NULL;
2167 
2168         // Look for existing ConN node of the same exact type.
2169         Compile* C = Compile::current();
2170         Node* r  = C->root();
2171         uint cnt = r->outcnt();
2172         for (uint i = 0; i < cnt; i++) {
2173           Node* m = r->raw_out(i);
2174           if (m!= NULL && m->Opcode() == Op_ConN &&
2175               m->bottom_type()->make_ptr() == t) {
2176             nn = m;
2177             break;
2178           }
2179         }
2180         if (nn != NULL) {
2181           // Decode a narrow oop to match address
2182           // [R12 + narrow_oop_reg<<3 + offset]
2183           nn = new (C,  2) DecodeNNode(nn, t);
2184           n->set_req(AddPNode::Base, nn);
2185           n->set_req(AddPNode::Address, nn);
2186           if (addp->outcnt() == 0) {
2187             addp->disconnect_inputs(NULL);
2188           }
2189         }
2190       }
2191     }
2192 #endif
2193     break;
2194   }
2195 
2196 #ifdef _LP64
2197   case Op_CastPP:
2198     if (n->in(1)->is_DecodeN() && Matcher::gen_narrow_oop_implicit_null_checks()) {
2199       Compile* C = Compile::current();
2200       Node* in1 = n->in(1);
2201       const Type* t = n->bottom_type();
2202       Node* new_in1 = in1->clone();
2203       new_in1->as_DecodeN()->set_type(t);
2204 
2205       if (!Matcher::narrow_oop_use_complex_address()) {
2206         //
2207         // x86, ARM and friends can handle 2 adds in addressing mode
2208         // and Matcher can fold a DecodeN node into address by using
2209         // a narrow oop directly and do implicit NULL check in address:
2210         //
2211         // [R12 + narrow_oop_reg<<3 + offset]
2212         // NullCheck narrow_oop_reg
2213         //
2214         // On other platforms (Sparc) we have to keep new DecodeN node and
2215         // use it to do implicit NULL check in address:
2216         //
2217         // decode_not_null narrow_oop_reg, base_reg
2218         // [base_reg + offset]
2219         // NullCheck base_reg
2220         //
2221         // Pin the new DecodeN node to non-null path on these platform (Sparc)
2222         // to keep the information to which NULL check the new DecodeN node
2223         // corresponds to use it as value in implicit_null_check().
2224         //
2225         new_in1->set_req(0, n->in(0));
2226       }
2227 
2228       n->subsume_by(new_in1);
2229       if (in1->outcnt() == 0) {
2230         in1->disconnect_inputs(NULL);
2231       }
2232     }
2233     break;
2234 
2235   case Op_CmpP:
2236     // Do this transformation here to preserve CmpPNode::sub() and
2237     // other TypePtr related Ideal optimizations (for example, ptr nullness).
2238     if (n->in(1)->is_DecodeN() || n->in(2)->is_DecodeN()) {
2239       Node* in1 = n->in(1);
2240       Node* in2 = n->in(2);
2241       if (!in1->is_DecodeN()) {
2242         in2 = in1;
2243         in1 = n->in(2);
2244       }
2245       assert(in1->is_DecodeN(), "sanity");
2246 
2247       Compile* C = Compile::current();
2248       Node* new_in2 = NULL;
2249       if (in2->is_DecodeN()) {
2250         new_in2 = in2->in(1);
2251       } else if (in2->Opcode() == Op_ConP) {
2252         const Type* t = in2->bottom_type();
2253         if (t == TypePtr::NULL_PTR) {
2254           // Don't convert CmpP null check into CmpN if compressed
2255           // oops implicit null check is not generated.
2256           // This will allow to generate normal oop implicit null check.
2257           if (Matcher::gen_narrow_oop_implicit_null_checks())
2258             new_in2 = ConNode::make(C, TypeNarrowOop::NULL_PTR);
2259           //
2260           // This transformation together with CastPP transformation above
2261           // will generated code for implicit NULL checks for compressed oops.
2262           //
2263           // The original code after Optimize()
2264           //
2265           //    LoadN memory, narrow_oop_reg
2266           //    decode narrow_oop_reg, base_reg
2267           //    CmpP base_reg, NULL
2268           //    CastPP base_reg // NotNull
2269           //    Load [base_reg + offset], val_reg
2270           //
2271           // after these transformations will be
2272           //
2273           //    LoadN memory, narrow_oop_reg
2274           //    CmpN narrow_oop_reg, NULL
2275           //    decode_not_null narrow_oop_reg, base_reg
2276           //    Load [base_reg + offset], val_reg
2277           //
2278           // and the uncommon path (== NULL) will use narrow_oop_reg directly
2279           // since narrow oops can be used in debug info now (see the code in
2280           // final_graph_reshaping_walk()).
2281           //
2282           // At the end the code will be matched to
2283           // on x86:
2284           //
2285           //    Load_narrow_oop memory, narrow_oop_reg
2286           //    Load [R12 + narrow_oop_reg<<3 + offset], val_reg
2287           //    NullCheck narrow_oop_reg
2288           //
2289           // and on sparc:
2290           //
2291           //    Load_narrow_oop memory, narrow_oop_reg
2292           //    decode_not_null narrow_oop_reg, base_reg
2293           //    Load [base_reg + offset], val_reg
2294           //    NullCheck base_reg
2295           //
2296         } else if (t->isa_oopptr()) {
2297           new_in2 = ConNode::make(C, t->make_narrowoop());
2298         }
2299       }
2300       if (new_in2 != NULL) {
2301         Node* cmpN = new (C, 3) CmpNNode(in1->in(1), new_in2);
2302         n->subsume_by( cmpN );
2303         if (in1->outcnt() == 0) {
2304           in1->disconnect_inputs(NULL);
2305         }
2306         if (in2->outcnt() == 0) {
2307           in2->disconnect_inputs(NULL);
2308         }
2309       }
2310     }
2311     break;
2312 
2313   case Op_DecodeN:
2314     assert(!n->in(1)->is_EncodeP(), "should be optimized out");
2315     // DecodeN could be pinned when it can't be fold into
2316     // an address expression, see the code for Op_CastPP above.
2317     assert(n->in(0) == NULL || !Matcher::narrow_oop_use_complex_address(), "no control");
2318     break;
2319 
2320   case Op_EncodeP: {
2321     Node* in1 = n->in(1);
2322     if (in1->is_DecodeN()) {
2323       n->subsume_by(in1->in(1));
2324     } else if (in1->Opcode() == Op_ConP) {
2325       Compile* C = Compile::current();
2326       const Type* t = in1->bottom_type();
2327       if (t == TypePtr::NULL_PTR) {
2328         n->subsume_by(ConNode::make(C, TypeNarrowOop::NULL_PTR));
2329       } else if (t->isa_oopptr()) {
2330         n->subsume_by(ConNode::make(C, t->make_narrowoop()));
2331       }
2332     }
2333     if (in1->outcnt() == 0) {
2334       in1->disconnect_inputs(NULL);
2335     }
2336     break;
2337   }
2338 
2339   case Op_Proj: {
2340     if (OptimizeStringConcat) {
2341       ProjNode* p = n->as_Proj();
2342       if (p->_is_io_use) {
2343         // Separate projections were used for the exception path which
2344         // are normally removed by a late inline.  If it wasn't inlined
2345         // then they will hang around and should just be replaced with
2346         // the original one.
2347         Node* proj = NULL;
2348         // Replace with just one
2349         for (SimpleDUIterator i(p->in(0)); i.has_next(); i.next()) {
2350           Node *use = i.get();
2351           if (use->is_Proj() && p != use && use->as_Proj()->_con == p->_con) {
2352             proj = use;
2353             break;
2354           }
2355         }
2356         assert(p != NULL, "must be found");
2357         p->subsume_by(proj);
2358       }
2359     }
2360     break;
2361   }
2362 
2363   case Op_Phi:
2364     if (n->as_Phi()->bottom_type()->isa_narrowoop()) {
2365       // The EncodeP optimization may create Phi with the same edges
2366       // for all paths. It is not handled well by Register Allocator.
2367       Node* unique_in = n->in(1);
2368       assert(unique_in != NULL, "");
2369       uint cnt = n->req();
2370       for (uint i = 2; i < cnt; i++) {
2371         Node* m = n->in(i);
2372         assert(m != NULL, "");
2373         if (unique_in != m)
2374           unique_in = NULL;
2375       }
2376       if (unique_in != NULL) {
2377         n->subsume_by(unique_in);
2378       }
2379     }
2380     break;
2381 
2382 #endif
2383 
2384   case Op_ModI:
2385     if (UseDivMod) {
2386       // Check if a%b and a/b both exist
2387       Node* d = n->find_similar(Op_DivI);
2388       if (d) {
2389         // Replace them with a fused divmod if supported
2390         Compile* C = Compile::current();
2391         if (Matcher::has_match_rule(Op_DivModI)) {
2392           DivModINode* divmod = DivModINode::make(C, n);
2393           d->subsume_by(divmod->div_proj());
2394           n->subsume_by(divmod->mod_proj());
2395         } else {
2396           // replace a%b with a-((a/b)*b)
2397           Node* mult = new (C, 3) MulINode(d, d->in(2));
2398           Node* sub  = new (C, 3) SubINode(d->in(1), mult);
2399           n->subsume_by( sub );
2400         }
2401       }
2402     }
2403     break;
2404 
2405   case Op_ModL:
2406     if (UseDivMod) {
2407       // Check if a%b and a/b both exist
2408       Node* d = n->find_similar(Op_DivL);
2409       if (d) {
2410         // Replace them with a fused divmod if supported
2411         Compile* C = Compile::current();
2412         if (Matcher::has_match_rule(Op_DivModL)) {
2413           DivModLNode* divmod = DivModLNode::make(C, n);
2414           d->subsume_by(divmod->div_proj());
2415           n->subsume_by(divmod->mod_proj());
2416         } else {
2417           // replace a%b with a-((a/b)*b)
2418           Node* mult = new (C, 3) MulLNode(d, d->in(2));
2419           Node* sub  = new (C, 3) SubLNode(d->in(1), mult);
2420           n->subsume_by( sub );
2421         }
2422       }
2423     }
2424     break;
2425 
2426   case Op_Load16B:
2427   case Op_Load8B:
2428   case Op_Load4B:
2429   case Op_Load8S:
2430   case Op_Load4S:
2431   case Op_Load2S:
2432   case Op_Load8C:
2433   case Op_Load4C:
2434   case Op_Load2C:
2435   case Op_Load4I:
2436   case Op_Load2I:
2437   case Op_Load2L:
2438   case Op_Load4F:
2439   case Op_Load2F:
2440   case Op_Load2D:
2441   case Op_Store16B:
2442   case Op_Store8B:
2443   case Op_Store4B:
2444   case Op_Store8C:
2445   case Op_Store4C:
2446   case Op_Store2C:
2447   case Op_Store4I:
2448   case Op_Store2I:
2449   case Op_Store2L:
2450   case Op_Store4F:
2451   case Op_Store2F:
2452   case Op_Store2D:
2453     break;
2454 
2455   case Op_PackB:
2456   case Op_PackS:
2457   case Op_PackC:
2458   case Op_PackI:
2459   case Op_PackF:
2460   case Op_PackL:
2461   case Op_PackD:
2462     if (n->req()-1 > 2) {
2463       // Replace many operand PackNodes with a binary tree for matching
2464       PackNode* p = (PackNode*) n;
2465       Node* btp = p->binaryTreePack(Compile::current(), 1, n->req());
2466       n->subsume_by(btp);
2467     }
2468     break;
2469   case Op_Loop:
2470   case Op_CountedLoop:
2471     if (n->as_Loop()->is_inner_loop()) {
2472       frc.inc_inner_loop_count();
2473     }
2474     break;
2475   default:
2476     assert( !n->is_Call(), "" );
2477     assert( !n->is_Mem(), "" );
2478     break;
2479   }
2480 
2481   // Collect CFG split points
2482   if (n->is_MultiBranch())
2483     frc._tests.push(n);
2484 }
2485 
2486 //------------------------------final_graph_reshaping_walk---------------------
2487 // Replacing Opaque nodes with their input in final_graph_reshaping_impl(),
2488 // requires that the walk visits a node's inputs before visiting the node.
2489 static void final_graph_reshaping_walk( Node_Stack &nstack, Node *root, Final_Reshape_Counts &frc ) {
2490   ResourceArea *area = Thread::current()->resource_area();
2491   Unique_Node_List sfpt(area);
2492 
2493   frc._visited.set(root->_idx); // first, mark node as visited
2494   uint cnt = root->req();
2495   Node *n = root;
2496   uint  i = 0;
2497   while (true) {
2498     if (i < cnt) {
2499       // Place all non-visited non-null inputs onto stack
2500       Node* m = n->in(i);
2501       ++i;
2502       if (m != NULL && !frc._visited.test_set(m->_idx)) {
2503         if (m->is_SafePoint() && m->as_SafePoint()->jvms() != NULL)
2504           sfpt.push(m);
2505         cnt = m->req();
2506         nstack.push(n, i); // put on stack parent and next input's index
2507         n = m;
2508         i = 0;
2509       }
2510     } else {
2511       // Now do post-visit work
2512       final_graph_reshaping_impl( n, frc );
2513       if (nstack.is_empty())
2514         break;             // finished
2515       n = nstack.node();   // Get node from stack
2516       cnt = n->req();
2517       i = nstack.index();
2518       nstack.pop();        // Shift to the next node on stack
2519     }
2520   }
2521 
2522   // Skip next transformation if compressed oops are not used.
2523   if (!UseCompressedOops || !Matcher::gen_narrow_oop_implicit_null_checks())
2524     return;
2525 
2526   // Go over safepoints nodes to skip DecodeN nodes for debug edges.
2527   // It could be done for an uncommon traps or any safepoints/calls
2528   // if the DecodeN node is referenced only in a debug info.
2529   while (sfpt.size() > 0) {
2530     n = sfpt.pop();
2531     JVMState *jvms = n->as_SafePoint()->jvms();
2532     assert(jvms != NULL, "sanity");
2533     int start = jvms->debug_start();
2534     int end   = n->req();
2535     bool is_uncommon = (n->is_CallStaticJava() &&
2536                         n->as_CallStaticJava()->uncommon_trap_request() != 0);
2537     for (int j = start; j < end; j++) {
2538       Node* in = n->in(j);
2539       if (in->is_DecodeN()) {
2540         bool safe_to_skip = true;
2541         if (!is_uncommon ) {
2542           // Is it safe to skip?
2543           for (uint i = 0; i < in->outcnt(); i++) {
2544             Node* u = in->raw_out(i);
2545             if (!u->is_SafePoint() ||
2546                  u->is_Call() && u->as_Call()->has_non_debug_use(n)) {
2547               safe_to_skip = false;
2548             }
2549           }
2550         }
2551         if (safe_to_skip) {
2552           n->set_req(j, in->in(1));
2553         }
2554         if (in->outcnt() == 0) {
2555           in->disconnect_inputs(NULL);
2556         }
2557       }
2558     }
2559   }
2560 }
2561 
2562 //------------------------------final_graph_reshaping--------------------------
2563 // Final Graph Reshaping.
2564 //
2565 // (1) Clone simple inputs to uncommon calls, so they can be scheduled late
2566 //     and not commoned up and forced early.  Must come after regular
2567 //     optimizations to avoid GVN undoing the cloning.  Clone constant
2568 //     inputs to Loop Phis; these will be split by the allocator anyways.
2569 //     Remove Opaque nodes.
2570 // (2) Move last-uses by commutative operations to the left input to encourage
2571 //     Intel update-in-place two-address operations and better register usage
2572 //     on RISCs.  Must come after regular optimizations to avoid GVN Ideal
2573 //     calls canonicalizing them back.
2574 // (3) Count the number of double-precision FP ops, single-precision FP ops
2575 //     and call sites.  On Intel, we can get correct rounding either by
2576 //     forcing singles to memory (requires extra stores and loads after each
2577 //     FP bytecode) or we can set a rounding mode bit (requires setting and
2578 //     clearing the mode bit around call sites).  The mode bit is only used
2579 //     if the relative frequency of single FP ops to calls is low enough.
2580 //     This is a key transform for SPEC mpeg_audio.
2581 // (4) Detect infinite loops; blobs of code reachable from above but not
2582 //     below.  Several of the Code_Gen algorithms fail on such code shapes,
2583 //     so we simply bail out.  Happens a lot in ZKM.jar, but also happens
2584 //     from time to time in other codes (such as -Xcomp finalizer loops, etc).
2585 //     Detection is by looking for IfNodes where only 1 projection is
2586 //     reachable from below or CatchNodes missing some targets.
2587 // (5) Assert for insane oop offsets in debug mode.
2588 
2589 bool Compile::final_graph_reshaping() {
2590   // an infinite loop may have been eliminated by the optimizer,
2591   // in which case the graph will be empty.
2592   if (root()->req() == 1) {
2593     record_method_not_compilable("trivial infinite loop");
2594     return true;
2595   }
2596 
2597   Final_Reshape_Counts frc;
2598 
2599   // Visit everybody reachable!
2600   // Allocate stack of size C->unique()/2 to avoid frequent realloc
2601   Node_Stack nstack(unique() >> 1);
2602   final_graph_reshaping_walk(nstack, root(), frc);
2603 
2604   // Check for unreachable (from below) code (i.e., infinite loops).
2605   for( uint i = 0; i < frc._tests.size(); i++ ) {
2606     MultiBranchNode *n = frc._tests[i]->as_MultiBranch();
2607     // Get number of CFG targets.
2608     // Note that PCTables include exception targets after calls.
2609     uint required_outcnt = n->required_outcnt();
2610     if (n->outcnt() != required_outcnt) {
2611       // Check for a few special cases.  Rethrow Nodes never take the
2612       // 'fall-thru' path, so expected kids is 1 less.
2613       if (n->is_PCTable() && n->in(0) && n->in(0)->in(0)) {
2614         if (n->in(0)->in(0)->is_Call()) {
2615           CallNode *call = n->in(0)->in(0)->as_Call();
2616           if (call->entry_point() == OptoRuntime::rethrow_stub()) {
2617             required_outcnt--;      // Rethrow always has 1 less kid
2618           } else if (call->req() > TypeFunc::Parms &&
2619                      call->is_CallDynamicJava()) {
2620             // Check for null receiver. In such case, the optimizer has
2621             // detected that the virtual call will always result in a null
2622             // pointer exception. The fall-through projection of this CatchNode
2623             // will not be populated.
2624             Node *arg0 = call->in(TypeFunc::Parms);
2625             if (arg0->is_Type() &&
2626                 arg0->as_Type()->type()->higher_equal(TypePtr::NULL_PTR)) {
2627               required_outcnt--;
2628             }
2629           } else if (call->entry_point() == OptoRuntime::new_array_Java() &&
2630                      call->req() > TypeFunc::Parms+1 &&
2631                      call->is_CallStaticJava()) {
2632             // Check for negative array length. In such case, the optimizer has
2633             // detected that the allocation attempt will always result in an
2634             // exception. There is no fall-through projection of this CatchNode .
2635             Node *arg1 = call->in(TypeFunc::Parms+1);
2636             if (arg1->is_Type() &&
2637                 arg1->as_Type()->type()->join(TypeInt::POS)->empty()) {
2638               required_outcnt--;
2639             }
2640           }
2641         }
2642       }
2643       // Recheck with a better notion of 'required_outcnt'
2644       if (n->outcnt() != required_outcnt) {
2645         record_method_not_compilable("malformed control flow");
2646         return true;            // Not all targets reachable!
2647       }
2648     }
2649     // Check that I actually visited all kids.  Unreached kids
2650     // must be infinite loops.
2651     for (DUIterator_Fast jmax, j = n->fast_outs(jmax); j < jmax; j++)
2652       if (!frc._visited.test(n->fast_out(j)->_idx)) {
2653         record_method_not_compilable("infinite loop");
2654         return true;            // Found unvisited kid; must be unreach
2655       }
2656   }
2657 
2658   // If original bytecodes contained a mixture of floats and doubles
2659   // check if the optimizer has made it homogenous, item (3).
2660   if( Use24BitFPMode && Use24BitFP && UseSSE == 0 &&
2661       frc.get_float_count() > 32 &&
2662       frc.get_double_count() == 0 &&
2663       (10 * frc.get_call_count() < frc.get_float_count()) ) {
2664     set_24_bit_selection_and_mode( false,  true );
2665   }
2666 
2667   set_java_calls(frc.get_java_call_count());
2668   set_inner_loops(frc.get_inner_loop_count());
2669 
2670   // No infinite loops, no reason to bail out.
2671   return false;
2672 }
2673 
2674 //-----------------------------too_many_traps----------------------------------
2675 // Report if there are too many traps at the current method and bci.
2676 // Return true if there was a trap, and/or PerMethodTrapLimit is exceeded.
2677 bool Compile::too_many_traps(ciMethod* method,
2678                              int bci,
2679                              Deoptimization::DeoptReason reason) {
2680   ciMethodData* md = method->method_data();
2681   if (md->is_empty()) {
2682     // Assume the trap has not occurred, or that it occurred only
2683     // because of a transient condition during start-up in the interpreter.
2684     return false;
2685   }
2686   if (md->has_trap_at(bci, reason) != 0) {
2687     // Assume PerBytecodeTrapLimit==0, for a more conservative heuristic.
2688     // Also, if there are multiple reasons, or if there is no per-BCI record,
2689     // assume the worst.
2690     if (log())
2691       log()->elem("observe trap='%s' count='%d'",
2692                   Deoptimization::trap_reason_name(reason),
2693                   md->trap_count(reason));
2694     return true;
2695   } else {
2696     // Ignore method/bci and see if there have been too many globally.
2697     return too_many_traps(reason, md);
2698   }
2699 }
2700 
2701 // Less-accurate variant which does not require a method and bci.
2702 bool Compile::too_many_traps(Deoptimization::DeoptReason reason,
2703                              ciMethodData* logmd) {
2704  if (trap_count(reason) >= (uint)PerMethodTrapLimit) {
2705     // Too many traps globally.
2706     // Note that we use cumulative trap_count, not just md->trap_count.
2707     if (log()) {
2708       int mcount = (logmd == NULL)? -1: (int)logmd->trap_count(reason);
2709       log()->elem("observe trap='%s' count='0' mcount='%d' ccount='%d'",
2710                   Deoptimization::trap_reason_name(reason),
2711                   mcount, trap_count(reason));
2712     }
2713     return true;
2714   } else {
2715     // The coast is clear.
2716     return false;
2717   }
2718 }
2719 
2720 //--------------------------too_many_recompiles--------------------------------
2721 // Report if there are too many recompiles at the current method and bci.
2722 // Consults PerBytecodeRecompilationCutoff and PerMethodRecompilationCutoff.
2723 // Is not eager to return true, since this will cause the compiler to use
2724 // Action_none for a trap point, to avoid too many recompilations.
2725 bool Compile::too_many_recompiles(ciMethod* method,
2726                                   int bci,
2727                                   Deoptimization::DeoptReason reason) {
2728   ciMethodData* md = method->method_data();
2729   if (md->is_empty()) {
2730     // Assume the trap has not occurred, or that it occurred only
2731     // because of a transient condition during start-up in the interpreter.
2732     return false;
2733   }
2734   // Pick a cutoff point well within PerBytecodeRecompilationCutoff.
2735   uint bc_cutoff = (uint) PerBytecodeRecompilationCutoff / 8;
2736   uint m_cutoff  = (uint) PerMethodRecompilationCutoff / 2 + 1;  // not zero
2737   Deoptimization::DeoptReason per_bc_reason
2738     = Deoptimization::reason_recorded_per_bytecode_if_any(reason);
2739   if ((per_bc_reason == Deoptimization::Reason_none
2740        || md->has_trap_at(bci, reason) != 0)
2741       // The trap frequency measure we care about is the recompile count:
2742       && md->trap_recompiled_at(bci)
2743       && md->overflow_recompile_count() >= bc_cutoff) {
2744     // Do not emit a trap here if it has already caused recompilations.
2745     // Also, if there are multiple reasons, or if there is no per-BCI record,
2746     // assume the worst.
2747     if (log())
2748       log()->elem("observe trap='%s recompiled' count='%d' recompiles2='%d'",
2749                   Deoptimization::trap_reason_name(reason),
2750                   md->trap_count(reason),
2751                   md->overflow_recompile_count());
2752     return true;
2753   } else if (trap_count(reason) != 0
2754              && decompile_count() >= m_cutoff) {
2755     // Too many recompiles globally, and we have seen this sort of trap.
2756     // Use cumulative decompile_count, not just md->decompile_count.
2757     if (log())
2758       log()->elem("observe trap='%s' count='%d' mcount='%d' decompiles='%d' mdecompiles='%d'",
2759                   Deoptimization::trap_reason_name(reason),
2760                   md->trap_count(reason), trap_count(reason),
2761                   md->decompile_count(), decompile_count());
2762     return true;
2763   } else {
2764     // The coast is clear.
2765     return false;
2766   }
2767 }
2768 
2769 
2770 #ifndef PRODUCT
2771 //------------------------------verify_graph_edges---------------------------
2772 // Walk the Graph and verify that there is a one-to-one correspondence
2773 // between Use-Def edges and Def-Use edges in the graph.
2774 void Compile::verify_graph_edges(bool no_dead_code) {
2775   if (VerifyGraphEdges) {
2776     ResourceArea *area = Thread::current()->resource_area();
2777     Unique_Node_List visited(area);
2778     // Call recursive graph walk to check edges
2779     _root->verify_edges(visited);
2780     if (no_dead_code) {
2781       // Now make sure that no visited node is used by an unvisited node.
2782       bool dead_nodes = 0;
2783       Unique_Node_List checked(area);
2784       while (visited.size() > 0) {
2785         Node* n = visited.pop();
2786         checked.push(n);
2787         for (uint i = 0; i < n->outcnt(); i++) {
2788           Node* use = n->raw_out(i);
2789           if (checked.member(use))  continue;  // already checked
2790           if (visited.member(use))  continue;  // already in the graph
2791           if (use->is_Con())        continue;  // a dead ConNode is OK
2792           // At this point, we have found a dead node which is DU-reachable.
2793           if (dead_nodes++ == 0)
2794             tty->print_cr("*** Dead nodes reachable via DU edges:");
2795           use->dump(2);
2796           tty->print_cr("---");
2797           checked.push(use);  // No repeats; pretend it is now checked.
2798         }
2799       }
2800       assert(dead_nodes == 0, "using nodes must be reachable from root");
2801     }
2802   }
2803 }
2804 #endif
2805 
2806 // The Compile object keeps track of failure reasons separately from the ciEnv.
2807 // This is required because there is not quite a 1-1 relation between the
2808 // ciEnv and its compilation task and the Compile object.  Note that one
2809 // ciEnv might use two Compile objects, if C2Compiler::compile_method decides
2810 // to backtrack and retry without subsuming loads.  Other than this backtracking
2811 // behavior, the Compile's failure reason is quietly copied up to the ciEnv
2812 // by the logic in C2Compiler.
2813 void Compile::record_failure(const char* reason) {
2814   if (log() != NULL) {
2815     log()->elem("failure reason='%s' phase='compile'", reason);
2816   }
2817   if (_failure_reason == NULL) {
2818     // Record the first failure reason.
2819     _failure_reason = reason;
2820   }
2821   if (!C->failure_reason_is(C2Compiler::retry_no_subsuming_loads())) {
2822     C->print_method(_failure_reason);
2823   }
2824   _root = NULL;  // flush the graph, too
2825 }
2826 
2827 Compile::TracePhase::TracePhase(const char* name, elapsedTimer* accumulator, bool dolog)
2828   : TraceTime(NULL, accumulator, false NOT_PRODUCT( || TimeCompiler ), false)
2829 {
2830   if (dolog) {
2831     C = Compile::current();
2832     _log = C->log();
2833   } else {
2834     C = NULL;
2835     _log = NULL;
2836   }
2837   if (_log != NULL) {
2838     _log->begin_head("phase name='%s' nodes='%d'", name, C->unique());
2839     _log->stamp();
2840     _log->end_head();
2841   }
2842 }
2843 
2844 Compile::TracePhase::~TracePhase() {
2845   if (_log != NULL) {
2846     _log->done("phase nodes='%d'", C->unique());
2847   }
2848 }