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