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