1 /*
   2  * Copyright 1997-2008 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 compiing 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 #ifndef PRODUCT
 444                   _trace_opto_output(TraceOptoOutput || method()->has_option("TraceOptoOutput")),
 445                   _printer(IdealGraphPrinter::printer()),
 446 #endif
 447                   _congraph(NULL) {
 448   C = this;
 449 
 450   CompileWrapper cw(this);
 451 #ifndef PRODUCT
 452   if (TimeCompiler2) {
 453     tty->print(" ");
 454     target->holder()->name()->print();
 455     tty->print(".");
 456     target->print_short_name();
 457     tty->print("  ");
 458   }
 459   TraceTime t1("Total compilation time", &_t_totalCompilation, TimeCompiler, TimeCompiler2);
 460   TraceTime t2(NULL, &_t_methodCompilation, TimeCompiler, false);
 461   bool print_opto_assembly = PrintOptoAssembly || _method->has_option("PrintOptoAssembly");
 462   if (!print_opto_assembly) {
 463     bool print_assembly = (PrintAssembly || _method->should_print_assembly());
 464     if (print_assembly && !Disassembler::can_decode()) {
 465       tty->print_cr("PrintAssembly request changed to PrintOptoAssembly");
 466       print_opto_assembly = true;
 467     }
 468   }
 469   set_print_assembly(print_opto_assembly);
 470 #endif
 471 
 472   if (ProfileTraps) {
 473     // Make sure the method being compiled gets its own MDO,
 474     // so we can at least track the decompile_count().
 475     method()->build_method_data();
 476   }
 477 
 478   Init(::AliasLevel);
 479 
 480 
 481   print_compile_messages();
 482 
 483   if (UseOldInlining || PrintCompilation NOT_PRODUCT( || PrintOpto) )
 484     _ilt = InlineTree::build_inline_tree_root();
 485   else
 486     _ilt = NULL;
 487 
 488   // Even if NO memory addresses are used, MergeMem nodes must have at least 1 slice
 489   assert(num_alias_types() >= AliasIdxRaw, "");
 490 
 491 #define MINIMUM_NODE_HASH  1023
 492   // Node list that Iterative GVN will start with
 493   Unique_Node_List for_igvn(comp_arena());
 494   set_for_igvn(&for_igvn);
 495 
 496   // GVN that will be run immediately on new nodes
 497   uint estimated_size = method()->code_size()*4+64;
 498   estimated_size = (estimated_size < MINIMUM_NODE_HASH ? MINIMUM_NODE_HASH : estimated_size);
 499   PhaseGVN gvn(node_arena(), estimated_size);
 500   set_initial_gvn(&gvn);
 501 
 502   { // Scope for timing the parser
 503     TracePhase t3("parse", &_t_parser, true);
 504 
 505     // Put top into the hash table ASAP.
 506     initial_gvn()->transform_no_reclaim(top());
 507 
 508     // Set up tf(), start(), and find a CallGenerator.
 509     CallGenerator* cg;
 510     if (is_osr_compilation()) {
 511       const TypeTuple *domain = StartOSRNode::osr_domain();
 512       const TypeTuple *range = TypeTuple::make_range(method()->signature());
 513       init_tf(TypeFunc::make(domain, range));
 514       StartNode* s = new (this, 2) StartOSRNode(root(), domain);
 515       initial_gvn()->set_type_bottom(s);
 516       init_start(s);
 517       cg = CallGenerator::for_osr(method(), entry_bci());
 518     } else {
 519       // Normal case.
 520       init_tf(TypeFunc::make(method()));
 521       StartNode* s = new (this, 2) StartNode(root(), tf()->domain());
 522       initial_gvn()->set_type_bottom(s);
 523       init_start(s);
 524       float past_uses = method()->interpreter_invocation_count();
 525       float expected_uses = past_uses;
 526       cg = CallGenerator::for_inline(method(), expected_uses);
 527     }
 528     if (failing())  return;
 529     if (cg == NULL) {
 530       record_method_not_compilable_all_tiers("cannot parse method");
 531       return;
 532     }
 533     JVMState* jvms = build_start_state(start(), tf());
 534     if ((jvms = cg->generate(jvms)) == NULL) {
 535       record_method_not_compilable("method parse failed");
 536       return;
 537     }
 538     GraphKit kit(jvms);
 539 
 540     if (!kit.stopped()) {
 541       // Accept return values, and transfer control we know not where.
 542       // This is done by a special, unique ReturnNode bound to root.
 543       return_values(kit.jvms());
 544     }
 545 
 546     if (kit.has_exceptions()) {
 547       // Any exceptions that escape from this call must be rethrown
 548       // to whatever caller is dynamically above us on the stack.
 549       // This is done by a special, unique RethrowNode bound to root.
 550       rethrow_exceptions(kit.transfer_exceptions_into_jvms());
 551     }
 552 
 553     // Remove clutter produced by parsing.
 554     if (!failing()) {
 555       ResourceMark rm;
 556       PhaseRemoveUseless pru(initial_gvn(), &for_igvn);
 557     }
 558   }
 559 
 560   // Note:  Large methods are capped off in do_one_bytecode().
 561   if (failing())  return;
 562 
 563   // After parsing, node notes are no longer automagic.
 564   // They must be propagated by register_new_node_with_optimizer(),
 565   // clone(), or the like.
 566   set_default_node_notes(NULL);
 567 
 568   for (;;) {
 569     int successes = Inline_Warm();
 570     if (failing())  return;
 571     if (successes == 0)  break;
 572   }
 573 
 574   // Drain the list.
 575   Finish_Warm();
 576 #ifndef PRODUCT
 577   if (_printer) {
 578     _printer->print_inlining(this);
 579   }
 580 #endif
 581 
 582   if (failing())  return;
 583   NOT_PRODUCT( verify_graph_edges(); )
 584 
 585   // Perform escape analysis
 586   if (_do_escape_analysis && ConnectionGraph::has_candidates(this)) {
 587     TracePhase t2("escapeAnalysis", &_t_escapeAnalysis, true);
 588     // Add ConP#NULL and ConN#NULL nodes before ConnectionGraph construction.
 589     PhaseGVN* igvn = initial_gvn();
 590     Node* oop_null = igvn->zerocon(T_OBJECT);
 591     Node* noop_null = igvn->zerocon(T_NARROWOOP);
 592 
 593     _congraph = new(comp_arena()) ConnectionGraph(this);
 594     bool has_non_escaping_obj = _congraph->compute_escape();
 595 
 596 #ifndef PRODUCT
 597     if (PrintEscapeAnalysis) {
 598       _congraph->dump();
 599     }
 600 #endif
 601     // Cleanup.
 602     if (oop_null->outcnt() == 0)
 603       igvn->hash_delete(oop_null);
 604     if (noop_null->outcnt() == 0)
 605       igvn->hash_delete(noop_null);
 606 
 607     if (!has_non_escaping_obj) {
 608       _congraph = NULL;
 609     }
 610 
 611     if (failing())  return;
 612   }
 613   // Now optimize
 614   Optimize();
 615   if (failing())  return;
 616   NOT_PRODUCT( verify_graph_edges(); )
 617 
 618   print_method("Before Matching");
 619 
 620 #ifndef PRODUCT
 621   if (PrintIdeal) {
 622     ttyLocker ttyl;  // keep the following output all in one block
 623     // This output goes directly to the tty, not the compiler log.
 624     // To enable tools to match it up with the compilation activity,
 625     // be sure to tag this tty output with the compile ID.
 626     if (xtty != NULL) {
 627       xtty->head("ideal compile_id='%d'%s", compile_id(),
 628                  is_osr_compilation()    ? " compile_kind='osr'" :
 629                  "");
 630     }
 631     root()->dump(9999);
 632     if (xtty != NULL) {
 633       xtty->tail("ideal");
 634     }
 635   }
 636 #endif
 637 
 638   // Now that we know the size of all the monitors we can add a fixed slot
 639   // for the original deopt pc.
 640 
 641   _orig_pc_slot =  fixed_slots();
 642   int next_slot = _orig_pc_slot + (sizeof(address) / VMRegImpl::stack_slot_size);
 643   set_fixed_slots(next_slot);
 644 
 645   // Now generate code
 646   Code_Gen();
 647   if (failing())  return;
 648 
 649   // Check if we want to skip execution of all compiled code.
 650   {
 651 #ifndef PRODUCT
 652     if (OptoNoExecute) {
 653       record_method_not_compilable("+OptoNoExecute");  // Flag as failed
 654       return;
 655     }
 656     TracePhase t2("install_code", &_t_registerMethod, TimeCompiler);
 657 #endif
 658 
 659     if (is_osr_compilation()) {
 660       _code_offsets.set_value(CodeOffsets::Verified_Entry, 0);
 661       _code_offsets.set_value(CodeOffsets::OSR_Entry, _first_block_size);
 662     } else {
 663       _code_offsets.set_value(CodeOffsets::Verified_Entry, _first_block_size);
 664       _code_offsets.set_value(CodeOffsets::OSR_Entry, 0);
 665     }
 666 
 667     env()->register_method(_method, _entry_bci,
 668                            &_code_offsets,
 669                            _orig_pc_slot_offset_in_bytes,
 670                            code_buffer(),
 671                            frame_size_in_words(), _oop_map_set,
 672                            &_handler_table, &_inc_table,
 673                            compiler,
 674                            env()->comp_level(),
 675                            true, /*has_debug_info*/
 676                            has_unsafe_access()
 677                            );
 678   }
 679 }
 680 
 681 //------------------------------Compile----------------------------------------
 682 // Compile a runtime stub
 683 Compile::Compile( ciEnv* ci_env,
 684                   TypeFunc_generator generator,
 685                   address stub_function,
 686                   const char *stub_name,
 687                   int is_fancy_jump,
 688                   bool pass_tls,
 689                   bool save_arg_registers,
 690                   bool return_pc )
 691   : Phase(Compiler),
 692     _env(ci_env),
 693     _log(ci_env->log()),
 694     _compile_id(-1),
 695     _save_argument_registers(save_arg_registers),
 696     _method(NULL),
 697     _stub_name(stub_name),
 698     _stub_function(stub_function),
 699     _stub_entry_point(NULL),
 700     _entry_bci(InvocationEntryBci),
 701     _initial_gvn(NULL),
 702     _for_igvn(NULL),
 703     _warm_calls(NULL),
 704     _orig_pc_slot(0),
 705     _orig_pc_slot_offset_in_bytes(0),
 706     _subsume_loads(true),
 707     _do_escape_analysis(false),
 708     _failure_reason(NULL),
 709     _code_buffer("Compile::Fill_buffer"),
 710     _node_bundling_limit(0),
 711     _node_bundling_base(NULL),
 712 #ifndef PRODUCT
 713     _trace_opto_output(TraceOptoOutput),
 714     _printer(NULL),
 715 #endif
 716     _congraph(NULL) {
 717   C = this;
 718 
 719 #ifndef PRODUCT
 720   TraceTime t1(NULL, &_t_totalCompilation, TimeCompiler, false);
 721   TraceTime t2(NULL, &_t_stubCompilation, TimeCompiler, false);
 722   set_print_assembly(PrintFrameConverterAssembly);
 723 #endif
 724   CompileWrapper cw(this);
 725   Init(/*AliasLevel=*/ 0);
 726   init_tf((*generator)());
 727 
 728   {
 729     // The following is a dummy for the sake of GraphKit::gen_stub
 730     Unique_Node_List for_igvn(comp_arena());
 731     set_for_igvn(&for_igvn);  // not used, but some GraphKit guys push on this
 732     PhaseGVN gvn(Thread::current()->resource_area(),255);
 733     set_initial_gvn(&gvn);    // not significant, but GraphKit guys use it pervasively
 734     gvn.transform_no_reclaim(top());
 735 
 736     GraphKit kit;
 737     kit.gen_stub(stub_function, stub_name, is_fancy_jump, pass_tls, return_pc);
 738   }
 739 
 740   NOT_PRODUCT( verify_graph_edges(); )
 741   Code_Gen();
 742   if (failing())  return;
 743 
 744 
 745   // Entry point will be accessed using compile->stub_entry_point();
 746   if (code_buffer() == NULL) {
 747     Matcher::soft_match_failure();
 748   } else {
 749     if (PrintAssembly && (WizardMode || Verbose))
 750       tty->print_cr("### Stub::%s", stub_name);
 751 
 752     if (!failing()) {
 753       assert(_fixed_slots == 0, "no fixed slots used for runtime stubs");
 754 
 755       // Make the NMethod
 756       // For now we mark the frame as never safe for profile stackwalking
 757       RuntimeStub *rs = RuntimeStub::new_runtime_stub(stub_name,
 758                                                       code_buffer(),
 759                                                       CodeOffsets::frame_never_safe,
 760                                                       // _code_offsets.value(CodeOffsets::Frame_Complete),
 761                                                       frame_size_in_words(),
 762                                                       _oop_map_set,
 763                                                       save_arg_registers);
 764       assert(rs != NULL && rs->is_runtime_stub(), "sanity check");
 765 
 766       _stub_entry_point = rs->entry_point();
 767     }
 768   }
 769 }
 770 
 771 #ifndef PRODUCT
 772 void print_opto_verbose_signature( const TypeFunc *j_sig, const char *stub_name ) {
 773   if(PrintOpto && Verbose) {
 774     tty->print("%s   ", stub_name); j_sig->print_flattened(); tty->cr();
 775   }
 776 }
 777 #endif
 778 
 779 void Compile::print_codes() {
 780 }
 781 
 782 //------------------------------Init-------------------------------------------
 783 // Prepare for a single compilation
 784 void Compile::Init(int aliaslevel) {
 785   _unique  = 0;
 786   _regalloc = NULL;
 787 
 788   _tf      = NULL;  // filled in later
 789   _top     = NULL;  // cached later
 790   _matcher = NULL;  // filled in later
 791   _cfg     = NULL;  // filled in later
 792 
 793   set_24_bit_selection_and_mode(Use24BitFP, false);
 794 
 795   _node_note_array = NULL;
 796   _default_node_notes = NULL;
 797 
 798   _immutable_memory = NULL; // filled in at first inquiry
 799 
 800   // Globally visible Nodes
 801   // First set TOP to NULL to give safe behavior during creation of RootNode
 802   set_cached_top_node(NULL);
 803   set_root(new (this, 3) RootNode());
 804   // Now that you have a Root to point to, create the real TOP
 805   set_cached_top_node( new (this, 1) ConNode(Type::TOP) );
 806   set_recent_alloc(NULL, NULL);
 807 
 808   // Create Debug Information Recorder to record scopes, oopmaps, etc.
 809   env()->set_oop_recorder(new OopRecorder(comp_arena()));
 810   env()->set_debug_info(new DebugInformationRecorder(env()->oop_recorder()));
 811   env()->set_dependencies(new Dependencies(env()));
 812 
 813   _fixed_slots = 0;
 814   set_has_split_ifs(false);
 815   set_has_loops(has_method() && method()->has_loops()); // first approximation
 816   _deopt_happens = true;  // start out assuming the worst
 817   _trap_can_recompile = false;  // no traps emitted yet
 818   _major_progress = true; // start out assuming good things will happen
 819   set_has_unsafe_access(false);
 820   Copy::zero_to_bytes(_trap_hist, sizeof(_trap_hist));
 821   set_decompile_count(0);
 822 
 823   // Compilation level related initialization
 824   if (env()->comp_level() == CompLevel_fast_compile) {
 825     set_num_loop_opts(Tier1LoopOptsCount);
 826     set_do_inlining(Tier1Inline != 0);
 827     set_max_inline_size(Tier1MaxInlineSize);
 828     set_freq_inline_size(Tier1FreqInlineSize);
 829     set_do_scheduling(false);
 830     set_do_count_invocations(Tier1CountInvocations);
 831     set_do_method_data_update(Tier1UpdateMethodData);
 832   } else {
 833     assert(env()->comp_level() == CompLevel_full_optimization, "unknown comp level");
 834     set_num_loop_opts(LoopOptsCount);
 835     set_do_inlining(Inline);
 836     set_max_inline_size(MaxInlineSize);
 837     set_freq_inline_size(FreqInlineSize);
 838     set_do_scheduling(OptoScheduling);
 839     set_do_count_invocations(false);
 840     set_do_method_data_update(false);
 841   }
 842 
 843   if (debug_info()->recording_non_safepoints()) {
 844     set_node_note_array(new(comp_arena()) GrowableArray<Node_Notes*>
 845                         (comp_arena(), 8, 0, NULL));
 846     set_default_node_notes(Node_Notes::make(this));
 847   }
 848 
 849   // // -- Initialize types before each compile --
 850   // // Update cached type information
 851   // if( _method && _method->constants() )
 852   //   Type::update_loaded_types(_method, _method->constants());
 853 
 854   // Init alias_type map.
 855   if (!_do_escape_analysis && aliaslevel == 3)
 856     aliaslevel = 2;  // No unique types without escape analysis
 857   _AliasLevel = aliaslevel;
 858   const int grow_ats = 16;
 859   _max_alias_types = grow_ats;
 860   _alias_types   = NEW_ARENA_ARRAY(comp_arena(), AliasType*, grow_ats);
 861   AliasType* ats = NEW_ARENA_ARRAY(comp_arena(), AliasType,  grow_ats);
 862   Copy::zero_to_bytes(ats, sizeof(AliasType)*grow_ats);
 863   {
 864     for (int i = 0; i < grow_ats; i++)  _alias_types[i] = &ats[i];
 865   }
 866   // Initialize the first few types.
 867   _alias_types[AliasIdxTop]->Init(AliasIdxTop, NULL);
 868   _alias_types[AliasIdxBot]->Init(AliasIdxBot, TypePtr::BOTTOM);
 869   _alias_types[AliasIdxRaw]->Init(AliasIdxRaw, TypeRawPtr::BOTTOM);
 870   _num_alias_types = AliasIdxRaw+1;
 871   // Zero out the alias type cache.
 872   Copy::zero_to_bytes(_alias_cache, sizeof(_alias_cache));
 873   // A NULL adr_type hits in the cache right away.  Preload the right answer.
 874   probe_alias_cache(NULL)->_index = AliasIdxTop;
 875 
 876   _intrinsics = NULL;
 877   _macro_nodes = new GrowableArray<Node*>(comp_arena(), 8,  0, NULL);
 878   register_library_intrinsics();
 879 }
 880 
 881 //---------------------------init_start----------------------------------------
 882 // Install the StartNode on this compile object.
 883 void Compile::init_start(StartNode* s) {
 884   if (failing())
 885     return; // already failing
 886   assert(s == start(), "");
 887 }
 888 
 889 StartNode* Compile::start() const {
 890   assert(!failing(), "");
 891   for (DUIterator_Fast imax, i = root()->fast_outs(imax); i < imax; i++) {
 892     Node* start = root()->fast_out(i);
 893     if( start->is_Start() )
 894       return start->as_Start();
 895   }
 896   ShouldNotReachHere();
 897   return NULL;
 898 }
 899 
 900 //-------------------------------immutable_memory-------------------------------------
 901 // Access immutable memory
 902 Node* Compile::immutable_memory() {
 903   if (_immutable_memory != NULL) {
 904     return _immutable_memory;
 905   }
 906   StartNode* s = start();
 907   for (DUIterator_Fast imax, i = s->fast_outs(imax); true; i++) {
 908     Node *p = s->fast_out(i);
 909     if (p != s && p->as_Proj()->_con == TypeFunc::Memory) {
 910       _immutable_memory = p;
 911       return _immutable_memory;
 912     }
 913   }
 914   ShouldNotReachHere();
 915   return NULL;
 916 }
 917 
 918 //----------------------set_cached_top_node------------------------------------
 919 // Install the cached top node, and make sure Node::is_top works correctly.
 920 void Compile::set_cached_top_node(Node* tn) {
 921   if (tn != NULL)  verify_top(tn);
 922   Node* old_top = _top;
 923   _top = tn;
 924   // Calling Node::setup_is_top allows the nodes the chance to adjust
 925   // their _out arrays.
 926   if (_top != NULL)     _top->setup_is_top();
 927   if (old_top != NULL)  old_top->setup_is_top();
 928   assert(_top == NULL || top()->is_top(), "");
 929 }
 930 
 931 #ifndef PRODUCT
 932 void Compile::verify_top(Node* tn) const {
 933   if (tn != NULL) {
 934     assert(tn->is_Con(), "top node must be a constant");
 935     assert(((ConNode*)tn)->type() == Type::TOP, "top node must have correct type");
 936     assert(tn->in(0) != NULL, "must have live top node");
 937   }
 938 }
 939 #endif
 940 
 941 
 942 ///-------------------Managing Per-Node Debug & Profile Info-------------------
 943 
 944 void Compile::grow_node_notes(GrowableArray<Node_Notes*>* arr, int grow_by) {
 945   guarantee(arr != NULL, "");
 946   int num_blocks = arr->length();
 947   if (grow_by < num_blocks)  grow_by = num_blocks;
 948   int num_notes = grow_by * _node_notes_block_size;
 949   Node_Notes* notes = NEW_ARENA_ARRAY(node_arena(), Node_Notes, num_notes);
 950   Copy::zero_to_bytes(notes, num_notes * sizeof(Node_Notes));
 951   while (num_notes > 0) {
 952     arr->append(notes);
 953     notes     += _node_notes_block_size;
 954     num_notes -= _node_notes_block_size;
 955   }
 956   assert(num_notes == 0, "exact multiple, please");
 957 }
 958 
 959 bool Compile::copy_node_notes_to(Node* dest, Node* source) {
 960   if (source == NULL || dest == NULL)  return false;
 961 
 962   if (dest->is_Con())
 963     return false;               // Do not push debug info onto constants.
 964 
 965 #ifdef ASSERT
 966   // Leave a bread crumb trail pointing to the original node:
 967   if (dest != NULL && dest != source && dest->debug_orig() == NULL) {
 968     dest->set_debug_orig(source);
 969   }
 970 #endif
 971 
 972   if (node_note_array() == NULL)
 973     return false;               // Not collecting any notes now.
 974 
 975   // This is a copy onto a pre-existing node, which may already have notes.
 976   // If both nodes have notes, do not overwrite any pre-existing notes.
 977   Node_Notes* source_notes = node_notes_at(source->_idx);
 978   if (source_notes == NULL || source_notes->is_clear())  return false;
 979   Node_Notes* dest_notes   = node_notes_at(dest->_idx);
 980   if (dest_notes == NULL || dest_notes->is_clear()) {
 981     return set_node_notes_at(dest->_idx, source_notes);
 982   }
 983 
 984   Node_Notes merged_notes = (*source_notes);
 985   // The order of operations here ensures that dest notes will win...
 986   merged_notes.update_from(dest_notes);
 987   return set_node_notes_at(dest->_idx, &merged_notes);
 988 }
 989 
 990 
 991 //--------------------------allow_range_check_smearing-------------------------
 992 // Gating condition for coalescing similar range checks.
 993 // Sometimes we try 'speculatively' replacing a series of a range checks by a
 994 // single covering check that is at least as strong as any of them.
 995 // If the optimization succeeds, the simplified (strengthened) range check
 996 // will always succeed.  If it fails, we will deopt, and then give up
 997 // on the optimization.
 998 bool Compile::allow_range_check_smearing() const {
 999   // If this method has already thrown a range-check,
1000   // assume it was because we already tried range smearing
1001   // and it failed.
1002   uint already_trapped = trap_count(Deoptimization::Reason_range_check);
1003   return !already_trapped;
1004 }
1005 
1006 
1007 //------------------------------flatten_alias_type-----------------------------
1008 const TypePtr *Compile::flatten_alias_type( const TypePtr *tj ) const {
1009   int offset = tj->offset();
1010   TypePtr::PTR ptr = tj->ptr();
1011 
1012   // Known instance (scalarizable allocation) alias only with itself.
1013   bool is_known_inst = tj->isa_oopptr() != NULL &&
1014                        tj->is_oopptr()->is_known_instance();
1015 
1016   // Process weird unsafe references.
1017   if (offset == Type::OffsetBot && (tj->isa_instptr() /*|| tj->isa_klassptr()*/)) {
1018     assert(InlineUnsafeOps, "indeterminate pointers come only from unsafe ops");
1019     assert(!is_known_inst, "scalarizable allocation should not have unsafe references");
1020     tj = TypeOopPtr::BOTTOM;
1021     ptr = tj->ptr();
1022     offset = tj->offset();
1023   }
1024 
1025   // Array pointers need some flattening
1026   const TypeAryPtr *ta = tj->isa_aryptr();
1027   if( ta && is_known_inst ) {
1028     if ( offset != Type::OffsetBot &&
1029          offset > arrayOopDesc::length_offset_in_bytes() ) {
1030       offset = Type::OffsetBot; // Flatten constant access into array body only
1031       tj = ta = TypeAryPtr::make(ptr, ta->ary(), ta->klass(), true, offset, ta->instance_id());
1032     }
1033   } else if( ta && _AliasLevel >= 2 ) {
1034     // For arrays indexed by constant indices, we flatten the alias
1035     // space to include all of the array body.  Only the header, klass
1036     // and array length can be accessed un-aliased.
1037     if( offset != Type::OffsetBot ) {
1038       if( ta->const_oop() ) { // methodDataOop or methodOop
1039         offset = Type::OffsetBot;   // Flatten constant access into array body
1040         tj = ta = TypeAryPtr::make(ptr,ta->const_oop(),ta->ary(),ta->klass(),false,offset);
1041       } else if( offset == arrayOopDesc::length_offset_in_bytes() ) {
1042         // range is OK as-is.
1043         tj = ta = TypeAryPtr::RANGE;
1044       } else if( offset == oopDesc::klass_offset_in_bytes() ) {
1045         tj = TypeInstPtr::KLASS; // all klass loads look alike
1046         ta = TypeAryPtr::RANGE; // generic ignored junk
1047         ptr = TypePtr::BotPTR;
1048       } else if( offset == oopDesc::mark_offset_in_bytes() ) {
1049         tj = TypeInstPtr::MARK;
1050         ta = TypeAryPtr::RANGE; // generic ignored junk
1051         ptr = TypePtr::BotPTR;
1052       } else {                  // Random constant offset into array body
1053         offset = Type::OffsetBot;   // Flatten constant access into array body
1054         tj = ta = TypeAryPtr::make(ptr,ta->ary(),ta->klass(),false,offset);
1055       }
1056     }
1057     // Arrays of fixed size alias with arrays of unknown size.
1058     if (ta->size() != TypeInt::POS) {
1059       const TypeAry *tary = TypeAry::make(ta->elem(), TypeInt::POS);
1060       tj = ta = TypeAryPtr::make(ptr,ta->const_oop(),tary,ta->klass(),false,offset);
1061     }
1062     // Arrays of known objects become arrays of unknown objects.
1063     if (ta->elem()->isa_narrowoop() && ta->elem() != TypeNarrowOop::BOTTOM) {
1064       const TypeAry *tary = TypeAry::make(TypeNarrowOop::BOTTOM, ta->size());
1065       tj = ta = TypeAryPtr::make(ptr,ta->const_oop(),tary,NULL,false,offset);
1066     }
1067     if (ta->elem()->isa_oopptr() && ta->elem() != TypeInstPtr::BOTTOM) {
1068       const TypeAry *tary = TypeAry::make(TypeInstPtr::BOTTOM, ta->size());
1069       tj = ta = TypeAryPtr::make(ptr,ta->const_oop(),tary,NULL,false,offset);
1070     }
1071     // Arrays of bytes and of booleans both use 'bastore' and 'baload' so
1072     // cannot be distinguished by bytecode alone.
1073     if (ta->elem() == TypeInt::BOOL) {
1074       const TypeAry *tary = TypeAry::make(TypeInt::BYTE, ta->size());
1075       ciKlass* aklass = ciTypeArrayKlass::make(T_BYTE);
1076       tj = ta = TypeAryPtr::make(ptr,ta->const_oop(),tary,aklass,false,offset);
1077     }
1078     // During the 2nd round of IterGVN, NotNull castings are removed.
1079     // Make sure the Bottom and NotNull variants alias the same.
1080     // Also, make sure exact and non-exact variants alias the same.
1081     if( ptr == TypePtr::NotNull || ta->klass_is_exact() ) {
1082       if (ta->const_oop()) {
1083         tj = ta = TypeAryPtr::make(TypePtr::Constant,ta->const_oop(),ta->ary(),ta->klass(),false,offset);
1084       } else {
1085         tj = ta = TypeAryPtr::make(TypePtr::BotPTR,ta->ary(),ta->klass(),false,offset);
1086       }
1087     }
1088   }
1089 
1090   // Oop pointers need some flattening
1091   const TypeInstPtr *to = tj->isa_instptr();
1092   if( to && _AliasLevel >= 2 && to != TypeOopPtr::BOTTOM ) {
1093     if( ptr == TypePtr::Constant ) {
1094       // No constant oop pointers (such as Strings); they alias with
1095       // unknown strings.
1096       assert(!is_known_inst, "not scalarizable allocation");
1097       tj = to = TypeInstPtr::make(TypePtr::BotPTR,to->klass(),false,0,offset);
1098     } else if( is_known_inst ) {
1099       tj = to; // Keep NotNull and klass_is_exact for instance type
1100     } else if( ptr == TypePtr::NotNull || to->klass_is_exact() ) {
1101       // During the 2nd round of IterGVN, NotNull castings are removed.
1102       // Make sure the Bottom and NotNull variants alias the same.
1103       // Also, make sure exact and non-exact variants alias the same.
1104       tj = to = TypeInstPtr::make(TypePtr::BotPTR,to->klass(),false,0,offset);
1105     }
1106     // Canonicalize the holder of this field
1107     ciInstanceKlass *k = to->klass()->as_instance_klass();
1108     if (offset >= 0 && offset < instanceOopDesc::base_offset_in_bytes()) {
1109       // First handle header references such as a LoadKlassNode, even if the
1110       // object's klass is unloaded at compile time (4965979).
1111       if (!is_known_inst) { // Do it only for non-instance types
1112         tj = to = TypeInstPtr::make(TypePtr::BotPTR, env()->Object_klass(), false, NULL, offset);
1113       }
1114     } else if (offset < 0 || offset >= k->size_helper() * wordSize) {
1115       to = NULL;
1116       tj = TypeOopPtr::BOTTOM;
1117       offset = tj->offset();
1118     } else {
1119       ciInstanceKlass *canonical_holder = k->get_canonical_holder(offset);
1120       if (!k->equals(canonical_holder) || tj->offset() != offset) {
1121         if( is_known_inst ) {
1122           tj = to = TypeInstPtr::make(to->ptr(), canonical_holder, true, NULL, offset, to->instance_id());
1123         } else {
1124           tj = to = TypeInstPtr::make(to->ptr(), canonical_holder, false, NULL, offset);
1125         }
1126       }
1127     }
1128   }
1129 
1130   // Klass pointers to object array klasses need some flattening
1131   const TypeKlassPtr *tk = tj->isa_klassptr();
1132   if( tk ) {
1133     // If we are referencing a field within a Klass, we need
1134     // to assume the worst case of an Object.  Both exact and
1135     // inexact types must flatten to the same alias class.
1136     // Since the flattened result for a klass is defined to be
1137     // precisely java.lang.Object, use a constant ptr.
1138     if ( offset == Type::OffsetBot || (offset >= 0 && (size_t)offset < sizeof(Klass)) ) {
1139 
1140       tj = tk = TypeKlassPtr::make(TypePtr::Constant,
1141                                    TypeKlassPtr::OBJECT->klass(),
1142                                    offset);
1143     }
1144 
1145     ciKlass* klass = tk->klass();
1146     if( klass->is_obj_array_klass() ) {
1147       ciKlass* k = TypeAryPtr::OOPS->klass();
1148       if( !k || !k->is_loaded() )                  // Only fails for some -Xcomp runs
1149         k = TypeInstPtr::BOTTOM->klass();
1150       tj = tk = TypeKlassPtr::make( TypePtr::NotNull, k, offset );
1151     }
1152 
1153     // Check for precise loads from the primary supertype array and force them
1154     // to the supertype cache alias index.  Check for generic array loads from
1155     // the primary supertype array and also force them to the supertype cache
1156     // alias index.  Since the same load can reach both, we need to merge
1157     // these 2 disparate memories into the same alias class.  Since the
1158     // primary supertype array is read-only, there's no chance of confusion
1159     // where we bypass an array load and an array store.
1160     uint off2 = offset - Klass::primary_supers_offset_in_bytes();
1161     if( offset == Type::OffsetBot ||
1162         off2 < Klass::primary_super_limit()*wordSize ) {
1163       offset = sizeof(oopDesc) +Klass::secondary_super_cache_offset_in_bytes();
1164       tj = tk = TypeKlassPtr::make( TypePtr::NotNull, tk->klass(), offset );
1165     }
1166   }
1167 
1168   // Flatten all Raw pointers together.
1169   if (tj->base() == Type::RawPtr)
1170     tj = TypeRawPtr::BOTTOM;
1171 
1172   if (tj->base() == Type::AnyPtr)
1173     tj = TypePtr::BOTTOM;      // An error, which the caller must check for.
1174 
1175   // Flatten all to bottom for now
1176   switch( _AliasLevel ) {
1177   case 0:
1178     tj = TypePtr::BOTTOM;
1179     break;
1180   case 1:                       // Flatten to: oop, static, field or array
1181     switch (tj->base()) {
1182     //case Type::AryPtr: tj = TypeAryPtr::RANGE;    break;
1183     case Type::RawPtr:   tj = TypeRawPtr::BOTTOM;   break;
1184     case Type::AryPtr:   // do not distinguish arrays at all
1185     case Type::InstPtr:  tj = TypeInstPtr::BOTTOM;  break;
1186     case Type::KlassPtr: tj = TypeKlassPtr::OBJECT; break;
1187     case Type::AnyPtr:   tj = TypePtr::BOTTOM;      break;  // caller checks it
1188     default: ShouldNotReachHere();
1189     }
1190     break;
1191   case 2:                       // No collasping at level 2; keep all splits
1192   case 3:                       // No collasping at level 3; keep all splits
1193     break;
1194   default:
1195     Unimplemented();
1196   }
1197 
1198   offset = tj->offset();
1199   assert( offset != Type::OffsetTop, "Offset has fallen from constant" );
1200 
1201   assert( (offset != Type::OffsetBot && tj->base() != Type::AryPtr) ||
1202           (offset == Type::OffsetBot && tj->base() == Type::AryPtr) ||
1203           (offset == Type::OffsetBot && tj == TypeOopPtr::BOTTOM) ||
1204           (offset == Type::OffsetBot && tj == TypePtr::BOTTOM) ||
1205           (offset == oopDesc::mark_offset_in_bytes() && tj->base() == Type::AryPtr) ||
1206           (offset == oopDesc::klass_offset_in_bytes() && tj->base() == Type::AryPtr) ||
1207           (offset == arrayOopDesc::length_offset_in_bytes() && tj->base() == Type::AryPtr)  ,
1208           "For oops, klasses, raw offset must be constant; for arrays the offset is never known" );
1209   assert( tj->ptr() != TypePtr::TopPTR &&
1210           tj->ptr() != TypePtr::AnyNull &&
1211           tj->ptr() != TypePtr::Null, "No imprecise addresses" );
1212 //    assert( tj->ptr() != TypePtr::Constant ||
1213 //            tj->base() == Type::RawPtr ||
1214 //            tj->base() == Type::KlassPtr, "No constant oop addresses" );
1215 
1216   return tj;
1217 }
1218 
1219 void Compile::AliasType::Init(int i, const TypePtr* at) {
1220   _index = i;
1221   _adr_type = at;
1222   _field = NULL;
1223   _is_rewritable = true; // default
1224   const TypeOopPtr *atoop = (at != NULL) ? at->isa_oopptr() : NULL;
1225   if (atoop != NULL && atoop->is_known_instance()) {
1226     const TypeOopPtr *gt = atoop->cast_to_instance_id(TypeOopPtr::InstanceBot);
1227     _general_index = Compile::current()->get_alias_index(gt);
1228   } else {
1229     _general_index = 0;
1230   }
1231 }
1232 
1233 //---------------------------------print_on------------------------------------
1234 #ifndef PRODUCT
1235 void Compile::AliasType::print_on(outputStream* st) {
1236   if (index() < 10)
1237         st->print("@ <%d> ", index());
1238   else  st->print("@ <%d>",  index());
1239   st->print(is_rewritable() ? "   " : " RO");
1240   int offset = adr_type()->offset();
1241   if (offset == Type::OffsetBot)
1242         st->print(" +any");
1243   else  st->print(" +%-3d", offset);
1244   st->print(" in ");
1245   adr_type()->dump_on(st);
1246   const TypeOopPtr* tjp = adr_type()->isa_oopptr();
1247   if (field() != NULL && tjp) {
1248     if (tjp->klass()  != field()->holder() ||
1249         tjp->offset() != field()->offset_in_bytes()) {
1250       st->print(" != ");
1251       field()->print();
1252       st->print(" ***");
1253     }
1254   }
1255 }
1256 
1257 void print_alias_types() {
1258   Compile* C = Compile::current();
1259   tty->print_cr("--- Alias types, AliasIdxBot .. %d", C->num_alias_types()-1);
1260   for (int idx = Compile::AliasIdxBot; idx < C->num_alias_types(); idx++) {
1261     C->alias_type(idx)->print_on(tty);
1262     tty->cr();
1263   }
1264 }
1265 #endif
1266 
1267 
1268 //----------------------------probe_alias_cache--------------------------------
1269 Compile::AliasCacheEntry* Compile::probe_alias_cache(const TypePtr* adr_type) {
1270   intptr_t key = (intptr_t) adr_type;
1271   key ^= key >> logAliasCacheSize;
1272   return &_alias_cache[key & right_n_bits(logAliasCacheSize)];
1273 }
1274 
1275 
1276 //-----------------------------grow_alias_types--------------------------------
1277 void Compile::grow_alias_types() {
1278   const int old_ats  = _max_alias_types; // how many before?
1279   const int new_ats  = old_ats;          // how many more?
1280   const int grow_ats = old_ats+new_ats;  // how many now?
1281   _max_alias_types = grow_ats;
1282   _alias_types =  REALLOC_ARENA_ARRAY(comp_arena(), AliasType*, _alias_types, old_ats, grow_ats);
1283   AliasType* ats =    NEW_ARENA_ARRAY(comp_arena(), AliasType, new_ats);
1284   Copy::zero_to_bytes(ats, sizeof(AliasType)*new_ats);
1285   for (int i = 0; i < new_ats; i++)  _alias_types[old_ats+i] = &ats[i];
1286 }
1287 
1288 
1289 //--------------------------------find_alias_type------------------------------
1290 Compile::AliasType* Compile::find_alias_type(const TypePtr* adr_type, bool no_create) {
1291   if (_AliasLevel == 0)
1292     return alias_type(AliasIdxBot);
1293 
1294   AliasCacheEntry* ace = probe_alias_cache(adr_type);
1295   if (ace->_adr_type == adr_type) {
1296     return alias_type(ace->_index);
1297   }
1298 
1299   // Handle special cases.
1300   if (adr_type == NULL)             return alias_type(AliasIdxTop);
1301   if (adr_type == TypePtr::BOTTOM)  return alias_type(AliasIdxBot);
1302 
1303   // Do it the slow way.
1304   const TypePtr* flat = flatten_alias_type(adr_type);
1305 
1306 #ifdef ASSERT
1307   assert(flat == flatten_alias_type(flat), "idempotent");
1308   assert(flat != TypePtr::BOTTOM,     "cannot alias-analyze an untyped ptr");
1309   if (flat->isa_oopptr() && !flat->isa_klassptr()) {
1310     const TypeOopPtr* foop = flat->is_oopptr();
1311     // Scalarizable allocations have exact klass always.
1312     bool exact = !foop->klass_is_exact() || foop->is_known_instance();
1313     const TypePtr* xoop = foop->cast_to_exactness(exact)->is_ptr();
1314     assert(foop == flatten_alias_type(xoop), "exactness must not affect alias type");
1315   }
1316   assert(flat == flatten_alias_type(flat), "exact bit doesn't matter");
1317 #endif
1318 
1319   int idx = AliasIdxTop;
1320   for (int i = 0; i < num_alias_types(); i++) {
1321     if (alias_type(i)->adr_type() == flat) {
1322       idx = i;
1323       break;
1324     }
1325   }
1326 
1327   if (idx == AliasIdxTop) {
1328     if (no_create)  return NULL;
1329     // Grow the array if necessary.
1330     if (_num_alias_types == _max_alias_types)  grow_alias_types();
1331     // Add a new alias type.
1332     idx = _num_alias_types++;
1333     _alias_types[idx]->Init(idx, flat);
1334     if (flat == TypeInstPtr::KLASS)  alias_type(idx)->set_rewritable(false);
1335     if (flat == TypeAryPtr::RANGE)   alias_type(idx)->set_rewritable(false);
1336     if (flat->isa_instptr()) {
1337       if (flat->offset() == java_lang_Class::klass_offset_in_bytes()
1338           && flat->is_instptr()->klass() == env()->Class_klass())
1339         alias_type(idx)->set_rewritable(false);
1340     }
1341     if (flat->isa_klassptr()) {
1342       if (flat->offset() == Klass::super_check_offset_offset_in_bytes() + (int)sizeof(oopDesc))
1343         alias_type(idx)->set_rewritable(false);
1344       if (flat->offset() == Klass::modifier_flags_offset_in_bytes() + (int)sizeof(oopDesc))
1345         alias_type(idx)->set_rewritable(false);
1346       if (flat->offset() == Klass::access_flags_offset_in_bytes() + (int)sizeof(oopDesc))
1347         alias_type(idx)->set_rewritable(false);
1348       if (flat->offset() == Klass::java_mirror_offset_in_bytes() + (int)sizeof(oopDesc))
1349         alias_type(idx)->set_rewritable(false);
1350     }
1351     // %%% (We would like to finalize JavaThread::threadObj_offset(),
1352     // but the base pointer type is not distinctive enough to identify
1353     // references into JavaThread.)
1354 
1355     // Check for final instance fields.
1356     const TypeInstPtr* tinst = flat->isa_instptr();
1357     if (tinst && tinst->offset() >= instanceOopDesc::base_offset_in_bytes()) {
1358       ciInstanceKlass *k = tinst->klass()->as_instance_klass();
1359       ciField* field = k->get_field_by_offset(tinst->offset(), false);
1360       // Set field() and is_rewritable() attributes.
1361       if (field != NULL)  alias_type(idx)->set_field(field);
1362     }
1363     const TypeKlassPtr* tklass = flat->isa_klassptr();
1364     // Check for final static fields.
1365     if (tklass && tklass->klass()->is_instance_klass()) {
1366       ciInstanceKlass *k = tklass->klass()->as_instance_klass();
1367       ciField* field = k->get_field_by_offset(tklass->offset(), true);
1368       // Set field() and is_rewritable() attributes.
1369       if (field != NULL)   alias_type(idx)->set_field(field);
1370     }
1371   }
1372 
1373   // Fill the cache for next time.
1374   ace->_adr_type = adr_type;
1375   ace->_index    = idx;
1376   assert(alias_type(adr_type) == alias_type(idx),  "type must be installed");
1377 
1378   // Might as well try to fill the cache for the flattened version, too.
1379   AliasCacheEntry* face = probe_alias_cache(flat);
1380   if (face->_adr_type == NULL) {
1381     face->_adr_type = flat;
1382     face->_index    = idx;
1383     assert(alias_type(flat) == alias_type(idx), "flat type must work too");
1384   }
1385 
1386   return alias_type(idx);
1387 }
1388 
1389 
1390 Compile::AliasType* Compile::alias_type(ciField* field) {
1391   const TypeOopPtr* t;
1392   if (field->is_static())
1393     t = TypeKlassPtr::make(field->holder());
1394   else
1395     t = TypeOopPtr::make_from_klass_raw(field->holder());
1396   AliasType* atp = alias_type(t->add_offset(field->offset_in_bytes()));
1397   assert(field->is_final() == !atp->is_rewritable(), "must get the rewritable bits correct");
1398   return atp;
1399 }
1400 
1401 
1402 //------------------------------have_alias_type--------------------------------
1403 bool Compile::have_alias_type(const TypePtr* adr_type) {
1404   AliasCacheEntry* ace = probe_alias_cache(adr_type);
1405   if (ace->_adr_type == adr_type) {
1406     return true;
1407   }
1408 
1409   // Handle special cases.
1410   if (adr_type == NULL)             return true;
1411   if (adr_type == TypePtr::BOTTOM)  return true;
1412 
1413   return find_alias_type(adr_type, true) != NULL;
1414 }
1415 
1416 //-----------------------------must_alias--------------------------------------
1417 // True if all values of the given address type are in the given alias category.
1418 bool Compile::must_alias(const TypePtr* adr_type, int alias_idx) {
1419   if (alias_idx == AliasIdxBot)         return true;  // the universal category
1420   if (adr_type == NULL)                 return true;  // NULL serves as TypePtr::TOP
1421   if (alias_idx == AliasIdxTop)         return false; // the empty category
1422   if (adr_type->base() == Type::AnyPtr) return false; // TypePtr::BOTTOM or its twins
1423 
1424   // the only remaining possible overlap is identity
1425   int adr_idx = get_alias_index(adr_type);
1426   assert(adr_idx != AliasIdxBot && adr_idx != AliasIdxTop, "");
1427   assert(adr_idx == alias_idx ||
1428          (alias_type(alias_idx)->adr_type() != TypeOopPtr::BOTTOM
1429           && adr_type                       != TypeOopPtr::BOTTOM),
1430          "should not be testing for overlap with an unsafe pointer");
1431   return adr_idx == alias_idx;
1432 }
1433 
1434 //------------------------------can_alias--------------------------------------
1435 // True if any values of the given address type are in the given alias category.
1436 bool Compile::can_alias(const TypePtr* adr_type, int alias_idx) {
1437   if (alias_idx == AliasIdxTop)         return false; // the empty category
1438   if (adr_type == NULL)                 return false; // NULL serves as TypePtr::TOP
1439   if (alias_idx == AliasIdxBot)         return true;  // the universal category
1440   if (adr_type->base() == Type::AnyPtr) return true;  // TypePtr::BOTTOM or its twins
1441 
1442   // the only remaining possible overlap is identity
1443   int adr_idx = get_alias_index(adr_type);
1444   assert(adr_idx != AliasIdxBot && adr_idx != AliasIdxTop, "");
1445   return adr_idx == alias_idx;
1446 }
1447 
1448 
1449 
1450 //---------------------------pop_warm_call-------------------------------------
1451 WarmCallInfo* Compile::pop_warm_call() {
1452   WarmCallInfo* wci = _warm_calls;
1453   if (wci != NULL)  _warm_calls = wci->remove_from(wci);
1454   return wci;
1455 }
1456 
1457 //----------------------------Inline_Warm--------------------------------------
1458 int Compile::Inline_Warm() {
1459   // If there is room, try to inline some more warm call sites.
1460   // %%% Do a graph index compaction pass when we think we're out of space?
1461   if (!InlineWarmCalls)  return 0;
1462 
1463   int calls_made_hot = 0;
1464   int room_to_grow   = NodeCountInliningCutoff - unique();
1465   int amount_to_grow = MIN2(room_to_grow, (int)NodeCountInliningStep);
1466   int amount_grown   = 0;
1467   WarmCallInfo* call;
1468   while (amount_to_grow > 0 && (call = pop_warm_call()) != NULL) {
1469     int est_size = (int)call->size();
1470     if (est_size > (room_to_grow - amount_grown)) {
1471       // This one won't fit anyway.  Get rid of it.
1472       call->make_cold();
1473       continue;
1474     }
1475     call->make_hot();
1476     calls_made_hot++;
1477     amount_grown   += est_size;
1478     amount_to_grow -= est_size;
1479   }
1480 
1481   if (calls_made_hot > 0)  set_major_progress();
1482   return calls_made_hot;
1483 }
1484 
1485 
1486 //----------------------------Finish_Warm--------------------------------------
1487 void Compile::Finish_Warm() {
1488   if (!InlineWarmCalls)  return;
1489   if (failing())  return;
1490   if (warm_calls() == NULL)  return;
1491 
1492   // Clean up loose ends, if we are out of space for inlining.
1493   WarmCallInfo* call;
1494   while ((call = pop_warm_call()) != NULL) {
1495     call->make_cold();
1496   }
1497 }
1498 
1499 
1500 //------------------------------Optimize---------------------------------------
1501 // Given a graph, optimize it.
1502 void Compile::Optimize() {
1503   TracePhase t1("optimizer", &_t_optimizer, true);
1504 
1505 #ifndef PRODUCT
1506   if (env()->break_at_compile()) {
1507     BREAKPOINT;
1508   }
1509 
1510 #endif
1511 
1512   ResourceMark rm;
1513   int          loop_opts_cnt;
1514 
1515   NOT_PRODUCT( verify_graph_edges(); )
1516 
1517   print_method("After Parsing");
1518 
1519  {
1520   // Iterative Global Value Numbering, including ideal transforms
1521   // Initialize IterGVN with types and values from parse-time GVN
1522   PhaseIterGVN igvn(initial_gvn());
1523   {
1524     NOT_PRODUCT( TracePhase t2("iterGVN", &_t_iterGVN, TimeCompiler); )
1525     igvn.optimize();
1526   }
1527 
1528   print_method("Iter GVN 1", 2);
1529 
1530   if (failing())  return;
1531 
1532   // get rid of the connection graph since it's information is not
1533   // updated by optimizations
1534   _congraph = NULL;
1535 
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("removeEmpty", &_t_removeEmptyBlocks, TimeCompiler); )
1703     cfg.RemoveEmpty();
1704   }
1705 
1706   // Perform any platform dependent postallocation verifications.
1707   debug_only( _regalloc->pd_postallocate_verify_hook(); )
1708 
1709   // Apply peephole optimizations
1710   if( OptoPeephole ) {
1711     NOT_PRODUCT( TracePhase t2("peephole", &_t_peephole, TimeCompiler); )
1712     PhasePeephole peep( _regalloc, cfg);
1713     peep.do_transform();
1714   }
1715 
1716   // Convert Nodes to instruction bits in a buffer
1717   {
1718     // %%%% workspace merge brought two timers together for one job
1719     TracePhase t2a("output", &_t_output, true);
1720     NOT_PRODUCT( TraceTime t2b(NULL, &_t_codeGeneration, TimeCompiler, false); )
1721     Output();
1722   }
1723 
1724   print_method("Final Code");
1725 
1726   // He's dead, Jim.
1727   _cfg     = (PhaseCFG*)0xdeadbeef;
1728   _regalloc = (PhaseChaitin*)0xdeadbeef;
1729 }
1730 
1731 
1732 //------------------------------dump_asm---------------------------------------
1733 // Dump formatted assembly
1734 #ifndef PRODUCT
1735 void Compile::dump_asm(int *pcs, uint pc_limit) {
1736   bool cut_short = false;
1737   tty->print_cr("#");
1738   tty->print("#  ");  _tf->dump();  tty->cr();
1739   tty->print_cr("#");
1740 
1741   // For all blocks
1742   int pc = 0x0;                 // Program counter
1743   char starts_bundle = ' ';
1744   _regalloc->dump_frame();
1745 
1746   Node *n = NULL;
1747   for( uint i=0; i<_cfg->_num_blocks; i++ ) {
1748     if (VMThread::should_terminate()) { cut_short = true; break; }
1749     Block *b = _cfg->_blocks[i];
1750     if (b->is_connector() && !Verbose) continue;
1751     n = b->_nodes[0];
1752     if (pcs && n->_idx < pc_limit)
1753       tty->print("%3.3x   ", pcs[n->_idx]);
1754     else
1755       tty->print("      ");
1756     b->dump_head( &_cfg->_bbs );
1757     if (b->is_connector()) {
1758       tty->print_cr("        # Empty connector block");
1759     } else if (b->num_preds() == 2 && b->pred(1)->is_CatchProj() && b->pred(1)->as_CatchProj()->_con == CatchProjNode::fall_through_index) {
1760       tty->print_cr("        # Block is sole successor of call");
1761     }
1762 
1763     // For all instructions
1764     Node *delay = NULL;
1765     for( uint j = 0; j<b->_nodes.size(); j++ ) {
1766       if (VMThread::should_terminate()) { cut_short = true; break; }
1767       n = b->_nodes[j];
1768       if (valid_bundle_info(n)) {
1769         Bundle *bundle = node_bundling(n);
1770         if (bundle->used_in_unconditional_delay()) {
1771           delay = n;
1772           continue;
1773         }
1774         if (bundle->starts_bundle())
1775           starts_bundle = '+';
1776       }
1777 
1778       if (WizardMode) n->dump();
1779 
1780       if( !n->is_Region() &&    // Dont print in the Assembly
1781           !n->is_Phi() &&       // a few noisely useless nodes
1782           !n->is_Proj() &&
1783           !n->is_MachTemp() &&
1784           !n->is_Catch() &&     // Would be nice to print exception table targets
1785           !n->is_MergeMem() &&  // Not very interesting
1786           !n->is_top() &&       // Debug info table constants
1787           !(n->is_Con() && !n->is_Mach())// Debug info table constants
1788           ) {
1789         if (pcs && n->_idx < pc_limit)
1790           tty->print("%3.3x", pcs[n->_idx]);
1791         else
1792           tty->print("   ");
1793         tty->print(" %c ", starts_bundle);
1794         starts_bundle = ' ';
1795         tty->print("\t");
1796         n->format(_regalloc, tty);
1797         tty->cr();
1798       }
1799 
1800       // If we have an instruction with a delay slot, and have seen a delay,
1801       // then back up and print it
1802       if (valid_bundle_info(n) && node_bundling(n)->use_unconditional_delay()) {
1803         assert(delay != NULL, "no unconditional delay instruction");
1804         if (WizardMode) delay->dump();
1805 
1806         if (node_bundling(delay)->starts_bundle())
1807           starts_bundle = '+';
1808         if (pcs && n->_idx < pc_limit)
1809           tty->print("%3.3x", pcs[n->_idx]);
1810         else
1811           tty->print("   ");
1812         tty->print(" %c ", starts_bundle);
1813         starts_bundle = ' ';
1814         tty->print("\t");
1815         delay->format(_regalloc, tty);
1816         tty->print_cr("");
1817         delay = NULL;
1818       }
1819 
1820       // Dump the exception table as well
1821       if( n->is_Catch() && (Verbose || WizardMode) ) {
1822         // Print the exception table for this offset
1823         _handler_table.print_subtable_for(pc);
1824       }
1825     }
1826 
1827     if (pcs && n->_idx < pc_limit)
1828       tty->print_cr("%3.3x", pcs[n->_idx]);
1829     else
1830       tty->print_cr("");
1831 
1832     assert(cut_short || delay == NULL, "no unconditional delay branch");
1833 
1834   } // End of per-block dump
1835   tty->print_cr("");
1836 
1837   if (cut_short)  tty->print_cr("*** disassembly is cut short ***");
1838 }
1839 #endif
1840 
1841 //------------------------------Final_Reshape_Counts---------------------------
1842 // This class defines counters to help identify when a method
1843 // may/must be executed using hardware with only 24-bit precision.
1844 struct Final_Reshape_Counts : public StackObj {
1845   int  _call_count;             // count non-inlined 'common' calls
1846   int  _float_count;            // count float ops requiring 24-bit precision
1847   int  _double_count;           // count double ops requiring more precision
1848   int  _java_call_count;        // count non-inlined 'java' calls
1849   VectorSet _visited;           // Visitation flags
1850   Node_List _tests;             // Set of IfNodes & PCTableNodes
1851 
1852   Final_Reshape_Counts() :
1853     _call_count(0), _float_count(0), _double_count(0), _java_call_count(0),
1854     _visited( Thread::current()->resource_area() ) { }
1855 
1856   void inc_call_count  () { _call_count  ++; }
1857   void inc_float_count () { _float_count ++; }
1858   void inc_double_count() { _double_count++; }
1859   void inc_java_call_count() { _java_call_count++; }
1860 
1861   int  get_call_count  () const { return _call_count  ; }
1862   int  get_float_count () const { return _float_count ; }
1863   int  get_double_count() const { return _double_count; }
1864   int  get_java_call_count() const { return _java_call_count; }
1865 };
1866 
1867 static bool oop_offset_is_sane(const TypeInstPtr* tp) {
1868   ciInstanceKlass *k = tp->klass()->as_instance_klass();
1869   // Make sure the offset goes inside the instance layout.
1870   return k->contains_field_offset(tp->offset());
1871   // Note that OffsetBot and OffsetTop are very negative.
1872 }
1873 
1874 //------------------------------final_graph_reshaping_impl----------------------
1875 // Implement items 1-5 from final_graph_reshaping below.
1876 static void final_graph_reshaping_impl( Node *n, Final_Reshape_Counts &fpu ) {
1877 
1878   if ( n->outcnt() == 0 ) return; // dead node
1879   uint nop = n->Opcode();
1880 
1881   // Check for 2-input instruction with "last use" on right input.
1882   // Swap to left input.  Implements item (2).
1883   if( n->req() == 3 &&          // two-input instruction
1884       n->in(1)->outcnt() > 1 && // left use is NOT a last use
1885       (!n->in(1)->is_Phi() || n->in(1)->in(2) != n) && // it is not data loop
1886       n->in(2)->outcnt() == 1 &&// right use IS a last use
1887       !n->in(2)->is_Con() ) {   // right use is not a constant
1888     // Check for commutative opcode
1889     switch( nop ) {
1890     case Op_AddI:  case Op_AddF:  case Op_AddD:  case Op_AddL:
1891     case Op_MaxI:  case Op_MinI:
1892     case Op_MulI:  case Op_MulF:  case Op_MulD:  case Op_MulL:
1893     case Op_AndL:  case Op_XorL:  case Op_OrL:
1894     case Op_AndI:  case Op_XorI:  case Op_OrI: {
1895       // Move "last use" input to left by swapping inputs
1896       n->swap_edges(1, 2);
1897       break;
1898     }
1899     default:
1900       break;
1901     }
1902   }
1903 
1904   // Count FPU ops and common calls, implements item (3)
1905   switch( nop ) {
1906   // Count all float operations that may use FPU
1907   case Op_AddF:
1908   case Op_SubF:
1909   case Op_MulF:
1910   case Op_DivF:
1911   case Op_NegF:
1912   case Op_ModF:
1913   case Op_ConvI2F:
1914   case Op_ConF:
1915   case Op_CmpF:
1916   case Op_CmpF3:
1917   // case Op_ConvL2F: // longs are split into 32-bit halves
1918     fpu.inc_float_count();
1919     break;
1920 
1921   case Op_ConvF2D:
1922   case Op_ConvD2F:
1923     fpu.inc_float_count();
1924     fpu.inc_double_count();
1925     break;
1926 
1927   // Count all double operations that may use FPU
1928   case Op_AddD:
1929   case Op_SubD:
1930   case Op_MulD:
1931   case Op_DivD:
1932   case Op_NegD:
1933   case Op_ModD:
1934   case Op_ConvI2D:
1935   case Op_ConvD2I:
1936   // case Op_ConvL2D: // handled by leaf call
1937   // case Op_ConvD2L: // handled by leaf call
1938   case Op_ConD:
1939   case Op_CmpD:
1940   case Op_CmpD3:
1941     fpu.inc_double_count();
1942     break;
1943   case Op_Opaque1:              // Remove Opaque Nodes before matching
1944   case Op_Opaque2:              // Remove Opaque Nodes before matching
1945     n->subsume_by(n->in(1));
1946     break;
1947   case Op_CallStaticJava:
1948   case Op_CallJava:
1949   case Op_CallDynamicJava:
1950     fpu.inc_java_call_count(); // Count java call site;
1951   case Op_CallRuntime:
1952   case Op_CallLeaf:
1953   case Op_CallLeafNoFP: {
1954     assert( n->is_Call(), "" );
1955     CallNode *call = n->as_Call();
1956     // Count call sites where the FP mode bit would have to be flipped.
1957     // Do not count uncommon runtime calls:
1958     // uncommon_trap, _complete_monitor_locking, _complete_monitor_unlocking,
1959     // _new_Java, _new_typeArray, _new_objArray, _rethrow_Java, ...
1960     if( !call->is_CallStaticJava() || !call->as_CallStaticJava()->_name ) {
1961       fpu.inc_call_count();   // Count the call site
1962     } else {                  // See if uncommon argument is shared
1963       Node *n = call->in(TypeFunc::Parms);
1964       int nop = n->Opcode();
1965       // Clone shared simple arguments to uncommon calls, item (1).
1966       if( n->outcnt() > 1 &&
1967           !n->is_Proj() &&
1968           nop != Op_CreateEx &&
1969           nop != Op_CheckCastPP &&
1970           !n->is_Mem() ) {
1971         Node *x = n->clone();
1972         call->set_req( TypeFunc::Parms, x );
1973       }
1974     }
1975     break;
1976   }
1977 
1978   case Op_StoreD:
1979   case Op_LoadD:
1980   case Op_LoadD_unaligned:
1981     fpu.inc_double_count();
1982     goto handle_mem;
1983   case Op_StoreF:
1984   case Op_LoadF:
1985     fpu.inc_float_count();
1986     goto handle_mem;
1987 
1988   case Op_StoreB:
1989   case Op_StoreC:
1990   case Op_StoreCM:
1991   case Op_StorePConditional:
1992   case Op_StoreI:
1993   case Op_StoreL:
1994   case Op_StoreLConditional:
1995   case Op_CompareAndSwapI:
1996   case Op_CompareAndSwapL:
1997   case Op_CompareAndSwapP:
1998   case Op_CompareAndSwapN:
1999   case Op_StoreP:
2000   case Op_StoreN:
2001   case Op_LoadB:
2002   case Op_LoadC:
2003   case Op_LoadI:
2004   case Op_LoadKlass:
2005   case Op_LoadNKlass:
2006   case Op_LoadL:
2007   case Op_LoadL_unaligned:
2008   case Op_LoadPLocked:
2009   case Op_LoadLLocked:
2010   case Op_LoadP:
2011   case Op_LoadN:
2012   case Op_LoadRange:
2013   case Op_LoadS: {
2014   handle_mem:
2015 #ifdef ASSERT
2016     if( VerifyOptoOopOffsets ) {
2017       assert( n->is_Mem(), "" );
2018       MemNode *mem  = (MemNode*)n;
2019       // Check to see if address types have grounded out somehow.
2020       const TypeInstPtr *tp = mem->in(MemNode::Address)->bottom_type()->isa_instptr();
2021       assert( !tp || oop_offset_is_sane(tp), "" );
2022     }
2023 #endif
2024     break;
2025   }
2026 
2027   case Op_AddP: {               // Assert sane base pointers
2028     Node *addp = n->in(AddPNode::Address);
2029     assert( !addp->is_AddP() ||
2030             addp->in(AddPNode::Base)->is_top() || // Top OK for allocation
2031             addp->in(AddPNode::Base) == n->in(AddPNode::Base),
2032             "Base pointers must match" );
2033 #ifdef _LP64
2034     if (UseCompressedOops &&
2035         addp->Opcode() == Op_ConP &&
2036         addp == n->in(AddPNode::Base) &&
2037         n->in(AddPNode::Offset)->is_Con()) {
2038       // Use addressing with narrow klass to load with offset on x86.
2039       // On sparc loading 32-bits constant and decoding it have less
2040       // instructions (4) then load 64-bits constant (7).
2041       // Do this transformation here since IGVN will convert ConN back to ConP.
2042       const Type* t = addp->bottom_type();
2043       if (t->isa_oopptr()) {
2044         Node* nn = NULL;
2045 
2046         // Look for existing ConN node of the same exact type.
2047         Compile* C = Compile::current();
2048         Node* r  = C->root();
2049         uint cnt = r->outcnt();
2050         for (uint i = 0; i < cnt; i++) {
2051           Node* m = r->raw_out(i);
2052           if (m!= NULL && m->Opcode() == Op_ConN &&
2053               m->bottom_type()->make_ptr() == t) {
2054             nn = m;
2055             break;
2056           }
2057         }
2058         if (nn != NULL) {
2059           // Decode a narrow oop to match address
2060           // [R12 + narrow_oop_reg<<3 + offset]
2061           nn = new (C,  2) DecodeNNode(nn, t);
2062           n->set_req(AddPNode::Base, nn);
2063           n->set_req(AddPNode::Address, nn);
2064           if (addp->outcnt() == 0) {
2065             addp->disconnect_inputs(NULL);
2066           }
2067         }
2068       }
2069     }
2070 #endif
2071     break;
2072   }
2073 
2074 #ifdef _LP64
2075   case Op_CmpP:
2076     // Do this transformation here to preserve CmpPNode::sub() and
2077     // other TypePtr related Ideal optimizations (for example, ptr nullness).
2078     if( n->in(1)->is_DecodeN() ) {
2079       Compile* C = Compile::current();
2080       Node* in2 = NULL;
2081       if( n->in(2)->is_DecodeN() ) {
2082         in2 = n->in(2)->in(1);
2083       } else if ( n->in(2)->Opcode() == Op_ConP ) {
2084         const Type* t = n->in(2)->bottom_type();
2085         if (t == TypePtr::NULL_PTR) {
2086           Node *in1 = n->in(1);
2087           if (Matcher::clone_shift_expressions) {
2088             // x86, ARM and friends can handle 2 adds in addressing mode.
2089             // Decode a narrow oop and do implicit NULL check in address
2090             // [R12 + narrow_oop_reg<<3 + offset]
2091             in2 = ConNode::make(C, TypeNarrowOop::NULL_PTR);
2092           } else {
2093             // Don't replace CmpP(o ,null) if 'o' is used in AddP
2094             // to generate implicit NULL check on Sparc where
2095             // narrow oops can't be used in address.
2096             uint i = 0;
2097             for (; i < in1->outcnt(); i++) {
2098               if (in1->raw_out(i)->is_AddP())
2099                 break;
2100             }
2101             if (i >= in1->outcnt()) {
2102               in2 = ConNode::make(C, TypeNarrowOop::NULL_PTR);
2103             }
2104           }
2105         } else if (t->isa_oopptr()) {
2106           in2 = ConNode::make(C, t->make_narrowoop());
2107         }
2108       }
2109       if( in2 != NULL ) {
2110         Node* cmpN = new (C, 3) CmpNNode(n->in(1)->in(1), in2);
2111         n->subsume_by( cmpN );
2112       }
2113     }
2114     break;
2115 #endif
2116 
2117   case Op_ModI:
2118     if (UseDivMod) {
2119       // Check if a%b and a/b both exist
2120       Node* d = n->find_similar(Op_DivI);
2121       if (d) {
2122         // Replace them with a fused divmod if supported
2123         Compile* C = Compile::current();
2124         if (Matcher::has_match_rule(Op_DivModI)) {
2125           DivModINode* divmod = DivModINode::make(C, n);
2126           d->subsume_by(divmod->div_proj());
2127           n->subsume_by(divmod->mod_proj());
2128         } else {
2129           // replace a%b with a-((a/b)*b)
2130           Node* mult = new (C, 3) MulINode(d, d->in(2));
2131           Node* sub  = new (C, 3) SubINode(d->in(1), mult);
2132           n->subsume_by( sub );
2133         }
2134       }
2135     }
2136     break;
2137 
2138   case Op_ModL:
2139     if (UseDivMod) {
2140       // Check if a%b and a/b both exist
2141       Node* d = n->find_similar(Op_DivL);
2142       if (d) {
2143         // Replace them with a fused divmod if supported
2144         Compile* C = Compile::current();
2145         if (Matcher::has_match_rule(Op_DivModL)) {
2146           DivModLNode* divmod = DivModLNode::make(C, n);
2147           d->subsume_by(divmod->div_proj());
2148           n->subsume_by(divmod->mod_proj());
2149         } else {
2150           // replace a%b with a-((a/b)*b)
2151           Node* mult = new (C, 3) MulLNode(d, d->in(2));
2152           Node* sub  = new (C, 3) SubLNode(d->in(1), mult);
2153           n->subsume_by( sub );
2154         }
2155       }
2156     }
2157     break;
2158 
2159   case Op_Load16B:
2160   case Op_Load8B:
2161   case Op_Load4B:
2162   case Op_Load8S:
2163   case Op_Load4S:
2164   case Op_Load2S:
2165   case Op_Load8C:
2166   case Op_Load4C:
2167   case Op_Load2C:
2168   case Op_Load4I:
2169   case Op_Load2I:
2170   case Op_Load2L:
2171   case Op_Load4F:
2172   case Op_Load2F:
2173   case Op_Load2D:
2174   case Op_Store16B:
2175   case Op_Store8B:
2176   case Op_Store4B:
2177   case Op_Store8C:
2178   case Op_Store4C:
2179   case Op_Store2C:
2180   case Op_Store4I:
2181   case Op_Store2I:
2182   case Op_Store2L:
2183   case Op_Store4F:
2184   case Op_Store2F:
2185   case Op_Store2D:
2186     break;
2187 
2188   case Op_PackB:
2189   case Op_PackS:
2190   case Op_PackC:
2191   case Op_PackI:
2192   case Op_PackF:
2193   case Op_PackL:
2194   case Op_PackD:
2195     if (n->req()-1 > 2) {
2196       // Replace many operand PackNodes with a binary tree for matching
2197       PackNode* p = (PackNode*) n;
2198       Node* btp = p->binaryTreePack(Compile::current(), 1, n->req());
2199       n->subsume_by(btp);
2200     }
2201     break;
2202   default:
2203     assert( !n->is_Call(), "" );
2204     assert( !n->is_Mem(), "" );
2205     break;
2206   }
2207 
2208   // Collect CFG split points
2209   if (n->is_MultiBranch())
2210     fpu._tests.push(n);
2211 }
2212 
2213 //------------------------------final_graph_reshaping_walk---------------------
2214 // Replacing Opaque nodes with their input in final_graph_reshaping_impl(),
2215 // requires that the walk visits a node's inputs before visiting the node.
2216 static void final_graph_reshaping_walk( Node_Stack &nstack, Node *root, Final_Reshape_Counts &fpu ) {
2217   fpu._visited.set(root->_idx); // first, mark node as visited
2218   uint cnt = root->req();
2219   Node *n = root;
2220   uint  i = 0;
2221   while (true) {
2222     if (i < cnt) {
2223       // Place all non-visited non-null inputs onto stack
2224       Node* m = n->in(i);
2225       ++i;
2226       if (m != NULL && !fpu._visited.test_set(m->_idx)) {
2227         cnt = m->req();
2228         nstack.push(n, i); // put on stack parent and next input's index
2229         n = m;
2230         i = 0;
2231       }
2232     } else {
2233       // Now do post-visit work
2234       final_graph_reshaping_impl( n, fpu );
2235       if (nstack.is_empty())
2236         break;             // finished
2237       n = nstack.node();   // Get node from stack
2238       cnt = n->req();
2239       i = nstack.index();
2240       nstack.pop();        // Shift to the next node on stack
2241     }
2242   }
2243 }
2244 
2245 //------------------------------final_graph_reshaping--------------------------
2246 // Final Graph Reshaping.
2247 //
2248 // (1) Clone simple inputs to uncommon calls, so they can be scheduled late
2249 //     and not commoned up and forced early.  Must come after regular
2250 //     optimizations to avoid GVN undoing the cloning.  Clone constant
2251 //     inputs to Loop Phis; these will be split by the allocator anyways.
2252 //     Remove Opaque nodes.
2253 // (2) Move last-uses by commutative operations to the left input to encourage
2254 //     Intel update-in-place two-address operations and better register usage
2255 //     on RISCs.  Must come after regular optimizations to avoid GVN Ideal
2256 //     calls canonicalizing them back.
2257 // (3) Count the number of double-precision FP ops, single-precision FP ops
2258 //     and call sites.  On Intel, we can get correct rounding either by
2259 //     forcing singles to memory (requires extra stores and loads after each
2260 //     FP bytecode) or we can set a rounding mode bit (requires setting and
2261 //     clearing the mode bit around call sites).  The mode bit is only used
2262 //     if the relative frequency of single FP ops to calls is low enough.
2263 //     This is a key transform for SPEC mpeg_audio.
2264 // (4) Detect infinite loops; blobs of code reachable from above but not
2265 //     below.  Several of the Code_Gen algorithms fail on such code shapes,
2266 //     so we simply bail out.  Happens a lot in ZKM.jar, but also happens
2267 //     from time to time in other codes (such as -Xcomp finalizer loops, etc).
2268 //     Detection is by looking for IfNodes where only 1 projection is
2269 //     reachable from below or CatchNodes missing some targets.
2270 // (5) Assert for insane oop offsets in debug mode.
2271 
2272 bool Compile::final_graph_reshaping() {
2273   // an infinite loop may have been eliminated by the optimizer,
2274   // in which case the graph will be empty.
2275   if (root()->req() == 1) {
2276     record_method_not_compilable("trivial infinite loop");
2277     return true;
2278   }
2279 
2280   Final_Reshape_Counts fpu;
2281 
2282   // Visit everybody reachable!
2283   // Allocate stack of size C->unique()/2 to avoid frequent realloc
2284   Node_Stack nstack(unique() >> 1);
2285   final_graph_reshaping_walk(nstack, root(), fpu);
2286 
2287   // Check for unreachable (from below) code (i.e., infinite loops).
2288   for( uint i = 0; i < fpu._tests.size(); i++ ) {
2289     MultiBranchNode *n = fpu._tests[i]->as_MultiBranch();
2290     // Get number of CFG targets.
2291     // Note that PCTables include exception targets after calls.
2292     uint required_outcnt = n->required_outcnt();
2293     if (n->outcnt() != required_outcnt) {
2294       // Check for a few special cases.  Rethrow Nodes never take the
2295       // 'fall-thru' path, so expected kids is 1 less.
2296       if (n->is_PCTable() && n->in(0) && n->in(0)->in(0)) {
2297         if (n->in(0)->in(0)->is_Call()) {
2298           CallNode *call = n->in(0)->in(0)->as_Call();
2299           if (call->entry_point() == OptoRuntime::rethrow_stub()) {
2300             required_outcnt--;      // Rethrow always has 1 less kid
2301           } else if (call->req() > TypeFunc::Parms &&
2302                      call->is_CallDynamicJava()) {
2303             // Check for null receiver. In such case, the optimizer has
2304             // detected that the virtual call will always result in a null
2305             // pointer exception. The fall-through projection of this CatchNode
2306             // will not be populated.
2307             Node *arg0 = call->in(TypeFunc::Parms);
2308             if (arg0->is_Type() &&
2309                 arg0->as_Type()->type()->higher_equal(TypePtr::NULL_PTR)) {
2310               required_outcnt--;
2311             }
2312           } else if (call->entry_point() == OptoRuntime::new_array_Java() &&
2313                      call->req() > TypeFunc::Parms+1 &&
2314                      call->is_CallStaticJava()) {
2315             // Check for negative array length. In such case, the optimizer has
2316             // detected that the allocation attempt will always result in an
2317             // exception. There is no fall-through projection of this CatchNode .
2318             Node *arg1 = call->in(TypeFunc::Parms+1);
2319             if (arg1->is_Type() &&
2320                 arg1->as_Type()->type()->join(TypeInt::POS)->empty()) {
2321               required_outcnt--;
2322             }
2323           }
2324         }
2325       }
2326       // Recheck with a better notion of 'required_outcnt'
2327       if (n->outcnt() != required_outcnt) {
2328         record_method_not_compilable("malformed control flow");
2329         return true;            // Not all targets reachable!
2330       }
2331     }
2332     // Check that I actually visited all kids.  Unreached kids
2333     // must be infinite loops.
2334     for (DUIterator_Fast jmax, j = n->fast_outs(jmax); j < jmax; j++)
2335       if (!fpu._visited.test(n->fast_out(j)->_idx)) {
2336         record_method_not_compilable("infinite loop");
2337         return true;            // Found unvisited kid; must be unreach
2338       }
2339   }
2340 
2341   // If original bytecodes contained a mixture of floats and doubles
2342   // check if the optimizer has made it homogenous, item (3).
2343   if( Use24BitFPMode && Use24BitFP &&
2344       fpu.get_float_count() > 32 &&
2345       fpu.get_double_count() == 0 &&
2346       (10 * fpu.get_call_count() < fpu.get_float_count()) ) {
2347     set_24_bit_selection_and_mode( false,  true );
2348   }
2349 
2350   set_has_java_calls(fpu.get_java_call_count() > 0);
2351 
2352   // No infinite loops, no reason to bail out.
2353   return false;
2354 }
2355 
2356 //-----------------------------too_many_traps----------------------------------
2357 // Report if there are too many traps at the current method and bci.
2358 // Return true if there was a trap, and/or PerMethodTrapLimit is exceeded.
2359 bool Compile::too_many_traps(ciMethod* method,
2360                              int bci,
2361                              Deoptimization::DeoptReason reason) {
2362   ciMethodData* md = method->method_data();
2363   if (md->is_empty()) {
2364     // Assume the trap has not occurred, or that it occurred only
2365     // because of a transient condition during start-up in the interpreter.
2366     return false;
2367   }
2368   if (md->has_trap_at(bci, reason) != 0) {
2369     // Assume PerBytecodeTrapLimit==0, for a more conservative heuristic.
2370     // Also, if there are multiple reasons, or if there is no per-BCI record,
2371     // assume the worst.
2372     if (log())
2373       log()->elem("observe trap='%s' count='%d'",
2374                   Deoptimization::trap_reason_name(reason),
2375                   md->trap_count(reason));
2376     return true;
2377   } else {
2378     // Ignore method/bci and see if there have been too many globally.
2379     return too_many_traps(reason, md);
2380   }
2381 }
2382 
2383 // Less-accurate variant which does not require a method and bci.
2384 bool Compile::too_many_traps(Deoptimization::DeoptReason reason,
2385                              ciMethodData* logmd) {
2386  if (trap_count(reason) >= (uint)PerMethodTrapLimit) {
2387     // Too many traps globally.
2388     // Note that we use cumulative trap_count, not just md->trap_count.
2389     if (log()) {
2390       int mcount = (logmd == NULL)? -1: (int)logmd->trap_count(reason);
2391       log()->elem("observe trap='%s' count='0' mcount='%d' ccount='%d'",
2392                   Deoptimization::trap_reason_name(reason),
2393                   mcount, trap_count(reason));
2394     }
2395     return true;
2396   } else {
2397     // The coast is clear.
2398     return false;
2399   }
2400 }
2401 
2402 //--------------------------too_many_recompiles--------------------------------
2403 // Report if there are too many recompiles at the current method and bci.
2404 // Consults PerBytecodeRecompilationCutoff and PerMethodRecompilationCutoff.
2405 // Is not eager to return true, since this will cause the compiler to use
2406 // Action_none for a trap point, to avoid too many recompilations.
2407 bool Compile::too_many_recompiles(ciMethod* method,
2408                                   int bci,
2409                                   Deoptimization::DeoptReason reason) {
2410   ciMethodData* md = method->method_data();
2411   if (md->is_empty()) {
2412     // Assume the trap has not occurred, or that it occurred only
2413     // because of a transient condition during start-up in the interpreter.
2414     return false;
2415   }
2416   // Pick a cutoff point well within PerBytecodeRecompilationCutoff.
2417   uint bc_cutoff = (uint) PerBytecodeRecompilationCutoff / 8;
2418   uint m_cutoff  = (uint) PerMethodRecompilationCutoff / 2 + 1;  // not zero
2419   Deoptimization::DeoptReason per_bc_reason
2420     = Deoptimization::reason_recorded_per_bytecode_if_any(reason);
2421   if ((per_bc_reason == Deoptimization::Reason_none
2422        || md->has_trap_at(bci, reason) != 0)
2423       // The trap frequency measure we care about is the recompile count:
2424       && md->trap_recompiled_at(bci)
2425       && md->overflow_recompile_count() >= bc_cutoff) {
2426     // Do not emit a trap here if it has already caused recompilations.
2427     // Also, if there are multiple reasons, or if there is no per-BCI record,
2428     // assume the worst.
2429     if (log())
2430       log()->elem("observe trap='%s recompiled' count='%d' recompiles2='%d'",
2431                   Deoptimization::trap_reason_name(reason),
2432                   md->trap_count(reason),
2433                   md->overflow_recompile_count());
2434     return true;
2435   } else if (trap_count(reason) != 0
2436              && decompile_count() >= m_cutoff) {
2437     // Too many recompiles globally, and we have seen this sort of trap.
2438     // Use cumulative decompile_count, not just md->decompile_count.
2439     if (log())
2440       log()->elem("observe trap='%s' count='%d' mcount='%d' decompiles='%d' mdecompiles='%d'",
2441                   Deoptimization::trap_reason_name(reason),
2442                   md->trap_count(reason), trap_count(reason),
2443                   md->decompile_count(), decompile_count());
2444     return true;
2445   } else {
2446     // The coast is clear.
2447     return false;
2448   }
2449 }
2450 
2451 
2452 #ifndef PRODUCT
2453 //------------------------------verify_graph_edges---------------------------
2454 // Walk the Graph and verify that there is a one-to-one correspondence
2455 // between Use-Def edges and Def-Use edges in the graph.
2456 void Compile::verify_graph_edges(bool no_dead_code) {
2457   if (VerifyGraphEdges) {
2458     ResourceArea *area = Thread::current()->resource_area();
2459     Unique_Node_List visited(area);
2460     // Call recursive graph walk to check edges
2461     _root->verify_edges(visited);
2462     if (no_dead_code) {
2463       // Now make sure that no visited node is used by an unvisited node.
2464       bool dead_nodes = 0;
2465       Unique_Node_List checked(area);
2466       while (visited.size() > 0) {
2467         Node* n = visited.pop();
2468         checked.push(n);
2469         for (uint i = 0; i < n->outcnt(); i++) {
2470           Node* use = n->raw_out(i);
2471           if (checked.member(use))  continue;  // already checked
2472           if (visited.member(use))  continue;  // already in the graph
2473           if (use->is_Con())        continue;  // a dead ConNode is OK
2474           // At this point, we have found a dead node which is DU-reachable.
2475           if (dead_nodes++ == 0)
2476             tty->print_cr("*** Dead nodes reachable via DU edges:");
2477           use->dump(2);
2478           tty->print_cr("---");
2479           checked.push(use);  // No repeats; pretend it is now checked.
2480         }
2481       }
2482       assert(dead_nodes == 0, "using nodes must be reachable from root");
2483     }
2484   }
2485 }
2486 #endif
2487 
2488 // The Compile object keeps track of failure reasons separately from the ciEnv.
2489 // This is required because there is not quite a 1-1 relation between the
2490 // ciEnv and its compilation task and the Compile object.  Note that one
2491 // ciEnv might use two Compile objects, if C2Compiler::compile_method decides
2492 // to backtrack and retry without subsuming loads.  Other than this backtracking
2493 // behavior, the Compile's failure reason is quietly copied up to the ciEnv
2494 // by the logic in C2Compiler.
2495 void Compile::record_failure(const char* reason) {
2496   if (log() != NULL) {
2497     log()->elem("failure reason='%s' phase='compile'", reason);
2498   }
2499   if (_failure_reason == NULL) {
2500     // Record the first failure reason.
2501     _failure_reason = reason;
2502   }
2503   if (!C->failure_reason_is(C2Compiler::retry_no_subsuming_loads())) {
2504     C->print_method(_failure_reason);
2505   }
2506   _root = NULL;  // flush the graph, too
2507 }
2508 
2509 Compile::TracePhase::TracePhase(const char* name, elapsedTimer* accumulator, bool dolog)
2510   : TraceTime(NULL, accumulator, false NOT_PRODUCT( || TimeCompiler ), false)
2511 {
2512   if (dolog) {
2513     C = Compile::current();
2514     _log = C->log();
2515   } else {
2516     C = NULL;
2517     _log = NULL;
2518   }
2519   if (_log != NULL) {
2520     _log->begin_head("phase name='%s' nodes='%d'", name, C->unique());
2521     _log->stamp();
2522     _log->end_head();
2523   }
2524 }
2525 
2526 Compile::TracePhase::~TracePhase() {
2527   if (_log != NULL) {
2528     _log->done("phase nodes='%d'", C->unique());
2529   }
2530 }