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