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