1 /*
2  * Copyright (c) 1997, 2020, Oracle and/or its affiliates. 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20  * or visit www.oracle.com if you need additional information or have any
21  * questions.
22  *
23  */
24 
25 #include "precompiled.hpp"
26 #include "asm/macroAssembler.hpp"
27 #include "asm/macroAssembler.inline.hpp"
28 #include "ci/ciReplay.hpp"
29 #include "classfile/systemDictionary.hpp"
30 #include "code/exceptionHandlerTable.hpp"
31 #include "code/nmethod.hpp"
32 #include "compiler/compileBroker.hpp"
33 #include "compiler/compileLog.hpp"
34 #include "compiler/disassembler.hpp"
35 #include "compiler/oopMap.hpp"
36 #include "gc/shared/barrierSet.hpp"
37 #include "gc/shared/c2/barrierSetC2.hpp"
38 #include "jfr/jfrEvents.hpp"
39 #include "memory/resourceArea.hpp"
40 #include "opto/addnode.hpp"
41 #include "opto/block.hpp"
42 #include "opto/c2compiler.hpp"
43 #include "opto/callGenerator.hpp"
44 #include "opto/callnode.hpp"
45 #include "opto/castnode.hpp"
46 #include "opto/cfgnode.hpp"
47 #include "opto/chaitin.hpp"
48 #include "opto/compile.hpp"
49 #include "opto/connode.hpp"
50 #include "opto/convertnode.hpp"
51 #include "opto/divnode.hpp"
52 #include "opto/escape.hpp"
53 #include "opto/idealGraphPrinter.hpp"
54 #include "opto/loopnode.hpp"
55 #include "opto/machnode.hpp"
56 #include "opto/macro.hpp"
57 #include "opto/matcher.hpp"
58 #include "opto/mathexactnode.hpp"
59 #include "opto/memnode.hpp"
60 #include "opto/mulnode.hpp"
61 #include "opto/narrowptrnode.hpp"
62 #include "opto/node.hpp"
63 #include "opto/opcodes.hpp"
64 #include "opto/output.hpp"
65 #include "opto/parse.hpp"
66 #include "opto/phaseX.hpp"
67 #include "opto/rootnode.hpp"
68 #include "opto/runtime.hpp"
69 #include "opto/stringopts.hpp"
70 #include "opto/type.hpp"
71 #include "opto/vectornode.hpp"
72 #include "runtime/arguments.hpp"
73 #include "runtime/sharedRuntime.hpp"
74 #include "runtime/signature.hpp"
75 #include "runtime/stubRoutines.hpp"
76 #include "runtime/timer.hpp"
77 #include "utilities/align.hpp"
78 #include "utilities/copy.hpp"
79 #include "utilities/macros.hpp"
80 #include "utilities/resourceHash.hpp"
81 
82 
83 // -------------------- Compile::mach_constant_base_node -----------------------
84 // Constant table base node singleton.
mach_constant_base_node()85 MachConstantBaseNode* Compile::mach_constant_base_node() {
86   if (_mach_constant_base_node == NULL) {
87     _mach_constant_base_node = new MachConstantBaseNode();
88     _mach_constant_base_node->add_req(C->root());
89   }
90   return _mach_constant_base_node;
91 }
92 
93 
94 /// Support for intrinsics.
95 
96 // Return the index at which m must be inserted (or already exists).
97 // The sort order is by the address of the ciMethod, with is_virtual as minor key.
98 class IntrinsicDescPair {
99  private:
100   ciMethod* _m;
101   bool _is_virtual;
102  public:
IntrinsicDescPair(ciMethod * m,bool is_virtual)103   IntrinsicDescPair(ciMethod* m, bool is_virtual) : _m(m), _is_virtual(is_virtual) {}
compare(IntrinsicDescPair * const & key,CallGenerator * const & elt)104   static int compare(IntrinsicDescPair* const& key, CallGenerator* const& elt) {
105     ciMethod* m= elt->method();
106     ciMethod* key_m = key->_m;
107     if (key_m < m)      return -1;
108     else if (key_m > m) return 1;
109     else {
110       bool is_virtual = elt->is_virtual();
111       bool key_virtual = key->_is_virtual;
112       if (key_virtual < is_virtual)      return -1;
113       else if (key_virtual > is_virtual) return 1;
114       else                               return 0;
115     }
116   }
117 };
intrinsic_insertion_index(ciMethod * m,bool is_virtual,bool & found)118 int Compile::intrinsic_insertion_index(ciMethod* m, bool is_virtual, bool& found) {
119 #ifdef ASSERT
120   for (int i = 1; i < _intrinsics->length(); i++) {
121     CallGenerator* cg1 = _intrinsics->at(i-1);
122     CallGenerator* cg2 = _intrinsics->at(i);
123     assert(cg1->method() != cg2->method()
124            ? cg1->method()     < cg2->method()
125            : cg1->is_virtual() < cg2->is_virtual(),
126            "compiler intrinsics list must stay sorted");
127   }
128 #endif
129   IntrinsicDescPair pair(m, is_virtual);
130   return _intrinsics->find_sorted<IntrinsicDescPair*, IntrinsicDescPair::compare>(&pair, found);
131 }
132 
register_intrinsic(CallGenerator * cg)133 void Compile::register_intrinsic(CallGenerator* cg) {
134   if (_intrinsics == NULL) {
135     _intrinsics = new (comp_arena())GrowableArray<CallGenerator*>(comp_arena(), 60, 0, NULL);
136   }
137   int len = _intrinsics->length();
138   bool found = false;
139   int index = intrinsic_insertion_index(cg->method(), cg->is_virtual(), found);
140   assert(!found, "registering twice");
141   _intrinsics->insert_before(index, cg);
142   assert(find_intrinsic(cg->method(), cg->is_virtual()) == cg, "registration worked");
143 }
144 
find_intrinsic(ciMethod * m,bool is_virtual)145 CallGenerator* Compile::find_intrinsic(ciMethod* m, bool is_virtual) {
146   assert(m->is_loaded(), "don't try this on unloaded methods");
147   if (_intrinsics != NULL) {
148     bool found = false;
149     int index = intrinsic_insertion_index(m, is_virtual, found);
150      if (found) {
151       return _intrinsics->at(index);
152     }
153   }
154   // Lazily create intrinsics for intrinsic IDs well-known in the runtime.
155   if (m->intrinsic_id() != vmIntrinsics::_none &&
156       m->intrinsic_id() <= vmIntrinsics::LAST_COMPILER_INLINE) {
157     CallGenerator* cg = make_vm_intrinsic(m, is_virtual);
158     if (cg != NULL) {
159       // Save it for next time:
160       register_intrinsic(cg);
161       return cg;
162     } else {
163       gather_intrinsic_statistics(m->intrinsic_id(), is_virtual, _intrinsic_disabled);
164     }
165   }
166   return NULL;
167 }
168 
169 // Compile:: register_library_intrinsics and make_vm_intrinsic are defined
170 // in library_call.cpp.
171 
172 
173 #ifndef PRODUCT
174 // statistics gathering...
175 
176 juint  Compile::_intrinsic_hist_count[vmIntrinsics::ID_LIMIT] = {0};
177 jubyte Compile::_intrinsic_hist_flags[vmIntrinsics::ID_LIMIT] = {0};
178 
gather_intrinsic_statistics(vmIntrinsics::ID id,bool is_virtual,int flags)179 bool Compile::gather_intrinsic_statistics(vmIntrinsics::ID id, bool is_virtual, int flags) {
180   assert(id > vmIntrinsics::_none && id < vmIntrinsics::ID_LIMIT, "oob");
181   int oflags = _intrinsic_hist_flags[id];
182   assert(flags != 0, "what happened?");
183   if (is_virtual) {
184     flags |= _intrinsic_virtual;
185   }
186   bool changed = (flags != oflags);
187   if ((flags & _intrinsic_worked) != 0) {
188     juint count = (_intrinsic_hist_count[id] += 1);
189     if (count == 1) {
190       changed = true;           // first time
191     }
192     // increment the overall count also:
193     _intrinsic_hist_count[vmIntrinsics::_none] += 1;
194   }
195   if (changed) {
196     if (((oflags ^ flags) & _intrinsic_virtual) != 0) {
197       // Something changed about the intrinsic's virtuality.
198       if ((flags & _intrinsic_virtual) != 0) {
199         // This is the first use of this intrinsic as a virtual call.
200         if (oflags != 0) {
201           // We already saw it as a non-virtual, so note both cases.
202           flags |= _intrinsic_both;
203         }
204       } else if ((oflags & _intrinsic_both) == 0) {
205         // This is the first use of this intrinsic as a non-virtual
206         flags |= _intrinsic_both;
207       }
208     }
209     _intrinsic_hist_flags[id] = (jubyte) (oflags | flags);
210   }
211   // update the overall flags also:
212   _intrinsic_hist_flags[vmIntrinsics::_none] |= (jubyte) flags;
213   return changed;
214 }
215 
format_flags(int flags,char * buf)216 static char* format_flags(int flags, char* buf) {
217   buf[0] = 0;
218   if ((flags & Compile::_intrinsic_worked) != 0)    strcat(buf, ",worked");
219   if ((flags & Compile::_intrinsic_failed) != 0)    strcat(buf, ",failed");
220   if ((flags & Compile::_intrinsic_disabled) != 0)  strcat(buf, ",disabled");
221   if ((flags & Compile::_intrinsic_virtual) != 0)   strcat(buf, ",virtual");
222   if ((flags & Compile::_intrinsic_both) != 0)      strcat(buf, ",nonvirtual");
223   if (buf[0] == 0)  strcat(buf, ",");
224   assert(buf[0] == ',', "must be");
225   return &buf[1];
226 }
227 
print_intrinsic_statistics()228 void Compile::print_intrinsic_statistics() {
229   char flagsbuf[100];
230   ttyLocker ttyl;
231   if (xtty != NULL)  xtty->head("statistics type='intrinsic'");
232   tty->print_cr("Compiler intrinsic usage:");
233   juint total = _intrinsic_hist_count[vmIntrinsics::_none];
234   if (total == 0)  total = 1;  // avoid div0 in case of no successes
235   #define PRINT_STAT_LINE(name, c, f) \
236     tty->print_cr("  %4d (%4.1f%%) %s (%s)", (int)(c), ((c) * 100.0) / total, name, f);
237   for (int index = 1 + (int)vmIntrinsics::_none; index < (int)vmIntrinsics::ID_LIMIT; index++) {
238     vmIntrinsics::ID id = (vmIntrinsics::ID) index;
239     int   flags = _intrinsic_hist_flags[id];
240     juint count = _intrinsic_hist_count[id];
241     if ((flags | count) != 0) {
242       PRINT_STAT_LINE(vmIntrinsics::name_at(id), count, format_flags(flags, flagsbuf));
243     }
244   }
245   PRINT_STAT_LINE("total", total, format_flags(_intrinsic_hist_flags[vmIntrinsics::_none], flagsbuf));
246   if (xtty != NULL)  xtty->tail("statistics");
247 }
248 
print_statistics()249 void Compile::print_statistics() {
250   { ttyLocker ttyl;
251     if (xtty != NULL)  xtty->head("statistics type='opto'");
252     Parse::print_statistics();
253     PhaseCCP::print_statistics();
254     PhaseRegAlloc::print_statistics();
255     PhaseOutput::print_statistics();
256     PhasePeephole::print_statistics();
257     PhaseIdealLoop::print_statistics();
258     if (xtty != NULL)  xtty->tail("statistics");
259   }
260   if (_intrinsic_hist_flags[vmIntrinsics::_none] != 0) {
261     // put this under its own <statistics> element.
262     print_intrinsic_statistics();
263   }
264 }
265 #endif //PRODUCT
266 
gvn_replace_by(Node * n,Node * nn)267 void Compile::gvn_replace_by(Node* n, Node* nn) {
268   for (DUIterator_Last imin, i = n->last_outs(imin); i >= imin; ) {
269     Node* use = n->last_out(i);
270     bool is_in_table = initial_gvn()->hash_delete(use);
271     uint uses_found = 0;
272     for (uint j = 0; j < use->len(); j++) {
273       if (use->in(j) == n) {
274         if (j < use->req())
275           use->set_req(j, nn);
276         else
277           use->set_prec(j, nn);
278         uses_found++;
279       }
280     }
281     if (is_in_table) {
282       // reinsert into table
283       initial_gvn()->hash_find_insert(use);
284     }
285     record_for_igvn(use);
286     i -= uses_found;    // we deleted 1 or more copies of this edge
287   }
288 }
289 
290 
not_a_node(const Node * n)291 static inline bool not_a_node(const Node* n) {
292   if (n == NULL)                   return true;
293   if (((intptr_t)n & 1) != 0)      return true;  // uninitialized, etc.
294   if (*(address*)n == badAddress)  return true;  // kill by Node::destruct
295   return false;
296 }
297 
298 // Identify all nodes that are reachable from below, useful.
299 // Use breadth-first pass that records state in a Unique_Node_List,
300 // recursive traversal is slower.
identify_useful_nodes(Unique_Node_List & useful)301 void Compile::identify_useful_nodes(Unique_Node_List &useful) {
302   int estimated_worklist_size = live_nodes();
303   useful.map( estimated_worklist_size, NULL );  // preallocate space
304 
305   // Initialize worklist
306   if (root() != NULL)     { useful.push(root()); }
307   // If 'top' is cached, declare it useful to preserve cached node
308   if( cached_top_node() ) { useful.push(cached_top_node()); }
309 
310   // Push all useful nodes onto the list, breadthfirst
311   for( uint next = 0; next < useful.size(); ++next ) {
312     assert( next < unique(), "Unique useful nodes < total nodes");
313     Node *n  = useful.at(next);
314     uint max = n->len();
315     for( uint i = 0; i < max; ++i ) {
316       Node *m = n->in(i);
317       if (not_a_node(m))  continue;
318       useful.push(m);
319     }
320   }
321 }
322 
323 // Update dead_node_list with any missing dead nodes using useful
324 // list. Consider all non-useful nodes to be useless i.e., dead nodes.
update_dead_node_list(Unique_Node_List & useful)325 void Compile::update_dead_node_list(Unique_Node_List &useful) {
326   uint max_idx = unique();
327   VectorSet& useful_node_set = useful.member_set();
328 
329   for (uint node_idx = 0; node_idx < max_idx; node_idx++) {
330     // If node with index node_idx is not in useful set,
331     // mark it as dead in dead node list.
332     if (!useful_node_set.test(node_idx)) {
333       record_dead_node(node_idx);
334     }
335   }
336 }
337 
remove_useless_late_inlines(GrowableArray<CallGenerator * > * inlines,Unique_Node_List & useful)338 void Compile::remove_useless_late_inlines(GrowableArray<CallGenerator*>* inlines, Unique_Node_List &useful) {
339   int shift = 0;
340   for (int i = 0; i < inlines->length(); i++) {
341     CallGenerator* cg = inlines->at(i);
342     CallNode* call = cg->call_node();
343     if (shift > 0) {
344       inlines->at_put(i-shift, cg);
345     }
346     if (!useful.member(call)) {
347       shift++;
348     }
349   }
350   inlines->trunc_to(inlines->length()-shift);
351 }
352 
353 // Disconnect all useless nodes by disconnecting those at the boundary.
remove_useless_nodes(Unique_Node_List & useful)354 void Compile::remove_useless_nodes(Unique_Node_List &useful) {
355   uint next = 0;
356   while (next < useful.size()) {
357     Node *n = useful.at(next++);
358     if (n->is_SafePoint()) {
359       // We're done with a parsing phase. Replaced nodes are not valid
360       // beyond that point.
361       n->as_SafePoint()->delete_replaced_nodes();
362     }
363     // Use raw traversal of out edges since this code removes out edges
364     int max = n->outcnt();
365     for (int j = 0; j < max; ++j) {
366       Node* child = n->raw_out(j);
367       if (! useful.member(child)) {
368         assert(!child->is_top() || child != top(),
369                "If top is cached in Compile object it is in useful list");
370         // Only need to remove this out-edge to the useless node
371         n->raw_del_out(j);
372         --j;
373         --max;
374       }
375     }
376     if (n->outcnt() == 1 && n->has_special_unique_user()) {
377       record_for_igvn(n->unique_out());
378     }
379   }
380   // Remove useless macro and predicate opaq nodes
381   for (int i = C->macro_count()-1; i >= 0; i--) {
382     Node* n = C->macro_node(i);
383     if (!useful.member(n)) {
384       remove_macro_node(n);
385     }
386   }
387   // Remove useless CastII nodes with range check dependency
388   for (int i = range_check_cast_count() - 1; i >= 0; i--) {
389     Node* cast = range_check_cast_node(i);
390     if (!useful.member(cast)) {
391       remove_range_check_cast(cast);
392     }
393   }
394   // Remove useless expensive nodes
395   for (int i = C->expensive_count()-1; i >= 0; i--) {
396     Node* n = C->expensive_node(i);
397     if (!useful.member(n)) {
398       remove_expensive_node(n);
399     }
400   }
401   // Remove useless Opaque4 nodes
402   for (int i = opaque4_count() - 1; i >= 0; i--) {
403     Node* opaq = opaque4_node(i);
404     if (!useful.member(opaq)) {
405       remove_opaque4_node(opaq);
406     }
407   }
408   BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
409   bs->eliminate_useless_gc_barriers(useful, this);
410   // clean up the late inline lists
411   remove_useless_late_inlines(&_string_late_inlines, useful);
412   remove_useless_late_inlines(&_boxing_late_inlines, useful);
413   remove_useless_late_inlines(&_late_inlines, useful);
414   debug_only(verify_graph_edges(true/*check for no_dead_code*/);)
415 }
416 
417 // ============================================================================
418 //------------------------------CompileWrapper---------------------------------
419 class CompileWrapper : public StackObj {
420   Compile *const _compile;
421  public:
422   CompileWrapper(Compile* compile);
423 
424   ~CompileWrapper();
425 };
426 
CompileWrapper(Compile * compile)427 CompileWrapper::CompileWrapper(Compile* compile) : _compile(compile) {
428   // the Compile* pointer is stored in the current ciEnv:
429   ciEnv* env = compile->env();
430   assert(env == ciEnv::current(), "must already be a ciEnv active");
431   assert(env->compiler_data() == NULL, "compile already active?");
432   env->set_compiler_data(compile);
433   assert(compile == Compile::current(), "sanity");
434 
435   compile->set_type_dict(NULL);
436   compile->set_clone_map(new Dict(cmpkey, hashkey, _compile->comp_arena()));
437   compile->clone_map().set_clone_idx(0);
438   compile->set_type_last_size(0);
439   compile->set_last_tf(NULL, NULL);
440   compile->set_indexSet_arena(NULL);
441   compile->set_indexSet_free_block_list(NULL);
442   compile->init_type_arena();
443   Type::Initialize(compile);
444   _compile->begin_method();
445   _compile->clone_map().set_debug(_compile->has_method() && _compile->directive()->CloneMapDebugOption);
446 }
~CompileWrapper()447 CompileWrapper::~CompileWrapper() {
448   _compile->end_method();
449   _compile->env()->set_compiler_data(NULL);
450 }
451 
452 
453 //----------------------------print_compile_messages---------------------------
print_compile_messages()454 void Compile::print_compile_messages() {
455 #ifndef PRODUCT
456   // Check if recompiling
457   if (_subsume_loads == false && PrintOpto) {
458     // Recompiling without allowing machine instructions to subsume loads
459     tty->print_cr("*********************************************************");
460     tty->print_cr("** Bailout: Recompile without subsuming loads          **");
461     tty->print_cr("*********************************************************");
462   }
463   if (_do_escape_analysis != DoEscapeAnalysis && PrintOpto) {
464     // Recompiling without escape analysis
465     tty->print_cr("*********************************************************");
466     tty->print_cr("** Bailout: Recompile without escape analysis          **");
467     tty->print_cr("*********************************************************");
468   }
469   if (_eliminate_boxing != EliminateAutoBox && PrintOpto) {
470     // Recompiling without boxing elimination
471     tty->print_cr("*********************************************************");
472     tty->print_cr("** Bailout: Recompile without boxing elimination       **");
473     tty->print_cr("*********************************************************");
474   }
475   if (C->directive()->BreakAtCompileOption) {
476     // Open the debugger when compiling this method.
477     tty->print("### Breaking when compiling: ");
478     method()->print_short_name();
479     tty->cr();
480     BREAKPOINT;
481   }
482 
483   if( PrintOpto ) {
484     if (is_osr_compilation()) {
485       tty->print("[OSR]%3d", _compile_id);
486     } else {
487       tty->print("%3d", _compile_id);
488     }
489   }
490 #endif
491 }
492 
493 // ============================================================================
494 //------------------------------Compile standard-------------------------------
debug_only(int Compile::_debug_idx=100000;)495 debug_only( int Compile::_debug_idx = 100000; )
496 
497 // Compile a method.  entry_bci is -1 for normal compilations and indicates
498 // the continuation bci for on stack replacement.
499 
500 
501 Compile::Compile( ciEnv* ci_env, ciMethod* target, int osr_bci,
502                   bool subsume_loads, bool do_escape_analysis, bool eliminate_boxing, DirectiveSet* directive)
503                 : Phase(Compiler),
504                   _compile_id(ci_env->compile_id()),
505                   _save_argument_registers(false),
506                   _subsume_loads(subsume_loads),
507                   _do_escape_analysis(do_escape_analysis),
508                   _eliminate_boxing(eliminate_boxing),
509                   _method(target),
510                   _entry_bci(osr_bci),
511                   _stub_function(NULL),
512                   _stub_name(NULL),
513                   _stub_entry_point(NULL),
514                   _max_node_limit(MaxNodeLimit),
515                   _inlining_progress(false),
516                   _inlining_incrementally(false),
517                   _do_cleanup(false),
518                   _has_reserved_stack_access(target->has_reserved_stack_access()),
519 #ifndef PRODUCT
520                   _trace_opto_output(directive->TraceOptoOutputOption),
521                   _print_ideal(directive->PrintIdealOption),
522 #endif
523                   _has_method_handle_invokes(false),
524                   _clinit_barrier_on_entry(false),
525                   _comp_arena(mtCompiler),
526                   _barrier_set_state(BarrierSet::barrier_set()->barrier_set_c2()->create_barrier_state(comp_arena())),
527                   _env(ci_env),
528                   _directive(directive),
529                   _log(ci_env->log()),
530                   _failure_reason(NULL),
531                   _congraph(NULL),
532 #ifndef PRODUCT
533                   _printer(IdealGraphPrinter::printer()),
534 #endif
535                   _dead_node_list(comp_arena()),
536                   _dead_node_count(0),
537                   _node_arena(mtCompiler),
538                   _old_arena(mtCompiler),
539                   _mach_constant_base_node(NULL),
540                   _Compile_types(mtCompiler),
541                   _initial_gvn(NULL),
542                   _for_igvn(NULL),
543                   _warm_calls(NULL),
544                   _late_inlines(comp_arena(), 2, 0, NULL),
545                   _string_late_inlines(comp_arena(), 2, 0, NULL),
546                   _boxing_late_inlines(comp_arena(), 2, 0, NULL),
547                   _late_inlines_pos(0),
548                   _number_of_mh_late_inlines(0),
549                   _print_inlining_stream(NULL),
550                   _print_inlining_list(NULL),
551                   _print_inlining_idx(0),
552                   _print_inlining_output(NULL),
553                   _replay_inline_data(NULL),
554                   _java_calls(0),
555                   _inner_loops(0),
556                   _interpreter_frame_size(0)
557 #ifndef PRODUCT
558                   , _in_dump_cnt(0)
559 #endif
560 {
561   C = this;
562 #ifndef PRODUCT
563   if (_printer != NULL) {
564     _printer->set_compile(this);
565   }
566 #endif
567   CompileWrapper cw(this);
568 
569   if (CITimeVerbose) {
570     tty->print(" ");
571     target->holder()->name()->print();
572     tty->print(".");
573     target->print_short_name();
574     tty->print("  ");
575   }
576   TraceTime t1("Total compilation time", &_t_totalCompilation, CITime, CITimeVerbose);
577   TraceTime t2(NULL, &_t_methodCompilation, CITime, false);
578 
579 #if defined(SUPPORT_ASSEMBLY) || defined(SUPPORT_ABSTRACT_ASSEMBLY)
580   bool print_opto_assembly = directive->PrintOptoAssemblyOption;
581   // We can always print a disassembly, either abstract (hex dump) or
582   // with the help of a suitable hsdis library. Thus, we should not
583   // couple print_assembly and print_opto_assembly controls.
584   // But: always print opto and regular assembly on compile command 'print'.
585   bool print_assembly = directive->PrintAssemblyOption;
586   set_print_assembly(print_opto_assembly || print_assembly);
587 #else
588   set_print_assembly(false); // must initialize.
589 #endif
590 
591 #ifndef PRODUCT
592   set_parsed_irreducible_loop(false);
593 
594   if (directive->ReplayInlineOption) {
595     _replay_inline_data = ciReplay::load_inline_data(method(), entry_bci(), ci_env->comp_level());
596   }
597 #endif
598   set_print_inlining(directive->PrintInliningOption || PrintOptoInlining);
599   set_print_intrinsics(directive->PrintIntrinsicsOption);
600   set_has_irreducible_loop(true); // conservative until build_loop_tree() reset it
601 
602   if (ProfileTraps RTM_OPT_ONLY( || UseRTMLocking )) {
603     // Make sure the method being compiled gets its own MDO,
604     // so we can at least track the decompile_count().
605     // Need MDO to record RTM code generation state.
606     method()->ensure_method_data();
607   }
608 
609   Init(::AliasLevel);
610 
611 
612   print_compile_messages();
613 
614   _ilt = InlineTree::build_inline_tree_root();
615 
616   // Even if NO memory addresses are used, MergeMem nodes must have at least 1 slice
617   assert(num_alias_types() >= AliasIdxRaw, "");
618 
619 #define MINIMUM_NODE_HASH  1023
620   // Node list that Iterative GVN will start with
621   Unique_Node_List for_igvn(comp_arena());
622   set_for_igvn(&for_igvn);
623 
624   // GVN that will be run immediately on new nodes
625   uint estimated_size = method()->code_size()*4+64;
626   estimated_size = (estimated_size < MINIMUM_NODE_HASH ? MINIMUM_NODE_HASH : estimated_size);
627   PhaseGVN gvn(node_arena(), estimated_size);
628   set_initial_gvn(&gvn);
629 
630   print_inlining_init();
631   { // Scope for timing the parser
632     TracePhase tp("parse", &timers[_t_parser]);
633 
634     // Put top into the hash table ASAP.
635     initial_gvn()->transform_no_reclaim(top());
636 
637     // Set up tf(), start(), and find a CallGenerator.
638     CallGenerator* cg = NULL;
639     if (is_osr_compilation()) {
640       const TypeTuple *domain = StartOSRNode::osr_domain();
641       const TypeTuple *range = TypeTuple::make_range(method()->signature());
642       init_tf(TypeFunc::make(domain, range));
643       StartNode* s = new StartOSRNode(root(), domain);
644       initial_gvn()->set_type_bottom(s);
645       init_start(s);
646       cg = CallGenerator::for_osr(method(), entry_bci());
647     } else {
648       // Normal case.
649       init_tf(TypeFunc::make(method()));
650       StartNode* s = new StartNode(root(), tf()->domain());
651       initial_gvn()->set_type_bottom(s);
652       init_start(s);
653       if (method()->intrinsic_id() == vmIntrinsics::_Reference_get) {
654         // With java.lang.ref.reference.get() we must go through the
655         // intrinsic - even when get() is the root
656         // method of the compile - so that, if necessary, the value in
657         // the referent field of the reference object gets recorded by
658         // the pre-barrier code.
659         cg = find_intrinsic(method(), false);
660       }
661       if (cg == NULL) {
662         float past_uses = method()->interpreter_invocation_count();
663         float expected_uses = past_uses;
664         cg = CallGenerator::for_inline(method(), expected_uses);
665       }
666     }
667     if (failing())  return;
668     if (cg == NULL) {
669       record_method_not_compilable("cannot parse method");
670       return;
671     }
672     JVMState* jvms = build_start_state(start(), tf());
673     if ((jvms = cg->generate(jvms)) == NULL) {
674       if (!failure_reason_is(C2Compiler::retry_class_loading_during_parsing())) {
675         record_method_not_compilable("method parse failed");
676       }
677       return;
678     }
679     GraphKit kit(jvms);
680 
681     if (!kit.stopped()) {
682       // Accept return values, and transfer control we know not where.
683       // This is done by a special, unique ReturnNode bound to root.
684       return_values(kit.jvms());
685     }
686 
687     if (kit.has_exceptions()) {
688       // Any exceptions that escape from this call must be rethrown
689       // to whatever caller is dynamically above us on the stack.
690       // This is done by a special, unique RethrowNode bound to root.
691       rethrow_exceptions(kit.transfer_exceptions_into_jvms());
692     }
693 
694     assert(IncrementalInline || (_late_inlines.length() == 0 && !has_mh_late_inlines()), "incremental inlining is off");
695 
696     if (_late_inlines.length() == 0 && !has_mh_late_inlines() && !failing() && has_stringbuilder()) {
697       inline_string_calls(true);
698     }
699 
700     if (failing())  return;
701 
702     print_method(PHASE_BEFORE_REMOVEUSELESS, 3);
703 
704     // Remove clutter produced by parsing.
705     if (!failing()) {
706       ResourceMark rm;
707       PhaseRemoveUseless pru(initial_gvn(), &for_igvn);
708     }
709   }
710 
711   // Note:  Large methods are capped off in do_one_bytecode().
712   if (failing())  return;
713 
714   // After parsing, node notes are no longer automagic.
715   // They must be propagated by register_new_node_with_optimizer(),
716   // clone(), or the like.
717   set_default_node_notes(NULL);
718 
719   for (;;) {
720     int successes = Inline_Warm();
721     if (failing())  return;
722     if (successes == 0)  break;
723   }
724 
725   // Drain the list.
726   Finish_Warm();
727 #ifndef PRODUCT
728   if (_printer && _printer->should_print(1)) {
729     _printer->print_inlining();
730   }
731 #endif
732 
733   if (failing())  return;
734   NOT_PRODUCT( verify_graph_edges(); )
735 
736   // Now optimize
737   Optimize();
738   if (failing())  return;
739   NOT_PRODUCT( verify_graph_edges(); )
740 
741 #ifndef PRODUCT
742   if (print_ideal()) {
743     ttyLocker ttyl;  // keep the following output all in one block
744     // This output goes directly to the tty, not the compiler log.
745     // To enable tools to match it up with the compilation activity,
746     // be sure to tag this tty output with the compile ID.
747     if (xtty != NULL) {
748       xtty->head("ideal compile_id='%d'%s", compile_id(),
749                  is_osr_compilation()    ? " compile_kind='osr'" :
750                  "");
751     }
752     root()->dump(9999);
753     if (xtty != NULL) {
754       xtty->tail("ideal");
755     }
756   }
757 #endif
758 
759 #ifdef ASSERT
760   BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
761   bs->verify_gc_barriers(this, BarrierSetC2::BeforeCodeGen);
762 #endif
763 
764   // Dump compilation data to replay it.
765   if (directive->DumpReplayOption) {
766     env()->dump_replay_data(_compile_id);
767   }
768   if (directive->DumpInlineOption && (ilt() != NULL)) {
769     env()->dump_inline_data(_compile_id);
770   }
771 
772   // Now that we know the size of all the monitors we can add a fixed slot
773   // for the original deopt pc.
774   int next_slot = fixed_slots() + (sizeof(address) / VMRegImpl::stack_slot_size);
775   set_fixed_slots(next_slot);
776 
777   // Compute when to use implicit null checks. Used by matching trap based
778   // nodes and NullCheck optimization.
779   set_allowed_deopt_reasons();
780 
781   // Now generate code
782   Code_Gen();
783 }
784 
785 //------------------------------Compile----------------------------------------
786 // Compile a runtime stub
Compile(ciEnv * ci_env,TypeFunc_generator generator,address stub_function,const char * stub_name,int is_fancy_jump,bool pass_tls,bool save_arg_registers,bool return_pc,DirectiveSet * directive)787 Compile::Compile( ciEnv* ci_env,
788                   TypeFunc_generator generator,
789                   address stub_function,
790                   const char *stub_name,
791                   int is_fancy_jump,
792                   bool pass_tls,
793                   bool save_arg_registers,
794                   bool return_pc,
795                   DirectiveSet* directive)
796   : Phase(Compiler),
797     _compile_id(0),
798     _save_argument_registers(save_arg_registers),
799     _subsume_loads(true),
800     _do_escape_analysis(false),
801     _eliminate_boxing(false),
802     _method(NULL),
803     _entry_bci(InvocationEntryBci),
804     _stub_function(stub_function),
805     _stub_name(stub_name),
806     _stub_entry_point(NULL),
807     _max_node_limit(MaxNodeLimit),
808     _inlining_progress(false),
809     _inlining_incrementally(false),
810     _has_reserved_stack_access(false),
811 #ifndef PRODUCT
812     _trace_opto_output(directive->TraceOptoOutputOption),
813     _print_ideal(directive->PrintIdealOption),
814 #endif
815     _has_method_handle_invokes(false),
816     _clinit_barrier_on_entry(false),
817     _comp_arena(mtCompiler),
818     _barrier_set_state(BarrierSet::barrier_set()->barrier_set_c2()->create_barrier_state(comp_arena())),
819     _env(ci_env),
820     _directive(directive),
821     _log(ci_env->log()),
822     _failure_reason(NULL),
823     _congraph(NULL),
824 #ifndef PRODUCT
825     _printer(NULL),
826 #endif
827     _dead_node_list(comp_arena()),
828     _dead_node_count(0),
829     _node_arena(mtCompiler),
830     _old_arena(mtCompiler),
831     _mach_constant_base_node(NULL),
832     _Compile_types(mtCompiler),
833     _initial_gvn(NULL),
834     _for_igvn(NULL),
835     _warm_calls(NULL),
836     _number_of_mh_late_inlines(0),
837     _print_inlining_stream(NULL),
838     _print_inlining_list(NULL),
839     _print_inlining_idx(0),
840     _print_inlining_output(NULL),
841     _replay_inline_data(NULL),
842     _java_calls(0),
843     _inner_loops(0),
844     _interpreter_frame_size(0),
845 #ifndef PRODUCT
846     _in_dump_cnt(0),
847 #endif
848     _allowed_reasons(0) {
849   C = this;
850 
851   TraceTime t1(NULL, &_t_totalCompilation, CITime, false);
852   TraceTime t2(NULL, &_t_stubCompilation, CITime, false);
853 
854 #ifndef PRODUCT
855   set_print_assembly(PrintFrameConverterAssembly);
856   set_parsed_irreducible_loop(false);
857 #else
858   set_print_assembly(false); // Must initialize.
859 #endif
860   set_has_irreducible_loop(false); // no loops
861 
862   CompileWrapper cw(this);
863   Init(/*AliasLevel=*/ 0);
864   init_tf((*generator)());
865 
866   {
867     // The following is a dummy for the sake of GraphKit::gen_stub
868     Unique_Node_List for_igvn(comp_arena());
869     set_for_igvn(&for_igvn);  // not used, but some GraphKit guys push on this
870     PhaseGVN gvn(Thread::current()->resource_area(),255);
871     set_initial_gvn(&gvn);    // not significant, but GraphKit guys use it pervasively
872     gvn.transform_no_reclaim(top());
873 
874     GraphKit kit;
875     kit.gen_stub(stub_function, stub_name, is_fancy_jump, pass_tls, return_pc);
876   }
877 
878   NOT_PRODUCT( verify_graph_edges(); )
879 
880   Code_Gen();
881 }
882 
883 //------------------------------Init-------------------------------------------
884 // Prepare for a single compilation
Init(int aliaslevel)885 void Compile::Init(int aliaslevel) {
886   _unique  = 0;
887   _regalloc = NULL;
888 
889   _tf      = NULL;  // filled in later
890   _top     = NULL;  // cached later
891   _matcher = NULL;  // filled in later
892   _cfg     = NULL;  // filled in later
893 
894   IA32_ONLY( set_24_bit_selection_and_mode(true, false); )
895 
896   _node_note_array = NULL;
897   _default_node_notes = NULL;
898   DEBUG_ONLY( _modified_nodes = NULL; ) // Used in Optimize()
899 
900   _immutable_memory = NULL; // filled in at first inquiry
901 
902   // Globally visible Nodes
903   // First set TOP to NULL to give safe behavior during creation of RootNode
904   set_cached_top_node(NULL);
905   set_root(new RootNode());
906   // Now that you have a Root to point to, create the real TOP
907   set_cached_top_node( new ConNode(Type::TOP) );
908   set_recent_alloc(NULL, NULL);
909 
910   // Create Debug Information Recorder to record scopes, oopmaps, etc.
911   env()->set_oop_recorder(new OopRecorder(env()->arena()));
912   env()->set_debug_info(new DebugInformationRecorder(env()->oop_recorder()));
913   env()->set_dependencies(new Dependencies(env()));
914 
915   _fixed_slots = 0;
916   set_has_split_ifs(false);
917   set_has_loops(has_method() && method()->has_loops()); // first approximation
918   set_has_stringbuilder(false);
919   set_has_boxed_value(false);
920   _trap_can_recompile = false;  // no traps emitted yet
921   _major_progress = true; // start out assuming good things will happen
922   set_has_unsafe_access(false);
923   set_max_vector_size(0);
924   set_clear_upper_avx(false);  //false as default for clear upper bits of ymm registers
925   Copy::zero_to_bytes(_trap_hist, sizeof(_trap_hist));
926   set_decompile_count(0);
927 
928   set_do_freq_based_layout(_directive->BlockLayoutByFrequencyOption);
929   _loop_opts_cnt = LoopOptsCount;
930   set_do_inlining(Inline);
931   set_max_inline_size(MaxInlineSize);
932   set_freq_inline_size(FreqInlineSize);
933   set_do_scheduling(OptoScheduling);
934   set_do_count_invocations(false);
935   set_do_method_data_update(false);
936 
937   set_do_vector_loop(false);
938 
939   if (AllowVectorizeOnDemand) {
940     if (has_method() && (_directive->VectorizeOption || _directive->VectorizeDebugOption)) {
941       set_do_vector_loop(true);
942       NOT_PRODUCT(if (do_vector_loop() && Verbose) {tty->print("Compile::Init: do vectorized loops (SIMD like) for method %s\n",  method()->name()->as_quoted_ascii());})
943     } else if (has_method() && method()->name() != 0 &&
944                method()->intrinsic_id() == vmIntrinsics::_forEachRemaining) {
945       set_do_vector_loop(true);
946     }
947   }
948   set_use_cmove(UseCMoveUnconditionally /* || do_vector_loop()*/); //TODO: consider do_vector_loop() mandate use_cmove unconditionally
949   NOT_PRODUCT(if (use_cmove() && Verbose && has_method()) {tty->print("Compile::Init: use CMove without profitability tests for method %s\n",  method()->name()->as_quoted_ascii());})
950 
951   set_age_code(has_method() && method()->profile_aging());
952   set_rtm_state(NoRTM); // No RTM lock eliding by default
953   _max_node_limit = _directive->MaxNodeLimitOption;
954 
955 #if INCLUDE_RTM_OPT
956   if (UseRTMLocking && has_method() && (method()->method_data_or_null() != NULL)) {
957     int rtm_state = method()->method_data()->rtm_state();
958     if (method_has_option("NoRTMLockEliding") || ((rtm_state & NoRTM) != 0)) {
959       // Don't generate RTM lock eliding code.
960       set_rtm_state(NoRTM);
961     } else if (method_has_option("UseRTMLockEliding") || ((rtm_state & UseRTM) != 0) || !UseRTMDeopt) {
962       // Generate RTM lock eliding code without abort ratio calculation code.
963       set_rtm_state(UseRTM);
964     } else if (UseRTMDeopt) {
965       // Generate RTM lock eliding code and include abort ratio calculation
966       // code if UseRTMDeopt is on.
967       set_rtm_state(ProfileRTM);
968     }
969   }
970 #endif
971   if (VM_Version::supports_fast_class_init_checks() && has_method() && !is_osr_compilation() && method()->needs_clinit_barrier()) {
972     set_clinit_barrier_on_entry(true);
973   }
974   if (debug_info()->recording_non_safepoints()) {
975     set_node_note_array(new(comp_arena()) GrowableArray<Node_Notes*>
976                         (comp_arena(), 8, 0, NULL));
977     set_default_node_notes(Node_Notes::make(this));
978   }
979 
980   // // -- Initialize types before each compile --
981   // // Update cached type information
982   // if( _method && _method->constants() )
983   //   Type::update_loaded_types(_method, _method->constants());
984 
985   // Init alias_type map.
986   if (!_do_escape_analysis && aliaslevel == 3)
987     aliaslevel = 2;  // No unique types without escape analysis
988   _AliasLevel = aliaslevel;
989   const int grow_ats = 16;
990   _max_alias_types = grow_ats;
991   _alias_types   = NEW_ARENA_ARRAY(comp_arena(), AliasType*, grow_ats);
992   AliasType* ats = NEW_ARENA_ARRAY(comp_arena(), AliasType,  grow_ats);
993   Copy::zero_to_bytes(ats, sizeof(AliasType)*grow_ats);
994   {
995     for (int i = 0; i < grow_ats; i++)  _alias_types[i] = &ats[i];
996   }
997   // Initialize the first few types.
998   _alias_types[AliasIdxTop]->Init(AliasIdxTop, NULL);
999   _alias_types[AliasIdxBot]->Init(AliasIdxBot, TypePtr::BOTTOM);
1000   _alias_types[AliasIdxRaw]->Init(AliasIdxRaw, TypeRawPtr::BOTTOM);
1001   _num_alias_types = AliasIdxRaw+1;
1002   // Zero out the alias type cache.
1003   Copy::zero_to_bytes(_alias_cache, sizeof(_alias_cache));
1004   // A NULL adr_type hits in the cache right away.  Preload the right answer.
1005   probe_alias_cache(NULL)->_index = AliasIdxTop;
1006 
1007   _intrinsics = NULL;
1008   _macro_nodes = new(comp_arena()) GrowableArray<Node*>(comp_arena(), 8,  0, NULL);
1009   _predicate_opaqs = new(comp_arena()) GrowableArray<Node*>(comp_arena(), 8,  0, NULL);
1010   _expensive_nodes = new(comp_arena()) GrowableArray<Node*>(comp_arena(), 8,  0, NULL);
1011   _range_check_casts = new(comp_arena()) GrowableArray<Node*>(comp_arena(), 8,  0, NULL);
1012   _opaque4_nodes = new(comp_arena()) GrowableArray<Node*>(comp_arena(), 8,  0, NULL);
1013   register_library_intrinsics();
1014 #ifdef ASSERT
1015   _type_verify_symmetry = true;
1016   _phase_optimize_finished = false;
1017 #endif
1018 }
1019 
1020 //---------------------------init_start----------------------------------------
1021 // Install the StartNode on this compile object.
init_start(StartNode * s)1022 void Compile::init_start(StartNode* s) {
1023   if (failing())
1024     return; // already failing
1025   assert(s == start(), "");
1026 }
1027 
1028 /**
1029  * Return the 'StartNode'. We must not have a pending failure, since the ideal graph
1030  * can be in an inconsistent state, i.e., we can get segmentation faults when traversing
1031  * the ideal graph.
1032  */
start() const1033 StartNode* Compile::start() const {
1034   assert (!failing(), "Must not have pending failure. Reason is: %s", failure_reason());
1035   for (DUIterator_Fast imax, i = root()->fast_outs(imax); i < imax; i++) {
1036     Node* start = root()->fast_out(i);
1037     if (start->is_Start()) {
1038       return start->as_Start();
1039     }
1040   }
1041   fatal("Did not find Start node!");
1042   return NULL;
1043 }
1044 
1045 //-------------------------------immutable_memory-------------------------------------
1046 // Access immutable memory
immutable_memory()1047 Node* Compile::immutable_memory() {
1048   if (_immutable_memory != NULL) {
1049     return _immutable_memory;
1050   }
1051   StartNode* s = start();
1052   for (DUIterator_Fast imax, i = s->fast_outs(imax); true; i++) {
1053     Node *p = s->fast_out(i);
1054     if (p != s && p->as_Proj()->_con == TypeFunc::Memory) {
1055       _immutable_memory = p;
1056       return _immutable_memory;
1057     }
1058   }
1059   ShouldNotReachHere();
1060   return NULL;
1061 }
1062 
1063 //----------------------set_cached_top_node------------------------------------
1064 // Install the cached top node, and make sure Node::is_top works correctly.
set_cached_top_node(Node * tn)1065 void Compile::set_cached_top_node(Node* tn) {
1066   if (tn != NULL)  verify_top(tn);
1067   Node* old_top = _top;
1068   _top = tn;
1069   // Calling Node::setup_is_top allows the nodes the chance to adjust
1070   // their _out arrays.
1071   if (_top != NULL)     _top->setup_is_top();
1072   if (old_top != NULL)  old_top->setup_is_top();
1073   assert(_top == NULL || top()->is_top(), "");
1074 }
1075 
1076 #ifdef ASSERT
count_live_nodes_by_graph_walk()1077 uint Compile::count_live_nodes_by_graph_walk() {
1078   Unique_Node_List useful(comp_arena());
1079   // Get useful node list by walking the graph.
1080   identify_useful_nodes(useful);
1081   return useful.size();
1082 }
1083 
print_missing_nodes()1084 void Compile::print_missing_nodes() {
1085 
1086   // Return if CompileLog is NULL and PrintIdealNodeCount is false.
1087   if ((_log == NULL) && (! PrintIdealNodeCount)) {
1088     return;
1089   }
1090 
1091   // This is an expensive function. It is executed only when the user
1092   // specifies VerifyIdealNodeCount option or otherwise knows the
1093   // additional work that needs to be done to identify reachable nodes
1094   // by walking the flow graph and find the missing ones using
1095   // _dead_node_list.
1096 
1097   Unique_Node_List useful(comp_arena());
1098   // Get useful node list by walking the graph.
1099   identify_useful_nodes(useful);
1100 
1101   uint l_nodes = C->live_nodes();
1102   uint l_nodes_by_walk = useful.size();
1103 
1104   if (l_nodes != l_nodes_by_walk) {
1105     if (_log != NULL) {
1106       _log->begin_head("mismatched_nodes count='%d'", abs((int) (l_nodes - l_nodes_by_walk)));
1107       _log->stamp();
1108       _log->end_head();
1109     }
1110     VectorSet& useful_member_set = useful.member_set();
1111     int last_idx = l_nodes_by_walk;
1112     for (int i = 0; i < last_idx; i++) {
1113       if (useful_member_set.test(i)) {
1114         if (_dead_node_list.test(i)) {
1115           if (_log != NULL) {
1116             _log->elem("mismatched_node_info node_idx='%d' type='both live and dead'", i);
1117           }
1118           if (PrintIdealNodeCount) {
1119             // Print the log message to tty
1120               tty->print_cr("mismatched_node idx='%d' both live and dead'", i);
1121               useful.at(i)->dump();
1122           }
1123         }
1124       }
1125       else if (! _dead_node_list.test(i)) {
1126         if (_log != NULL) {
1127           _log->elem("mismatched_node_info node_idx='%d' type='neither live nor dead'", i);
1128         }
1129         if (PrintIdealNodeCount) {
1130           // Print the log message to tty
1131           tty->print_cr("mismatched_node idx='%d' type='neither live nor dead'", i);
1132         }
1133       }
1134     }
1135     if (_log != NULL) {
1136       _log->tail("mismatched_nodes");
1137     }
1138   }
1139 }
record_modified_node(Node * n)1140 void Compile::record_modified_node(Node* n) {
1141   if (_modified_nodes != NULL && !_inlining_incrementally &&
1142       n->outcnt() != 0 && !n->is_Con()) {
1143     _modified_nodes->push(n);
1144   }
1145 }
1146 
remove_modified_node(Node * n)1147 void Compile::remove_modified_node(Node* n) {
1148   if (_modified_nodes != NULL) {
1149     _modified_nodes->remove(n);
1150   }
1151 }
1152 #endif
1153 
1154 #ifndef PRODUCT
verify_top(Node * tn) const1155 void Compile::verify_top(Node* tn) const {
1156   if (tn != NULL) {
1157     assert(tn->is_Con(), "top node must be a constant");
1158     assert(((ConNode*)tn)->type() == Type::TOP, "top node must have correct type");
1159     assert(tn->in(0) != NULL, "must have live top node");
1160   }
1161 }
1162 #endif
1163 
1164 
1165 ///-------------------Managing Per-Node Debug & Profile Info-------------------
1166 
grow_node_notes(GrowableArray<Node_Notes * > * arr,int grow_by)1167 void Compile::grow_node_notes(GrowableArray<Node_Notes*>* arr, int grow_by) {
1168   guarantee(arr != NULL, "");
1169   int num_blocks = arr->length();
1170   if (grow_by < num_blocks)  grow_by = num_blocks;
1171   int num_notes = grow_by * _node_notes_block_size;
1172   Node_Notes* notes = NEW_ARENA_ARRAY(node_arena(), Node_Notes, num_notes);
1173   Copy::zero_to_bytes(notes, num_notes * sizeof(Node_Notes));
1174   while (num_notes > 0) {
1175     arr->append(notes);
1176     notes     += _node_notes_block_size;
1177     num_notes -= _node_notes_block_size;
1178   }
1179   assert(num_notes == 0, "exact multiple, please");
1180 }
1181 
copy_node_notes_to(Node * dest,Node * source)1182 bool Compile::copy_node_notes_to(Node* dest, Node* source) {
1183   if (source == NULL || dest == NULL)  return false;
1184 
1185   if (dest->is_Con())
1186     return false;               // Do not push debug info onto constants.
1187 
1188 #ifdef ASSERT
1189   // Leave a bread crumb trail pointing to the original node:
1190   if (dest != NULL && dest != source && dest->debug_orig() == NULL) {
1191     dest->set_debug_orig(source);
1192   }
1193 #endif
1194 
1195   if (node_note_array() == NULL)
1196     return false;               // Not collecting any notes now.
1197 
1198   // This is a copy onto a pre-existing node, which may already have notes.
1199   // If both nodes have notes, do not overwrite any pre-existing notes.
1200   Node_Notes* source_notes = node_notes_at(source->_idx);
1201   if (source_notes == NULL || source_notes->is_clear())  return false;
1202   Node_Notes* dest_notes   = node_notes_at(dest->_idx);
1203   if (dest_notes == NULL || dest_notes->is_clear()) {
1204     return set_node_notes_at(dest->_idx, source_notes);
1205   }
1206 
1207   Node_Notes merged_notes = (*source_notes);
1208   // The order of operations here ensures that dest notes will win...
1209   merged_notes.update_from(dest_notes);
1210   return set_node_notes_at(dest->_idx, &merged_notes);
1211 }
1212 
1213 
1214 //--------------------------allow_range_check_smearing-------------------------
1215 // Gating condition for coalescing similar range checks.
1216 // Sometimes we try 'speculatively' replacing a series of a range checks by a
1217 // single covering check that is at least as strong as any of them.
1218 // If the optimization succeeds, the simplified (strengthened) range check
1219 // will always succeed.  If it fails, we will deopt, and then give up
1220 // on the optimization.
allow_range_check_smearing() const1221 bool Compile::allow_range_check_smearing() const {
1222   // If this method has already thrown a range-check,
1223   // assume it was because we already tried range smearing
1224   // and it failed.
1225   uint already_trapped = trap_count(Deoptimization::Reason_range_check);
1226   return !already_trapped;
1227 }
1228 
1229 
1230 //------------------------------flatten_alias_type-----------------------------
flatten_alias_type(const TypePtr * tj) const1231 const TypePtr *Compile::flatten_alias_type( const TypePtr *tj ) const {
1232   int offset = tj->offset();
1233   TypePtr::PTR ptr = tj->ptr();
1234 
1235   // Known instance (scalarizable allocation) alias only with itself.
1236   bool is_known_inst = tj->isa_oopptr() != NULL &&
1237                        tj->is_oopptr()->is_known_instance();
1238 
1239   // Process weird unsafe references.
1240   if (offset == Type::OffsetBot && (tj->isa_instptr() /*|| tj->isa_klassptr()*/)) {
1241     assert(InlineUnsafeOps, "indeterminate pointers come only from unsafe ops");
1242     assert(!is_known_inst, "scalarizable allocation should not have unsafe references");
1243     tj = TypeOopPtr::BOTTOM;
1244     ptr = tj->ptr();
1245     offset = tj->offset();
1246   }
1247 
1248   // Array pointers need some flattening
1249   const TypeAryPtr *ta = tj->isa_aryptr();
1250   if (ta && ta->is_stable()) {
1251     // Erase stability property for alias analysis.
1252     tj = ta = ta->cast_to_stable(false);
1253   }
1254   if( ta && is_known_inst ) {
1255     if ( offset != Type::OffsetBot &&
1256          offset > arrayOopDesc::length_offset_in_bytes() ) {
1257       offset = Type::OffsetBot; // Flatten constant access into array body only
1258       tj = ta = TypeAryPtr::make(ptr, ta->ary(), ta->klass(), true, offset, ta->instance_id());
1259     }
1260   } else if( ta && _AliasLevel >= 2 ) {
1261     // For arrays indexed by constant indices, we flatten the alias
1262     // space to include all of the array body.  Only the header, klass
1263     // and array length can be accessed un-aliased.
1264     if( offset != Type::OffsetBot ) {
1265       if( ta->const_oop() ) { // MethodData* or Method*
1266         offset = Type::OffsetBot;   // Flatten constant access into array body
1267         tj = ta = TypeAryPtr::make(ptr,ta->const_oop(),ta->ary(),ta->klass(),false,offset);
1268       } else if( offset == arrayOopDesc::length_offset_in_bytes() ) {
1269         // range is OK as-is.
1270         tj = ta = TypeAryPtr::RANGE;
1271       } else if( offset == oopDesc::klass_offset_in_bytes() ) {
1272         tj = TypeInstPtr::KLASS; // all klass loads look alike
1273         ta = TypeAryPtr::RANGE; // generic ignored junk
1274         ptr = TypePtr::BotPTR;
1275       } else if( offset == oopDesc::mark_offset_in_bytes() ) {
1276         tj = TypeInstPtr::MARK;
1277         ta = TypeAryPtr::RANGE; // generic ignored junk
1278         ptr = TypePtr::BotPTR;
1279       } else {                  // Random constant offset into array body
1280         offset = Type::OffsetBot;   // Flatten constant access into array body
1281         tj = ta = TypeAryPtr::make(ptr,ta->ary(),ta->klass(),false,offset);
1282       }
1283     }
1284     // Arrays of fixed size alias with arrays of unknown size.
1285     if (ta->size() != TypeInt::POS) {
1286       const TypeAry *tary = TypeAry::make(ta->elem(), TypeInt::POS);
1287       tj = ta = TypeAryPtr::make(ptr,ta->const_oop(),tary,ta->klass(),false,offset);
1288     }
1289     // Arrays of known objects become arrays of unknown objects.
1290     if (ta->elem()->isa_narrowoop() && ta->elem() != TypeNarrowOop::BOTTOM) {
1291       const TypeAry *tary = TypeAry::make(TypeNarrowOop::BOTTOM, ta->size());
1292       tj = ta = TypeAryPtr::make(ptr,ta->const_oop(),tary,NULL,false,offset);
1293     }
1294     if (ta->elem()->isa_oopptr() && ta->elem() != TypeInstPtr::BOTTOM) {
1295       const TypeAry *tary = TypeAry::make(TypeInstPtr::BOTTOM, ta->size());
1296       tj = ta = TypeAryPtr::make(ptr,ta->const_oop(),tary,NULL,false,offset);
1297     }
1298     // Arrays of bytes and of booleans both use 'bastore' and 'baload' so
1299     // cannot be distinguished by bytecode alone.
1300     if (ta->elem() == TypeInt::BOOL) {
1301       const TypeAry *tary = TypeAry::make(TypeInt::BYTE, ta->size());
1302       ciKlass* aklass = ciTypeArrayKlass::make(T_BYTE);
1303       tj = ta = TypeAryPtr::make(ptr,ta->const_oop(),tary,aklass,false,offset);
1304     }
1305     // During the 2nd round of IterGVN, NotNull castings are removed.
1306     // Make sure the Bottom and NotNull variants alias the same.
1307     // Also, make sure exact and non-exact variants alias the same.
1308     if (ptr == TypePtr::NotNull || ta->klass_is_exact() || ta->speculative() != NULL) {
1309       tj = ta = TypeAryPtr::make(TypePtr::BotPTR,ta->ary(),ta->klass(),false,offset);
1310     }
1311   }
1312 
1313   // Oop pointers need some flattening
1314   const TypeInstPtr *to = tj->isa_instptr();
1315   if( to && _AliasLevel >= 2 && to != TypeOopPtr::BOTTOM ) {
1316     ciInstanceKlass *k = to->klass()->as_instance_klass();
1317     if( ptr == TypePtr::Constant ) {
1318       if (to->klass() != ciEnv::current()->Class_klass() ||
1319           offset < k->size_helper() * wordSize) {
1320         // No constant oop pointers (such as Strings); they alias with
1321         // unknown strings.
1322         assert(!is_known_inst, "not scalarizable allocation");
1323         tj = to = TypeInstPtr::make(TypePtr::BotPTR,to->klass(),false,0,offset);
1324       }
1325     } else if( is_known_inst ) {
1326       tj = to; // Keep NotNull and klass_is_exact for instance type
1327     } else if( ptr == TypePtr::NotNull || to->klass_is_exact() ) {
1328       // During the 2nd round of IterGVN, NotNull castings are removed.
1329       // Make sure the Bottom and NotNull variants alias the same.
1330       // Also, make sure exact and non-exact variants alias the same.
1331       tj = to = TypeInstPtr::make(TypePtr::BotPTR,to->klass(),false,0,offset);
1332     }
1333     if (to->speculative() != NULL) {
1334       tj = to = TypeInstPtr::make(to->ptr(),to->klass(),to->klass_is_exact(),to->const_oop(),to->offset(), to->instance_id());
1335     }
1336     // Canonicalize the holder of this field
1337     if (offset >= 0 && offset < instanceOopDesc::base_offset_in_bytes()) {
1338       // First handle header references such as a LoadKlassNode, even if the
1339       // object's klass is unloaded at compile time (4965979).
1340       if (!is_known_inst) { // Do it only for non-instance types
1341         tj = to = TypeInstPtr::make(TypePtr::BotPTR, env()->Object_klass(), false, NULL, offset);
1342       }
1343     } else if (offset < 0 || offset >= k->size_helper() * wordSize) {
1344       // Static fields are in the space above the normal instance
1345       // fields in the java.lang.Class instance.
1346       if (to->klass() != ciEnv::current()->Class_klass()) {
1347         to = NULL;
1348         tj = TypeOopPtr::BOTTOM;
1349         offset = tj->offset();
1350       }
1351     } else {
1352       ciInstanceKlass *canonical_holder = k->get_canonical_holder(offset);
1353       if (!k->equals(canonical_holder) || tj->offset() != offset) {
1354         if( is_known_inst ) {
1355           tj = to = TypeInstPtr::make(to->ptr(), canonical_holder, true, NULL, offset, to->instance_id());
1356         } else {
1357           tj = to = TypeInstPtr::make(to->ptr(), canonical_holder, false, NULL, offset);
1358         }
1359       }
1360     }
1361   }
1362 
1363   // Klass pointers to object array klasses need some flattening
1364   const TypeKlassPtr *tk = tj->isa_klassptr();
1365   if( tk ) {
1366     // If we are referencing a field within a Klass, we need
1367     // to assume the worst case of an Object.  Both exact and
1368     // inexact types must flatten to the same alias class so
1369     // use NotNull as the PTR.
1370     if ( offset == Type::OffsetBot || (offset >= 0 && (size_t)offset < sizeof(Klass)) ) {
1371 
1372       tj = tk = TypeKlassPtr::make(TypePtr::NotNull,
1373                                    TypeKlassPtr::OBJECT->klass(),
1374                                    offset);
1375     }
1376 
1377     ciKlass* klass = tk->klass();
1378     if( klass->is_obj_array_klass() ) {
1379       ciKlass* k = TypeAryPtr::OOPS->klass();
1380       if( !k || !k->is_loaded() )                  // Only fails for some -Xcomp runs
1381         k = TypeInstPtr::BOTTOM->klass();
1382       tj = tk = TypeKlassPtr::make( TypePtr::NotNull, k, offset );
1383     }
1384 
1385     // Check for precise loads from the primary supertype array and force them
1386     // to the supertype cache alias index.  Check for generic array loads from
1387     // the primary supertype array and also force them to the supertype cache
1388     // alias index.  Since the same load can reach both, we need to merge
1389     // these 2 disparate memories into the same alias class.  Since the
1390     // primary supertype array is read-only, there's no chance of confusion
1391     // where we bypass an array load and an array store.
1392     int primary_supers_offset = in_bytes(Klass::primary_supers_offset());
1393     if (offset == Type::OffsetBot ||
1394         (offset >= primary_supers_offset &&
1395          offset < (int)(primary_supers_offset + Klass::primary_super_limit() * wordSize)) ||
1396         offset == (int)in_bytes(Klass::secondary_super_cache_offset())) {
1397       offset = in_bytes(Klass::secondary_super_cache_offset());
1398       tj = tk = TypeKlassPtr::make( TypePtr::NotNull, tk->klass(), offset );
1399     }
1400   }
1401 
1402   // Flatten all Raw pointers together.
1403   if (tj->base() == Type::RawPtr)
1404     tj = TypeRawPtr::BOTTOM;
1405 
1406   if (tj->base() == Type::AnyPtr)
1407     tj = TypePtr::BOTTOM;      // An error, which the caller must check for.
1408 
1409   // Flatten all to bottom for now
1410   switch( _AliasLevel ) {
1411   case 0:
1412     tj = TypePtr::BOTTOM;
1413     break;
1414   case 1:                       // Flatten to: oop, static, field or array
1415     switch (tj->base()) {
1416     //case Type::AryPtr: tj = TypeAryPtr::RANGE;    break;
1417     case Type::RawPtr:   tj = TypeRawPtr::BOTTOM;   break;
1418     case Type::AryPtr:   // do not distinguish arrays at all
1419     case Type::InstPtr:  tj = TypeInstPtr::BOTTOM;  break;
1420     case Type::KlassPtr: tj = TypeKlassPtr::OBJECT; break;
1421     case Type::AnyPtr:   tj = TypePtr::BOTTOM;      break;  // caller checks it
1422     default: ShouldNotReachHere();
1423     }
1424     break;
1425   case 2:                       // No collapsing at level 2; keep all splits
1426   case 3:                       // No collapsing at level 3; keep all splits
1427     break;
1428   default:
1429     Unimplemented();
1430   }
1431 
1432   offset = tj->offset();
1433   assert( offset != Type::OffsetTop, "Offset has fallen from constant" );
1434 
1435   assert( (offset != Type::OffsetBot && tj->base() != Type::AryPtr) ||
1436           (offset == Type::OffsetBot && tj->base() == Type::AryPtr) ||
1437           (offset == Type::OffsetBot && tj == TypeOopPtr::BOTTOM) ||
1438           (offset == Type::OffsetBot && tj == TypePtr::BOTTOM) ||
1439           (offset == oopDesc::mark_offset_in_bytes() && tj->base() == Type::AryPtr) ||
1440           (offset == oopDesc::klass_offset_in_bytes() && tj->base() == Type::AryPtr) ||
1441           (offset == arrayOopDesc::length_offset_in_bytes() && tj->base() == Type::AryPtr),
1442           "For oops, klasses, raw offset must be constant; for arrays the offset is never known" );
1443   assert( tj->ptr() != TypePtr::TopPTR &&
1444           tj->ptr() != TypePtr::AnyNull &&
1445           tj->ptr() != TypePtr::Null, "No imprecise addresses" );
1446 //    assert( tj->ptr() != TypePtr::Constant ||
1447 //            tj->base() == Type::RawPtr ||
1448 //            tj->base() == Type::KlassPtr, "No constant oop addresses" );
1449 
1450   return tj;
1451 }
1452 
Init(int i,const TypePtr * at)1453 void Compile::AliasType::Init(int i, const TypePtr* at) {
1454   assert(AliasIdxTop <= i && i < Compile::current()->_max_alias_types, "Invalid alias index");
1455   _index = i;
1456   _adr_type = at;
1457   _field = NULL;
1458   _element = NULL;
1459   _is_rewritable = true; // default
1460   const TypeOopPtr *atoop = (at != NULL) ? at->isa_oopptr() : NULL;
1461   if (atoop != NULL && atoop->is_known_instance()) {
1462     const TypeOopPtr *gt = atoop->cast_to_instance_id(TypeOopPtr::InstanceBot);
1463     _general_index = Compile::current()->get_alias_index(gt);
1464   } else {
1465     _general_index = 0;
1466   }
1467 }
1468 
basic_type() const1469 BasicType Compile::AliasType::basic_type() const {
1470   if (element() != NULL) {
1471     const Type* element = adr_type()->is_aryptr()->elem();
1472     return element->isa_narrowoop() ? T_OBJECT : element->array_element_basic_type();
1473   } if (field() != NULL) {
1474     return field()->layout_type();
1475   } else {
1476     return T_ILLEGAL; // unknown
1477   }
1478 }
1479 
1480 //---------------------------------print_on------------------------------------
1481 #ifndef PRODUCT
print_on(outputStream * st)1482 void Compile::AliasType::print_on(outputStream* st) {
1483   if (index() < 10)
1484         st->print("@ <%d> ", index());
1485   else  st->print("@ <%d>",  index());
1486   st->print(is_rewritable() ? "   " : " RO");
1487   int offset = adr_type()->offset();
1488   if (offset == Type::OffsetBot)
1489         st->print(" +any");
1490   else  st->print(" +%-3d", offset);
1491   st->print(" in ");
1492   adr_type()->dump_on(st);
1493   const TypeOopPtr* tjp = adr_type()->isa_oopptr();
1494   if (field() != NULL && tjp) {
1495     if (tjp->klass()  != field()->holder() ||
1496         tjp->offset() != field()->offset_in_bytes()) {
1497       st->print(" != ");
1498       field()->print();
1499       st->print(" ***");
1500     }
1501   }
1502 }
1503 
print_alias_types()1504 void print_alias_types() {
1505   Compile* C = Compile::current();
1506   tty->print_cr("--- Alias types, AliasIdxBot .. %d", C->num_alias_types()-1);
1507   for (int idx = Compile::AliasIdxBot; idx < C->num_alias_types(); idx++) {
1508     C->alias_type(idx)->print_on(tty);
1509     tty->cr();
1510   }
1511 }
1512 #endif
1513 
1514 
1515 //----------------------------probe_alias_cache--------------------------------
probe_alias_cache(const TypePtr * adr_type)1516 Compile::AliasCacheEntry* Compile::probe_alias_cache(const TypePtr* adr_type) {
1517   intptr_t key = (intptr_t) adr_type;
1518   key ^= key >> logAliasCacheSize;
1519   return &_alias_cache[key & right_n_bits(logAliasCacheSize)];
1520 }
1521 
1522 
1523 //-----------------------------grow_alias_types--------------------------------
grow_alias_types()1524 void Compile::grow_alias_types() {
1525   const int old_ats  = _max_alias_types; // how many before?
1526   const int new_ats  = old_ats;          // how many more?
1527   const int grow_ats = old_ats+new_ats;  // how many now?
1528   _max_alias_types = grow_ats;
1529   _alias_types =  REALLOC_ARENA_ARRAY(comp_arena(), AliasType*, _alias_types, old_ats, grow_ats);
1530   AliasType* ats =    NEW_ARENA_ARRAY(comp_arena(), AliasType, new_ats);
1531   Copy::zero_to_bytes(ats, sizeof(AliasType)*new_ats);
1532   for (int i = 0; i < new_ats; i++)  _alias_types[old_ats+i] = &ats[i];
1533 }
1534 
1535 
1536 //--------------------------------find_alias_type------------------------------
find_alias_type(const TypePtr * adr_type,bool no_create,ciField * original_field)1537 Compile::AliasType* Compile::find_alias_type(const TypePtr* adr_type, bool no_create, ciField* original_field) {
1538   if (_AliasLevel == 0)
1539     return alias_type(AliasIdxBot);
1540 
1541   AliasCacheEntry* ace = probe_alias_cache(adr_type);
1542   if (ace->_adr_type == adr_type) {
1543     return alias_type(ace->_index);
1544   }
1545 
1546   // Handle special cases.
1547   if (adr_type == NULL)             return alias_type(AliasIdxTop);
1548   if (adr_type == TypePtr::BOTTOM)  return alias_type(AliasIdxBot);
1549 
1550   // Do it the slow way.
1551   const TypePtr* flat = flatten_alias_type(adr_type);
1552 
1553 #ifdef ASSERT
1554   {
1555     ResourceMark rm;
1556     assert(flat == flatten_alias_type(flat), "not idempotent: adr_type = %s; flat = %s => %s",
1557            Type::str(adr_type), Type::str(flat), Type::str(flatten_alias_type(flat)));
1558     assert(flat != TypePtr::BOTTOM, "cannot alias-analyze an untyped ptr: adr_type = %s",
1559            Type::str(adr_type));
1560     if (flat->isa_oopptr() && !flat->isa_klassptr()) {
1561       const TypeOopPtr* foop = flat->is_oopptr();
1562       // Scalarizable allocations have exact klass always.
1563       bool exact = !foop->klass_is_exact() || foop->is_known_instance();
1564       const TypePtr* xoop = foop->cast_to_exactness(exact)->is_ptr();
1565       assert(foop == flatten_alias_type(xoop), "exactness must not affect alias type: foop = %s; xoop = %s",
1566              Type::str(foop), Type::str(xoop));
1567     }
1568   }
1569 #endif
1570 
1571   int idx = AliasIdxTop;
1572   for (int i = 0; i < num_alias_types(); i++) {
1573     if (alias_type(i)->adr_type() == flat) {
1574       idx = i;
1575       break;
1576     }
1577   }
1578 
1579   if (idx == AliasIdxTop) {
1580     if (no_create)  return NULL;
1581     // Grow the array if necessary.
1582     if (_num_alias_types == _max_alias_types)  grow_alias_types();
1583     // Add a new alias type.
1584     idx = _num_alias_types++;
1585     _alias_types[idx]->Init(idx, flat);
1586     if (flat == TypeInstPtr::KLASS)  alias_type(idx)->set_rewritable(false);
1587     if (flat == TypeAryPtr::RANGE)   alias_type(idx)->set_rewritable(false);
1588     if (flat->isa_instptr()) {
1589       if (flat->offset() == java_lang_Class::klass_offset()
1590           && flat->is_instptr()->klass() == env()->Class_klass())
1591         alias_type(idx)->set_rewritable(false);
1592     }
1593     if (flat->isa_aryptr()) {
1594 #ifdef ASSERT
1595       const int header_size_min  = arrayOopDesc::base_offset_in_bytes(T_BYTE);
1596       // (T_BYTE has the weakest alignment and size restrictions...)
1597       assert(flat->offset() < header_size_min, "array body reference must be OffsetBot");
1598 #endif
1599       if (flat->offset() == TypePtr::OffsetBot) {
1600         alias_type(idx)->set_element(flat->is_aryptr()->elem());
1601       }
1602     }
1603     if (flat->isa_klassptr()) {
1604       if (flat->offset() == in_bytes(Klass::super_check_offset_offset()))
1605         alias_type(idx)->set_rewritable(false);
1606       if (flat->offset() == in_bytes(Klass::modifier_flags_offset()))
1607         alias_type(idx)->set_rewritable(false);
1608       if (flat->offset() == in_bytes(Klass::access_flags_offset()))
1609         alias_type(idx)->set_rewritable(false);
1610       if (flat->offset() == in_bytes(Klass::java_mirror_offset()))
1611         alias_type(idx)->set_rewritable(false);
1612       if (flat->offset() == in_bytes(Klass::secondary_super_cache_offset()))
1613         alias_type(idx)->set_rewritable(false);
1614     }
1615     // %%% (We would like to finalize JavaThread::threadObj_offset(),
1616     // but the base pointer type is not distinctive enough to identify
1617     // references into JavaThread.)
1618 
1619     // Check for final fields.
1620     const TypeInstPtr* tinst = flat->isa_instptr();
1621     if (tinst && tinst->offset() >= instanceOopDesc::base_offset_in_bytes()) {
1622       ciField* field;
1623       if (tinst->const_oop() != NULL &&
1624           tinst->klass() == ciEnv::current()->Class_klass() &&
1625           tinst->offset() >= (tinst->klass()->as_instance_klass()->size_helper() * wordSize)) {
1626         // static field
1627         ciInstanceKlass* k = tinst->const_oop()->as_instance()->java_lang_Class_klass()->as_instance_klass();
1628         field = k->get_field_by_offset(tinst->offset(), true);
1629       } else {
1630         ciInstanceKlass *k = tinst->klass()->as_instance_klass();
1631         field = k->get_field_by_offset(tinst->offset(), false);
1632       }
1633       assert(field == NULL ||
1634              original_field == NULL ||
1635              (field->holder() == original_field->holder() &&
1636               field->offset() == original_field->offset() &&
1637               field->is_static() == original_field->is_static()), "wrong field?");
1638       // Set field() and is_rewritable() attributes.
1639       if (field != NULL)  alias_type(idx)->set_field(field);
1640     }
1641   }
1642 
1643   // Fill the cache for next time.
1644   ace->_adr_type = adr_type;
1645   ace->_index    = idx;
1646   assert(alias_type(adr_type) == alias_type(idx),  "type must be installed");
1647 
1648   // Might as well try to fill the cache for the flattened version, too.
1649   AliasCacheEntry* face = probe_alias_cache(flat);
1650   if (face->_adr_type == NULL) {
1651     face->_adr_type = flat;
1652     face->_index    = idx;
1653     assert(alias_type(flat) == alias_type(idx), "flat type must work too");
1654   }
1655 
1656   return alias_type(idx);
1657 }
1658 
1659 
alias_type(ciField * field)1660 Compile::AliasType* Compile::alias_type(ciField* field) {
1661   const TypeOopPtr* t;
1662   if (field->is_static())
1663     t = TypeInstPtr::make(field->holder()->java_mirror());
1664   else
1665     t = TypeOopPtr::make_from_klass_raw(field->holder());
1666   AliasType* atp = alias_type(t->add_offset(field->offset_in_bytes()), field);
1667   assert((field->is_final() || field->is_stable()) == !atp->is_rewritable(), "must get the rewritable bits correct");
1668   return atp;
1669 }
1670 
1671 
1672 //------------------------------have_alias_type--------------------------------
have_alias_type(const TypePtr * adr_type)1673 bool Compile::have_alias_type(const TypePtr* adr_type) {
1674   AliasCacheEntry* ace = probe_alias_cache(adr_type);
1675   if (ace->_adr_type == adr_type) {
1676     return true;
1677   }
1678 
1679   // Handle special cases.
1680   if (adr_type == NULL)             return true;
1681   if (adr_type == TypePtr::BOTTOM)  return true;
1682 
1683   return find_alias_type(adr_type, true, NULL) != NULL;
1684 }
1685 
1686 //-----------------------------must_alias--------------------------------------
1687 // True if all values of the given address type are in the given alias category.
must_alias(const TypePtr * adr_type,int alias_idx)1688 bool Compile::must_alias(const TypePtr* adr_type, int alias_idx) {
1689   if (alias_idx == AliasIdxBot)         return true;  // the universal category
1690   if (adr_type == NULL)                 return true;  // NULL serves as TypePtr::TOP
1691   if (alias_idx == AliasIdxTop)         return false; // the empty category
1692   if (adr_type->base() == Type::AnyPtr) return false; // TypePtr::BOTTOM or its twins
1693 
1694   // the only remaining possible overlap is identity
1695   int adr_idx = get_alias_index(adr_type);
1696   assert(adr_idx != AliasIdxBot && adr_idx != AliasIdxTop, "");
1697   assert(adr_idx == alias_idx ||
1698          (alias_type(alias_idx)->adr_type() != TypeOopPtr::BOTTOM
1699           && adr_type                       != TypeOopPtr::BOTTOM),
1700          "should not be testing for overlap with an unsafe pointer");
1701   return adr_idx == alias_idx;
1702 }
1703 
1704 //------------------------------can_alias--------------------------------------
1705 // True if any values of the given address type are in the given alias category.
can_alias(const TypePtr * adr_type,int alias_idx)1706 bool Compile::can_alias(const TypePtr* adr_type, int alias_idx) {
1707   if (alias_idx == AliasIdxTop)         return false; // the empty category
1708   if (adr_type == NULL)                 return false; // NULL serves as TypePtr::TOP
1709   // Known instance doesn't alias with bottom memory
1710   if (alias_idx == AliasIdxBot)         return !adr_type->is_known_instance();                   // the universal category
1711   if (adr_type->base() == Type::AnyPtr) return !C->get_adr_type(alias_idx)->is_known_instance(); // TypePtr::BOTTOM or its twins
1712 
1713   // the only remaining possible overlap is identity
1714   int adr_idx = get_alias_index(adr_type);
1715   assert(adr_idx != AliasIdxBot && adr_idx != AliasIdxTop, "");
1716   return adr_idx == alias_idx;
1717 }
1718 
1719 
1720 
1721 //---------------------------pop_warm_call-------------------------------------
pop_warm_call()1722 WarmCallInfo* Compile::pop_warm_call() {
1723   WarmCallInfo* wci = _warm_calls;
1724   if (wci != NULL)  _warm_calls = wci->remove_from(wci);
1725   return wci;
1726 }
1727 
1728 //----------------------------Inline_Warm--------------------------------------
Inline_Warm()1729 int Compile::Inline_Warm() {
1730   // If there is room, try to inline some more warm call sites.
1731   // %%% Do a graph index compaction pass when we think we're out of space?
1732   if (!InlineWarmCalls)  return 0;
1733 
1734   int calls_made_hot = 0;
1735   int room_to_grow   = NodeCountInliningCutoff - unique();
1736   int amount_to_grow = MIN2(room_to_grow, (int)NodeCountInliningStep);
1737   int amount_grown   = 0;
1738   WarmCallInfo* call;
1739   while (amount_to_grow > 0 && (call = pop_warm_call()) != NULL) {
1740     int est_size = (int)call->size();
1741     if (est_size > (room_to_grow - amount_grown)) {
1742       // This one won't fit anyway.  Get rid of it.
1743       call->make_cold();
1744       continue;
1745     }
1746     call->make_hot();
1747     calls_made_hot++;
1748     amount_grown   += est_size;
1749     amount_to_grow -= est_size;
1750   }
1751 
1752   if (calls_made_hot > 0)  set_major_progress();
1753   return calls_made_hot;
1754 }
1755 
1756 
1757 //----------------------------Finish_Warm--------------------------------------
Finish_Warm()1758 void Compile::Finish_Warm() {
1759   if (!InlineWarmCalls)  return;
1760   if (failing())  return;
1761   if (warm_calls() == NULL)  return;
1762 
1763   // Clean up loose ends, if we are out of space for inlining.
1764   WarmCallInfo* call;
1765   while ((call = pop_warm_call()) != NULL) {
1766     call->make_cold();
1767   }
1768 }
1769 
1770 //---------------------cleanup_loop_predicates-----------------------
1771 // Remove the opaque nodes that protect the predicates so that all unused
1772 // checks and uncommon_traps will be eliminated from the ideal graph
cleanup_loop_predicates(PhaseIterGVN & igvn)1773 void Compile::cleanup_loop_predicates(PhaseIterGVN &igvn) {
1774   if (predicate_count()==0) return;
1775   for (int i = predicate_count(); i > 0; i--) {
1776     Node * n = predicate_opaque1_node(i-1);
1777     assert(n->Opcode() == Op_Opaque1, "must be");
1778     igvn.replace_node(n, n->in(1));
1779   }
1780   assert(predicate_count()==0, "should be clean!");
1781 }
1782 
add_range_check_cast(Node * n)1783 void Compile::add_range_check_cast(Node* n) {
1784   assert(n->isa_CastII()->has_range_check(), "CastII should have range check dependency");
1785   assert(!_range_check_casts->contains(n), "duplicate entry in range check casts");
1786   _range_check_casts->append(n);
1787 }
1788 
1789 // Remove all range check dependent CastIINodes.
remove_range_check_casts(PhaseIterGVN & igvn)1790 void Compile::remove_range_check_casts(PhaseIterGVN &igvn) {
1791   for (int i = range_check_cast_count(); i > 0; i--) {
1792     Node* cast = range_check_cast_node(i-1);
1793     assert(cast->isa_CastII()->has_range_check(), "CastII should have range check dependency");
1794     igvn.replace_node(cast, cast->in(1));
1795   }
1796   assert(range_check_cast_count() == 0, "should be empty");
1797 }
1798 
add_opaque4_node(Node * n)1799 void Compile::add_opaque4_node(Node* n) {
1800   assert(n->Opcode() == Op_Opaque4, "Opaque4 only");
1801   assert(!_opaque4_nodes->contains(n), "duplicate entry in Opaque4 list");
1802   _opaque4_nodes->append(n);
1803 }
1804 
1805 // Remove all Opaque4 nodes.
remove_opaque4_nodes(PhaseIterGVN & igvn)1806 void Compile::remove_opaque4_nodes(PhaseIterGVN &igvn) {
1807   for (int i = opaque4_count(); i > 0; i--) {
1808     Node* opaq = opaque4_node(i-1);
1809     assert(opaq->Opcode() == Op_Opaque4, "Opaque4 only");
1810     // With Opaque4 nodes, the expectation is that the test of input 1
1811     // is always equal to the constant value of input 2. So we can
1812     // remove the Opaque4 and replace it by input 2. In debug builds,
1813     // leave the non constant test in instead to sanity check that it
1814     // never fails (if it does, that subgraph was constructed so, at
1815     // runtime, a Halt node is executed).
1816 #ifdef ASSERT
1817     igvn.replace_node(opaq, opaq->in(1));
1818 #else
1819     igvn.replace_node(opaq, opaq->in(2));
1820 #endif
1821   }
1822   assert(opaque4_count() == 0, "should be empty");
1823 }
1824 
1825 // StringOpts and late inlining of string methods
inline_string_calls(bool parse_time)1826 void Compile::inline_string_calls(bool parse_time) {
1827   {
1828     // remove useless nodes to make the usage analysis simpler
1829     ResourceMark rm;
1830     PhaseRemoveUseless pru(initial_gvn(), for_igvn());
1831   }
1832 
1833   {
1834     ResourceMark rm;
1835     print_method(PHASE_BEFORE_STRINGOPTS, 3);
1836     PhaseStringOpts pso(initial_gvn(), for_igvn());
1837     print_method(PHASE_AFTER_STRINGOPTS, 3);
1838   }
1839 
1840   // now inline anything that we skipped the first time around
1841   if (!parse_time) {
1842     _late_inlines_pos = _late_inlines.length();
1843   }
1844 
1845   while (_string_late_inlines.length() > 0) {
1846     CallGenerator* cg = _string_late_inlines.pop();
1847     cg->do_late_inline();
1848     if (failing())  return;
1849   }
1850   _string_late_inlines.trunc_to(0);
1851 }
1852 
1853 // Late inlining of boxing methods
inline_boxing_calls(PhaseIterGVN & igvn)1854 void Compile::inline_boxing_calls(PhaseIterGVN& igvn) {
1855   if (_boxing_late_inlines.length() > 0) {
1856     assert(has_boxed_value(), "inconsistent");
1857 
1858     PhaseGVN* gvn = initial_gvn();
1859     set_inlining_incrementally(true);
1860 
1861     assert( igvn._worklist.size() == 0, "should be done with igvn" );
1862     for_igvn()->clear();
1863     gvn->replace_with(&igvn);
1864 
1865     _late_inlines_pos = _late_inlines.length();
1866 
1867     while (_boxing_late_inlines.length() > 0) {
1868       CallGenerator* cg = _boxing_late_inlines.pop();
1869       cg->do_late_inline();
1870       if (failing())  return;
1871     }
1872     _boxing_late_inlines.trunc_to(0);
1873 
1874     inline_incrementally_cleanup(igvn);
1875 
1876     set_inlining_incrementally(false);
1877   }
1878 }
1879 
inline_incrementally_one()1880 bool Compile::inline_incrementally_one() {
1881   assert(IncrementalInline, "incremental inlining should be on");
1882 
1883   TracePhase tp("incrementalInline_inline", &timers[_t_incrInline_inline]);
1884   set_inlining_progress(false);
1885   set_do_cleanup(false);
1886   int i = 0;
1887   for (; i <_late_inlines.length() && !inlining_progress(); i++) {
1888     CallGenerator* cg = _late_inlines.at(i);
1889     _late_inlines_pos = i+1;
1890     cg->do_late_inline();
1891     if (failing())  return false;
1892   }
1893   int j = 0;
1894   for (; i < _late_inlines.length(); i++, j++) {
1895     _late_inlines.at_put(j, _late_inlines.at(i));
1896   }
1897   _late_inlines.trunc_to(j);
1898   assert(inlining_progress() || _late_inlines.length() == 0, "");
1899 
1900   bool needs_cleanup = do_cleanup() || over_inlining_cutoff();
1901 
1902   set_inlining_progress(false);
1903   set_do_cleanup(false);
1904   return (_late_inlines.length() > 0) && !needs_cleanup;
1905 }
1906 
inline_incrementally_cleanup(PhaseIterGVN & igvn)1907 void Compile::inline_incrementally_cleanup(PhaseIterGVN& igvn) {
1908   {
1909     TracePhase tp("incrementalInline_pru", &timers[_t_incrInline_pru]);
1910     ResourceMark rm;
1911     PhaseRemoveUseless pru(initial_gvn(), for_igvn());
1912   }
1913   {
1914     TracePhase tp("incrementalInline_igvn", &timers[_t_incrInline_igvn]);
1915     igvn = PhaseIterGVN(initial_gvn());
1916     igvn.optimize();
1917   }
1918 }
1919 
1920 // Perform incremental inlining until bound on number of live nodes is reached
inline_incrementally(PhaseIterGVN & igvn)1921 void Compile::inline_incrementally(PhaseIterGVN& igvn) {
1922   TracePhase tp("incrementalInline", &timers[_t_incrInline]);
1923 
1924   set_inlining_incrementally(true);
1925   uint low_live_nodes = 0;
1926 
1927   while (_late_inlines.length() > 0) {
1928     if (live_nodes() > (uint)LiveNodeCountInliningCutoff) {
1929       if (low_live_nodes < (uint)LiveNodeCountInliningCutoff * 8 / 10) {
1930         TracePhase tp("incrementalInline_ideal", &timers[_t_incrInline_ideal]);
1931         // PhaseIdealLoop is expensive so we only try it once we are
1932         // out of live nodes and we only try it again if the previous
1933         // helped got the number of nodes down significantly
1934         PhaseIdealLoop::optimize(igvn, LoopOptsNone);
1935         if (failing())  return;
1936         low_live_nodes = live_nodes();
1937         _major_progress = true;
1938       }
1939 
1940       if (live_nodes() > (uint)LiveNodeCountInliningCutoff) {
1941         break; // finish
1942       }
1943     }
1944 
1945     for_igvn()->clear();
1946     initial_gvn()->replace_with(&igvn);
1947 
1948     while (inline_incrementally_one()) {
1949       assert(!failing(), "inconsistent");
1950     }
1951 
1952     if (failing())  return;
1953 
1954     inline_incrementally_cleanup(igvn);
1955 
1956     if (failing())  return;
1957   }
1958   assert( igvn._worklist.size() == 0, "should be done with igvn" );
1959 
1960   if (_string_late_inlines.length() > 0) {
1961     assert(has_stringbuilder(), "inconsistent");
1962     for_igvn()->clear();
1963     initial_gvn()->replace_with(&igvn);
1964 
1965     inline_string_calls(false);
1966 
1967     if (failing())  return;
1968 
1969     inline_incrementally_cleanup(igvn);
1970   }
1971 
1972   set_inlining_incrementally(false);
1973 }
1974 
1975 
optimize_loops(PhaseIterGVN & igvn,LoopOptsMode mode)1976 bool Compile::optimize_loops(PhaseIterGVN& igvn, LoopOptsMode mode) {
1977   if(_loop_opts_cnt > 0) {
1978     debug_only( int cnt = 0; );
1979     while(major_progress() && (_loop_opts_cnt > 0)) {
1980       TracePhase tp("idealLoop", &timers[_t_idealLoop]);
1981       assert( cnt++ < 40, "infinite cycle in loop optimization" );
1982       PhaseIdealLoop::optimize(igvn, mode);
1983       _loop_opts_cnt--;
1984       if (failing())  return false;
1985       if (major_progress()) print_method(PHASE_PHASEIDEALLOOP_ITERATIONS, 2);
1986     }
1987   }
1988   return true;
1989 }
1990 
1991 // Remove edges from "root" to each SafePoint at a backward branch.
1992 // They were inserted during parsing (see add_safepoint()) to make
1993 // infinite loops without calls or exceptions visible to root, i.e.,
1994 // useful.
remove_root_to_sfpts_edges(PhaseIterGVN & igvn)1995 void Compile::remove_root_to_sfpts_edges(PhaseIterGVN& igvn) {
1996   Node *r = root();
1997   if (r != NULL) {
1998     for (uint i = r->req(); i < r->len(); ++i) {
1999       Node *n = r->in(i);
2000       if (n != NULL && n->is_SafePoint()) {
2001         r->rm_prec(i);
2002         if (n->outcnt() == 0) {
2003           igvn.remove_dead_node(n);
2004         }
2005         --i;
2006       }
2007     }
2008     // Parsing may have added top inputs to the root node (Path
2009     // leading to the Halt node proven dead). Make sure we get a
2010     // chance to clean them up.
2011     igvn._worklist.push(r);
2012     igvn.optimize();
2013   }
2014 }
2015 
2016 //------------------------------Optimize---------------------------------------
2017 // Given a graph, optimize it.
Optimize()2018 void Compile::Optimize() {
2019   TracePhase tp("optimizer", &timers[_t_optimizer]);
2020 
2021 #ifndef PRODUCT
2022   if (_directive->BreakAtCompileOption) {
2023     BREAKPOINT;
2024   }
2025 
2026 #endif
2027 
2028   BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
2029 #ifdef ASSERT
2030   bs->verify_gc_barriers(this, BarrierSetC2::BeforeOptimize);
2031 #endif
2032 
2033   ResourceMark rm;
2034 
2035   print_inlining_reinit();
2036 
2037   NOT_PRODUCT( verify_graph_edges(); )
2038 
2039   print_method(PHASE_AFTER_PARSING);
2040 
2041  {
2042   // Iterative Global Value Numbering, including ideal transforms
2043   // Initialize IterGVN with types and values from parse-time GVN
2044   PhaseIterGVN igvn(initial_gvn());
2045 #ifdef ASSERT
2046   _modified_nodes = new (comp_arena()) Unique_Node_List(comp_arena());
2047 #endif
2048   {
2049     TracePhase tp("iterGVN", &timers[_t_iterGVN]);
2050     igvn.optimize();
2051   }
2052 
2053   if (failing())  return;
2054 
2055   print_method(PHASE_ITER_GVN1, 2);
2056 
2057   inline_incrementally(igvn);
2058 
2059   print_method(PHASE_INCREMENTAL_INLINE, 2);
2060 
2061   if (failing())  return;
2062 
2063   if (eliminate_boxing()) {
2064     // Inline valueOf() methods now.
2065     inline_boxing_calls(igvn);
2066 
2067     if (AlwaysIncrementalInline) {
2068       inline_incrementally(igvn);
2069     }
2070 
2071     print_method(PHASE_INCREMENTAL_BOXING_INLINE, 2);
2072 
2073     if (failing())  return;
2074   }
2075 
2076   // Now that all inlining is over, cut edge from root to loop
2077   // safepoints
2078   remove_root_to_sfpts_edges(igvn);
2079 
2080   // Remove the speculative part of types and clean up the graph from
2081   // the extra CastPP nodes whose only purpose is to carry them. Do
2082   // that early so that optimizations are not disrupted by the extra
2083   // CastPP nodes.
2084   remove_speculative_types(igvn);
2085 
2086   // No more new expensive nodes will be added to the list from here
2087   // so keep only the actual candidates for optimizations.
2088   cleanup_expensive_nodes(igvn);
2089 
2090   if (!failing() && RenumberLiveNodes && live_nodes() + NodeLimitFudgeFactor < unique()) {
2091     Compile::TracePhase tp("", &timers[_t_renumberLive]);
2092     initial_gvn()->replace_with(&igvn);
2093     for_igvn()->clear();
2094     Unique_Node_List new_worklist(C->comp_arena());
2095     {
2096       ResourceMark rm;
2097       PhaseRenumberLive prl = PhaseRenumberLive(initial_gvn(), for_igvn(), &new_worklist);
2098     }
2099     set_for_igvn(&new_worklist);
2100     igvn = PhaseIterGVN(initial_gvn());
2101     igvn.optimize();
2102   }
2103 
2104   // Perform escape analysis
2105   if (_do_escape_analysis && ConnectionGraph::has_candidates(this)) {
2106     if (has_loops()) {
2107       // Cleanup graph (remove dead nodes).
2108       TracePhase tp("idealLoop", &timers[_t_idealLoop]);
2109       PhaseIdealLoop::optimize(igvn, LoopOptsMaxUnroll);
2110       if (major_progress()) print_method(PHASE_PHASEIDEAL_BEFORE_EA, 2);
2111       if (failing())  return;
2112     }
2113     ConnectionGraph::do_analysis(this, &igvn);
2114 
2115     if (failing())  return;
2116 
2117     // Optimize out fields loads from scalar replaceable allocations.
2118     igvn.optimize();
2119     print_method(PHASE_ITER_GVN_AFTER_EA, 2);
2120 
2121     if (failing())  return;
2122 
2123     if (congraph() != NULL && macro_count() > 0) {
2124       TracePhase tp("macroEliminate", &timers[_t_macroEliminate]);
2125       PhaseMacroExpand mexp(igvn);
2126       mexp.eliminate_macro_nodes();
2127       igvn.set_delay_transform(false);
2128 
2129       igvn.optimize();
2130       print_method(PHASE_ITER_GVN_AFTER_ELIMINATION, 2);
2131 
2132       if (failing())  return;
2133     }
2134   }
2135 
2136   // Loop transforms on the ideal graph.  Range Check Elimination,
2137   // peeling, unrolling, etc.
2138 
2139   // Set loop opts counter
2140   if((_loop_opts_cnt > 0) && (has_loops() || has_split_ifs())) {
2141     {
2142       TracePhase tp("idealLoop", &timers[_t_idealLoop]);
2143       PhaseIdealLoop::optimize(igvn, LoopOptsDefault);
2144       _loop_opts_cnt--;
2145       if (major_progress()) print_method(PHASE_PHASEIDEALLOOP1, 2);
2146       if (failing())  return;
2147     }
2148     // Loop opts pass if partial peeling occurred in previous pass
2149     if(PartialPeelLoop && major_progress() && (_loop_opts_cnt > 0)) {
2150       TracePhase tp("idealLoop", &timers[_t_idealLoop]);
2151       PhaseIdealLoop::optimize(igvn, LoopOptsSkipSplitIf);
2152       _loop_opts_cnt--;
2153       if (major_progress()) print_method(PHASE_PHASEIDEALLOOP2, 2);
2154       if (failing())  return;
2155     }
2156     // Loop opts pass for loop-unrolling before CCP
2157     if(major_progress() && (_loop_opts_cnt > 0)) {
2158       TracePhase tp("idealLoop", &timers[_t_idealLoop]);
2159       PhaseIdealLoop::optimize(igvn, LoopOptsSkipSplitIf);
2160       _loop_opts_cnt--;
2161       if (major_progress()) print_method(PHASE_PHASEIDEALLOOP3, 2);
2162     }
2163     if (!failing()) {
2164       // Verify that last round of loop opts produced a valid graph
2165       TracePhase tp("idealLoopVerify", &timers[_t_idealLoopVerify]);
2166       PhaseIdealLoop::verify(igvn);
2167     }
2168   }
2169   if (failing())  return;
2170 
2171   // Conditional Constant Propagation;
2172   PhaseCCP ccp( &igvn );
2173   assert( true, "Break here to ccp.dump_nodes_and_types(_root,999,1)");
2174   {
2175     TracePhase tp("ccp", &timers[_t_ccp]);
2176     ccp.do_transform();
2177   }
2178   print_method(PHASE_CPP1, 2);
2179 
2180   assert( true, "Break here to ccp.dump_old2new_map()");
2181 
2182   // Iterative Global Value Numbering, including ideal transforms
2183   {
2184     TracePhase tp("iterGVN2", &timers[_t_iterGVN2]);
2185     igvn = ccp;
2186     igvn.optimize();
2187   }
2188   print_method(PHASE_ITER_GVN2, 2);
2189 
2190   if (failing())  return;
2191 
2192   // Loop transforms on the ideal graph.  Range Check Elimination,
2193   // peeling, unrolling, etc.
2194   if (!optimize_loops(igvn, LoopOptsDefault)) {
2195     return;
2196   }
2197 
2198   if (failing())  return;
2199 
2200   // Ensure that major progress is now clear
2201   C->clear_major_progress();
2202 
2203   {
2204     // Verify that all previous optimizations produced a valid graph
2205     // at least to this point, even if no loop optimizations were done.
2206     TracePhase tp("idealLoopVerify", &timers[_t_idealLoopVerify]);
2207     PhaseIdealLoop::verify(igvn);
2208   }
2209 
2210   if (range_check_cast_count() > 0) {
2211     // No more loop optimizations. Remove all range check dependent CastIINodes.
2212     C->remove_range_check_casts(igvn);
2213     igvn.optimize();
2214   }
2215 
2216 #ifdef ASSERT
2217   bs->verify_gc_barriers(this, BarrierSetC2::BeforeMacroExpand);
2218 #endif
2219 
2220   {
2221     TracePhase tp("macroExpand", &timers[_t_macroExpand]);
2222     PhaseMacroExpand  mex(igvn);
2223     if (mex.expand_macro_nodes()) {
2224       assert(failing(), "must bail out w/ explicit message");
2225       return;
2226     }
2227     print_method(PHASE_MACRO_EXPANSION, 2);
2228   }
2229 
2230   {
2231     TracePhase tp("barrierExpand", &timers[_t_barrierExpand]);
2232     if (bs->expand_barriers(this, igvn)) {
2233       assert(failing(), "must bail out w/ explicit message");
2234       return;
2235     }
2236     print_method(PHASE_BARRIER_EXPANSION, 2);
2237   }
2238 
2239   if (opaque4_count() > 0) {
2240     C->remove_opaque4_nodes(igvn);
2241     igvn.optimize();
2242   }
2243 
2244   if (C->max_vector_size() > 0) {
2245     C->optimize_logic_cones(igvn);
2246     igvn.optimize();
2247   }
2248 
2249   DEBUG_ONLY( _modified_nodes = NULL; )
2250  } // (End scope of igvn; run destructor if necessary for asserts.)
2251 
2252  process_print_inlining();
2253  // A method with only infinite loops has no edges entering loops from root
2254  {
2255    TracePhase tp("graphReshape", &timers[_t_graphReshaping]);
2256    if (final_graph_reshaping()) {
2257      assert(failing(), "must bail out w/ explicit message");
2258      return;
2259    }
2260  }
2261 
2262  print_method(PHASE_OPTIMIZE_FINISHED, 2);
2263  DEBUG_ONLY(set_phase_optimize_finished();)
2264 }
2265 
2266 //---------------------------- Bitwise operation packing optimization ---------------------------
2267 
is_vector_unary_bitwise_op(Node * n)2268 static bool is_vector_unary_bitwise_op(Node* n) {
2269   return n->Opcode() == Op_XorV &&
2270          VectorNode::is_vector_bitwise_not_pattern(n);
2271 }
2272 
is_vector_binary_bitwise_op(Node * n)2273 static bool is_vector_binary_bitwise_op(Node* n) {
2274   switch (n->Opcode()) {
2275     case Op_AndV:
2276     case Op_OrV:
2277       return true;
2278 
2279     case Op_XorV:
2280       return !is_vector_unary_bitwise_op(n);
2281 
2282     default:
2283       return false;
2284   }
2285 }
2286 
is_vector_ternary_bitwise_op(Node * n)2287 static bool is_vector_ternary_bitwise_op(Node* n) {
2288   return n->Opcode() == Op_MacroLogicV;
2289 }
2290 
is_vector_bitwise_op(Node * n)2291 static bool is_vector_bitwise_op(Node* n) {
2292   return is_vector_unary_bitwise_op(n)  ||
2293          is_vector_binary_bitwise_op(n) ||
2294          is_vector_ternary_bitwise_op(n);
2295 }
2296 
is_vector_bitwise_cone_root(Node * n)2297 static bool is_vector_bitwise_cone_root(Node* n) {
2298   if (!is_vector_bitwise_op(n)) {
2299     return false;
2300   }
2301   for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
2302     if (is_vector_bitwise_op(n->fast_out(i))) {
2303       return false;
2304     }
2305   }
2306   return true;
2307 }
2308 
collect_unique_inputs(Node * n,Unique_Node_List & partition,Unique_Node_List & inputs)2309 static uint collect_unique_inputs(Node* n, Unique_Node_List& partition, Unique_Node_List& inputs) {
2310   uint cnt = 0;
2311   if (is_vector_bitwise_op(n)) {
2312     if (VectorNode::is_vector_bitwise_not_pattern(n)) {
2313       for (uint i = 1; i < n->req(); i++) {
2314         Node* in = n->in(i);
2315         bool skip = VectorNode::is_all_ones_vector(in);
2316         if (!skip && !inputs.member(in)) {
2317           inputs.push(in);
2318           cnt++;
2319         }
2320       }
2321       assert(cnt <= 1, "not unary");
2322     } else {
2323       uint last_req = n->req();
2324       if (is_vector_ternary_bitwise_op(n)) {
2325         last_req = n->req() - 1; // skip last input
2326       }
2327       for (uint i = 1; i < last_req; i++) {
2328         Node* def = n->in(i);
2329         if (!inputs.member(def)) {
2330           inputs.push(def);
2331           cnt++;
2332         }
2333       }
2334     }
2335     partition.push(n);
2336   } else { // not a bitwise operations
2337     if (!inputs.member(n)) {
2338       inputs.push(n);
2339       cnt++;
2340     }
2341   }
2342   return cnt;
2343 }
2344 
collect_logic_cone_roots(Unique_Node_List & list)2345 void Compile::collect_logic_cone_roots(Unique_Node_List& list) {
2346   Unique_Node_List useful_nodes;
2347   C->identify_useful_nodes(useful_nodes);
2348 
2349   for (uint i = 0; i < useful_nodes.size(); i++) {
2350     Node* n = useful_nodes.at(i);
2351     if (is_vector_bitwise_cone_root(n)) {
2352       list.push(n);
2353     }
2354   }
2355 }
2356 
xform_to_MacroLogicV(PhaseIterGVN & igvn,const TypeVect * vt,Unique_Node_List & partition,Unique_Node_List & inputs)2357 Node* Compile::xform_to_MacroLogicV(PhaseIterGVN& igvn,
2358                                     const TypeVect* vt,
2359                                     Unique_Node_List& partition,
2360                                     Unique_Node_List& inputs) {
2361   assert(partition.size() == 2 || partition.size() == 3, "not supported");
2362   assert(inputs.size()    == 2 || inputs.size()    == 3, "not supported");
2363   assert(Matcher::match_rule_supported_vector(Op_MacroLogicV, vt->length(), vt->element_basic_type()), "not supported");
2364 
2365   Node* in1 = inputs.at(0);
2366   Node* in2 = inputs.at(1);
2367   Node* in3 = (inputs.size() == 3 ? inputs.at(2) : in2);
2368 
2369   uint func = compute_truth_table(partition, inputs);
2370   return igvn.transform(MacroLogicVNode::make(igvn, in3, in2, in1, func, vt));
2371 }
2372 
extract_bit(uint func,uint pos)2373 static uint extract_bit(uint func, uint pos) {
2374   return (func & (1 << pos)) >> pos;
2375 }
2376 
2377 //
2378 //  A macro logic node represents a truth table. It has 4 inputs,
2379 //  First three inputs corresponds to 3 columns of a truth table
2380 //  and fourth input captures the logic function.
2381 //
2382 //  eg.  fn = (in1 AND in2) OR in3;
2383 //
2384 //      MacroNode(in1,in2,in3,fn)
2385 //
2386 //  -----------------
2387 //  in1 in2 in3  fn
2388 //  -----------------
2389 //  0    0   0    0
2390 //  0    0   1    1
2391 //  0    1   0    0
2392 //  0    1   1    1
2393 //  1    0   0    0
2394 //  1    0   1    1
2395 //  1    1   0    1
2396 //  1    1   1    1
2397 //
2398 
eval_macro_logic_op(uint func,uint in1,uint in2,uint in3)2399 uint Compile::eval_macro_logic_op(uint func, uint in1 , uint in2, uint in3) {
2400   int res = 0;
2401   for (int i = 0; i < 8; i++) {
2402     int bit1 = extract_bit(in1, i);
2403     int bit2 = extract_bit(in2, i);
2404     int bit3 = extract_bit(in3, i);
2405 
2406     int func_bit_pos = (bit1 << 2 | bit2 << 1 | bit3);
2407     int func_bit = extract_bit(func, func_bit_pos);
2408 
2409     res |= func_bit << i;
2410   }
2411   return res;
2412 }
2413 
eval_operand(Node * n,ResourceHashtable<Node *,uint> & eval_map)2414 static uint eval_operand(Node* n, ResourceHashtable<Node*,uint>& eval_map) {
2415   assert(n != NULL, "");
2416   assert(eval_map.contains(n), "absent");
2417   return *(eval_map.get(n));
2418 }
2419 
eval_operands(Node * n,uint & func1,uint & func2,uint & func3,ResourceHashtable<Node *,uint> & eval_map)2420 static void eval_operands(Node* n,
2421                           uint& func1, uint& func2, uint& func3,
2422                           ResourceHashtable<Node*,uint>& eval_map) {
2423   assert(is_vector_bitwise_op(n), "");
2424   func1 = eval_operand(n->in(1), eval_map);
2425 
2426   if (is_vector_binary_bitwise_op(n)) {
2427     func2 = eval_operand(n->in(2), eval_map);
2428   } else if (is_vector_ternary_bitwise_op(n)) {
2429     func2 = eval_operand(n->in(2), eval_map);
2430     func3 = eval_operand(n->in(3), eval_map);
2431   } else {
2432     assert(is_vector_unary_bitwise_op(n), "not unary");
2433   }
2434 }
2435 
compute_truth_table(Unique_Node_List & partition,Unique_Node_List & inputs)2436 uint Compile::compute_truth_table(Unique_Node_List& partition, Unique_Node_List& inputs) {
2437   assert(inputs.size() <= 3, "sanity");
2438   ResourceMark rm;
2439   uint res = 0;
2440   ResourceHashtable<Node*,uint> eval_map;
2441 
2442   // Populate precomputed functions for inputs.
2443   // Each input corresponds to one column of 3 input truth-table.
2444   uint input_funcs[] = { 0xAA,   // (_, _, a) -> a
2445                          0xCC,   // (_, b, _) -> b
2446                          0xF0 }; // (c, _, _) -> c
2447   for (uint i = 0; i < inputs.size(); i++) {
2448     eval_map.put(inputs.at(i), input_funcs[i]);
2449   }
2450 
2451   for (uint i = 0; i < partition.size(); i++) {
2452     Node* n = partition.at(i);
2453 
2454     uint func1 = 0, func2 = 0, func3 = 0;
2455     eval_operands(n, func1, func2, func3, eval_map);
2456 
2457     switch (n->Opcode()) {
2458       case Op_OrV:
2459         assert(func3 == 0, "not binary");
2460         res = func1 | func2;
2461         break;
2462       case Op_AndV:
2463         assert(func3 == 0, "not binary");
2464         res = func1 & func2;
2465         break;
2466       case Op_XorV:
2467         if (VectorNode::is_vector_bitwise_not_pattern(n)) {
2468           assert(func2 == 0 && func3 == 0, "not unary");
2469           res = (~func1) & 0xFF;
2470         } else {
2471           assert(func3 == 0, "not binary");
2472           res = func1 ^ func2;
2473         }
2474         break;
2475       case Op_MacroLogicV:
2476         // Ordering of inputs may change during evaluation of sub-tree
2477         // containing MacroLogic node as a child node, thus a re-evaluation
2478         // makes sure that function is evaluated in context of current
2479         // inputs.
2480         res = eval_macro_logic_op(n->in(4)->get_int(), func1, func2, func3);
2481         break;
2482 
2483       default: assert(false, "not supported: %s", n->Name());
2484     }
2485     assert(res <= 0xFF, "invalid");
2486     eval_map.put(n, res);
2487   }
2488   return res;
2489 }
2490 
compute_logic_cone(Node * n,Unique_Node_List & partition,Unique_Node_List & inputs)2491 bool Compile::compute_logic_cone(Node* n, Unique_Node_List& partition, Unique_Node_List& inputs) {
2492   assert(partition.size() == 0, "not empty");
2493   assert(inputs.size() == 0, "not empty");
2494   if (is_vector_ternary_bitwise_op(n)) {
2495     return false;
2496   }
2497 
2498   bool is_unary_op = is_vector_unary_bitwise_op(n);
2499   if (is_unary_op) {
2500     assert(collect_unique_inputs(n, partition, inputs) == 1, "not unary");
2501     return false; // too few inputs
2502   }
2503 
2504   assert(is_vector_binary_bitwise_op(n), "not binary");
2505   Node* in1 = n->in(1);
2506   Node* in2 = n->in(2);
2507 
2508   int in1_unique_inputs_cnt = collect_unique_inputs(in1, partition, inputs);
2509   int in2_unique_inputs_cnt = collect_unique_inputs(in2, partition, inputs);
2510   partition.push(n);
2511 
2512   // Too many inputs?
2513   if (inputs.size() > 3) {
2514     partition.clear();
2515     inputs.clear();
2516     { // Recompute in2 inputs
2517       Unique_Node_List not_used;
2518       in2_unique_inputs_cnt = collect_unique_inputs(in2, not_used, not_used);
2519     }
2520     // Pick the node with minimum number of inputs.
2521     if (in1_unique_inputs_cnt >= 3 && in2_unique_inputs_cnt >= 3) {
2522       return false; // still too many inputs
2523     }
2524     // Recompute partition & inputs.
2525     Node* child       = (in1_unique_inputs_cnt < in2_unique_inputs_cnt ? in1 : in2);
2526     collect_unique_inputs(child, partition, inputs);
2527 
2528     Node* other_input = (in1_unique_inputs_cnt < in2_unique_inputs_cnt ? in2 : in1);
2529     inputs.push(other_input);
2530 
2531     partition.push(n);
2532   }
2533 
2534   return (partition.size() == 2 || partition.size() == 3) &&
2535          (inputs.size()    == 2 || inputs.size()    == 3);
2536 }
2537 
2538 
process_logic_cone_root(PhaseIterGVN & igvn,Node * n,VectorSet & visited)2539 void Compile::process_logic_cone_root(PhaseIterGVN &igvn, Node *n, VectorSet &visited) {
2540   assert(is_vector_bitwise_op(n), "not a root");
2541 
2542   visited.set(n->_idx);
2543 
2544   // 1) Do a DFS walk over the logic cone.
2545   for (uint i = 1; i < n->req(); i++) {
2546     Node* in = n->in(i);
2547     if (!visited.test(in->_idx) && is_vector_bitwise_op(in)) {
2548       process_logic_cone_root(igvn, in, visited);
2549     }
2550   }
2551 
2552   // 2) Bottom up traversal: Merge node[s] with
2553   // the parent to form macro logic node.
2554   Unique_Node_List partition;
2555   Unique_Node_List inputs;
2556   if (compute_logic_cone(n, partition, inputs)) {
2557     const TypeVect* vt = n->bottom_type()->is_vect();
2558     Node* macro_logic = xform_to_MacroLogicV(igvn, vt, partition, inputs);
2559     igvn.replace_node(n, macro_logic);
2560   }
2561 }
2562 
optimize_logic_cones(PhaseIterGVN & igvn)2563 void Compile::optimize_logic_cones(PhaseIterGVN &igvn) {
2564   ResourceMark rm;
2565   if (Matcher::match_rule_supported(Op_MacroLogicV)) {
2566     Unique_Node_List list;
2567     collect_logic_cone_roots(list);
2568 
2569     while (list.size() > 0) {
2570       Node* n = list.pop();
2571       const TypeVect* vt = n->bottom_type()->is_vect();
2572       bool supported = Matcher::match_rule_supported_vector(Op_MacroLogicV, vt->length(), vt->element_basic_type());
2573       if (supported) {
2574         VectorSet visited(comp_arena());
2575         process_logic_cone_root(igvn, n, visited);
2576       }
2577     }
2578   }
2579 }
2580 
2581 //------------------------------Code_Gen---------------------------------------
2582 // Given a graph, generate code for it
Code_Gen()2583 void Compile::Code_Gen() {
2584   if (failing()) {
2585     return;
2586   }
2587 
2588   // Perform instruction selection.  You might think we could reclaim Matcher
2589   // memory PDQ, but actually the Matcher is used in generating spill code.
2590   // Internals of the Matcher (including some VectorSets) must remain live
2591   // for awhile - thus I cannot reclaim Matcher memory lest a VectorSet usage
2592   // set a bit in reclaimed memory.
2593 
2594   // In debug mode can dump m._nodes.dump() for mapping of ideal to machine
2595   // nodes.  Mapping is only valid at the root of each matched subtree.
2596   NOT_PRODUCT( verify_graph_edges(); )
2597 
2598   Matcher matcher;
2599   _matcher = &matcher;
2600   {
2601     TracePhase tp("matcher", &timers[_t_matcher]);
2602     matcher.match();
2603     if (failing()) {
2604       return;
2605     }
2606   }
2607 
2608   // In debug mode can dump m._nodes.dump() for mapping of ideal to machine
2609   // nodes.  Mapping is only valid at the root of each matched subtree.
2610   NOT_PRODUCT( verify_graph_edges(); )
2611 
2612   // If you have too many nodes, or if matching has failed, bail out
2613   check_node_count(0, "out of nodes matching instructions");
2614   if (failing()) {
2615     return;
2616   }
2617 
2618   print_method(PHASE_MATCHING, 2);
2619 
2620   // Build a proper-looking CFG
2621   PhaseCFG cfg(node_arena(), root(), matcher);
2622   _cfg = &cfg;
2623   {
2624     TracePhase tp("scheduler", &timers[_t_scheduler]);
2625     bool success = cfg.do_global_code_motion();
2626     if (!success) {
2627       return;
2628     }
2629 
2630     print_method(PHASE_GLOBAL_CODE_MOTION, 2);
2631     NOT_PRODUCT( verify_graph_edges(); )
2632     debug_only( cfg.verify(); )
2633   }
2634 
2635   PhaseChaitin regalloc(unique(), cfg, matcher, false);
2636   _regalloc = &regalloc;
2637   {
2638     TracePhase tp("regalloc", &timers[_t_registerAllocation]);
2639     // Perform register allocation.  After Chaitin, use-def chains are
2640     // no longer accurate (at spill code) and so must be ignored.
2641     // Node->LRG->reg mappings are still accurate.
2642     _regalloc->Register_Allocate();
2643 
2644     // Bail out if the allocator builds too many nodes
2645     if (failing()) {
2646       return;
2647     }
2648   }
2649 
2650   // Prior to register allocation we kept empty basic blocks in case the
2651   // the allocator needed a place to spill.  After register allocation we
2652   // are not adding any new instructions.  If any basic block is empty, we
2653   // can now safely remove it.
2654   {
2655     TracePhase tp("blockOrdering", &timers[_t_blockOrdering]);
2656     cfg.remove_empty_blocks();
2657     if (do_freq_based_layout()) {
2658       PhaseBlockLayout layout(cfg);
2659     } else {
2660       cfg.set_loop_alignment();
2661     }
2662     cfg.fixup_flow();
2663   }
2664 
2665   // Apply peephole optimizations
2666   if( OptoPeephole ) {
2667     TracePhase tp("peephole", &timers[_t_peephole]);
2668     PhasePeephole peep( _regalloc, cfg);
2669     peep.do_transform();
2670   }
2671 
2672   // Do late expand if CPU requires this.
2673   if (Matcher::require_postalloc_expand) {
2674     TracePhase tp("postalloc_expand", &timers[_t_postalloc_expand]);
2675     cfg.postalloc_expand(_regalloc);
2676   }
2677 
2678   // Convert Nodes to instruction bits in a buffer
2679   {
2680     TracePhase tp("output", &timers[_t_output]);
2681     PhaseOutput output;
2682     output.Output();
2683     if (failing())  return;
2684     output.install();
2685   }
2686 
2687   print_method(PHASE_FINAL_CODE);
2688 
2689   // He's dead, Jim.
2690   _cfg     = (PhaseCFG*)((intptr_t)0xdeadbeef);
2691   _regalloc = (PhaseChaitin*)((intptr_t)0xdeadbeef);
2692 }
2693 
2694 //------------------------------Final_Reshape_Counts---------------------------
2695 // This class defines counters to help identify when a method
2696 // may/must be executed using hardware with only 24-bit precision.
2697 struct Final_Reshape_Counts : public StackObj {
2698   int  _call_count;             // count non-inlined 'common' calls
2699   int  _float_count;            // count float ops requiring 24-bit precision
2700   int  _double_count;           // count double ops requiring more precision
2701   int  _java_call_count;        // count non-inlined 'java' calls
2702   int  _inner_loop_count;       // count loops which need alignment
2703   VectorSet _visited;           // Visitation flags
2704   Node_List _tests;             // Set of IfNodes & PCTableNodes
2705 
Final_Reshape_CountsFinal_Reshape_Counts2706   Final_Reshape_Counts() :
2707     _call_count(0), _float_count(0), _double_count(0),
2708     _java_call_count(0), _inner_loop_count(0),
2709     _visited( Thread::current()->resource_area() ) { }
2710 
inc_call_countFinal_Reshape_Counts2711   void inc_call_count  () { _call_count  ++; }
inc_float_countFinal_Reshape_Counts2712   void inc_float_count () { _float_count ++; }
inc_double_countFinal_Reshape_Counts2713   void inc_double_count() { _double_count++; }
inc_java_call_countFinal_Reshape_Counts2714   void inc_java_call_count() { _java_call_count++; }
inc_inner_loop_countFinal_Reshape_Counts2715   void inc_inner_loop_count() { _inner_loop_count++; }
2716 
get_call_countFinal_Reshape_Counts2717   int  get_call_count  () const { return _call_count  ; }
get_float_countFinal_Reshape_Counts2718   int  get_float_count () const { return _float_count ; }
get_double_countFinal_Reshape_Counts2719   int  get_double_count() const { return _double_count; }
get_java_call_countFinal_Reshape_Counts2720   int  get_java_call_count() const { return _java_call_count; }
get_inner_loop_countFinal_Reshape_Counts2721   int  get_inner_loop_count() const { return _inner_loop_count; }
2722 };
2723 
2724 #ifdef ASSERT
oop_offset_is_sane(const TypeInstPtr * tp)2725 static bool oop_offset_is_sane(const TypeInstPtr* tp) {
2726   ciInstanceKlass *k = tp->klass()->as_instance_klass();
2727   // Make sure the offset goes inside the instance layout.
2728   return k->contains_field_offset(tp->offset());
2729   // Note that OffsetBot and OffsetTop are very negative.
2730 }
2731 #endif
2732 
2733 // Eliminate trivially redundant StoreCMs and accumulate their
2734 // precedence edges.
eliminate_redundant_card_marks(Node * n)2735 void Compile::eliminate_redundant_card_marks(Node* n) {
2736   assert(n->Opcode() == Op_StoreCM, "expected StoreCM");
2737   if (n->in(MemNode::Address)->outcnt() > 1) {
2738     // There are multiple users of the same address so it might be
2739     // possible to eliminate some of the StoreCMs
2740     Node* mem = n->in(MemNode::Memory);
2741     Node* adr = n->in(MemNode::Address);
2742     Node* val = n->in(MemNode::ValueIn);
2743     Node* prev = n;
2744     bool done = false;
2745     // Walk the chain of StoreCMs eliminating ones that match.  As
2746     // long as it's a chain of single users then the optimization is
2747     // safe.  Eliminating partially redundant StoreCMs would require
2748     // cloning copies down the other paths.
2749     while (mem->Opcode() == Op_StoreCM && mem->outcnt() == 1 && !done) {
2750       if (adr == mem->in(MemNode::Address) &&
2751           val == mem->in(MemNode::ValueIn)) {
2752         // redundant StoreCM
2753         if (mem->req() > MemNode::OopStore) {
2754           // Hasn't been processed by this code yet.
2755           n->add_prec(mem->in(MemNode::OopStore));
2756         } else {
2757           // Already converted to precedence edge
2758           for (uint i = mem->req(); i < mem->len(); i++) {
2759             // Accumulate any precedence edges
2760             if (mem->in(i) != NULL) {
2761               n->add_prec(mem->in(i));
2762             }
2763           }
2764           // Everything above this point has been processed.
2765           done = true;
2766         }
2767         // Eliminate the previous StoreCM
2768         prev->set_req(MemNode::Memory, mem->in(MemNode::Memory));
2769         assert(mem->outcnt() == 0, "should be dead");
2770         mem->disconnect_inputs(NULL, this);
2771       } else {
2772         prev = mem;
2773       }
2774       mem = prev->in(MemNode::Memory);
2775     }
2776   }
2777 }
2778 
2779 //------------------------------final_graph_reshaping_impl----------------------
2780 // Implement items 1-5 from final_graph_reshaping below.
final_graph_reshaping_impl(Node * n,Final_Reshape_Counts & frc)2781 void Compile::final_graph_reshaping_impl( Node *n, Final_Reshape_Counts &frc) {
2782 
2783   if ( n->outcnt() == 0 ) return; // dead node
2784   uint nop = n->Opcode();
2785 
2786   // Check for 2-input instruction with "last use" on right input.
2787   // Swap to left input.  Implements item (2).
2788   if( n->req() == 3 &&          // two-input instruction
2789       n->in(1)->outcnt() > 1 && // left use is NOT a last use
2790       (!n->in(1)->is_Phi() || n->in(1)->in(2) != n) && // it is not data loop
2791       n->in(2)->outcnt() == 1 &&// right use IS a last use
2792       !n->in(2)->is_Con() ) {   // right use is not a constant
2793     // Check for commutative opcode
2794     switch( nop ) {
2795     case Op_AddI:  case Op_AddF:  case Op_AddD:  case Op_AddL:
2796     case Op_MaxI:  case Op_MinI:
2797     case Op_MulI:  case Op_MulF:  case Op_MulD:  case Op_MulL:
2798     case Op_AndL:  case Op_XorL:  case Op_OrL:
2799     case Op_AndI:  case Op_XorI:  case Op_OrI: {
2800       // Move "last use" input to left by swapping inputs
2801       n->swap_edges(1, 2);
2802       break;
2803     }
2804     default:
2805       break;
2806     }
2807   }
2808 
2809 #ifdef ASSERT
2810   if( n->is_Mem() ) {
2811     int alias_idx = get_alias_index(n->as_Mem()->adr_type());
2812     assert( n->in(0) != NULL || alias_idx != Compile::AliasIdxRaw ||
2813             // oop will be recorded in oop map if load crosses safepoint
2814             n->is_Load() && (n->as_Load()->bottom_type()->isa_oopptr() ||
2815                              LoadNode::is_immutable_value(n->in(MemNode::Address))),
2816             "raw memory operations should have control edge");
2817   }
2818   if (n->is_MemBar()) {
2819     MemBarNode* mb = n->as_MemBar();
2820     if (mb->trailing_store() || mb->trailing_load_store()) {
2821       assert(mb->leading_membar()->trailing_membar() == mb, "bad membar pair");
2822       Node* mem = BarrierSet::barrier_set()->barrier_set_c2()->step_over_gc_barrier(mb->in(MemBarNode::Precedent));
2823       assert((mb->trailing_store() && mem->is_Store() && mem->as_Store()->is_release()) ||
2824              (mb->trailing_load_store() && mem->is_LoadStore()), "missing mem op");
2825     } else if (mb->leading()) {
2826       assert(mb->trailing_membar()->leading_membar() == mb, "bad membar pair");
2827     }
2828   }
2829 #endif
2830   // Count FPU ops and common calls, implements item (3)
2831   bool gc_handled = BarrierSet::barrier_set()->barrier_set_c2()->final_graph_reshaping(this, n, nop);
2832   if (!gc_handled) {
2833     final_graph_reshaping_main_switch(n, frc, nop);
2834   }
2835 
2836   // Collect CFG split points
2837   if (n->is_MultiBranch() && !n->is_RangeCheck()) {
2838     frc._tests.push(n);
2839   }
2840 }
2841 
final_graph_reshaping_main_switch(Node * n,Final_Reshape_Counts & frc,uint nop)2842 void Compile::final_graph_reshaping_main_switch(Node* n, Final_Reshape_Counts& frc, uint nop) {
2843   switch( nop ) {
2844   // Count all float operations that may use FPU
2845   case Op_AddF:
2846   case Op_SubF:
2847   case Op_MulF:
2848   case Op_DivF:
2849   case Op_NegF:
2850   case Op_ModF:
2851   case Op_ConvI2F:
2852   case Op_ConF:
2853   case Op_CmpF:
2854   case Op_CmpF3:
2855   // case Op_ConvL2F: // longs are split into 32-bit halves
2856     frc.inc_float_count();
2857     break;
2858 
2859   case Op_ConvF2D:
2860   case Op_ConvD2F:
2861     frc.inc_float_count();
2862     frc.inc_double_count();
2863     break;
2864 
2865   // Count all double operations that may use FPU
2866   case Op_AddD:
2867   case Op_SubD:
2868   case Op_MulD:
2869   case Op_DivD:
2870   case Op_NegD:
2871   case Op_ModD:
2872   case Op_ConvI2D:
2873   case Op_ConvD2I:
2874   // case Op_ConvL2D: // handled by leaf call
2875   // case Op_ConvD2L: // handled by leaf call
2876   case Op_ConD:
2877   case Op_CmpD:
2878   case Op_CmpD3:
2879     frc.inc_double_count();
2880     break;
2881   case Op_Opaque1:              // Remove Opaque Nodes before matching
2882   case Op_Opaque2:              // Remove Opaque Nodes before matching
2883   case Op_Opaque3:
2884     n->subsume_by(n->in(1), this);
2885     break;
2886   case Op_CallStaticJava:
2887   case Op_CallJava:
2888   case Op_CallDynamicJava:
2889     frc.inc_java_call_count(); // Count java call site;
2890   case Op_CallRuntime:
2891   case Op_CallLeaf:
2892   case Op_CallLeafNoFP: {
2893     assert (n->is_Call(), "");
2894     CallNode *call = n->as_Call();
2895     // Count call sites where the FP mode bit would have to be flipped.
2896     // Do not count uncommon runtime calls:
2897     // uncommon_trap, _complete_monitor_locking, _complete_monitor_unlocking,
2898     // _new_Java, _new_typeArray, _new_objArray, _rethrow_Java, ...
2899     if (!call->is_CallStaticJava() || !call->as_CallStaticJava()->_name) {
2900       frc.inc_call_count();   // Count the call site
2901     } else {                  // See if uncommon argument is shared
2902       Node *n = call->in(TypeFunc::Parms);
2903       int nop = n->Opcode();
2904       // Clone shared simple arguments to uncommon calls, item (1).
2905       if (n->outcnt() > 1 &&
2906           !n->is_Proj() &&
2907           nop != Op_CreateEx &&
2908           nop != Op_CheckCastPP &&
2909           nop != Op_DecodeN &&
2910           nop != Op_DecodeNKlass &&
2911           !n->is_Mem() &&
2912           !n->is_Phi()) {
2913         Node *x = n->clone();
2914         call->set_req(TypeFunc::Parms, x);
2915       }
2916     }
2917     break;
2918   }
2919 
2920   case Op_StoreD:
2921   case Op_LoadD:
2922   case Op_LoadD_unaligned:
2923     frc.inc_double_count();
2924     goto handle_mem;
2925   case Op_StoreF:
2926   case Op_LoadF:
2927     frc.inc_float_count();
2928     goto handle_mem;
2929 
2930   case Op_StoreCM:
2931     {
2932       // Convert OopStore dependence into precedence edge
2933       Node* prec = n->in(MemNode::OopStore);
2934       n->del_req(MemNode::OopStore);
2935       n->add_prec(prec);
2936       eliminate_redundant_card_marks(n);
2937     }
2938 
2939     // fall through
2940 
2941   case Op_StoreB:
2942   case Op_StoreC:
2943   case Op_StorePConditional:
2944   case Op_StoreI:
2945   case Op_StoreL:
2946   case Op_StoreIConditional:
2947   case Op_StoreLConditional:
2948   case Op_CompareAndSwapB:
2949   case Op_CompareAndSwapS:
2950   case Op_CompareAndSwapI:
2951   case Op_CompareAndSwapL:
2952   case Op_CompareAndSwapP:
2953   case Op_CompareAndSwapN:
2954   case Op_WeakCompareAndSwapB:
2955   case Op_WeakCompareAndSwapS:
2956   case Op_WeakCompareAndSwapI:
2957   case Op_WeakCompareAndSwapL:
2958   case Op_WeakCompareAndSwapP:
2959   case Op_WeakCompareAndSwapN:
2960   case Op_CompareAndExchangeB:
2961   case Op_CompareAndExchangeS:
2962   case Op_CompareAndExchangeI:
2963   case Op_CompareAndExchangeL:
2964   case Op_CompareAndExchangeP:
2965   case Op_CompareAndExchangeN:
2966   case Op_GetAndAddS:
2967   case Op_GetAndAddB:
2968   case Op_GetAndAddI:
2969   case Op_GetAndAddL:
2970   case Op_GetAndSetS:
2971   case Op_GetAndSetB:
2972   case Op_GetAndSetI:
2973   case Op_GetAndSetL:
2974   case Op_GetAndSetP:
2975   case Op_GetAndSetN:
2976   case Op_StoreP:
2977   case Op_StoreN:
2978   case Op_StoreNKlass:
2979   case Op_LoadB:
2980   case Op_LoadUB:
2981   case Op_LoadUS:
2982   case Op_LoadI:
2983   case Op_LoadKlass:
2984   case Op_LoadNKlass:
2985   case Op_LoadL:
2986   case Op_LoadL_unaligned:
2987   case Op_LoadPLocked:
2988   case Op_LoadP:
2989   case Op_LoadN:
2990   case Op_LoadRange:
2991   case Op_LoadS: {
2992   handle_mem:
2993 #ifdef ASSERT
2994     if( VerifyOptoOopOffsets ) {
2995       MemNode* mem  = n->as_Mem();
2996       // Check to see if address types have grounded out somehow.
2997       const TypeInstPtr *tp = mem->in(MemNode::Address)->bottom_type()->isa_instptr();
2998       assert( !tp || oop_offset_is_sane(tp), "" );
2999     }
3000 #endif
3001     break;
3002   }
3003 
3004   case Op_AddP: {               // Assert sane base pointers
3005     Node *addp = n->in(AddPNode::Address);
3006     assert( !addp->is_AddP() ||
3007             addp->in(AddPNode::Base)->is_top() || // Top OK for allocation
3008             addp->in(AddPNode::Base) == n->in(AddPNode::Base),
3009             "Base pointers must match (addp %u)", addp->_idx );
3010 #ifdef _LP64
3011     if ((UseCompressedOops || UseCompressedClassPointers) &&
3012         addp->Opcode() == Op_ConP &&
3013         addp == n->in(AddPNode::Base) &&
3014         n->in(AddPNode::Offset)->is_Con()) {
3015       // If the transformation of ConP to ConN+DecodeN is beneficial depends
3016       // on the platform and on the compressed oops mode.
3017       // Use addressing with narrow klass to load with offset on x86.
3018       // Some platforms can use the constant pool to load ConP.
3019       // Do this transformation here since IGVN will convert ConN back to ConP.
3020       const Type* t = addp->bottom_type();
3021       bool is_oop   = t->isa_oopptr() != NULL;
3022       bool is_klass = t->isa_klassptr() != NULL;
3023 
3024       if ((is_oop   && Matcher::const_oop_prefer_decode()  ) ||
3025           (is_klass && Matcher::const_klass_prefer_decode())) {
3026         Node* nn = NULL;
3027 
3028         int op = is_oop ? Op_ConN : Op_ConNKlass;
3029 
3030         // Look for existing ConN node of the same exact type.
3031         Node* r  = root();
3032         uint cnt = r->outcnt();
3033         for (uint i = 0; i < cnt; i++) {
3034           Node* m = r->raw_out(i);
3035           if (m!= NULL && m->Opcode() == op &&
3036               m->bottom_type()->make_ptr() == t) {
3037             nn = m;
3038             break;
3039           }
3040         }
3041         if (nn != NULL) {
3042           // Decode a narrow oop to match address
3043           // [R12 + narrow_oop_reg<<3 + offset]
3044           if (is_oop) {
3045             nn = new DecodeNNode(nn, t);
3046           } else {
3047             nn = new DecodeNKlassNode(nn, t);
3048           }
3049           // Check for succeeding AddP which uses the same Base.
3050           // Otherwise we will run into the assertion above when visiting that guy.
3051           for (uint i = 0; i < n->outcnt(); ++i) {
3052             Node *out_i = n->raw_out(i);
3053             if (out_i && out_i->is_AddP() && out_i->in(AddPNode::Base) == addp) {
3054               out_i->set_req(AddPNode::Base, nn);
3055 #ifdef ASSERT
3056               for (uint j = 0; j < out_i->outcnt(); ++j) {
3057                 Node *out_j = out_i->raw_out(j);
3058                 assert(out_j == NULL || !out_j->is_AddP() || out_j->in(AddPNode::Base) != addp,
3059                        "more than 2 AddP nodes in a chain (out_j %u)", out_j->_idx);
3060               }
3061 #endif
3062             }
3063           }
3064           n->set_req(AddPNode::Base, nn);
3065           n->set_req(AddPNode::Address, nn);
3066           if (addp->outcnt() == 0) {
3067             addp->disconnect_inputs(NULL, this);
3068           }
3069         }
3070       }
3071     }
3072 #endif
3073     // platform dependent reshaping of the address expression
3074     reshape_address(n->as_AddP());
3075     break;
3076   }
3077 
3078   case Op_CastPP: {
3079     // Remove CastPP nodes to gain more freedom during scheduling but
3080     // keep the dependency they encode as control or precedence edges
3081     // (if control is set already) on memory operations. Some CastPP
3082     // nodes don't have a control (don't carry a dependency): skip
3083     // those.
3084     if (n->in(0) != NULL) {
3085       ResourceMark rm;
3086       Unique_Node_List wq;
3087       wq.push(n);
3088       for (uint next = 0; next < wq.size(); ++next) {
3089         Node *m = wq.at(next);
3090         for (DUIterator_Fast imax, i = m->fast_outs(imax); i < imax; i++) {
3091           Node* use = m->fast_out(i);
3092           if (use->is_Mem() || use->is_EncodeNarrowPtr()) {
3093             use->ensure_control_or_add_prec(n->in(0));
3094           } else {
3095             switch(use->Opcode()) {
3096             case Op_AddP:
3097             case Op_DecodeN:
3098             case Op_DecodeNKlass:
3099             case Op_CheckCastPP:
3100             case Op_CastPP:
3101               wq.push(use);
3102               break;
3103             }
3104           }
3105         }
3106       }
3107     }
3108     const bool is_LP64 = LP64_ONLY(true) NOT_LP64(false);
3109     if (is_LP64 && n->in(1)->is_DecodeN() && Matcher::gen_narrow_oop_implicit_null_checks()) {
3110       Node* in1 = n->in(1);
3111       const Type* t = n->bottom_type();
3112       Node* new_in1 = in1->clone();
3113       new_in1->as_DecodeN()->set_type(t);
3114 
3115       if (!Matcher::narrow_oop_use_complex_address()) {
3116         //
3117         // x86, ARM and friends can handle 2 adds in addressing mode
3118         // and Matcher can fold a DecodeN node into address by using
3119         // a narrow oop directly and do implicit NULL check in address:
3120         //
3121         // [R12 + narrow_oop_reg<<3 + offset]
3122         // NullCheck narrow_oop_reg
3123         //
3124         // On other platforms (Sparc) we have to keep new DecodeN node and
3125         // use it to do implicit NULL check in address:
3126         //
3127         // decode_not_null narrow_oop_reg, base_reg
3128         // [base_reg + offset]
3129         // NullCheck base_reg
3130         //
3131         // Pin the new DecodeN node to non-null path on these platform (Sparc)
3132         // to keep the information to which NULL check the new DecodeN node
3133         // corresponds to use it as value in implicit_null_check().
3134         //
3135         new_in1->set_req(0, n->in(0));
3136       }
3137 
3138       n->subsume_by(new_in1, this);
3139       if (in1->outcnt() == 0) {
3140         in1->disconnect_inputs(NULL, this);
3141       }
3142     } else {
3143       n->subsume_by(n->in(1), this);
3144       if (n->outcnt() == 0) {
3145         n->disconnect_inputs(NULL, this);
3146       }
3147     }
3148     break;
3149   }
3150 #ifdef _LP64
3151   case Op_CmpP:
3152     // Do this transformation here to preserve CmpPNode::sub() and
3153     // other TypePtr related Ideal optimizations (for example, ptr nullness).
3154     if (n->in(1)->is_DecodeNarrowPtr() || n->in(2)->is_DecodeNarrowPtr()) {
3155       Node* in1 = n->in(1);
3156       Node* in2 = n->in(2);
3157       if (!in1->is_DecodeNarrowPtr()) {
3158         in2 = in1;
3159         in1 = n->in(2);
3160       }
3161       assert(in1->is_DecodeNarrowPtr(), "sanity");
3162 
3163       Node* new_in2 = NULL;
3164       if (in2->is_DecodeNarrowPtr()) {
3165         assert(in2->Opcode() == in1->Opcode(), "must be same node type");
3166         new_in2 = in2->in(1);
3167       } else if (in2->Opcode() == Op_ConP) {
3168         const Type* t = in2->bottom_type();
3169         if (t == TypePtr::NULL_PTR) {
3170           assert(in1->is_DecodeN(), "compare klass to null?");
3171           // Don't convert CmpP null check into CmpN if compressed
3172           // oops implicit null check is not generated.
3173           // This will allow to generate normal oop implicit null check.
3174           if (Matcher::gen_narrow_oop_implicit_null_checks())
3175             new_in2 = ConNode::make(TypeNarrowOop::NULL_PTR);
3176           //
3177           // This transformation together with CastPP transformation above
3178           // will generated code for implicit NULL checks for compressed oops.
3179           //
3180           // The original code after Optimize()
3181           //
3182           //    LoadN memory, narrow_oop_reg
3183           //    decode narrow_oop_reg, base_reg
3184           //    CmpP base_reg, NULL
3185           //    CastPP base_reg // NotNull
3186           //    Load [base_reg + offset], val_reg
3187           //
3188           // after these transformations will be
3189           //
3190           //    LoadN memory, narrow_oop_reg
3191           //    CmpN narrow_oop_reg, NULL
3192           //    decode_not_null narrow_oop_reg, base_reg
3193           //    Load [base_reg + offset], val_reg
3194           //
3195           // and the uncommon path (== NULL) will use narrow_oop_reg directly
3196           // since narrow oops can be used in debug info now (see the code in
3197           // final_graph_reshaping_walk()).
3198           //
3199           // At the end the code will be matched to
3200           // on x86:
3201           //
3202           //    Load_narrow_oop memory, narrow_oop_reg
3203           //    Load [R12 + narrow_oop_reg<<3 + offset], val_reg
3204           //    NullCheck narrow_oop_reg
3205           //
3206           // and on sparc:
3207           //
3208           //    Load_narrow_oop memory, narrow_oop_reg
3209           //    decode_not_null narrow_oop_reg, base_reg
3210           //    Load [base_reg + offset], val_reg
3211           //    NullCheck base_reg
3212           //
3213         } else if (t->isa_oopptr()) {
3214           new_in2 = ConNode::make(t->make_narrowoop());
3215         } else if (t->isa_klassptr()) {
3216           new_in2 = ConNode::make(t->make_narrowklass());
3217         }
3218       }
3219       if (new_in2 != NULL) {
3220         Node* cmpN = new CmpNNode(in1->in(1), new_in2);
3221         n->subsume_by(cmpN, this);
3222         if (in1->outcnt() == 0) {
3223           in1->disconnect_inputs(NULL, this);
3224         }
3225         if (in2->outcnt() == 0) {
3226           in2->disconnect_inputs(NULL, this);
3227         }
3228       }
3229     }
3230     break;
3231 
3232   case Op_DecodeN:
3233   case Op_DecodeNKlass:
3234     assert(!n->in(1)->is_EncodeNarrowPtr(), "should be optimized out");
3235     // DecodeN could be pinned when it can't be fold into
3236     // an address expression, see the code for Op_CastPP above.
3237     assert(n->in(0) == NULL || (UseCompressedOops && !Matcher::narrow_oop_use_complex_address()), "no control");
3238     break;
3239 
3240   case Op_EncodeP:
3241   case Op_EncodePKlass: {
3242     Node* in1 = n->in(1);
3243     if (in1->is_DecodeNarrowPtr()) {
3244       n->subsume_by(in1->in(1), this);
3245     } else if (in1->Opcode() == Op_ConP) {
3246       const Type* t = in1->bottom_type();
3247       if (t == TypePtr::NULL_PTR) {
3248         assert(t->isa_oopptr(), "null klass?");
3249         n->subsume_by(ConNode::make(TypeNarrowOop::NULL_PTR), this);
3250       } else if (t->isa_oopptr()) {
3251         n->subsume_by(ConNode::make(t->make_narrowoop()), this);
3252       } else if (t->isa_klassptr()) {
3253         n->subsume_by(ConNode::make(t->make_narrowklass()), this);
3254       }
3255     }
3256     if (in1->outcnt() == 0) {
3257       in1->disconnect_inputs(NULL, this);
3258     }
3259     break;
3260   }
3261 
3262   case Op_Proj: {
3263     if (OptimizeStringConcat) {
3264       ProjNode* p = n->as_Proj();
3265       if (p->_is_io_use) {
3266         // Separate projections were used for the exception path which
3267         // are normally removed by a late inline.  If it wasn't inlined
3268         // then they will hang around and should just be replaced with
3269         // the original one.
3270         Node* proj = NULL;
3271         // Replace with just one
3272         for (SimpleDUIterator i(p->in(0)); i.has_next(); i.next()) {
3273           Node *use = i.get();
3274           if (use->is_Proj() && p != use && use->as_Proj()->_con == p->_con) {
3275             proj = use;
3276             break;
3277           }
3278         }
3279         assert(proj != NULL || p->_con == TypeFunc::I_O, "io may be dropped at an infinite loop");
3280         if (proj != NULL) {
3281           p->subsume_by(proj, this);
3282         }
3283       }
3284     }
3285     break;
3286   }
3287 
3288   case Op_Phi:
3289     if (n->as_Phi()->bottom_type()->isa_narrowoop() || n->as_Phi()->bottom_type()->isa_narrowklass()) {
3290       // The EncodeP optimization may create Phi with the same edges
3291       // for all paths. It is not handled well by Register Allocator.
3292       Node* unique_in = n->in(1);
3293       assert(unique_in != NULL, "");
3294       uint cnt = n->req();
3295       for (uint i = 2; i < cnt; i++) {
3296         Node* m = n->in(i);
3297         assert(m != NULL, "");
3298         if (unique_in != m)
3299           unique_in = NULL;
3300       }
3301       if (unique_in != NULL) {
3302         n->subsume_by(unique_in, this);
3303       }
3304     }
3305     break;
3306 
3307 #endif
3308 
3309 #ifdef ASSERT
3310   case Op_CastII:
3311     // Verify that all range check dependent CastII nodes were removed.
3312     if (n->isa_CastII()->has_range_check()) {
3313       n->dump(3);
3314       assert(false, "Range check dependent CastII node was not removed");
3315     }
3316     break;
3317 #endif
3318 
3319   case Op_ModI:
3320     if (UseDivMod) {
3321       // Check if a%b and a/b both exist
3322       Node* d = n->find_similar(Op_DivI);
3323       if (d) {
3324         // Replace them with a fused divmod if supported
3325         if (Matcher::has_match_rule(Op_DivModI)) {
3326           DivModINode* divmod = DivModINode::make(n);
3327           d->subsume_by(divmod->div_proj(), this);
3328           n->subsume_by(divmod->mod_proj(), this);
3329         } else {
3330           // replace a%b with a-((a/b)*b)
3331           Node* mult = new MulINode(d, d->in(2));
3332           Node* sub  = new SubINode(d->in(1), mult);
3333           n->subsume_by(sub, this);
3334         }
3335       }
3336     }
3337     break;
3338 
3339   case Op_ModL:
3340     if (UseDivMod) {
3341       // Check if a%b and a/b both exist
3342       Node* d = n->find_similar(Op_DivL);
3343       if (d) {
3344         // Replace them with a fused divmod if supported
3345         if (Matcher::has_match_rule(Op_DivModL)) {
3346           DivModLNode* divmod = DivModLNode::make(n);
3347           d->subsume_by(divmod->div_proj(), this);
3348           n->subsume_by(divmod->mod_proj(), this);
3349         } else {
3350           // replace a%b with a-((a/b)*b)
3351           Node* mult = new MulLNode(d, d->in(2));
3352           Node* sub  = new SubLNode(d->in(1), mult);
3353           n->subsume_by(sub, this);
3354         }
3355       }
3356     }
3357     break;
3358 
3359   case Op_LoadVector:
3360   case Op_StoreVector:
3361     break;
3362 
3363   case Op_AddReductionVI:
3364   case Op_AddReductionVL:
3365   case Op_AddReductionVF:
3366   case Op_AddReductionVD:
3367   case Op_MulReductionVI:
3368   case Op_MulReductionVL:
3369   case Op_MulReductionVF:
3370   case Op_MulReductionVD:
3371   case Op_MinReductionV:
3372   case Op_MaxReductionV:
3373   case Op_AndReductionV:
3374   case Op_OrReductionV:
3375   case Op_XorReductionV:
3376     break;
3377 
3378   case Op_PackB:
3379   case Op_PackS:
3380   case Op_PackI:
3381   case Op_PackF:
3382   case Op_PackL:
3383   case Op_PackD:
3384     if (n->req()-1 > 2) {
3385       // Replace many operand PackNodes with a binary tree for matching
3386       PackNode* p = (PackNode*) n;
3387       Node* btp = p->binary_tree_pack(1, n->req());
3388       n->subsume_by(btp, this);
3389     }
3390     break;
3391   case Op_Loop:
3392   case Op_CountedLoop:
3393   case Op_OuterStripMinedLoop:
3394     if (n->as_Loop()->is_inner_loop()) {
3395       frc.inc_inner_loop_count();
3396     }
3397     n->as_Loop()->verify_strip_mined(0);
3398     break;
3399   case Op_LShiftI:
3400   case Op_RShiftI:
3401   case Op_URShiftI:
3402   case Op_LShiftL:
3403   case Op_RShiftL:
3404   case Op_URShiftL:
3405     if (Matcher::need_masked_shift_count) {
3406       // The cpu's shift instructions don't restrict the count to the
3407       // lower 5/6 bits. We need to do the masking ourselves.
3408       Node* in2 = n->in(2);
3409       juint mask = (n->bottom_type() == TypeInt::INT) ? (BitsPerInt - 1) : (BitsPerLong - 1);
3410       const TypeInt* t = in2->find_int_type();
3411       if (t != NULL && t->is_con()) {
3412         juint shift = t->get_con();
3413         if (shift > mask) { // Unsigned cmp
3414           n->set_req(2, ConNode::make(TypeInt::make(shift & mask)));
3415         }
3416       } else {
3417         if (t == NULL || t->_lo < 0 || t->_hi > (int)mask) {
3418           Node* shift = new AndINode(in2, ConNode::make(TypeInt::make(mask)));
3419           n->set_req(2, shift);
3420         }
3421       }
3422       if (in2->outcnt() == 0) { // Remove dead node
3423         in2->disconnect_inputs(NULL, this);
3424       }
3425     }
3426     break;
3427   case Op_MemBarStoreStore:
3428   case Op_MemBarRelease:
3429     // Break the link with AllocateNode: it is no longer useful and
3430     // confuses register allocation.
3431     if (n->req() > MemBarNode::Precedent) {
3432       n->set_req(MemBarNode::Precedent, top());
3433     }
3434     break;
3435   case Op_MemBarAcquire: {
3436     if (n->as_MemBar()->trailing_load() && n->req() > MemBarNode::Precedent) {
3437       // At parse time, the trailing MemBarAcquire for a volatile load
3438       // is created with an edge to the load. After optimizations,
3439       // that input may be a chain of Phis. If those phis have no
3440       // other use, then the MemBarAcquire keeps them alive and
3441       // register allocation can be confused.
3442       ResourceMark rm;
3443       Unique_Node_List wq;
3444       wq.push(n->in(MemBarNode::Precedent));
3445       n->set_req(MemBarNode::Precedent, top());
3446       while (wq.size() > 0) {
3447         Node* m = wq.pop();
3448         if (m->outcnt() == 0) {
3449           for (uint j = 0; j < m->req(); j++) {
3450             Node* in = m->in(j);
3451             if (in != NULL) {
3452               wq.push(in);
3453             }
3454           }
3455           m->disconnect_inputs(NULL, this);
3456         }
3457       }
3458     }
3459     break;
3460   }
3461   case Op_RangeCheck: {
3462     RangeCheckNode* rc = n->as_RangeCheck();
3463     Node* iff = new IfNode(rc->in(0), rc->in(1), rc->_prob, rc->_fcnt);
3464     n->subsume_by(iff, this);
3465     frc._tests.push(iff);
3466     break;
3467   }
3468   case Op_ConvI2L: {
3469     if (!Matcher::convi2l_type_required) {
3470       // Code generation on some platforms doesn't need accurate
3471       // ConvI2L types. Widening the type can help remove redundant
3472       // address computations.
3473       n->as_Type()->set_type(TypeLong::INT);
3474       ResourceMark rm;
3475       Unique_Node_List wq;
3476       wq.push(n);
3477       for (uint next = 0; next < wq.size(); next++) {
3478         Node *m = wq.at(next);
3479 
3480         for(;;) {
3481           // Loop over all nodes with identical inputs edges as m
3482           Node* k = m->find_similar(m->Opcode());
3483           if (k == NULL) {
3484             break;
3485           }
3486           // Push their uses so we get a chance to remove node made
3487           // redundant
3488           for (DUIterator_Fast imax, i = k->fast_outs(imax); i < imax; i++) {
3489             Node* u = k->fast_out(i);
3490             if (u->Opcode() == Op_LShiftL ||
3491                 u->Opcode() == Op_AddL ||
3492                 u->Opcode() == Op_SubL ||
3493                 u->Opcode() == Op_AddP) {
3494               wq.push(u);
3495             }
3496           }
3497           // Replace all nodes with identical edges as m with m
3498           k->subsume_by(m, this);
3499         }
3500       }
3501     }
3502     break;
3503   }
3504   case Op_CmpUL: {
3505     if (!Matcher::has_match_rule(Op_CmpUL)) {
3506       // No support for unsigned long comparisons
3507       ConINode* sign_pos = new ConINode(TypeInt::make(BitsPerLong - 1));
3508       Node* sign_bit_mask = new RShiftLNode(n->in(1), sign_pos);
3509       Node* orl = new OrLNode(n->in(1), sign_bit_mask);
3510       ConLNode* remove_sign_mask = new ConLNode(TypeLong::make(max_jlong));
3511       Node* andl = new AndLNode(orl, remove_sign_mask);
3512       Node* cmp = new CmpLNode(andl, n->in(2));
3513       n->subsume_by(cmp, this);
3514     }
3515     break;
3516   }
3517   default:
3518     assert(!n->is_Call(), "");
3519     assert(!n->is_Mem(), "");
3520     assert(nop != Op_ProfileBoolean, "should be eliminated during IGVN");
3521     break;
3522   }
3523 }
3524 
3525 //------------------------------final_graph_reshaping_walk---------------------
3526 // Replacing Opaque nodes with their input in final_graph_reshaping_impl(),
3527 // requires that the walk visits a node's inputs before visiting the node.
final_graph_reshaping_walk(Node_Stack & nstack,Node * root,Final_Reshape_Counts & frc)3528 void Compile::final_graph_reshaping_walk( Node_Stack &nstack, Node *root, Final_Reshape_Counts &frc ) {
3529   ResourceArea *area = Thread::current()->resource_area();
3530   Unique_Node_List sfpt(area);
3531 
3532   frc._visited.set(root->_idx); // first, mark node as visited
3533   uint cnt = root->req();
3534   Node *n = root;
3535   uint  i = 0;
3536   while (true) {
3537     if (i < cnt) {
3538       // Place all non-visited non-null inputs onto stack
3539       Node* m = n->in(i);
3540       ++i;
3541       if (m != NULL && !frc._visited.test_set(m->_idx)) {
3542         if (m->is_SafePoint() && m->as_SafePoint()->jvms() != NULL) {
3543           // compute worst case interpreter size in case of a deoptimization
3544           update_interpreter_frame_size(m->as_SafePoint()->jvms()->interpreter_frame_size());
3545 
3546           sfpt.push(m);
3547         }
3548         cnt = m->req();
3549         nstack.push(n, i); // put on stack parent and next input's index
3550         n = m;
3551         i = 0;
3552       }
3553     } else {
3554       // Now do post-visit work
3555       final_graph_reshaping_impl( n, frc );
3556       if (nstack.is_empty())
3557         break;             // finished
3558       n = nstack.node();   // Get node from stack
3559       cnt = n->req();
3560       i = nstack.index();
3561       nstack.pop();        // Shift to the next node on stack
3562     }
3563   }
3564 
3565   // Skip next transformation if compressed oops are not used.
3566   if ((UseCompressedOops && !Matcher::gen_narrow_oop_implicit_null_checks()) ||
3567       (!UseCompressedOops && !UseCompressedClassPointers))
3568     return;
3569 
3570   // Go over safepoints nodes to skip DecodeN/DecodeNKlass nodes for debug edges.
3571   // It could be done for an uncommon traps or any safepoints/calls
3572   // if the DecodeN/DecodeNKlass node is referenced only in a debug info.
3573   while (sfpt.size() > 0) {
3574     n = sfpt.pop();
3575     JVMState *jvms = n->as_SafePoint()->jvms();
3576     assert(jvms != NULL, "sanity");
3577     int start = jvms->debug_start();
3578     int end   = n->req();
3579     bool is_uncommon = (n->is_CallStaticJava() &&
3580                         n->as_CallStaticJava()->uncommon_trap_request() != 0);
3581     for (int j = start; j < end; j++) {
3582       Node* in = n->in(j);
3583       if (in->is_DecodeNarrowPtr()) {
3584         bool safe_to_skip = true;
3585         if (!is_uncommon ) {
3586           // Is it safe to skip?
3587           for (uint i = 0; i < in->outcnt(); i++) {
3588             Node* u = in->raw_out(i);
3589             if (!u->is_SafePoint() ||
3590                 (u->is_Call() && u->as_Call()->has_non_debug_use(n))) {
3591               safe_to_skip = false;
3592             }
3593           }
3594         }
3595         if (safe_to_skip) {
3596           n->set_req(j, in->in(1));
3597         }
3598         if (in->outcnt() == 0) {
3599           in->disconnect_inputs(NULL, this);
3600         }
3601       }
3602     }
3603   }
3604 }
3605 
3606 //------------------------------final_graph_reshaping--------------------------
3607 // Final Graph Reshaping.
3608 //
3609 // (1) Clone simple inputs to uncommon calls, so they can be scheduled late
3610 //     and not commoned up and forced early.  Must come after regular
3611 //     optimizations to avoid GVN undoing the cloning.  Clone constant
3612 //     inputs to Loop Phis; these will be split by the allocator anyways.
3613 //     Remove Opaque nodes.
3614 // (2) Move last-uses by commutative operations to the left input to encourage
3615 //     Intel update-in-place two-address operations and better register usage
3616 //     on RISCs.  Must come after regular optimizations to avoid GVN Ideal
3617 //     calls canonicalizing them back.
3618 // (3) Count the number of double-precision FP ops, single-precision FP ops
3619 //     and call sites.  On Intel, we can get correct rounding either by
3620 //     forcing singles to memory (requires extra stores and loads after each
3621 //     FP bytecode) or we can set a rounding mode bit (requires setting and
3622 //     clearing the mode bit around call sites).  The mode bit is only used
3623 //     if the relative frequency of single FP ops to calls is low enough.
3624 //     This is a key transform for SPEC mpeg_audio.
3625 // (4) Detect infinite loops; blobs of code reachable from above but not
3626 //     below.  Several of the Code_Gen algorithms fail on such code shapes,
3627 //     so we simply bail out.  Happens a lot in ZKM.jar, but also happens
3628 //     from time to time in other codes (such as -Xcomp finalizer loops, etc).
3629 //     Detection is by looking for IfNodes where only 1 projection is
3630 //     reachable from below or CatchNodes missing some targets.
3631 // (5) Assert for insane oop offsets in debug mode.
3632 
final_graph_reshaping()3633 bool Compile::final_graph_reshaping() {
3634   // an infinite loop may have been eliminated by the optimizer,
3635   // in which case the graph will be empty.
3636   if (root()->req() == 1) {
3637     record_method_not_compilable("trivial infinite loop");
3638     return true;
3639   }
3640 
3641   // Expensive nodes have their control input set to prevent the GVN
3642   // from freely commoning them. There's no GVN beyond this point so
3643   // no need to keep the control input. We want the expensive nodes to
3644   // be freely moved to the least frequent code path by gcm.
3645   assert(OptimizeExpensiveOps || expensive_count() == 0, "optimization off but list non empty?");
3646   for (int i = 0; i < expensive_count(); i++) {
3647     _expensive_nodes->at(i)->set_req(0, NULL);
3648   }
3649 
3650   Final_Reshape_Counts frc;
3651 
3652   // Visit everybody reachable!
3653   // Allocate stack of size C->live_nodes()/2 to avoid frequent realloc
3654   Node_Stack nstack(live_nodes() >> 1);
3655   final_graph_reshaping_walk(nstack, root(), frc);
3656 
3657   // Check for unreachable (from below) code (i.e., infinite loops).
3658   for( uint i = 0; i < frc._tests.size(); i++ ) {
3659     MultiBranchNode *n = frc._tests[i]->as_MultiBranch();
3660     // Get number of CFG targets.
3661     // Note that PCTables include exception targets after calls.
3662     uint required_outcnt = n->required_outcnt();
3663     if (n->outcnt() != required_outcnt) {
3664       // Check for a few special cases.  Rethrow Nodes never take the
3665       // 'fall-thru' path, so expected kids is 1 less.
3666       if (n->is_PCTable() && n->in(0) && n->in(0)->in(0)) {
3667         if (n->in(0)->in(0)->is_Call()) {
3668           CallNode *call = n->in(0)->in(0)->as_Call();
3669           if (call->entry_point() == OptoRuntime::rethrow_stub()) {
3670             required_outcnt--;      // Rethrow always has 1 less kid
3671           } else if (call->req() > TypeFunc::Parms &&
3672                      call->is_CallDynamicJava()) {
3673             // Check for null receiver. In such case, the optimizer has
3674             // detected that the virtual call will always result in a null
3675             // pointer exception. The fall-through projection of this CatchNode
3676             // will not be populated.
3677             Node *arg0 = call->in(TypeFunc::Parms);
3678             if (arg0->is_Type() &&
3679                 arg0->as_Type()->type()->higher_equal(TypePtr::NULL_PTR)) {
3680               required_outcnt--;
3681             }
3682           } else if (call->entry_point() == OptoRuntime::new_array_Java() &&
3683                      call->req() > TypeFunc::Parms+1 &&
3684                      call->is_CallStaticJava()) {
3685             // Check for negative array length. In such case, the optimizer has
3686             // detected that the allocation attempt will always result in an
3687             // exception. There is no fall-through projection of this CatchNode .
3688             Node *arg1 = call->in(TypeFunc::Parms+1);
3689             if (arg1->is_Type() &&
3690                 arg1->as_Type()->type()->join(TypeInt::POS)->empty()) {
3691               required_outcnt--;
3692             }
3693           }
3694         }
3695       }
3696       // Recheck with a better notion of 'required_outcnt'
3697       if (n->outcnt() != required_outcnt) {
3698         record_method_not_compilable("malformed control flow");
3699         return true;            // Not all targets reachable!
3700       }
3701     }
3702     // Check that I actually visited all kids.  Unreached kids
3703     // must be infinite loops.
3704     for (DUIterator_Fast jmax, j = n->fast_outs(jmax); j < jmax; j++)
3705       if (!frc._visited.test(n->fast_out(j)->_idx)) {
3706         record_method_not_compilable("infinite loop");
3707         return true;            // Found unvisited kid; must be unreach
3708       }
3709 
3710     // Here so verification code in final_graph_reshaping_walk()
3711     // always see an OuterStripMinedLoopEnd
3712     if (n->is_OuterStripMinedLoopEnd()) {
3713       IfNode* init_iff = n->as_If();
3714       Node* iff = new IfNode(init_iff->in(0), init_iff->in(1), init_iff->_prob, init_iff->_fcnt);
3715       n->subsume_by(iff, this);
3716     }
3717   }
3718 
3719 #ifdef IA32
3720   // If original bytecodes contained a mixture of floats and doubles
3721   // check if the optimizer has made it homogenous, item (3).
3722   if (UseSSE == 0 &&
3723       frc.get_float_count() > 32 &&
3724       frc.get_double_count() == 0 &&
3725       (10 * frc.get_call_count() < frc.get_float_count()) ) {
3726     set_24_bit_selection_and_mode(false, true);
3727   }
3728 #endif // IA32
3729 
3730   set_java_calls(frc.get_java_call_count());
3731   set_inner_loops(frc.get_inner_loop_count());
3732 
3733   // No infinite loops, no reason to bail out.
3734   return false;
3735 }
3736 
3737 //-----------------------------too_many_traps----------------------------------
3738 // Report if there are too many traps at the current method and bci.
3739 // Return true if there was a trap, and/or PerMethodTrapLimit is exceeded.
too_many_traps(ciMethod * method,int bci,Deoptimization::DeoptReason reason)3740 bool Compile::too_many_traps(ciMethod* method,
3741                              int bci,
3742                              Deoptimization::DeoptReason reason) {
3743   ciMethodData* md = method->method_data();
3744   if (md->is_empty()) {
3745     // Assume the trap has not occurred, or that it occurred only
3746     // because of a transient condition during start-up in the interpreter.
3747     return false;
3748   }
3749   ciMethod* m = Deoptimization::reason_is_speculate(reason) ? this->method() : NULL;
3750   if (md->has_trap_at(bci, m, reason) != 0) {
3751     // Assume PerBytecodeTrapLimit==0, for a more conservative heuristic.
3752     // Also, if there are multiple reasons, or if there is no per-BCI record,
3753     // assume the worst.
3754     if (log())
3755       log()->elem("observe trap='%s' count='%d'",
3756                   Deoptimization::trap_reason_name(reason),
3757                   md->trap_count(reason));
3758     return true;
3759   } else {
3760     // Ignore method/bci and see if there have been too many globally.
3761     return too_many_traps(reason, md);
3762   }
3763 }
3764 
3765 // Less-accurate variant which does not require a method and bci.
too_many_traps(Deoptimization::DeoptReason reason,ciMethodData * logmd)3766 bool Compile::too_many_traps(Deoptimization::DeoptReason reason,
3767                              ciMethodData* logmd) {
3768   if (trap_count(reason) >= Deoptimization::per_method_trap_limit(reason)) {
3769     // Too many traps globally.
3770     // Note that we use cumulative trap_count, not just md->trap_count.
3771     if (log()) {
3772       int mcount = (logmd == NULL)? -1: (int)logmd->trap_count(reason);
3773       log()->elem("observe trap='%s' count='0' mcount='%d' ccount='%d'",
3774                   Deoptimization::trap_reason_name(reason),
3775                   mcount, trap_count(reason));
3776     }
3777     return true;
3778   } else {
3779     // The coast is clear.
3780     return false;
3781   }
3782 }
3783 
3784 //--------------------------too_many_recompiles--------------------------------
3785 // Report if there are too many recompiles at the current method and bci.
3786 // Consults PerBytecodeRecompilationCutoff and PerMethodRecompilationCutoff.
3787 // Is not eager to return true, since this will cause the compiler to use
3788 // Action_none for a trap point, to avoid too many recompilations.
too_many_recompiles(ciMethod * method,int bci,Deoptimization::DeoptReason reason)3789 bool Compile::too_many_recompiles(ciMethod* method,
3790                                   int bci,
3791                                   Deoptimization::DeoptReason reason) {
3792   ciMethodData* md = method->method_data();
3793   if (md->is_empty()) {
3794     // Assume the trap has not occurred, or that it occurred only
3795     // because of a transient condition during start-up in the interpreter.
3796     return false;
3797   }
3798   // Pick a cutoff point well within PerBytecodeRecompilationCutoff.
3799   uint bc_cutoff = (uint) PerBytecodeRecompilationCutoff / 8;
3800   uint m_cutoff  = (uint) PerMethodRecompilationCutoff / 2 + 1;  // not zero
3801   Deoptimization::DeoptReason per_bc_reason
3802     = Deoptimization::reason_recorded_per_bytecode_if_any(reason);
3803   ciMethod* m = Deoptimization::reason_is_speculate(reason) ? this->method() : NULL;
3804   if ((per_bc_reason == Deoptimization::Reason_none
3805        || md->has_trap_at(bci, m, reason) != 0)
3806       // The trap frequency measure we care about is the recompile count:
3807       && md->trap_recompiled_at(bci, m)
3808       && md->overflow_recompile_count() >= bc_cutoff) {
3809     // Do not emit a trap here if it has already caused recompilations.
3810     // Also, if there are multiple reasons, or if there is no per-BCI record,
3811     // assume the worst.
3812     if (log())
3813       log()->elem("observe trap='%s recompiled' count='%d' recompiles2='%d'",
3814                   Deoptimization::trap_reason_name(reason),
3815                   md->trap_count(reason),
3816                   md->overflow_recompile_count());
3817     return true;
3818   } else if (trap_count(reason) != 0
3819              && decompile_count() >= m_cutoff) {
3820     // Too many recompiles globally, and we have seen this sort of trap.
3821     // Use cumulative decompile_count, not just md->decompile_count.
3822     if (log())
3823       log()->elem("observe trap='%s' count='%d' mcount='%d' decompiles='%d' mdecompiles='%d'",
3824                   Deoptimization::trap_reason_name(reason),
3825                   md->trap_count(reason), trap_count(reason),
3826                   md->decompile_count(), decompile_count());
3827     return true;
3828   } else {
3829     // The coast is clear.
3830     return false;
3831   }
3832 }
3833 
3834 // Compute when not to trap. Used by matching trap based nodes and
3835 // NullCheck optimization.
set_allowed_deopt_reasons()3836 void Compile::set_allowed_deopt_reasons() {
3837   _allowed_reasons = 0;
3838   if (is_method_compilation()) {
3839     for (int rs = (int)Deoptimization::Reason_none+1; rs < Compile::trapHistLength; rs++) {
3840       assert(rs < BitsPerInt, "recode bit map");
3841       if (!too_many_traps((Deoptimization::DeoptReason) rs)) {
3842         _allowed_reasons |= nth_bit(rs);
3843       }
3844     }
3845   }
3846 }
3847 
needs_clinit_barrier(ciMethod * method,ciMethod * accessing_method)3848 bool Compile::needs_clinit_barrier(ciMethod* method, ciMethod* accessing_method) {
3849   return method->is_static() && needs_clinit_barrier(method->holder(), accessing_method);
3850 }
3851 
needs_clinit_barrier(ciField * field,ciMethod * accessing_method)3852 bool Compile::needs_clinit_barrier(ciField* field, ciMethod* accessing_method) {
3853   return field->is_static() && needs_clinit_barrier(field->holder(), accessing_method);
3854 }
3855 
needs_clinit_barrier(ciInstanceKlass * holder,ciMethod * accessing_method)3856 bool Compile::needs_clinit_barrier(ciInstanceKlass* holder, ciMethod* accessing_method) {
3857   if (holder->is_initialized()) {
3858     return false;
3859   }
3860   if (holder->is_being_initialized()) {
3861     if (accessing_method->holder() == holder) {
3862       // Access inside a class. The barrier can be elided when access happens in <clinit>,
3863       // <init>, or a static method. In all those cases, there was an initialization
3864       // barrier on the holder klass passed.
3865       if (accessing_method->is_static_initializer() ||
3866           accessing_method->is_object_initializer() ||
3867           accessing_method->is_static()) {
3868         return false;
3869       }
3870     } else if (accessing_method->holder()->is_subclass_of(holder)) {
3871       // Access from a subclass. The barrier can be elided only when access happens in <clinit>.
3872       // In case of <init> or a static method, the barrier is on the subclass is not enough:
3873       // child class can become fully initialized while its parent class is still being initialized.
3874       if (accessing_method->is_static_initializer()) {
3875         return false;
3876       }
3877     }
3878     ciMethod* root = method(); // the root method of compilation
3879     if (root != accessing_method) {
3880       return needs_clinit_barrier(holder, root); // check access in the context of compilation root
3881     }
3882   }
3883   return true;
3884 }
3885 
3886 #ifndef PRODUCT
3887 //------------------------------verify_graph_edges---------------------------
3888 // Walk the Graph and verify that there is a one-to-one correspondence
3889 // between Use-Def edges and Def-Use edges in the graph.
verify_graph_edges(bool no_dead_code)3890 void Compile::verify_graph_edges(bool no_dead_code) {
3891   if (VerifyGraphEdges) {
3892     ResourceArea *area = Thread::current()->resource_area();
3893     Unique_Node_List visited(area);
3894     // Call recursive graph walk to check edges
3895     _root->verify_edges(visited);
3896     if (no_dead_code) {
3897       // Now make sure that no visited node is used by an unvisited node.
3898       bool dead_nodes = false;
3899       Unique_Node_List checked(area);
3900       while (visited.size() > 0) {
3901         Node* n = visited.pop();
3902         checked.push(n);
3903         for (uint i = 0; i < n->outcnt(); i++) {
3904           Node* use = n->raw_out(i);
3905           if (checked.member(use))  continue;  // already checked
3906           if (visited.member(use))  continue;  // already in the graph
3907           if (use->is_Con())        continue;  // a dead ConNode is OK
3908           // At this point, we have found a dead node which is DU-reachable.
3909           if (!dead_nodes) {
3910             tty->print_cr("*** Dead nodes reachable via DU edges:");
3911             dead_nodes = true;
3912           }
3913           use->dump(2);
3914           tty->print_cr("---");
3915           checked.push(use);  // No repeats; pretend it is now checked.
3916         }
3917       }
3918       assert(!dead_nodes, "using nodes must be reachable from root");
3919     }
3920   }
3921 }
3922 #endif
3923 
3924 // The Compile object keeps track of failure reasons separately from the ciEnv.
3925 // This is required because there is not quite a 1-1 relation between the
3926 // ciEnv and its compilation task and the Compile object.  Note that one
3927 // ciEnv might use two Compile objects, if C2Compiler::compile_method decides
3928 // to backtrack and retry without subsuming loads.  Other than this backtracking
3929 // behavior, the Compile's failure reason is quietly copied up to the ciEnv
3930 // by the logic in C2Compiler.
record_failure(const char * reason)3931 void Compile::record_failure(const char* reason) {
3932   if (log() != NULL) {
3933     log()->elem("failure reason='%s' phase='compile'", reason);
3934   }
3935   if (_failure_reason == NULL) {
3936     // Record the first failure reason.
3937     _failure_reason = reason;
3938   }
3939 
3940   if (!C->failure_reason_is(C2Compiler::retry_no_subsuming_loads())) {
3941     C->print_method(PHASE_FAILURE);
3942   }
3943   _root = NULL;  // flush the graph, too
3944 }
3945 
TracePhase(const char * name,elapsedTimer * accumulator)3946 Compile::TracePhase::TracePhase(const char* name, elapsedTimer* accumulator)
3947   : TraceTime(name, accumulator, CITime, CITimeVerbose),
3948     _phase_name(name), _dolog(CITimeVerbose)
3949 {
3950   if (_dolog) {
3951     C = Compile::current();
3952     _log = C->log();
3953   } else {
3954     C = NULL;
3955     _log = NULL;
3956   }
3957   if (_log != NULL) {
3958     _log->begin_head("phase name='%s' nodes='%d' live='%d'", _phase_name, C->unique(), C->live_nodes());
3959     _log->stamp();
3960     _log->end_head();
3961   }
3962 }
3963 
~TracePhase()3964 Compile::TracePhase::~TracePhase() {
3965 
3966   C = Compile::current();
3967   if (_dolog) {
3968     _log = C->log();
3969   } else {
3970     _log = NULL;
3971   }
3972 
3973 #ifdef ASSERT
3974   if (PrintIdealNodeCount) {
3975     tty->print_cr("phase name='%s' nodes='%d' live='%d' live_graph_walk='%d'",
3976                   _phase_name, C->unique(), C->live_nodes(), C->count_live_nodes_by_graph_walk());
3977   }
3978 
3979   if (VerifyIdealNodeCount) {
3980     Compile::current()->print_missing_nodes();
3981   }
3982 #endif
3983 
3984   if (_log != NULL) {
3985     _log->done("phase name='%s' nodes='%d' live='%d'", _phase_name, C->unique(), C->live_nodes());
3986   }
3987 }
3988 
3989 //----------------------------static_subtype_check-----------------------------
3990 // Shortcut important common cases when superklass is exact:
3991 // (0) superklass is java.lang.Object (can occur in reflective code)
3992 // (1) subklass is already limited to a subtype of superklass => always ok
3993 // (2) subklass does not overlap with superklass => always fail
3994 // (3) superklass has NO subtypes and we can check with a simple compare.
static_subtype_check(ciKlass * superk,ciKlass * subk)3995 int Compile::static_subtype_check(ciKlass* superk, ciKlass* subk) {
3996   if (StressReflectiveCode) {
3997     return SSC_full_test;       // Let caller generate the general case.
3998   }
3999 
4000   if (superk == env()->Object_klass()) {
4001     return SSC_always_true;     // (0) this test cannot fail
4002   }
4003 
4004   ciType* superelem = superk;
4005   if (superelem->is_array_klass())
4006     superelem = superelem->as_array_klass()->base_element_type();
4007 
4008   if (!subk->is_interface()) {  // cannot trust static interface types yet
4009     if (subk->is_subtype_of(superk)) {
4010       return SSC_always_true;   // (1) false path dead; no dynamic test needed
4011     }
4012     if (!(superelem->is_klass() && superelem->as_klass()->is_interface()) &&
4013         !superk->is_subtype_of(subk)) {
4014       return SSC_always_false;
4015     }
4016   }
4017 
4018   // If casting to an instance klass, it must have no subtypes
4019   if (superk->is_interface()) {
4020     // Cannot trust interfaces yet.
4021     // %%% S.B. superk->nof_implementors() == 1
4022   } else if (superelem->is_instance_klass()) {
4023     ciInstanceKlass* ik = superelem->as_instance_klass();
4024     if (!ik->has_subklass() && !ik->is_interface()) {
4025       if (!ik->is_final()) {
4026         // Add a dependency if there is a chance of a later subclass.
4027         dependencies()->assert_leaf_type(ik);
4028       }
4029       return SSC_easy_test;     // (3) caller can do a simple ptr comparison
4030     }
4031   } else {
4032     // A primitive array type has no subtypes.
4033     return SSC_easy_test;       // (3) caller can do a simple ptr comparison
4034   }
4035 
4036   return SSC_full_test;
4037 }
4038 
conv_I2X_index(PhaseGVN * phase,Node * idx,const TypeInt * sizetype,Node * ctrl)4039 Node* Compile::conv_I2X_index(PhaseGVN* phase, Node* idx, const TypeInt* sizetype, Node* ctrl) {
4040 #ifdef _LP64
4041   // The scaled index operand to AddP must be a clean 64-bit value.
4042   // Java allows a 32-bit int to be incremented to a negative
4043   // value, which appears in a 64-bit register as a large
4044   // positive number.  Using that large positive number as an
4045   // operand in pointer arithmetic has bad consequences.
4046   // On the other hand, 32-bit overflow is rare, and the possibility
4047   // can often be excluded, if we annotate the ConvI2L node with
4048   // a type assertion that its value is known to be a small positive
4049   // number.  (The prior range check has ensured this.)
4050   // This assertion is used by ConvI2LNode::Ideal.
4051   int index_max = max_jint - 1;  // array size is max_jint, index is one less
4052   if (sizetype != NULL) index_max = sizetype->_hi - 1;
4053   const TypeInt* iidxtype = TypeInt::make(0, index_max, Type::WidenMax);
4054   idx = constrained_convI2L(phase, idx, iidxtype, ctrl);
4055 #endif
4056   return idx;
4057 }
4058 
4059 // Convert integer value to a narrowed long type dependent on ctrl (for example, a range check)
constrained_convI2L(PhaseGVN * phase,Node * value,const TypeInt * itype,Node * ctrl)4060 Node* Compile::constrained_convI2L(PhaseGVN* phase, Node* value, const TypeInt* itype, Node* ctrl) {
4061   if (ctrl != NULL) {
4062     // Express control dependency by a CastII node with a narrow type.
4063     value = new CastIINode(value, itype, false, true /* range check dependency */);
4064     // Make the CastII node dependent on the control input to prevent the narrowed ConvI2L
4065     // node from floating above the range check during loop optimizations. Otherwise, the
4066     // ConvI2L node may be eliminated independently of the range check, causing the data path
4067     // to become TOP while the control path is still there (although it's unreachable).
4068     value->set_req(0, ctrl);
4069     // Save CastII node to remove it after loop optimizations.
4070     phase->C->add_range_check_cast(value);
4071     value = phase->transform(value);
4072   }
4073   const TypeLong* ltype = TypeLong::make(itype->_lo, itype->_hi, itype->_widen);
4074   return phase->transform(new ConvI2LNode(value, ltype));
4075 }
4076 
print_inlining_stream_free()4077 void Compile::print_inlining_stream_free() {
4078   if (_print_inlining_stream != NULL) {
4079     _print_inlining_stream->~stringStream();
4080     _print_inlining_stream = NULL;
4081   }
4082 }
4083 
4084 // The message about the current inlining is accumulated in
4085 // _print_inlining_stream and transfered into the _print_inlining_list
4086 // once we know whether inlining succeeds or not. For regular
4087 // inlining, messages are appended to the buffer pointed by
4088 // _print_inlining_idx in the _print_inlining_list. For late inlining,
4089 // a new buffer is added after _print_inlining_idx in the list. This
4090 // way we can update the inlining message for late inlining call site
4091 // when the inlining is attempted again.
print_inlining_init()4092 void Compile::print_inlining_init() {
4093   if (print_inlining() || print_intrinsics()) {
4094     // print_inlining_init is actually called several times.
4095     print_inlining_stream_free();
4096     _print_inlining_stream = new stringStream();
4097     // Watch out: The memory initialized by the constructor call PrintInliningBuffer()
4098     // will be copied into the only initial element. The default destructor of
4099     // PrintInliningBuffer will be called when leaving the scope here. If it
4100     // would destuct the  enclosed stringStream _print_inlining_list[0]->_ss
4101     // would be destructed, too!
4102     _print_inlining_list = new (comp_arena())GrowableArray<PrintInliningBuffer>(comp_arena(), 1, 1, PrintInliningBuffer());
4103   }
4104 }
4105 
print_inlining_reinit()4106 void Compile::print_inlining_reinit() {
4107   if (print_inlining() || print_intrinsics()) {
4108     print_inlining_stream_free();
4109     // Re allocate buffer when we change ResourceMark
4110     _print_inlining_stream = new stringStream();
4111   }
4112 }
4113 
print_inlining_reset()4114 void Compile::print_inlining_reset() {
4115   _print_inlining_stream->reset();
4116 }
4117 
print_inlining_commit()4118 void Compile::print_inlining_commit() {
4119   assert(print_inlining() || print_intrinsics(), "PrintInlining off?");
4120   // Transfer the message from _print_inlining_stream to the current
4121   // _print_inlining_list buffer and clear _print_inlining_stream.
4122   _print_inlining_list->at(_print_inlining_idx).ss()->write(_print_inlining_stream->base(), _print_inlining_stream->size());
4123   print_inlining_reset();
4124 }
4125 
print_inlining_push()4126 void Compile::print_inlining_push() {
4127   // Add new buffer to the _print_inlining_list at current position
4128   _print_inlining_idx++;
4129   _print_inlining_list->insert_before(_print_inlining_idx, PrintInliningBuffer());
4130 }
4131 
print_inlining_current()4132 Compile::PrintInliningBuffer& Compile::print_inlining_current() {
4133   return _print_inlining_list->at(_print_inlining_idx);
4134 }
4135 
print_inlining_update(CallGenerator * cg)4136 void Compile::print_inlining_update(CallGenerator* cg) {
4137   if (print_inlining() || print_intrinsics()) {
4138     if (!cg->is_late_inline()) {
4139       if (print_inlining_current().cg() != NULL) {
4140         print_inlining_push();
4141       }
4142       print_inlining_commit();
4143     } else {
4144       if (print_inlining_current().cg() != cg &&
4145           (print_inlining_current().cg() != NULL ||
4146            print_inlining_current().ss()->size() != 0)) {
4147         print_inlining_push();
4148       }
4149       print_inlining_commit();
4150       print_inlining_current().set_cg(cg);
4151     }
4152   }
4153 }
4154 
print_inlining_move_to(CallGenerator * cg)4155 void Compile::print_inlining_move_to(CallGenerator* cg) {
4156   // We resume inlining at a late inlining call site. Locate the
4157   // corresponding inlining buffer so that we can update it.
4158   if (print_inlining()) {
4159     for (int i = 0; i < _print_inlining_list->length(); i++) {
4160       if (_print_inlining_list->adr_at(i)->cg() == cg) {
4161         _print_inlining_idx = i;
4162         return;
4163       }
4164     }
4165     ShouldNotReachHere();
4166   }
4167 }
4168 
print_inlining_update_delayed(CallGenerator * cg)4169 void Compile::print_inlining_update_delayed(CallGenerator* cg) {
4170   if (print_inlining()) {
4171     assert(_print_inlining_stream->size() > 0, "missing inlining msg");
4172     assert(print_inlining_current().cg() == cg, "wrong entry");
4173     // replace message with new message
4174     _print_inlining_list->at_put(_print_inlining_idx, PrintInliningBuffer());
4175     print_inlining_commit();
4176     print_inlining_current().set_cg(cg);
4177   }
4178 }
4179 
print_inlining_assert_ready()4180 void Compile::print_inlining_assert_ready() {
4181   assert(!_print_inlining || _print_inlining_stream->size() == 0, "loosing data");
4182 }
4183 
process_print_inlining()4184 void Compile::process_print_inlining() {
4185   bool do_print_inlining = print_inlining() || print_intrinsics();
4186   if (do_print_inlining || log() != NULL) {
4187     // Print inlining message for candidates that we couldn't inline
4188     // for lack of space
4189     for (int i = 0; i < _late_inlines.length(); i++) {
4190       CallGenerator* cg = _late_inlines.at(i);
4191       if (!cg->is_mh_late_inline()) {
4192         const char* msg = "live nodes > LiveNodeCountInliningCutoff";
4193         if (do_print_inlining) {
4194           cg->print_inlining_late(msg);
4195         }
4196         log_late_inline_failure(cg, msg);
4197       }
4198     }
4199   }
4200   if (do_print_inlining) {
4201     ResourceMark rm;
4202     stringStream ss;
4203     assert(_print_inlining_list != NULL, "process_print_inlining should be called only once.");
4204     for (int i = 0; i < _print_inlining_list->length(); i++) {
4205       ss.print("%s", _print_inlining_list->adr_at(i)->ss()->as_string());
4206       _print_inlining_list->at(i).freeStream();
4207     }
4208     // Reset _print_inlining_list, it only contains destructed objects.
4209     // It is on the arena, so it will be freed when the arena is reset.
4210     _print_inlining_list = NULL;
4211     // _print_inlining_stream won't be used anymore, either.
4212     print_inlining_stream_free();
4213     size_t end = ss.size();
4214     _print_inlining_output = NEW_ARENA_ARRAY(comp_arena(), char, end+1);
4215     strncpy(_print_inlining_output, ss.base(), end+1);
4216     _print_inlining_output[end] = 0;
4217   }
4218 }
4219 
dump_print_inlining()4220 void Compile::dump_print_inlining() {
4221   if (_print_inlining_output != NULL) {
4222     tty->print_raw(_print_inlining_output);
4223   }
4224 }
4225 
log_late_inline(CallGenerator * cg)4226 void Compile::log_late_inline(CallGenerator* cg) {
4227   if (log() != NULL) {
4228     log()->head("late_inline method='%d'  inline_id='" JLONG_FORMAT "'", log()->identify(cg->method()),
4229                 cg->unique_id());
4230     JVMState* p = cg->call_node()->jvms();
4231     while (p != NULL) {
4232       log()->elem("jvms bci='%d' method='%d'", p->bci(), log()->identify(p->method()));
4233       p = p->caller();
4234     }
4235     log()->tail("late_inline");
4236   }
4237 }
4238 
log_late_inline_failure(CallGenerator * cg,const char * msg)4239 void Compile::log_late_inline_failure(CallGenerator* cg, const char* msg) {
4240   log_late_inline(cg);
4241   if (log() != NULL) {
4242     log()->inline_fail(msg);
4243   }
4244 }
4245 
log_inline_id(CallGenerator * cg)4246 void Compile::log_inline_id(CallGenerator* cg) {
4247   if (log() != NULL) {
4248     // The LogCompilation tool needs a unique way to identify late
4249     // inline call sites. This id must be unique for this call site in
4250     // this compilation. Try to have it unique across compilations as
4251     // well because it can be convenient when grepping through the log
4252     // file.
4253     // Distinguish OSR compilations from others in case CICountOSR is
4254     // on.
4255     jlong id = ((jlong)unique()) + (((jlong)compile_id()) << 33) + (CICountOSR && is_osr_compilation() ? ((jlong)1) << 32 : 0);
4256     cg->set_unique_id(id);
4257     log()->elem("inline_id id='" JLONG_FORMAT "'", id);
4258   }
4259 }
4260 
log_inline_failure(const char * msg)4261 void Compile::log_inline_failure(const char* msg) {
4262   if (C->log() != NULL) {
4263     C->log()->inline_fail(msg);
4264   }
4265 }
4266 
4267 
4268 // Dump inlining replay data to the stream.
4269 // Don't change thread state and acquire any locks.
dump_inline_data(outputStream * out)4270 void Compile::dump_inline_data(outputStream* out) {
4271   InlineTree* inl_tree = ilt();
4272   if (inl_tree != NULL) {
4273     out->print(" inline %d", inl_tree->count());
4274     inl_tree->dump_replay_data(out);
4275   }
4276 }
4277 
cmp_expensive_nodes(Node * n1,Node * n2)4278 int Compile::cmp_expensive_nodes(Node* n1, Node* n2) {
4279   if (n1->Opcode() < n2->Opcode())      return -1;
4280   else if (n1->Opcode() > n2->Opcode()) return 1;
4281 
4282   assert(n1->req() == n2->req(), "can't compare %s nodes: n1->req() = %d, n2->req() = %d", NodeClassNames[n1->Opcode()], n1->req(), n2->req());
4283   for (uint i = 1; i < n1->req(); i++) {
4284     if (n1->in(i) < n2->in(i))      return -1;
4285     else if (n1->in(i) > n2->in(i)) return 1;
4286   }
4287 
4288   return 0;
4289 }
4290 
cmp_expensive_nodes(Node ** n1p,Node ** n2p)4291 int Compile::cmp_expensive_nodes(Node** n1p, Node** n2p) {
4292   Node* n1 = *n1p;
4293   Node* n2 = *n2p;
4294 
4295   return cmp_expensive_nodes(n1, n2);
4296 }
4297 
sort_expensive_nodes()4298 void Compile::sort_expensive_nodes() {
4299   if (!expensive_nodes_sorted()) {
4300     _expensive_nodes->sort(cmp_expensive_nodes);
4301   }
4302 }
4303 
expensive_nodes_sorted() const4304 bool Compile::expensive_nodes_sorted() const {
4305   for (int i = 1; i < _expensive_nodes->length(); i++) {
4306     if (cmp_expensive_nodes(_expensive_nodes->adr_at(i), _expensive_nodes->adr_at(i-1)) < 0) {
4307       return false;
4308     }
4309   }
4310   return true;
4311 }
4312 
should_optimize_expensive_nodes(PhaseIterGVN & igvn)4313 bool Compile::should_optimize_expensive_nodes(PhaseIterGVN &igvn) {
4314   if (_expensive_nodes->length() == 0) {
4315     return false;
4316   }
4317 
4318   assert(OptimizeExpensiveOps, "optimization off?");
4319 
4320   // Take this opportunity to remove dead nodes from the list
4321   int j = 0;
4322   for (int i = 0; i < _expensive_nodes->length(); i++) {
4323     Node* n = _expensive_nodes->at(i);
4324     if (!n->is_unreachable(igvn)) {
4325       assert(n->is_expensive(), "should be expensive");
4326       _expensive_nodes->at_put(j, n);
4327       j++;
4328     }
4329   }
4330   _expensive_nodes->trunc_to(j);
4331 
4332   // Then sort the list so that similar nodes are next to each other
4333   // and check for at least two nodes of identical kind with same data
4334   // inputs.
4335   sort_expensive_nodes();
4336 
4337   for (int i = 0; i < _expensive_nodes->length()-1; i++) {
4338     if (cmp_expensive_nodes(_expensive_nodes->adr_at(i), _expensive_nodes->adr_at(i+1)) == 0) {
4339       return true;
4340     }
4341   }
4342 
4343   return false;
4344 }
4345 
cleanup_expensive_nodes(PhaseIterGVN & igvn)4346 void Compile::cleanup_expensive_nodes(PhaseIterGVN &igvn) {
4347   if (_expensive_nodes->length() == 0) {
4348     return;
4349   }
4350 
4351   assert(OptimizeExpensiveOps, "optimization off?");
4352 
4353   // Sort to bring similar nodes next to each other and clear the
4354   // control input of nodes for which there's only a single copy.
4355   sort_expensive_nodes();
4356 
4357   int j = 0;
4358   int identical = 0;
4359   int i = 0;
4360   bool modified = false;
4361   for (; i < _expensive_nodes->length()-1; i++) {
4362     assert(j <= i, "can't write beyond current index");
4363     if (_expensive_nodes->at(i)->Opcode() == _expensive_nodes->at(i+1)->Opcode()) {
4364       identical++;
4365       _expensive_nodes->at_put(j++, _expensive_nodes->at(i));
4366       continue;
4367     }
4368     if (identical > 0) {
4369       _expensive_nodes->at_put(j++, _expensive_nodes->at(i));
4370       identical = 0;
4371     } else {
4372       Node* n = _expensive_nodes->at(i);
4373       igvn.replace_input_of(n, 0, NULL);
4374       igvn.hash_insert(n);
4375       modified = true;
4376     }
4377   }
4378   if (identical > 0) {
4379     _expensive_nodes->at_put(j++, _expensive_nodes->at(i));
4380   } else if (_expensive_nodes->length() >= 1) {
4381     Node* n = _expensive_nodes->at(i);
4382     igvn.replace_input_of(n, 0, NULL);
4383     igvn.hash_insert(n);
4384     modified = true;
4385   }
4386   _expensive_nodes->trunc_to(j);
4387   if (modified) {
4388     igvn.optimize();
4389   }
4390 }
4391 
add_expensive_node(Node * n)4392 void Compile::add_expensive_node(Node * n) {
4393   assert(!_expensive_nodes->contains(n), "duplicate entry in expensive list");
4394   assert(n->is_expensive(), "expensive nodes with non-null control here only");
4395   assert(!n->is_CFG() && !n->is_Mem(), "no cfg or memory nodes here");
4396   if (OptimizeExpensiveOps) {
4397     _expensive_nodes->append(n);
4398   } else {
4399     // Clear control input and let IGVN optimize expensive nodes if
4400     // OptimizeExpensiveOps is off.
4401     n->set_req(0, NULL);
4402   }
4403 }
4404 
4405 /**
4406  * Remove the speculative part of types and clean up the graph
4407  */
remove_speculative_types(PhaseIterGVN & igvn)4408 void Compile::remove_speculative_types(PhaseIterGVN &igvn) {
4409   if (UseTypeSpeculation) {
4410     Unique_Node_List worklist;
4411     worklist.push(root());
4412     int modified = 0;
4413     // Go over all type nodes that carry a speculative type, drop the
4414     // speculative part of the type and enqueue the node for an igvn
4415     // which may optimize it out.
4416     for (uint next = 0; next < worklist.size(); ++next) {
4417       Node *n  = worklist.at(next);
4418       if (n->is_Type()) {
4419         TypeNode* tn = n->as_Type();
4420         const Type* t = tn->type();
4421         const Type* t_no_spec = t->remove_speculative();
4422         if (t_no_spec != t) {
4423           bool in_hash = igvn.hash_delete(n);
4424           assert(in_hash, "node should be in igvn hash table");
4425           tn->set_type(t_no_spec);
4426           igvn.hash_insert(n);
4427           igvn._worklist.push(n); // give it a chance to go away
4428           modified++;
4429         }
4430       }
4431       uint max = n->len();
4432       for( uint i = 0; i < max; ++i ) {
4433         Node *m = n->in(i);
4434         if (not_a_node(m))  continue;
4435         worklist.push(m);
4436       }
4437     }
4438     // Drop the speculative part of all types in the igvn's type table
4439     igvn.remove_speculative_types();
4440     if (modified > 0) {
4441       igvn.optimize();
4442     }
4443 #ifdef ASSERT
4444     // Verify that after the IGVN is over no speculative type has resurfaced
4445     worklist.clear();
4446     worklist.push(root());
4447     for (uint next = 0; next < worklist.size(); ++next) {
4448       Node *n  = worklist.at(next);
4449       const Type* t = igvn.type_or_null(n);
4450       assert((t == NULL) || (t == t->remove_speculative()), "no more speculative types");
4451       if (n->is_Type()) {
4452         t = n->as_Type()->type();
4453         assert(t == t->remove_speculative(), "no more speculative types");
4454       }
4455       uint max = n->len();
4456       for( uint i = 0; i < max; ++i ) {
4457         Node *m = n->in(i);
4458         if (not_a_node(m))  continue;
4459         worklist.push(m);
4460       }
4461     }
4462     igvn.check_no_speculative_types();
4463 #endif
4464   }
4465 }
4466 
4467 // Auxiliary method to support randomized stressing/fuzzing.
4468 //
4469 // This method can be called the arbitrary number of times, with current count
4470 // as the argument. The logic allows selecting a single candidate from the
4471 // running list of candidates as follows:
4472 //    int count = 0;
4473 //    Cand* selected = null;
4474 //    while(cand = cand->next()) {
4475 //      if (randomized_select(++count)) {
4476 //        selected = cand;
4477 //      }
4478 //    }
4479 //
4480 // Including count equalizes the chances any candidate is "selected".
4481 // This is useful when we don't have the complete list of candidates to choose
4482 // from uniformly. In this case, we need to adjust the randomicity of the
4483 // selection, or else we will end up biasing the selection towards the latter
4484 // candidates.
4485 //
4486 // Quick back-envelope calculation shows that for the list of n candidates
4487 // the equal probability for the candidate to persist as "best" can be
4488 // achieved by replacing it with "next" k-th candidate with the probability
4489 // of 1/k. It can be easily shown that by the end of the run, the
4490 // probability for any candidate is converged to 1/n, thus giving the
4491 // uniform distribution among all the candidates.
4492 //
4493 // We don't care about the domain size as long as (RANDOMIZED_DOMAIN / count) is large.
4494 #define RANDOMIZED_DOMAIN_POW 29
4495 #define RANDOMIZED_DOMAIN (1 << RANDOMIZED_DOMAIN_POW)
4496 #define RANDOMIZED_DOMAIN_MASK ((1 << (RANDOMIZED_DOMAIN_POW + 1)) - 1)
randomized_select(int count)4497 bool Compile::randomized_select(int count) {
4498   assert(count > 0, "only positive");
4499   return (os::random() & RANDOMIZED_DOMAIN_MASK) < (RANDOMIZED_DOMAIN / count);
4500 }
4501 
clone_map()4502 CloneMap&     Compile::clone_map()                 { return _clone_map; }
set_clone_map(Dict * d)4503 void          Compile::set_clone_map(Dict* d)      { _clone_map._dict = d; }
4504 
dump() const4505 void NodeCloneInfo::dump() const {
4506   tty->print(" {%d:%d} ", idx(), gen());
4507 }
4508 
clone(Node * old,Node * nnn,int gen)4509 void CloneMap::clone(Node* old, Node* nnn, int gen) {
4510   uint64_t val = value(old->_idx);
4511   NodeCloneInfo cio(val);
4512   assert(val != 0, "old node should be in the map");
4513   NodeCloneInfo cin(cio.idx(), gen + cio.gen());
4514   insert(nnn->_idx, cin.get());
4515 #ifndef PRODUCT
4516   if (is_debug()) {
4517     tty->print_cr("CloneMap::clone inserted node %d info {%d:%d} into CloneMap", nnn->_idx, cin.idx(), cin.gen());
4518   }
4519 #endif
4520 }
4521 
verify_insert_and_clone(Node * old,Node * nnn,int gen)4522 void CloneMap::verify_insert_and_clone(Node* old, Node* nnn, int gen) {
4523   NodeCloneInfo cio(value(old->_idx));
4524   if (cio.get() == 0) {
4525     cio.set(old->_idx, 0);
4526     insert(old->_idx, cio.get());
4527 #ifndef PRODUCT
4528     if (is_debug()) {
4529       tty->print_cr("CloneMap::verify_insert_and_clone inserted node %d info {%d:%d} into CloneMap", old->_idx, cio.idx(), cio.gen());
4530     }
4531 #endif
4532   }
4533   clone(old, nnn, gen);
4534 }
4535 
max_gen() const4536 int CloneMap::max_gen() const {
4537   int g = 0;
4538   DictI di(_dict);
4539   for(; di.test(); ++di) {
4540     int t = gen(di._key);
4541     if (g < t) {
4542       g = t;
4543 #ifndef PRODUCT
4544       if (is_debug()) {
4545         tty->print_cr("CloneMap::max_gen() update max=%d from %d", g, _2_node_idx_t(di._key));
4546       }
4547 #endif
4548     }
4549   }
4550   return g;
4551 }
4552 
dump(node_idx_t key) const4553 void CloneMap::dump(node_idx_t key) const {
4554   uint64_t val = value(key);
4555   if (val != 0) {
4556     NodeCloneInfo ni(val);
4557     ni.dump();
4558   }
4559 }
4560 
4561 // Move Allocate nodes to the start of the list
sort_macro_nodes()4562 void Compile::sort_macro_nodes() {
4563   int count = macro_count();
4564   int allocates = 0;
4565   for (int i = 0; i < count; i++) {
4566     Node* n = macro_node(i);
4567     if (n->is_Allocate()) {
4568       if (i != allocates) {
4569         Node* tmp = macro_node(allocates);
4570         _macro_nodes->at_put(allocates, n);
4571         _macro_nodes->at_put(i, tmp);
4572       }
4573       allocates++;
4574     }
4575   }
4576 }
4577 
print_method(CompilerPhaseType cpt,int level,int idx)4578 void Compile::print_method(CompilerPhaseType cpt, int level, int idx) {
4579   EventCompilerPhase event;
4580   if (event.should_commit()) {
4581     CompilerEvent::PhaseEvent::post(event, C->_latest_stage_start_counter, cpt, C->_compile_id, level);
4582   }
4583 
4584 #ifndef PRODUCT
4585   if (should_print(level)) {
4586     char output[1024];
4587     if (idx != 0) {
4588       jio_snprintf(output, sizeof(output), "%s:%d", CompilerPhaseTypeHelper::to_string(cpt), idx);
4589     } else {
4590       jio_snprintf(output, sizeof(output), "%s", CompilerPhaseTypeHelper::to_string(cpt));
4591     }
4592     _printer->print_method(output, level);
4593   }
4594 #endif
4595   C->_latest_stage_start_counter.stamp();
4596 }
4597 
end_method(int level)4598 void Compile::end_method(int level) {
4599   EventCompilerPhase event;
4600   if (event.should_commit()) {
4601     CompilerEvent::PhaseEvent::post(event, C->_latest_stage_start_counter, PHASE_END, C->_compile_id, level);
4602   }
4603 
4604 #ifndef PRODUCT
4605   if (_printer && _printer->should_print(level)) {
4606     _printer->end_method();
4607   }
4608 #endif
4609 }
4610 
4611 
4612 #ifndef PRODUCT
4613 IdealGraphPrinter* Compile::_debug_file_printer = NULL;
4614 IdealGraphPrinter* Compile::_debug_network_printer = NULL;
4615 
4616 // Called from debugger. Prints method to the default file with the default phase name.
4617 // This works regardless of any Ideal Graph Visualizer flags set or not.
igv_print()4618 void igv_print() {
4619   Compile::current()->igv_print_method_to_file();
4620 }
4621 
4622 // Same as igv_print() above but with a specified phase name.
igv_print(const char * phase_name)4623 void igv_print(const char* phase_name) {
4624   Compile::current()->igv_print_method_to_file(phase_name);
4625 }
4626 
4627 // Called from debugger. Prints method with the default phase name to the default network or the one specified with
4628 // the network flags for the Ideal Graph Visualizer, or to the default file depending on the 'network' argument.
4629 // This works regardless of any Ideal Graph Visualizer flags set or not.
igv_print(bool network)4630 void igv_print(bool network) {
4631   if (network) {
4632     Compile::current()->igv_print_method_to_network();
4633   } else {
4634     Compile::current()->igv_print_method_to_file();
4635   }
4636 }
4637 
4638 // Same as igv_print(bool network) above but with a specified phase name.
igv_print(bool network,const char * phase_name)4639 void igv_print(bool network, const char* phase_name) {
4640   if (network) {
4641     Compile::current()->igv_print_method_to_network(phase_name);
4642   } else {
4643     Compile::current()->igv_print_method_to_file(phase_name);
4644   }
4645 }
4646 
4647 // Called from debugger. Normal write to the default _printer. Only works if Ideal Graph Visualizer printing flags are set.
igv_print_default()4648 void igv_print_default() {
4649   Compile::current()->print_method(PHASE_DEBUG, 0, 0);
4650 }
4651 
4652 // Called from debugger, especially when replaying a trace in which the program state cannot be altered like with rr replay.
4653 // A method is appended to an existing default file with the default phase name. This means that igv_append() must follow
4654 // an earlier igv_print(*) call which sets up the file. This works regardless of any Ideal Graph Visualizer flags set or not.
igv_append()4655 void igv_append() {
4656   Compile::current()->igv_print_method_to_file("Debug", true);
4657 }
4658 
4659 // Same as igv_append() above but with a specified phase name.
igv_append(const char * phase_name)4660 void igv_append(const char* phase_name) {
4661   Compile::current()->igv_print_method_to_file(phase_name, true);
4662 }
4663 
igv_print_method_to_file(const char * phase_name,bool append)4664 void Compile::igv_print_method_to_file(const char* phase_name, bool append) {
4665   const char* file_name = "custom_debug.xml";
4666   if (_debug_file_printer == NULL) {
4667     _debug_file_printer = new IdealGraphPrinter(C, file_name, append);
4668   } else {
4669     _debug_file_printer->update_compiled_method(C->method());
4670   }
4671   tty->print_cr("Method %s to %s", append ? "appended" : "printed", file_name);
4672   _debug_file_printer->print_method(phase_name, 0);
4673 }
4674 
igv_print_method_to_network(const char * phase_name)4675 void Compile::igv_print_method_to_network(const char* phase_name) {
4676   if (_debug_network_printer == NULL) {
4677     _debug_network_printer = new IdealGraphPrinter(C);
4678   } else {
4679     _debug_network_printer->update_compiled_method(C->method());
4680   }
4681   tty->print_cr("Method printed over network stream to IGV");
4682   _debug_network_printer->print_method(phase_name, 0);
4683 }
4684 #endif
4685 
4686