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