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