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