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