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