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 if (n->is_CallLeafPure()) {
3238 // A pure call whose result projection is unused should have been
3239 // eliminated by CallLeafPureNode::Ideal during IGVN.
3240 assert(n->as_CallLeafPure()->proj_out_or_null(TypeFunc::Parms) != nullptr,
3241 "unused CallLeafPureNode should have been removed before final graph reshaping");
3242 }
3243 #endif
3244 // Count FPU ops and common calls, implements item (3)
3245 bool gc_handled = BarrierSet::barrier_set()->barrier_set_c2()->final_graph_reshaping(this, n, nop, dead_nodes);
3246 if (!gc_handled) {
3247 final_graph_reshaping_main_switch(n, frc, nop, dead_nodes);
3248 }
3249
3250 // Collect CFG split points
3251 if (n->is_MultiBranch() && !n->is_RangeCheck()) {
3252 frc._tests.push(n);
3253 }
3254 }
3255
3256 void Compile::handle_div_mod_op(Node* n, BasicType bt, bool is_unsigned) {
3257 if (!UseDivMod) {
3258 return;
3259 }
3260
3261 // Check if "a % b" and "a / b" both exist
3262 Node* d = n->find_similar(Op_DivIL(bt, is_unsigned));
3263 if (d == nullptr) {
3264 return;
3265 }
3266
3267 // Replace them with a fused divmod if supported
3268 if (Matcher::has_match_rule(Op_DivModIL(bt, is_unsigned))) {
3269 DivModNode* divmod = DivModNode::make(n, bt, is_unsigned);
3270 // If the divisor input for a Div (or Mod etc.) is not zero, then the control input of the Div is set to zero.
3271 // It could be that the divisor input is found not zero because its type is narrowed down by a CastII in the
3272 // subgraph for that input. Range check CastIIs are removed during final graph reshape. To preserve the dependency
3273 // carried by a CastII, precedence edges are added to the Div node. We need to transfer the precedence edges to the
3274 // DivMod node so the dependency is not lost.
3275 divmod->add_prec_from(n);
3276 divmod->add_prec_from(d);
3277 d->subsume_by(divmod->div_proj(), this);
3278 n->subsume_by(divmod->mod_proj(), this);
3279 } else {
3280 // Replace "a % b" with "a - ((a / b) * b)"
3281 Node* mult = MulNode::make(d, d->in(2), bt);
3282 Node* sub = SubNode::make(d->in(1), mult, bt);
3283 n->subsume_by(sub, this);
3284 }
3285 }
3286
3287 void Compile::final_graph_reshaping_main_switch(Node* n, Final_Reshape_Counts& frc, uint nop, Unique_Node_List& dead_nodes) {
3288 switch( nop ) {
3289 // Count all float operations that may use FPU
3290 case Op_AddHF:
3291 case Op_MulHF:
3292 case Op_AddF:
3293 case Op_SubF:
3294 case Op_MulF:
3295 case Op_DivF:
3296 case Op_NegF:
3297 case Op_ModF:
3298 case Op_ConvI2F:
3299 case Op_ConF:
3300 case Op_CmpF:
3301 case Op_CmpF3:
3302 case Op_StoreF:
3303 case Op_LoadF:
3304 // case Op_ConvL2F: // longs are split into 32-bit halves
3305 frc.inc_float_count();
3306 break;
3307
3308 case Op_ConvF2D:
3309 case Op_ConvD2F:
3310 frc.inc_float_count();
3311 frc.inc_double_count();
3312 break;
3313
3314 // Count all double operations that may use FPU
3315 case Op_AddD:
3316 case Op_SubD:
3317 case Op_MulD:
3318 case Op_DivD:
3319 case Op_NegD:
3320 case Op_ModD:
3321 case Op_ConvI2D:
3322 case Op_ConvD2I:
3323 // case Op_ConvL2D: // handled by leaf call
3324 // case Op_ConvD2L: // handled by leaf call
3325 case Op_ConD:
3326 case Op_CmpD:
3327 case Op_CmpD3:
3328 case Op_StoreD:
3329 case Op_LoadD:
3330 case Op_LoadD_unaligned:
3331 frc.inc_double_count();
3332 break;
3333 case Op_Opaque1: // Remove Opaque Nodes before matching
3334 n->subsume_by(n->in(1), this);
3335 break;
3336 case Op_CallLeafPure: {
3337 // If the pure call is not supported, then lower to a CallLeaf.
3338 if (!Matcher::match_rule_supported(Op_CallLeafPure)) {
3339 CallNode* call = n->as_Call();
3340 CallNode* new_call = new CallLeafNode(call->tf(), call->entry_point(),
3341 call->_name, TypeRawPtr::BOTTOM);
3342 new_call->init_req(TypeFunc::Control, call->in(TypeFunc::Control));
3343 new_call->init_req(TypeFunc::I_O, C->top());
3344 new_call->init_req(TypeFunc::Memory, C->top());
3345 new_call->init_req(TypeFunc::ReturnAdr, C->top());
3346 new_call->init_req(TypeFunc::FramePtr, C->top());
3347 for (unsigned int i = TypeFunc::Parms; i < call->tf()->domain()->cnt(); i++) {
3348 new_call->init_req(i, call->in(i));
3349 }
3350 n->subsume_by(new_call, this);
3351 }
3352 frc.inc_call_count();
3353 break;
3354 }
3355 case Op_CallStaticJava:
3356 case Op_CallJava:
3357 case Op_CallDynamicJava:
3358 frc.inc_java_call_count(); // Count java call site;
3359 case Op_CallRuntime:
3360 case Op_CallLeaf:
3361 case Op_CallLeafVector:
3362 case Op_CallLeafNoFP: {
3363 assert (n->is_Call(), "");
3364 CallNode *call = n->as_Call();
3365 // Count call sites where the FP mode bit would have to be flipped.
3366 // Do not count uncommon runtime calls:
3367 // uncommon_trap, _complete_monitor_locking, _complete_monitor_unlocking,
3368 // _new_Java, _new_typeArray, _new_objArray, _rethrow_Java, ...
3369 if (!call->is_CallStaticJava() || !call->as_CallStaticJava()->_name) {
3370 frc.inc_call_count(); // Count the call site
3371 } else { // See if uncommon argument is shared
3372 Node *n = call->in(TypeFunc::Parms);
3373 int nop = n->Opcode();
3374 // Clone shared simple arguments to uncommon calls, item (1).
3375 if (n->outcnt() > 1 &&
3376 !n->is_Proj() &&
3377 nop != Op_CreateEx &&
3378 nop != Op_CheckCastPP &&
3379 nop != Op_DecodeN &&
3380 nop != Op_DecodeNKlass &&
3381 !n->is_Mem() &&
3382 !n->is_Phi()) {
3383 Node *x = n->clone();
3384 call->set_req(TypeFunc::Parms, x);
3385 }
3386 }
3387 break;
3388 }
3389 case Op_StoreB:
3390 case Op_StoreC:
3391 case Op_StoreI:
3392 case Op_StoreL:
3393 case Op_CompareAndSwapB:
3394 case Op_CompareAndSwapS:
3395 case Op_CompareAndSwapI:
3396 case Op_CompareAndSwapL:
3397 case Op_CompareAndSwapP:
3398 case Op_CompareAndSwapN:
3399 case Op_WeakCompareAndSwapB:
3400 case Op_WeakCompareAndSwapS:
3401 case Op_WeakCompareAndSwapI:
3402 case Op_WeakCompareAndSwapL:
3403 case Op_WeakCompareAndSwapP:
3404 case Op_WeakCompareAndSwapN:
3405 case Op_CompareAndExchangeB:
3406 case Op_CompareAndExchangeS:
3407 case Op_CompareAndExchangeI:
3408 case Op_CompareAndExchangeL:
3409 case Op_CompareAndExchangeP:
3410 case Op_CompareAndExchangeN:
3411 case Op_GetAndAddS:
3412 case Op_GetAndAddB:
3413 case Op_GetAndAddI:
3414 case Op_GetAndAddL:
3415 case Op_GetAndSetS:
3416 case Op_GetAndSetB:
3417 case Op_GetAndSetI:
3418 case Op_GetAndSetL:
3419 case Op_GetAndSetP:
3420 case Op_GetAndSetN:
3421 case Op_StoreP:
3422 case Op_StoreN:
3423 case Op_StoreNKlass:
3424 case Op_LoadB:
3425 case Op_LoadUB:
3426 case Op_LoadUS:
3427 case Op_LoadI:
3428 case Op_LoadKlass:
3429 case Op_LoadNKlass:
3430 case Op_LoadL:
3431 case Op_LoadL_unaligned:
3432 case Op_LoadP:
3433 case Op_LoadN:
3434 case Op_LoadRange:
3435 case Op_LoadS:
3436 break;
3437
3438 case Op_AddP: { // Assert sane base pointers
3439 Node *addp = n->in(AddPNode::Address);
3440 assert(n->as_AddP()->address_input_has_same_base(), "Base pointers must match (addp %u)", addp->_idx );
3441 #ifdef _LP64
3442 if (addp->Opcode() == Op_ConP &&
3443 addp == n->in(AddPNode::Base) &&
3444 n->in(AddPNode::Offset)->is_Con()) {
3445 // If the transformation of ConP to ConN+DecodeN is beneficial depends
3446 // on the platform and on the compressed oops mode.
3447 // Use addressing with narrow klass to load with offset on x86.
3448 // Some platforms can use the constant pool to load ConP.
3449 // Do this transformation here since IGVN will convert ConN back to ConP.
3450 const Type* t = addp->bottom_type();
3451 bool is_oop = t->isa_oopptr() != nullptr;
3452 bool is_klass = t->isa_klassptr() != nullptr;
3453
3454 if ((is_oop && UseCompressedOops && Matcher::const_oop_prefer_decode() ) ||
3455 (is_klass && Matcher::const_klass_prefer_decode() &&
3456 t->isa_klassptr()->exact_klass()->is_in_encoding_range())) {
3457 Node* nn = nullptr;
3458
3459 int op = is_oop ? Op_ConN : Op_ConNKlass;
3460
3461 // Look for existing ConN node of the same exact type.
3462 Node* r = root();
3463 uint cnt = r->outcnt();
3464 for (uint i = 0; i < cnt; i++) {
3465 Node* m = r->raw_out(i);
3466 if (m!= nullptr && m->Opcode() == op &&
3467 m->bottom_type()->make_ptr() == t) {
3468 nn = m;
3469 break;
3470 }
3471 }
3472 if (nn != nullptr) {
3473 // Decode a narrow oop to match address
3474 // [R12 + narrow_oop_reg<<3 + offset]
3475 if (is_oop) {
3476 nn = new DecodeNNode(nn, t);
3477 } else {
3478 nn = new DecodeNKlassNode(nn, t);
3479 }
3480 // Check for succeeding AddP which uses the same Base.
3481 // Otherwise we will run into the assertion above when visiting that guy.
3482 for (uint i = 0; i < n->outcnt(); ++i) {
3483 Node *out_i = n->raw_out(i);
3484 if (out_i && out_i->is_AddP() && out_i->in(AddPNode::Base) == addp) {
3485 out_i->set_req(AddPNode::Base, nn);
3486 #ifdef ASSERT
3487 for (uint j = 0; j < out_i->outcnt(); ++j) {
3488 Node *out_j = out_i->raw_out(j);
3489 assert(out_j == nullptr || !out_j->is_AddP() || out_j->in(AddPNode::Base) != addp,
3490 "more than 2 AddP nodes in a chain (out_j %u)", out_j->_idx);
3491 }
3492 #endif
3493 }
3494 }
3495 n->set_req(AddPNode::Base, nn);
3496 n->set_req(AddPNode::Address, nn);
3497 if (addp->outcnt() == 0) {
3498 addp->disconnect_inputs(this);
3499 }
3500 }
3501 }
3502 }
3503 #endif
3504 break;
3505 }
3506
3507 case Op_CastPP: {
3508 // Remove CastPP nodes to gain more freedom during scheduling but
3509 // keep the dependency they encode as control or precedence edges
3510 // (if control is set already) on memory operations. Some CastPP
3511 // nodes don't have a control (don't carry a dependency): skip
3512 // those.
3513 if (n->in(0) != nullptr) {
3514 ResourceMark rm;
3515 Unique_Node_List wq;
3516 wq.push(n);
3517 for (uint next = 0; next < wq.size(); ++next) {
3518 Node *m = wq.at(next);
3519 for (DUIterator_Fast imax, i = m->fast_outs(imax); i < imax; i++) {
3520 Node* use = m->fast_out(i);
3521 if (use->is_Mem() || use->is_EncodeNarrowPtr()) {
3522 use->ensure_control_or_add_prec(n->in(0));
3523 } else {
3524 switch(use->Opcode()) {
3525 case Op_AddP:
3526 case Op_DecodeN:
3527 case Op_DecodeNKlass:
3528 case Op_CheckCastPP:
3529 case Op_CastPP:
3530 wq.push(use);
3531 break;
3532 }
3533 }
3534 }
3535 }
3536 }
3537 const bool is_LP64 = LP64_ONLY(true) NOT_LP64(false);
3538 if (is_LP64 && n->in(1)->is_DecodeN() && Matcher::gen_narrow_oop_implicit_null_checks()) {
3539 Node* in1 = n->in(1);
3540 const Type* t = n->bottom_type();
3541 Node* new_in1 = in1->clone();
3542 new_in1->as_DecodeN()->set_type(t);
3543
3544 if (!Matcher::narrow_oop_use_complex_address()) {
3545 //
3546 // x86, ARM and friends can handle 2 adds in addressing mode
3547 // and Matcher can fold a DecodeN node into address by using
3548 // a narrow oop directly and do implicit null check in address:
3549 //
3550 // [R12 + narrow_oop_reg<<3 + offset]
3551 // NullCheck narrow_oop_reg
3552 //
3553 // On other platforms (Sparc) we have to keep new DecodeN node and
3554 // use it to do implicit null check in address:
3555 //
3556 // decode_not_null narrow_oop_reg, base_reg
3557 // [base_reg + offset]
3558 // NullCheck base_reg
3559 //
3560 // Pin the new DecodeN node to non-null path on these platform (Sparc)
3561 // to keep the information to which null check the new DecodeN node
3562 // corresponds to use it as value in implicit_null_check().
3563 //
3564 new_in1->set_req(0, n->in(0));
3565 }
3566
3567 n->subsume_by(new_in1, this);
3568 if (in1->outcnt() == 0) {
3569 in1->disconnect_inputs(this);
3570 }
3571 } else {
3572 n->subsume_by(n->in(1), this);
3573 if (n->outcnt() == 0) {
3574 n->disconnect_inputs(this);
3575 }
3576 }
3577 break;
3578 }
3579 case Op_CastII: {
3580 n->as_CastII()->remove_range_check_cast(this);
3581 break;
3582 }
3583 #ifdef _LP64
3584 case Op_CmpP:
3585 // Do this transformation here to preserve CmpPNode::sub() and
3586 // other TypePtr related Ideal optimizations (for example, ptr nullness).
3587 if (n->in(1)->is_DecodeNarrowPtr() || n->in(2)->is_DecodeNarrowPtr()) {
3588 Node* in1 = n->in(1);
3589 Node* in2 = n->in(2);
3590 if (!in1->is_DecodeNarrowPtr()) {
3591 in2 = in1;
3592 in1 = n->in(2);
3593 }
3594 assert(in1->is_DecodeNarrowPtr(), "sanity");
3595
3596 Node* new_in2 = nullptr;
3597 if (in2->is_DecodeNarrowPtr()) {
3598 assert(in2->Opcode() == in1->Opcode(), "must be same node type");
3599 new_in2 = in2->in(1);
3600 } else if (in2->Opcode() == Op_ConP) {
3601 const Type* t = in2->bottom_type();
3602 if (t == TypePtr::NULL_PTR) {
3603 assert(in1->is_DecodeN(), "compare klass to null?");
3604 // Don't convert CmpP null check into CmpN if compressed
3605 // oops implicit null check is not generated.
3606 // This will allow to generate normal oop implicit null check.
3607 if (Matcher::gen_narrow_oop_implicit_null_checks())
3608 new_in2 = ConNode::make(TypeNarrowOop::NULL_PTR);
3609 //
3610 // This transformation together with CastPP transformation above
3611 // will generated code for implicit null checks for compressed oops.
3612 //
3613 // The original code after Optimize()
3614 //
3615 // LoadN memory, narrow_oop_reg
3616 // decode narrow_oop_reg, base_reg
3617 // CmpP base_reg, nullptr
3618 // CastPP base_reg // NotNull
3619 // Load [base_reg + offset], val_reg
3620 //
3621 // after these transformations will be
3622 //
3623 // LoadN memory, narrow_oop_reg
3624 // CmpN narrow_oop_reg, nullptr
3625 // decode_not_null narrow_oop_reg, base_reg
3626 // Load [base_reg + offset], val_reg
3627 //
3628 // and the uncommon path (== nullptr) will use narrow_oop_reg directly
3629 // since narrow oops can be used in debug info now (see the code in
3630 // final_graph_reshaping_walk()).
3631 //
3632 // At the end the code will be matched to
3633 // on x86:
3634 //
3635 // Load_narrow_oop memory, narrow_oop_reg
3636 // Load [R12 + narrow_oop_reg<<3 + offset], val_reg
3637 // NullCheck narrow_oop_reg
3638 //
3639 // and on sparc:
3640 //
3641 // Load_narrow_oop memory, narrow_oop_reg
3642 // decode_not_null narrow_oop_reg, base_reg
3643 // Load [base_reg + offset], val_reg
3644 // NullCheck base_reg
3645 //
3646 } else if (t->isa_oopptr()) {
3647 new_in2 = ConNode::make(t->make_narrowoop());
3648 } else if (t->isa_klassptr()) {
3649 ciKlass* klass = t->is_klassptr()->exact_klass();
3650 if (klass->is_in_encoding_range()) {
3651 new_in2 = ConNode::make(t->make_narrowklass());
3652 }
3653 }
3654 }
3655 if (new_in2 != nullptr) {
3656 Node* cmpN = new CmpNNode(in1->in(1), new_in2);
3657 n->subsume_by(cmpN, this);
3658 if (in1->outcnt() == 0) {
3659 in1->disconnect_inputs(this);
3660 }
3661 if (in2->outcnt() == 0) {
3662 in2->disconnect_inputs(this);
3663 }
3664 }
3665 }
3666 break;
3667
3668 case Op_DecodeN:
3669 case Op_DecodeNKlass:
3670 assert(!n->in(1)->is_EncodeNarrowPtr(), "should be optimized out");
3671 // DecodeN could be pinned when it can't be fold into
3672 // an address expression, see the code for Op_CastPP above.
3673 assert(n->in(0) == nullptr || (UseCompressedOops && !Matcher::narrow_oop_use_complex_address()), "no control");
3674 break;
3675
3676 case Op_EncodeP:
3677 case Op_EncodePKlass: {
3678 Node* in1 = n->in(1);
3679 if (in1->is_DecodeNarrowPtr()) {
3680 n->subsume_by(in1->in(1), this);
3681 } else if (in1->Opcode() == Op_ConP) {
3682 const Type* t = in1->bottom_type();
3683 if (t == TypePtr::NULL_PTR) {
3684 assert(t->isa_oopptr(), "null klass?");
3685 n->subsume_by(ConNode::make(TypeNarrowOop::NULL_PTR), this);
3686 } else if (t->isa_oopptr()) {
3687 n->subsume_by(ConNode::make(t->make_narrowoop()), this);
3688 } else if (t->isa_klassptr()) {
3689 ciKlass* klass = t->is_klassptr()->exact_klass();
3690 if (klass->is_in_encoding_range()) {
3691 n->subsume_by(ConNode::make(t->make_narrowklass()), this);
3692 } else {
3693 assert(false, "unencodable klass in ConP -> EncodeP");
3694 C->record_failure("unencodable klass in ConP -> EncodeP");
3695 }
3696 }
3697 }
3698 if (in1->outcnt() == 0) {
3699 in1->disconnect_inputs(this);
3700 }
3701 break;
3702 }
3703
3704 case Op_Proj: {
3705 if (OptimizeStringConcat || IncrementalInline) {
3706 ProjNode* proj = n->as_Proj();
3707 if (proj->_is_io_use) {
3708 assert(proj->_con == TypeFunc::I_O || proj->_con == TypeFunc::Memory, "");
3709 // Separate projections were used for the exception path which
3710 // are normally removed by a late inline. If it wasn't inlined
3711 // then they will hang around and should just be replaced with
3712 // the original one. Merge them.
3713 Node* non_io_proj = proj->in(0)->as_Multi()->proj_out_or_null(proj->_con, false /*is_io_use*/);
3714 if (non_io_proj != nullptr) {
3715 proj->subsume_by(non_io_proj , this);
3716 }
3717 }
3718 }
3719 break;
3720 }
3721
3722 case Op_Phi:
3723 if (n->as_Phi()->bottom_type()->isa_narrowoop() || n->as_Phi()->bottom_type()->isa_narrowklass()) {
3724 // The EncodeP optimization may create Phi with the same edges
3725 // for all paths. It is not handled well by Register Allocator.
3726 Node* unique_in = n->in(1);
3727 assert(unique_in != nullptr, "");
3728 uint cnt = n->req();
3729 for (uint i = 2; i < cnt; i++) {
3730 Node* m = n->in(i);
3731 assert(m != nullptr, "");
3732 if (unique_in != m)
3733 unique_in = nullptr;
3734 }
3735 if (unique_in != nullptr) {
3736 n->subsume_by(unique_in, this);
3737 }
3738 }
3739 break;
3740
3741 #endif
3742
3743 case Op_ModI:
3744 handle_div_mod_op(n, T_INT, false);
3745 break;
3746
3747 case Op_ModL:
3748 handle_div_mod_op(n, T_LONG, false);
3749 break;
3750
3751 case Op_UModI:
3752 handle_div_mod_op(n, T_INT, true);
3753 break;
3754
3755 case Op_UModL:
3756 handle_div_mod_op(n, T_LONG, true);
3757 break;
3758
3759 case Op_LoadVector:
3760 case Op_StoreVector:
3761 #ifdef ASSERT
3762 // Add VerifyVectorAlignment node between adr and load / store.
3763 if (VerifyAlignVector && Matcher::has_match_rule(Op_VerifyVectorAlignment)) {
3764 bool must_verify_alignment = n->is_LoadVector() ? n->as_LoadVector()->must_verify_alignment() :
3765 n->as_StoreVector()->must_verify_alignment();
3766 if (must_verify_alignment) {
3767 jlong vector_width = n->is_LoadVector() ? n->as_LoadVector()->memory_size() :
3768 n->as_StoreVector()->memory_size();
3769 // The memory access should be aligned to the vector width in bytes.
3770 // However, the underlying array is possibly less well aligned, but at least
3771 // to ObjectAlignmentInBytes. Hence, even if multiple arrays are accessed in
3772 // a loop we can expect at least the following alignment:
3773 jlong guaranteed_alignment = MIN2(vector_width, (jlong)ObjectAlignmentInBytes);
3774 assert(2 <= guaranteed_alignment && guaranteed_alignment <= 64, "alignment must be in range");
3775 assert(is_power_of_2(guaranteed_alignment), "alignment must be power of 2");
3776 // Create mask from alignment. e.g. 0b1000 -> 0b0111
3777 jlong mask = guaranteed_alignment - 1;
3778 Node* mask_con = ConLNode::make(mask);
3779 VerifyVectorAlignmentNode* va = new VerifyVectorAlignmentNode(n->in(MemNode::Address), mask_con);
3780 n->set_req(MemNode::Address, va);
3781 }
3782 }
3783 #endif
3784 break;
3785
3786 case Op_LoadVectorGather:
3787 case Op_StoreVectorScatter:
3788 case Op_LoadVectorGatherMasked:
3789 case Op_StoreVectorScatterMasked:
3790 case Op_VectorCmpMasked:
3791 case Op_VectorMaskGen:
3792 case Op_LoadVectorMasked:
3793 case Op_StoreVectorMasked:
3794 break;
3795
3796 case Op_AddReductionVI:
3797 case Op_AddReductionVL:
3798 case Op_AddReductionVHF:
3799 case Op_AddReductionVF:
3800 case Op_AddReductionVD:
3801 case Op_MulReductionVI:
3802 case Op_MulReductionVL:
3803 case Op_MulReductionVHF:
3804 case Op_MulReductionVF:
3805 case Op_MulReductionVD:
3806 case Op_MinReductionV:
3807 case Op_MaxReductionV:
3808 case Op_UMinReductionV:
3809 case Op_UMaxReductionV:
3810 case Op_AndReductionV:
3811 case Op_OrReductionV:
3812 case Op_XorReductionV:
3813 break;
3814
3815 case Op_PackB:
3816 case Op_PackS:
3817 case Op_PackI:
3818 case Op_PackF:
3819 case Op_PackL:
3820 case Op_PackD:
3821 if (n->req()-1 > 2) {
3822 // Replace many operand PackNodes with a binary tree for matching
3823 PackNode* p = (PackNode*) n;
3824 Node* btp = p->binary_tree_pack(1, n->req());
3825 n->subsume_by(btp, this);
3826 }
3827 break;
3828 case Op_Loop:
3829 // When StressCountedLoop is enabled, this loop may intentionally avoid a counted loop conversion.
3830 // This is expected behavior for the stress mode, which exercises alternative compilation paths.
3831 if (!StressCountedLoop) {
3832 assert(!n->as_Loop()->is_loop_nest_inner_loop() || _loop_opts_cnt == 0, "should have been turned into a counted loop");
3833 }
3834 case Op_CountedLoop:
3835 case Op_LongCountedLoop:
3836 case Op_OuterStripMinedLoop:
3837 if (n->as_Loop()->is_inner_loop()) {
3838 frc.inc_inner_loop_count();
3839 }
3840 n->as_Loop()->verify_strip_mined(0);
3841 break;
3842 case Op_LShiftI:
3843 case Op_RShiftI:
3844 case Op_URShiftI:
3845 case Op_LShiftL:
3846 case Op_RShiftL:
3847 case Op_URShiftL:
3848 if (Matcher::need_masked_shift_count) {
3849 // The cpu's shift instructions don't restrict the count to the
3850 // lower 5/6 bits. We need to do the masking ourselves.
3851 Node* in2 = n->in(2);
3852 juint mask = (n->bottom_type() == TypeInt::INT) ? (BitsPerInt - 1) : (BitsPerLong - 1);
3853 const TypeInt* t = in2->find_int_type();
3854 if (t != nullptr && t->is_con()) {
3855 juint shift = t->get_con();
3856 if (shift > mask) { // Unsigned cmp
3857 n->set_req(2, ConNode::make(TypeInt::make(shift & mask)));
3858 }
3859 } else {
3860 if (t == nullptr || t->_lo < 0 || t->_hi > (int)mask) {
3861 Node* shift = new AndINode(in2, ConNode::make(TypeInt::make(mask)));
3862 n->set_req(2, shift);
3863 }
3864 }
3865 if (in2->outcnt() == 0) { // Remove dead node
3866 in2->disconnect_inputs(this);
3867 }
3868 }
3869 break;
3870 case Op_MemBarStoreStore:
3871 case Op_MemBarRelease:
3872 // Break the link with AllocateNode: it is no longer useful and
3873 // confuses register allocation.
3874 if (n->req() > MemBarNode::Precedent) {
3875 n->set_req(MemBarNode::Precedent, top());
3876 }
3877 break;
3878 case Op_MemBarAcquire: {
3879 if (n->as_MemBar()->trailing_load() && n->req() > MemBarNode::Precedent) {
3880 // At parse time, the trailing MemBarAcquire for a volatile load
3881 // is created with an edge to the load. After optimizations,
3882 // that input may be a chain of Phis. If those phis have no
3883 // other use, then the MemBarAcquire keeps them alive and
3884 // register allocation can be confused.
3885 dead_nodes.push(n->in(MemBarNode::Precedent));
3886 n->set_req(MemBarNode::Precedent, top());
3887 }
3888 break;
3889 }
3890 case Op_Blackhole:
3891 break;
3892 case Op_RangeCheck: {
3893 RangeCheckNode* rc = n->as_RangeCheck();
3894 Node* iff = new IfNode(rc->in(0), rc->in(1), rc->_prob, rc->_fcnt);
3895 n->subsume_by(iff, this);
3896 frc._tests.push(iff);
3897 break;
3898 }
3899 case Op_ConvI2L: {
3900 if (!Matcher::convi2l_type_required) {
3901 // Code generation on some platforms doesn't need accurate
3902 // ConvI2L types. Widening the type can help remove redundant
3903 // address computations.
3904 n->as_Type()->set_type(TypeLong::INT);
3905 ResourceMark rm;
3906 Unique_Node_List wq;
3907 wq.push(n);
3908 for (uint next = 0; next < wq.size(); next++) {
3909 Node *m = wq.at(next);
3910
3911 for(;;) {
3912 // Loop over all nodes with identical inputs edges as m
3913 Node* k = m->find_similar(m->Opcode());
3914 if (k == nullptr) {
3915 break;
3916 }
3917 // Push their uses so we get a chance to remove node made
3918 // redundant
3919 for (DUIterator_Fast imax, i = k->fast_outs(imax); i < imax; i++) {
3920 Node* u = k->fast_out(i);
3921 if (u->Opcode() == Op_LShiftL ||
3922 u->Opcode() == Op_AddL ||
3923 u->Opcode() == Op_SubL ||
3924 u->Opcode() == Op_AddP) {
3925 wq.push(u);
3926 }
3927 }
3928 // Replace all nodes with identical edges as m with m
3929 k->subsume_by(m, this);
3930 }
3931 }
3932 }
3933 break;
3934 }
3935 case Op_CmpUL: {
3936 if (!Matcher::has_match_rule(Op_CmpUL)) {
3937 // No support for unsigned long comparisons
3938 ConINode* sign_pos = new ConINode(TypeInt::make(BitsPerLong - 1));
3939 Node* sign_bit_mask = new RShiftLNode(n->in(1), sign_pos);
3940 Node* orl = new OrLNode(n->in(1), sign_bit_mask);
3941 ConLNode* remove_sign_mask = new ConLNode(TypeLong::make(max_jlong));
3942 Node* andl = new AndLNode(orl, remove_sign_mask);
3943 Node* cmp = new CmpLNode(andl, n->in(2));
3944 n->subsume_by(cmp, this);
3945 }
3946 break;
3947 }
3948 #ifdef ASSERT
3949 case Op_ConNKlass: {
3950 const TypePtr* tp = n->as_Type()->type()->make_ptr();
3951 ciKlass* klass = tp->is_klassptr()->exact_klass();
3952 assert(klass->is_in_encoding_range(), "klass cannot be compressed");
3953 break;
3954 }
3955 #endif
3956 default:
3957 assert(!n->is_Call(), "");
3958 assert(!n->is_Mem(), "");
3959 assert(nop != Op_ProfileBoolean, "should be eliminated during IGVN");
3960 break;
3961 }
3962 }
3963
3964 //------------------------------final_graph_reshaping_walk---------------------
3965 // Replacing Opaque nodes with their input in final_graph_reshaping_impl(),
3966 // requires that the walk visits a node's inputs before visiting the node.
3967 void Compile::final_graph_reshaping_walk(Node_Stack& nstack, Node* root, Final_Reshape_Counts& frc, Unique_Node_List& dead_nodes) {
3968 Unique_Node_List sfpt;
3969
3970 frc._visited.set(root->_idx); // first, mark node as visited
3971 uint cnt = root->req();
3972 Node *n = root;
3973 uint i = 0;
3974 while (true) {
3975 if (i < cnt) {
3976 // Place all non-visited non-null inputs onto stack
3977 Node* m = n->in(i);
3978 ++i;
3979 if (m != nullptr && !frc._visited.test_set(m->_idx)) {
3980 if (m->is_SafePoint() && m->as_SafePoint()->jvms() != nullptr) {
3981 // compute worst case interpreter size in case of a deoptimization
3982 update_interpreter_frame_size(m->as_SafePoint()->jvms()->interpreter_frame_size());
3983
3984 sfpt.push(m);
3985 }
3986 cnt = m->req();
3987 nstack.push(n, i); // put on stack parent and next input's index
3988 n = m;
3989 i = 0;
3990 }
3991 } else {
3992 // Now do post-visit work
3993 final_graph_reshaping_impl(n, frc, dead_nodes);
3994 if (nstack.is_empty())
3995 break; // finished
3996 n = nstack.node(); // Get node from stack
3997 cnt = n->req();
3998 i = nstack.index();
3999 nstack.pop(); // Shift to the next node on stack
4000 }
4001 }
4002
4003 expand_reachability_edges(sfpt);
4004
4005 // Skip next transformation if compressed oops are not used.
4006 if (UseCompressedOops && !Matcher::gen_narrow_oop_implicit_null_checks())
4007 return;
4008
4009 // Go over ReachabilityFence nodes to skip DecodeN nodes for referents.
4010 // The sole purpose of RF node is to keep the referent oop alive and
4011 // decoding the oop for that is not needed.
4012 for (int i = 0; i < C->reachability_fences_count(); i++) {
4013 ReachabilityFenceNode* rf = C->reachability_fence(i);
4014 DecodeNNode* dn = rf->in(1)->isa_DecodeN();
4015 if (dn != nullptr) {
4016 if (!dn->has_non_debug_uses() || Matcher::narrow_oop_use_complex_address()) {
4017 rf->set_req(1, dn->in(1));
4018 if (dn->outcnt() == 0) {
4019 dn->disconnect_inputs(this);
4020 }
4021 }
4022 }
4023 }
4024
4025 // Go over safepoints nodes to skip DecodeN/DecodeNKlass nodes for debug edges.
4026 // It could be done for an uncommon traps or any safepoints/calls
4027 // if the DecodeN/DecodeNKlass node is referenced only in a debug info.
4028 while (sfpt.size() > 0) {
4029 n = sfpt.pop();
4030 JVMState *jvms = n->as_SafePoint()->jvms();
4031 assert(jvms != nullptr, "sanity");
4032 int start = jvms->debug_start();
4033 int end = n->req();
4034 bool is_uncommon = (n->is_CallStaticJava() &&
4035 n->as_CallStaticJava()->uncommon_trap_request() != 0);
4036 for (int j = start; j < end; j++) {
4037 Node* in = n->in(j);
4038 if (in->is_DecodeNarrowPtr() && (is_uncommon || !in->has_non_debug_uses())) {
4039 n->set_req(j, in->in(1));
4040 if (in->outcnt() == 0) {
4041 in->disconnect_inputs(this);
4042 }
4043 }
4044 }
4045 }
4046 }
4047
4048 //------------------------------final_graph_reshaping--------------------------
4049 // Final Graph Reshaping.
4050 //
4051 // (1) Clone simple inputs to uncommon calls, so they can be scheduled late
4052 // and not commoned up and forced early. Must come after regular
4053 // optimizations to avoid GVN undoing the cloning. Clone constant
4054 // inputs to Loop Phis; these will be split by the allocator anyways.
4055 // Remove Opaque nodes.
4056 // (2) Move last-uses by commutative operations to the left input to encourage
4057 // Intel update-in-place two-address operations and better register usage
4058 // on RISCs. Must come after regular optimizations to avoid GVN Ideal
4059 // calls canonicalizing them back.
4060 // (3) Count the number of double-precision FP ops, single-precision FP ops
4061 // and call sites. On Intel, we can get correct rounding either by
4062 // forcing singles to memory (requires extra stores and loads after each
4063 // FP bytecode) or we can set a rounding mode bit (requires setting and
4064 // clearing the mode bit around call sites). The mode bit is only used
4065 // if the relative frequency of single FP ops to calls is low enough.
4066 // This is a key transform for SPEC mpeg_audio.
4067 // (4) Detect infinite loops; blobs of code reachable from above but not
4068 // below. Several of the Code_Gen algorithms fail on such code shapes,
4069 // so we simply bail out. Happens a lot in ZKM.jar, but also happens
4070 // from time to time in other codes (such as -Xcomp finalizer loops, etc).
4071 // Detection is by looking for IfNodes where only 1 projection is
4072 // reachable from below or CatchNodes missing some targets.
4073 // (5) Assert for insane oop offsets in debug mode.
4074
4075 bool Compile::final_graph_reshaping() {
4076 // an infinite loop may have been eliminated by the optimizer,
4077 // in which case the graph will be empty.
4078 if (root()->req() == 1) {
4079 // Do not compile method that is only a trivial infinite loop,
4080 // since the content of the loop may have been eliminated.
4081 record_method_not_compilable("trivial infinite loop");
4082 return true;
4083 }
4084
4085 // Expensive nodes have their control input set to prevent the GVN
4086 // from freely commoning them. There's no GVN beyond this point so
4087 // no need to keep the control input. We want the expensive nodes to
4088 // be freely moved to the least frequent code path by gcm.
4089 assert(OptimizeExpensiveOps || expensive_count() == 0, "optimization off but list non empty?");
4090 for (int i = 0; i < expensive_count(); i++) {
4091 _expensive_nodes.at(i)->set_req(0, nullptr);
4092 }
4093
4094 Final_Reshape_Counts frc;
4095
4096 // Visit everybody reachable!
4097 // Allocate stack of size C->live_nodes()/2 to avoid frequent realloc
4098 Node_Stack nstack(live_nodes() >> 1);
4099 Unique_Node_List dead_nodes;
4100 final_graph_reshaping_walk(nstack, root(), frc, dead_nodes);
4101
4102 // Check for unreachable (from below) code (i.e., infinite loops).
4103 for( uint i = 0; i < frc._tests.size(); i++ ) {
4104 MultiBranchNode *n = frc._tests[i]->as_MultiBranch();
4105 // Get number of CFG targets.
4106 // Note that PCTables include exception targets after calls.
4107 uint required_outcnt = n->required_outcnt();
4108 if (n->outcnt() != required_outcnt) {
4109 // Check for a few special cases. Rethrow Nodes never take the
4110 // 'fall-thru' path, so expected kids is 1 less.
4111 if (n->is_PCTable() && n->in(0) && n->in(0)->in(0)) {
4112 if (n->in(0)->in(0)->is_Call()) {
4113 CallNode* call = n->in(0)->in(0)->as_Call();
4114 if (call->entry_point() == OptoRuntime::rethrow_stub()) {
4115 required_outcnt--; // Rethrow always has 1 less kid
4116 } else if (call->req() > TypeFunc::Parms &&
4117 call->is_CallDynamicJava()) {
4118 // Check for null receiver. In such case, the optimizer has
4119 // detected that the virtual call will always result in a null
4120 // pointer exception. The fall-through projection of this CatchNode
4121 // will not be populated.
4122 Node* arg0 = call->in(TypeFunc::Parms);
4123 if (arg0->is_Type() &&
4124 arg0->as_Type()->type()->higher_equal(TypePtr::NULL_PTR)) {
4125 required_outcnt--;
4126 }
4127 } else if (call->entry_point() == OptoRuntime::new_array_Java() ||
4128 call->entry_point() == OptoRuntime::new_array_nozero_Java()) {
4129 // Check for illegal array length. In such case, the optimizer has
4130 // detected that the allocation attempt will always result in an
4131 // exception. There is no fall-through projection of this CatchNode .
4132 assert(call->is_CallStaticJava(), "static call expected");
4133 assert(call->req() == call->jvms()->endoff() + 1, "missing extra input");
4134 uint valid_length_test_input = call->req() - 1;
4135 Node* valid_length_test = call->in(valid_length_test_input);
4136 call->del_req(valid_length_test_input);
4137 if (valid_length_test->find_int_con(1) == 0) {
4138 required_outcnt--;
4139 }
4140 dead_nodes.push(valid_length_test);
4141 assert(n->outcnt() == required_outcnt, "malformed control flow");
4142 continue;
4143 }
4144 }
4145 }
4146
4147 // Recheck with a better notion of 'required_outcnt'
4148 if (n->outcnt() != required_outcnt) {
4149 record_method_not_compilable("malformed control flow");
4150 return true; // Not all targets reachable!
4151 }
4152 } else if (n->is_PCTable() && n->in(0) && n->in(0)->in(0) && n->in(0)->in(0)->is_Call()) {
4153 CallNode* call = n->in(0)->in(0)->as_Call();
4154 if (call->entry_point() == OptoRuntime::new_array_Java() ||
4155 call->entry_point() == OptoRuntime::new_array_nozero_Java()) {
4156 assert(call->is_CallStaticJava(), "static call expected");
4157 assert(call->req() == call->jvms()->endoff() + 1, "missing extra input");
4158 uint valid_length_test_input = call->req() - 1;
4159 dead_nodes.push(call->in(valid_length_test_input));
4160 call->del_req(valid_length_test_input); // valid length test useless now
4161 }
4162 }
4163 // Check that I actually visited all kids. Unreached kids
4164 // must be infinite loops.
4165 for (DUIterator_Fast jmax, j = n->fast_outs(jmax); j < jmax; j++)
4166 if (!frc._visited.test(n->fast_out(j)->_idx)) {
4167 record_method_not_compilable("infinite loop");
4168 return true; // Found unvisited kid; must be unreach
4169 }
4170
4171 // Here so verification code in final_graph_reshaping_walk()
4172 // always see an OuterStripMinedLoopEnd
4173 if (n->is_OuterStripMinedLoopEnd() || n->is_LongCountedLoopEnd()) {
4174 IfNode* init_iff = n->as_If();
4175 Node* iff = new IfNode(init_iff->in(0), init_iff->in(1), init_iff->_prob, init_iff->_fcnt);
4176 n->subsume_by(iff, this);
4177 }
4178 }
4179
4180 while (dead_nodes.size() > 0) {
4181 Node* m = dead_nodes.pop();
4182 if (m->outcnt() == 0 && m != top()) {
4183 for (uint j = 0; j < m->req(); j++) {
4184 Node* in = m->in(j);
4185 if (in != nullptr) {
4186 dead_nodes.push(in);
4187 }
4188 }
4189 m->disconnect_inputs(this);
4190 }
4191 }
4192
4193 set_java_calls(frc.get_java_call_count());
4194 set_inner_loops(frc.get_inner_loop_count());
4195
4196 // No infinite loops, no reason to bail out.
4197 return false;
4198 }
4199
4200 //-----------------------------too_many_traps----------------------------------
4201 // Report if there are too many traps at the current method and bci.
4202 // Return true if there was a trap, and/or PerMethodTrapLimit is exceeded.
4203 bool Compile::too_many_traps(ciMethod* method,
4204 int bci,
4205 Deoptimization::DeoptReason reason) {
4206 ciMethodData* md = method->method_data();
4207 if (md->is_empty()) {
4208 // Assume the trap has not occurred, or that it occurred only
4209 // because of a transient condition during start-up in the interpreter.
4210 return false;
4211 }
4212 ciMethod* m = Deoptimization::reason_is_speculate(reason) ? this->method() : nullptr;
4213 if (md->has_trap_at(bci, m, reason) != 0) {
4214 // Assume PerBytecodeTrapLimit==0, for a more conservative heuristic.
4215 // Also, if there are multiple reasons, or if there is no per-BCI record,
4216 // assume the worst.
4217 if (log())
4218 log()->elem("observe trap='%s' count='%d'",
4219 Deoptimization::trap_reason_name(reason),
4220 md->trap_count(reason));
4221 return true;
4222 } else {
4223 // Ignore method/bci and see if there have been too many globally.
4224 return too_many_traps(reason, md);
4225 }
4226 }
4227
4228 // Less-accurate variant which does not require a method and bci.
4229 bool Compile::too_many_traps(Deoptimization::DeoptReason reason,
4230 ciMethodData* logmd) {
4231 if (trap_count(reason) >= Deoptimization::per_method_trap_limit(reason)) {
4232 // Too many traps globally.
4233 // Note that we use cumulative trap_count, not just md->trap_count.
4234 if (log()) {
4235 int mcount = (logmd == nullptr)? -1: (int)logmd->trap_count(reason);
4236 log()->elem("observe trap='%s' count='0' mcount='%d' ccount='%d'",
4237 Deoptimization::trap_reason_name(reason),
4238 mcount, trap_count(reason));
4239 }
4240 return true;
4241 } else {
4242 // The coast is clear.
4243 return false;
4244 }
4245 }
4246
4247 //--------------------------too_many_recompiles--------------------------------
4248 // Report if there are too many recompiles at the current method and bci.
4249 // Consults PerBytecodeRecompilationCutoff and PerMethodRecompilationCutoff.
4250 // Is not eager to return true, since this will cause the compiler to use
4251 // Action_none for a trap point, to avoid too many recompilations.
4252 bool Compile::too_many_recompiles(ciMethod* method,
4253 int bci,
4254 Deoptimization::DeoptReason reason) {
4255 ciMethodData* md = method->method_data();
4256 if (md->is_empty()) {
4257 // Assume the trap has not occurred, or that it occurred only
4258 // because of a transient condition during start-up in the interpreter.
4259 return false;
4260 }
4261 // Pick a cutoff point well within PerBytecodeRecompilationCutoff.
4262 uint bc_cutoff = (uint) PerBytecodeRecompilationCutoff / 8;
4263 uint m_cutoff = (uint) PerMethodRecompilationCutoff / 2 + 1; // not zero
4264 Deoptimization::DeoptReason per_bc_reason
4265 = Deoptimization::reason_recorded_per_bytecode_if_any(reason);
4266 ciMethod* m = Deoptimization::reason_is_speculate(reason) ? this->method() : nullptr;
4267 if ((per_bc_reason == Deoptimization::Reason_none
4268 || md->has_trap_at(bci, m, reason) != 0)
4269 // The trap frequency measure we care about is the recompile count:
4270 && md->trap_recompiled_at(bci, m)
4271 && md->overflow_recompile_count() >= bc_cutoff) {
4272 // Do not emit a trap here if it has already caused recompilations.
4273 // Also, if there are multiple reasons, or if there is no per-BCI record,
4274 // assume the worst.
4275 if (log())
4276 log()->elem("observe trap='%s recompiled' count='%d' recompiles2='%d'",
4277 Deoptimization::trap_reason_name(reason),
4278 md->trap_count(reason),
4279 md->overflow_recompile_count());
4280 return true;
4281 } else if (trap_count(reason) != 0
4282 && decompile_count() >= m_cutoff) {
4283 // Too many recompiles globally, and we have seen this sort of trap.
4284 // Use cumulative decompile_count, not just md->decompile_count.
4285 if (log())
4286 log()->elem("observe trap='%s' count='%d' mcount='%d' decompiles='%d' mdecompiles='%d'",
4287 Deoptimization::trap_reason_name(reason),
4288 md->trap_count(reason), trap_count(reason),
4289 md->decompile_count(), decompile_count());
4290 return true;
4291 } else {
4292 // The coast is clear.
4293 return false;
4294 }
4295 }
4296
4297 // Compute when not to trap. Used by matching trap based nodes and
4298 // NullCheck optimization.
4299 void Compile::set_allowed_deopt_reasons() {
4300 _allowed_reasons = 0;
4301 if (is_method_compilation()) {
4302 for (int rs = (int)Deoptimization::Reason_none+1; rs < Compile::trapHistLength; rs++) {
4303 assert(rs < BitsPerInt, "recode bit map");
4304 if (!too_many_traps((Deoptimization::DeoptReason) rs)) {
4305 _allowed_reasons |= nth_bit(rs);
4306 }
4307 }
4308 }
4309 }
4310
4311 bool Compile::needs_clinit_barrier(ciMethod* method, ciMethod* accessing_method) {
4312 return method->is_static() && needs_clinit_barrier(method->holder(), accessing_method);
4313 }
4314
4315 bool Compile::needs_clinit_barrier(ciField* field, ciMethod* accessing_method) {
4316 return field->is_static() && needs_clinit_barrier(field->holder(), accessing_method);
4317 }
4318
4319 bool Compile::needs_clinit_barrier(ciInstanceKlass* holder, ciMethod* accessing_method) {
4320 if (holder->is_initialized()) {
4321 return false;
4322 }
4323 if (holder->is_being_initialized()) {
4324 if (accessing_method->holder() == holder) {
4325 // Access inside a class. The barrier can be elided when access happens in <clinit>,
4326 // <init>, or a static method. In all those cases, there was an initialization
4327 // barrier on the holder klass passed.
4328 if (accessing_method->is_static_initializer() ||
4329 accessing_method->is_object_initializer() ||
4330 accessing_method->is_static()) {
4331 return false;
4332 }
4333 } else if (accessing_method->holder()->is_subclass_of(holder)) {
4334 // Access from a subclass. The barrier can be elided only when access happens in <clinit>.
4335 // In case of <init> or a static method, the barrier is on the subclass is not enough:
4336 // child class can become fully initialized while its parent class is still being initialized.
4337 if (accessing_method->is_static_initializer()) {
4338 return false;
4339 }
4340 }
4341 ciMethod* root = method(); // the root method of compilation
4342 if (root != accessing_method) {
4343 return needs_clinit_barrier(holder, root); // check access in the context of compilation root
4344 }
4345 }
4346 return true;
4347 }
4348
4349 #ifndef PRODUCT
4350 //------------------------------verify_bidirectional_edges---------------------
4351 // For each input edge to a node (ie - for each Use-Def edge), verify that
4352 // there is a corresponding Def-Use edge.
4353 void Compile::verify_bidirectional_edges(Unique_Node_List& visited, const Unique_Node_List* root_and_safepoints) const {
4354 // Allocate stack of size C->live_nodes()/16 to avoid frequent realloc
4355 uint stack_size = live_nodes() >> 4;
4356 Node_List nstack(MAX2(stack_size, (uint) OptoNodeListSize));
4357 if (root_and_safepoints != nullptr) {
4358 assert(root_and_safepoints->member(_root), "root is not in root_and_safepoints");
4359 for (uint i = 0, limit = root_and_safepoints->size(); i < limit; i++) {
4360 Node* root_or_safepoint = root_and_safepoints->at(i);
4361 // If the node is a safepoint, let's check if it still has a control input
4362 // Lack of control input signifies that this node was killed by CCP or
4363 // recursively by remove_globally_dead_node and it shouldn't be a starting
4364 // point.
4365 if (!root_or_safepoint->is_SafePoint() || root_or_safepoint->in(0) != nullptr) {
4366 nstack.push(root_or_safepoint);
4367 }
4368 }
4369 } else {
4370 nstack.push(_root);
4371 }
4372
4373 while (nstack.size() > 0) {
4374 Node* n = nstack.pop();
4375 if (visited.member(n)) {
4376 continue;
4377 }
4378 visited.push(n);
4379
4380 // Walk over all input edges, checking for correspondence
4381 uint length = n->len();
4382 for (uint i = 0; i < length; i++) {
4383 Node* in = n->in(i);
4384 if (in != nullptr && !visited.member(in)) {
4385 nstack.push(in); // Put it on stack
4386 }
4387 if (in != nullptr && !in->is_top()) {
4388 // Count instances of `next`
4389 int cnt = 0;
4390 for (uint idx = 0; idx < in->_outcnt; idx++) {
4391 if (in->_out[idx] == n) {
4392 cnt++;
4393 }
4394 }
4395 assert(cnt > 0, "Failed to find Def-Use edge.");
4396 // Check for duplicate edges
4397 // walk the input array downcounting the input edges to n
4398 for (uint j = 0; j < length; j++) {
4399 if (n->in(j) == in) {
4400 cnt--;
4401 }
4402 }
4403 assert(cnt == 0, "Mismatched edge count.");
4404 } else if (in == nullptr) {
4405 assert(i == 0 || i >= n->req() ||
4406 n->is_Region() || n->is_Phi() || n->is_ArrayCopy() ||
4407 (n->is_Unlock() && i == (n->req() - 1)) ||
4408 (n->is_MemBar() && i == 5), // the precedence edge to a membar can be removed during macro node expansion
4409 "only region, phi, arraycopy, unlock or membar nodes have null data edges");
4410 } else {
4411 assert(in->is_top(), "sanity");
4412 // Nothing to check.
4413 }
4414 }
4415 }
4416 }
4417
4418 //------------------------------verify_graph_edges---------------------------
4419 // Walk the Graph and verify that there is a one-to-one correspondence
4420 // between Use-Def edges and Def-Use edges in the graph.
4421 void Compile::verify_graph_edges(bool no_dead_code, const Unique_Node_List* root_and_safepoints) const {
4422 if (VerifyGraphEdges) {
4423 Unique_Node_List visited;
4424
4425 // Call graph walk to check edges
4426 verify_bidirectional_edges(visited, root_and_safepoints);
4427 if (no_dead_code) {
4428 // Now make sure that no visited node is used by an unvisited node.
4429 bool dead_nodes = false;
4430 Unique_Node_List checked;
4431 while (visited.size() > 0) {
4432 Node* n = visited.pop();
4433 checked.push(n);
4434 for (uint i = 0; i < n->outcnt(); i++) {
4435 Node* use = n->raw_out(i);
4436 if (checked.member(use)) continue; // already checked
4437 if (visited.member(use)) continue; // already in the graph
4438 if (use->is_Con()) continue; // a dead ConNode is OK
4439 // At this point, we have found a dead node which is DU-reachable.
4440 if (!dead_nodes) {
4441 tty->print_cr("*** Dead nodes reachable via DU edges:");
4442 dead_nodes = true;
4443 }
4444 use->dump(2);
4445 tty->print_cr("---");
4446 checked.push(use); // No repeats; pretend it is now checked.
4447 }
4448 }
4449 assert(!dead_nodes, "using nodes must be reachable from root");
4450 }
4451 }
4452 }
4453 #endif
4454
4455 // The Compile object keeps track of failure reasons separately from the ciEnv.
4456 // This is required because there is not quite a 1-1 relation between the
4457 // ciEnv and its compilation task and the Compile object. Note that one
4458 // ciEnv might use two Compile objects, if C2Compiler::compile_method decides
4459 // to backtrack and retry without subsuming loads. Other than this backtracking
4460 // behavior, the Compile's failure reason is quietly copied up to the ciEnv
4461 // by the logic in C2Compiler.
4462 void Compile::record_failure(const char* reason DEBUG_ONLY(COMMA bool allow_multiple_failures)) {
4463 if (log() != nullptr) {
4464 log()->elem("failure reason='%s' phase='compile'", reason);
4465 }
4466 if (_failure_reason.get() == nullptr) {
4467 // Record the first failure reason.
4468 _failure_reason.set(reason);
4469 if (CaptureBailoutInformation) {
4470 _first_failure_details = new CompilationFailureInfo(reason);
4471 }
4472 } else {
4473 assert(!StressBailout || allow_multiple_failures, "should have handled previous failure.");
4474 }
4475
4476 if (!C->failure_reason_is(C2Compiler::retry_no_subsuming_loads())) {
4477 C->print_method(PHASE_FAILURE, 1);
4478 }
4479 _root = nullptr; // flush the graph, too
4480 }
4481
4482 Compile::TracePhase::TracePhase(const char* name, PhaseTraceId id)
4483 : TraceTime(name, &Phase::timers[id], CITime, CITimeVerbose),
4484 _compile(Compile::current()),
4485 _log(nullptr),
4486 _dolog(CITimeVerbose)
4487 {
4488 assert(_compile != nullptr, "sanity check");
4489 assert(id != PhaseTraceId::_t_none, "Don't use none");
4490 if (_dolog) {
4491 _log = _compile->log();
4492 }
4493 if (_log != nullptr) {
4494 _log->begin_head("phase name='%s' nodes='%d' live='%d'", phase_name(), _compile->unique(), _compile->live_nodes());
4495 _log->stamp();
4496 _log->end_head();
4497 }
4498
4499 // Inform memory statistic, if enabled
4500 if (CompilationMemoryStatistic::enabled()) {
4501 CompilationMemoryStatistic::on_phase_start((int)id, name);
4502 }
4503 }
4504
4505 Compile::TracePhase::TracePhase(PhaseTraceId id)
4506 : TracePhase(Phase::get_phase_trace_id_text(id), id) {}
4507
4508 Compile::TracePhase::~TracePhase() {
4509
4510 // Inform memory statistic, if enabled
4511 if (CompilationMemoryStatistic::enabled()) {
4512 CompilationMemoryStatistic::on_phase_end();
4513 }
4514
4515 if (_compile->failing_internal()) {
4516 if (_log != nullptr) {
4517 _log->done("phase");
4518 }
4519 return; // timing code, not stressing bailouts.
4520 }
4521 #ifdef ASSERT
4522 if (PrintIdealNodeCount) {
4523 tty->print_cr("phase name='%s' nodes='%d' live='%d' live_graph_walk='%d'",
4524 phase_name(), _compile->unique(), _compile->live_nodes(), _compile->count_live_nodes_by_graph_walk());
4525 }
4526
4527 if (VerifyIdealNodeCount) {
4528 _compile->print_missing_nodes();
4529 }
4530 #endif
4531
4532 if (_log != nullptr) {
4533 _log->done("phase name='%s' nodes='%d' live='%d'", phase_name(), _compile->unique(), _compile->live_nodes());
4534 }
4535 }
4536
4537 //----------------------------static_subtype_check-----------------------------
4538 // Shortcut important common cases when superklass is exact:
4539 // (0) superklass is java.lang.Object (can occur in reflective code)
4540 // (1) subklass is already limited to a subtype of superklass => always ok
4541 // (2) subklass does not overlap with superklass => always fail
4542 // (3) superklass has NO subtypes and we can check with a simple compare.
4543 Compile::SubTypeCheckResult Compile::static_subtype_check(const TypeKlassPtr* superk, const TypeKlassPtr* subk, bool skip) {
4544 if (skip) {
4545 return SSC_full_test; // Let caller generate the general case.
4546 }
4547
4548 if (subk->is_java_subtype_of(superk)) {
4549 return SSC_always_true; // (0) and (1) this test cannot fail
4550 }
4551
4552 if (!subk->maybe_java_subtype_of(superk)) {
4553 return SSC_always_false; // (2) true path dead; no dynamic test needed
4554 }
4555
4556 const Type* superelem = superk;
4557 if (superk->isa_aryklassptr()) {
4558 int ignored;
4559 superelem = superk->is_aryklassptr()->base_element_type(ignored);
4560 }
4561
4562 if (superelem->isa_instklassptr()) {
4563 ciInstanceKlass* ik = superelem->is_instklassptr()->instance_klass();
4564 if (!ik->has_subklass()) {
4565 if (!ik->is_final()) {
4566 // Add a dependency if there is a chance of a later subclass.
4567 dependencies()->assert_leaf_type(ik);
4568 }
4569 if (!superk->maybe_java_subtype_of(subk)) {
4570 return SSC_always_false;
4571 }
4572 return SSC_easy_test; // (3) caller can do a simple ptr comparison
4573 }
4574 } else {
4575 // A primitive array type has no subtypes.
4576 return SSC_easy_test; // (3) caller can do a simple ptr comparison
4577 }
4578
4579 return SSC_full_test;
4580 }
4581
4582 Node* Compile::conv_I2X_index(PhaseGVN* phase, Node* idx, const TypeInt* sizetype, Node* ctrl) {
4583 #ifdef _LP64
4584 // The scaled index operand to AddP must be a clean 64-bit value.
4585 // Java allows a 32-bit int to be incremented to a negative
4586 // value, which appears in a 64-bit register as a large
4587 // positive number. Using that large positive number as an
4588 // operand in pointer arithmetic has bad consequences.
4589 // On the other hand, 32-bit overflow is rare, and the possibility
4590 // can often be excluded, if we annotate the ConvI2L node with
4591 // a type assertion that its value is known to be a small positive
4592 // number. (The prior range check has ensured this.)
4593 // This assertion is used by ConvI2LNode::Ideal.
4594 int index_max = max_jint - 1; // array size is max_jint, index is one less
4595 if (sizetype != nullptr && sizetype->_hi > 0) {
4596 index_max = sizetype->_hi - 1;
4597 }
4598 const TypeInt* iidxtype = TypeInt::make(0, index_max, Type::WidenMax);
4599 idx = constrained_convI2L(phase, idx, iidxtype, ctrl);
4600 #endif
4601 return idx;
4602 }
4603
4604 // Convert integer value to a narrowed long type dependent on ctrl (for example, a range check)
4605 Node* Compile::constrained_convI2L(PhaseGVN* phase, Node* value, const TypeInt* itype, Node* ctrl, bool carry_dependency) {
4606 if (ctrl != nullptr) {
4607 // Express control dependency by a CastII node with a narrow type.
4608 // Make the CastII node dependent on the control input to prevent the narrowed ConvI2L
4609 // node from floating above the range check during loop optimizations. Otherwise, the
4610 // ConvI2L node may be eliminated independently of the range check, causing the data path
4611 // to become TOP while the control path is still there (although it's unreachable).
4612 value = new CastIINode(ctrl, value, itype, carry_dependency ? ConstraintCastNode::DependencyType::NonFloatingNarrowing : ConstraintCastNode::DependencyType::FloatingNarrowing, true /* range check dependency */);
4613 value = phase->transform(value);
4614 }
4615 const TypeLong* ltype = TypeLong::make(itype->_lo, itype->_hi, itype->_widen);
4616 return phase->transform(new ConvI2LNode(value, ltype));
4617 }
4618
4619 void Compile::dump_print_inlining() {
4620 inline_printer()->print_on(tty);
4621 }
4622
4623 void Compile::log_late_inline(CallGenerator* cg) {
4624 if (log() != nullptr) {
4625 log()->head("late_inline method='%d' inline_id='" JLONG_FORMAT "'", log()->identify(cg->method()),
4626 cg->unique_id());
4627 JVMState* p = cg->call_node()->jvms();
4628 while (p != nullptr) {
4629 log()->elem("jvms bci='%d' method='%d'", p->bci(), log()->identify(p->method()));
4630 p = p->caller();
4631 }
4632 log()->tail("late_inline");
4633 }
4634 }
4635
4636 void Compile::log_late_inline_failure(CallGenerator* cg, const char* msg) {
4637 log_late_inline(cg);
4638 if (log() != nullptr) {
4639 log()->inline_fail(msg);
4640 }
4641 }
4642
4643 void Compile::log_inline_id(CallGenerator* cg) {
4644 if (log() != nullptr) {
4645 // The LogCompilation tool needs a unique way to identify late
4646 // inline call sites. This id must be unique for this call site in
4647 // this compilation. Try to have it unique across compilations as
4648 // well because it can be convenient when grepping through the log
4649 // file.
4650 // Distinguish OSR compilations from others in case CICountOSR is
4651 // on.
4652 jlong id = ((jlong)unique()) + (((jlong)compile_id()) << 33) + (CICountOSR && is_osr_compilation() ? ((jlong)1) << 32 : 0);
4653 cg->set_unique_id(id);
4654 log()->elem("inline_id id='" JLONG_FORMAT "'", id);
4655 }
4656 }
4657
4658 void Compile::log_inline_failure(const char* msg) {
4659 if (C->log() != nullptr) {
4660 C->log()->inline_fail(msg);
4661 }
4662 }
4663
4664
4665 // Dump inlining replay data to the stream.
4666 // Don't change thread state and acquire any locks.
4667 void Compile::dump_inline_data(outputStream* out) {
4668 InlineTree* inl_tree = ilt();
4669 if (inl_tree != nullptr) {
4670 out->print(" inline %d", inl_tree->count());
4671 inl_tree->dump_replay_data(out);
4672 }
4673 }
4674
4675 void Compile::dump_inline_data_reduced(outputStream* out) {
4676 assert(ReplayReduce, "");
4677
4678 InlineTree* inl_tree = ilt();
4679 if (inl_tree == nullptr) {
4680 return;
4681 }
4682 // Enable iterative replay file reduction
4683 // Output "compile" lines for depth 1 subtrees,
4684 // simulating that those trees were compiled
4685 // instead of inlined.
4686 for (int i = 0; i < inl_tree->subtrees().length(); ++i) {
4687 InlineTree* sub = inl_tree->subtrees().at(i);
4688 if (sub->inline_level() != 1) {
4689 continue;
4690 }
4691
4692 ciMethod* method = sub->method();
4693 int entry_bci = -1;
4694 int comp_level = env()->task()->comp_level();
4695 out->print("compile ");
4696 method->dump_name_as_ascii(out);
4697 out->print(" %d %d", entry_bci, comp_level);
4698 out->print(" inline %d", sub->count());
4699 sub->dump_replay_data(out, -1);
4700 out->cr();
4701 }
4702 }
4703
4704 int Compile::cmp_expensive_nodes(Node* n1, Node* n2) {
4705 if (n1->Opcode() < n2->Opcode()) return -1;
4706 else if (n1->Opcode() > n2->Opcode()) return 1;
4707
4708 assert(n1->req() == n2->req(), "can't compare %s nodes: n1->req() = %d, n2->req() = %d", NodeClassNames[n1->Opcode()], n1->req(), n2->req());
4709 for (uint i = 1; i < n1->req(); i++) {
4710 if (n1->in(i) < n2->in(i)) return -1;
4711 else if (n1->in(i) > n2->in(i)) return 1;
4712 }
4713
4714 return 0;
4715 }
4716
4717 int Compile::cmp_expensive_nodes(Node** n1p, Node** n2p) {
4718 Node* n1 = *n1p;
4719 Node* n2 = *n2p;
4720
4721 return cmp_expensive_nodes(n1, n2);
4722 }
4723
4724 void Compile::sort_expensive_nodes() {
4725 if (!expensive_nodes_sorted()) {
4726 _expensive_nodes.sort(cmp_expensive_nodes);
4727 }
4728 }
4729
4730 bool Compile::expensive_nodes_sorted() const {
4731 for (int i = 1; i < _expensive_nodes.length(); i++) {
4732 if (cmp_expensive_nodes(_expensive_nodes.adr_at(i), _expensive_nodes.adr_at(i-1)) < 0) {
4733 return false;
4734 }
4735 }
4736 return true;
4737 }
4738
4739 bool Compile::should_optimize_expensive_nodes(PhaseIterGVN &igvn) {
4740 if (_expensive_nodes.length() == 0) {
4741 return false;
4742 }
4743
4744 assert(OptimizeExpensiveOps, "optimization off?");
4745
4746 // Take this opportunity to remove dead nodes from the list
4747 int j = 0;
4748 for (int i = 0; i < _expensive_nodes.length(); i++) {
4749 Node* n = _expensive_nodes.at(i);
4750 if (!n->is_unreachable(igvn)) {
4751 assert(n->is_expensive(), "should be expensive");
4752 _expensive_nodes.at_put(j, n);
4753 j++;
4754 }
4755 }
4756 _expensive_nodes.trunc_to(j);
4757
4758 // Then sort the list so that similar nodes are next to each other
4759 // and check for at least two nodes of identical kind with same data
4760 // inputs.
4761 sort_expensive_nodes();
4762
4763 for (int i = 0; i < _expensive_nodes.length()-1; i++) {
4764 if (cmp_expensive_nodes(_expensive_nodes.adr_at(i), _expensive_nodes.adr_at(i+1)) == 0) {
4765 return true;
4766 }
4767 }
4768
4769 return false;
4770 }
4771
4772 void Compile::cleanup_expensive_nodes(PhaseIterGVN &igvn) {
4773 if (_expensive_nodes.length() == 0) {
4774 return;
4775 }
4776
4777 assert(OptimizeExpensiveOps, "optimization off?");
4778
4779 // Sort to bring similar nodes next to each other and clear the
4780 // control input of nodes for which there's only a single copy.
4781 sort_expensive_nodes();
4782
4783 int j = 0;
4784 int identical = 0;
4785 int i = 0;
4786 bool modified = false;
4787 for (; i < _expensive_nodes.length()-1; i++) {
4788 assert(j <= i, "can't write beyond current index");
4789 if (_expensive_nodes.at(i)->Opcode() == _expensive_nodes.at(i+1)->Opcode()) {
4790 identical++;
4791 _expensive_nodes.at_put(j++, _expensive_nodes.at(i));
4792 continue;
4793 }
4794 if (identical > 0) {
4795 _expensive_nodes.at_put(j++, _expensive_nodes.at(i));
4796 identical = 0;
4797 } else {
4798 Node* n = _expensive_nodes.at(i);
4799 igvn.replace_input_of(n, 0, nullptr);
4800 igvn.hash_insert(n);
4801 modified = true;
4802 }
4803 }
4804 if (identical > 0) {
4805 _expensive_nodes.at_put(j++, _expensive_nodes.at(i));
4806 } else if (_expensive_nodes.length() >= 1) {
4807 Node* n = _expensive_nodes.at(i);
4808 igvn.replace_input_of(n, 0, nullptr);
4809 igvn.hash_insert(n);
4810 modified = true;
4811 }
4812 _expensive_nodes.trunc_to(j);
4813 if (modified) {
4814 igvn.optimize();
4815 }
4816 }
4817
4818 void Compile::add_expensive_node(Node * n) {
4819 assert(!_expensive_nodes.contains(n), "duplicate entry in expensive list");
4820 assert(n->is_expensive(), "expensive nodes with non-null control here only");
4821 assert(!n->is_CFG() && !n->is_Mem(), "no cfg or memory nodes here");
4822 if (OptimizeExpensiveOps) {
4823 _expensive_nodes.append(n);
4824 } else {
4825 // Clear control input and let IGVN optimize expensive nodes if
4826 // OptimizeExpensiveOps is off.
4827 n->set_req(0, nullptr);
4828 }
4829 }
4830
4831 /**
4832 * Track coarsened Lock and Unlock nodes.
4833 */
4834
4835 class Lock_List : public Node_List {
4836 uint _origin_cnt;
4837 public:
4838 Lock_List(Arena *a, uint cnt) : Node_List(a), _origin_cnt(cnt) {}
4839 uint origin_cnt() const { return _origin_cnt; }
4840 };
4841
4842 void Compile::add_coarsened_locks(GrowableArray<AbstractLockNode*>& locks) {
4843 int length = locks.length();
4844 if (length > 0) {
4845 // Have to keep this list until locks elimination during Macro nodes elimination.
4846 Lock_List* locks_list = new (comp_arena()) Lock_List(comp_arena(), length);
4847 AbstractLockNode* alock = locks.at(0);
4848 BoxLockNode* box = alock->box_node()->as_BoxLock();
4849 for (int i = 0; i < length; i++) {
4850 AbstractLockNode* lock = locks.at(i);
4851 assert(lock->is_coarsened(), "expecting only coarsened AbstractLock nodes, but got '%s'[%d] node", lock->Name(), lock->_idx);
4852 locks_list->push(lock);
4853 BoxLockNode* this_box = lock->box_node()->as_BoxLock();
4854 if (this_box != box) {
4855 // Locking regions (BoxLock) could be Unbalanced here:
4856 // - its coarsened locks were eliminated in earlier
4857 // macro nodes elimination followed by loop unroll
4858 // - it is OSR locking region (no Lock node)
4859 // Preserve Unbalanced status in such cases.
4860 if (!this_box->is_unbalanced()) {
4861 this_box->set_coarsened();
4862 }
4863 if (!box->is_unbalanced()) {
4864 box->set_coarsened();
4865 }
4866 }
4867 }
4868 _coarsened_locks.append(locks_list);
4869 }
4870 }
4871
4872 void Compile::remove_useless_coarsened_locks(Unique_Node_List& useful) {
4873 int count = coarsened_count();
4874 for (int i = 0; i < count; i++) {
4875 Node_List* locks_list = _coarsened_locks.at(i);
4876 for (uint j = 0; j < locks_list->size(); j++) {
4877 Node* lock = locks_list->at(j);
4878 assert(lock->is_AbstractLock(), "sanity");
4879 if (!useful.member(lock)) {
4880 locks_list->yank(lock);
4881 }
4882 }
4883 }
4884 }
4885
4886 void Compile::remove_coarsened_lock(Node* n) {
4887 if (n->is_AbstractLock()) {
4888 int count = coarsened_count();
4889 for (int i = 0; i < count; i++) {
4890 Node_List* locks_list = _coarsened_locks.at(i);
4891 locks_list->yank(n);
4892 }
4893 }
4894 }
4895
4896 bool Compile::coarsened_locks_consistent() {
4897 int count = coarsened_count();
4898 for (int i = 0; i < count; i++) {
4899 bool unbalanced = false;
4900 bool modified = false; // track locks kind modifications
4901 Lock_List* locks_list = (Lock_List*)_coarsened_locks.at(i);
4902 uint size = locks_list->size();
4903 if (size == 0) {
4904 unbalanced = false; // All locks were eliminated - good
4905 } else if (size != locks_list->origin_cnt()) {
4906 unbalanced = true; // Some locks were removed from list
4907 } else {
4908 for (uint j = 0; j < size; j++) {
4909 Node* lock = locks_list->at(j);
4910 // All nodes in group should have the same state (modified or not)
4911 if (!lock->as_AbstractLock()->is_coarsened()) {
4912 if (j == 0) {
4913 // first on list was modified, the rest should be too for consistency
4914 modified = true;
4915 } else if (!modified) {
4916 // this lock was modified but previous locks on the list were not
4917 unbalanced = true;
4918 break;
4919 }
4920 } else if (modified) {
4921 // previous locks on list were modified but not this lock
4922 unbalanced = true;
4923 break;
4924 }
4925 }
4926 }
4927 if (unbalanced) {
4928 // unbalanced monitor enter/exit - only some [un]lock nodes were removed or modified
4929 #ifdef ASSERT
4930 if (PrintEliminateLocks) {
4931 tty->print_cr("=== unbalanced coarsened locks ===");
4932 for (uint l = 0; l < size; l++) {
4933 locks_list->at(l)->dump();
4934 }
4935 }
4936 #endif
4937 record_failure(C2Compiler::retry_no_locks_coarsening());
4938 return false;
4939 }
4940 }
4941 return true;
4942 }
4943
4944 // Mark locking regions (identified by BoxLockNode) as unbalanced if
4945 // locks coarsening optimization removed Lock/Unlock nodes from them.
4946 // Such regions become unbalanced because coarsening only removes part
4947 // of Lock/Unlock nodes in region. As result we can't execute other
4948 // locks elimination optimizations which assume all code paths have
4949 // corresponding pair of Lock/Unlock nodes - they are balanced.
4950 void Compile::mark_unbalanced_boxes() const {
4951 int count = coarsened_count();
4952 for (int i = 0; i < count; i++) {
4953 Node_List* locks_list = _coarsened_locks.at(i);
4954 uint size = locks_list->size();
4955 if (size > 0) {
4956 AbstractLockNode* alock = locks_list->at(0)->as_AbstractLock();
4957 BoxLockNode* box = alock->box_node()->as_BoxLock();
4958 if (alock->is_coarsened()) {
4959 // coarsened_locks_consistent(), which is called before this method, verifies
4960 // that the rest of Lock/Unlock nodes on locks_list are also coarsened.
4961 assert(!box->is_eliminated(), "regions with coarsened locks should not be marked as eliminated");
4962 for (uint j = 1; j < size; j++) {
4963 assert(locks_list->at(j)->as_AbstractLock()->is_coarsened(), "only coarsened locks are expected here");
4964 BoxLockNode* this_box = locks_list->at(j)->as_AbstractLock()->box_node()->as_BoxLock();
4965 if (box != this_box) {
4966 assert(!this_box->is_eliminated(), "regions with coarsened locks should not be marked as eliminated");
4967 box->set_unbalanced();
4968 this_box->set_unbalanced();
4969 }
4970 }
4971 }
4972 }
4973 }
4974 }
4975
4976 /**
4977 * Remove the speculative part of types and clean up the graph
4978 */
4979 void Compile::remove_speculative_types(PhaseIterGVN &igvn) {
4980 if (UseTypeSpeculation) {
4981 Unique_Node_List worklist;
4982 worklist.push(root());
4983 int modified = 0;
4984 // Go over all type nodes that carry a speculative type, drop the
4985 // speculative part of the type and enqueue the node for an igvn
4986 // which may optimize it out.
4987 for (uint next = 0; next < worklist.size(); ++next) {
4988 Node *n = worklist.at(next);
4989 if (n->is_Type()) {
4990 TypeNode* tn = n->as_Type();
4991 const Type* t = tn->type();
4992 const Type* t_no_spec = t->remove_speculative();
4993 if (t_no_spec != t) {
4994 bool in_hash = igvn.hash_delete(n);
4995 assert(in_hash || n->hash() == Node::NO_HASH, "node should be in igvn hash table");
4996 tn->set_type(t_no_spec);
4997 igvn.hash_insert(n);
4998 igvn._worklist.push(n); // give it a chance to go away
4999 modified++;
5000 }
5001 }
5002 // Iterate over outs - endless loops is unreachable from below
5003 for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
5004 Node *m = n->fast_out(i);
5005 if (not_a_node(m)) {
5006 continue;
5007 }
5008 worklist.push(m);
5009 }
5010 }
5011 // Drop the speculative part of all types in the igvn's type table
5012 igvn.remove_speculative_types();
5013 if (modified > 0) {
5014 igvn.optimize();
5015 if (failing()) return;
5016 }
5017 #ifdef ASSERT
5018 // Verify that after the IGVN is over no speculative type has resurfaced
5019 worklist.clear();
5020 worklist.push(root());
5021 for (uint next = 0; next < worklist.size(); ++next) {
5022 Node *n = worklist.at(next);
5023 const Type* t = igvn.type_or_null(n);
5024 assert((t == nullptr) || (t == t->remove_speculative()), "no more speculative types");
5025 if (n->is_Type()) {
5026 t = n->as_Type()->type();
5027 assert(t == t->remove_speculative(), "no more speculative types");
5028 }
5029 // Iterate over outs - endless loops is unreachable from below
5030 for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
5031 Node *m = n->fast_out(i);
5032 if (not_a_node(m)) {
5033 continue;
5034 }
5035 worklist.push(m);
5036 }
5037 }
5038 igvn.check_no_speculative_types();
5039 #endif
5040 }
5041 }
5042
5043 // Auxiliary methods to support randomized stressing/fuzzing.
5044
5045 void Compile::initialize_stress_seed(const DirectiveSet* directive) {
5046 if (FLAG_IS_DEFAULT(StressSeed) || (FLAG_IS_ERGO(StressSeed) && directive->RepeatCompilationOption)) {
5047 _stress_seed = static_cast<uint>(Ticks::now().nanoseconds());
5048 FLAG_SET_ERGO(StressSeed, _stress_seed);
5049 } else {
5050 _stress_seed = StressSeed;
5051 }
5052 if (_log != nullptr) {
5053 _log->elem("stress_test seed='%u'", _stress_seed);
5054 }
5055 }
5056
5057 int Compile::random() {
5058 _stress_seed = os::next_random(_stress_seed);
5059 return static_cast<int>(_stress_seed);
5060 }
5061
5062 // This method can be called the arbitrary number of times, with current count
5063 // as the argument. The logic allows selecting a single candidate from the
5064 // running list of candidates as follows:
5065 // int count = 0;
5066 // Cand* selected = null;
5067 // while(cand = cand->next()) {
5068 // if (randomized_select(++count)) {
5069 // selected = cand;
5070 // }
5071 // }
5072 //
5073 // Including count equalizes the chances any candidate is "selected".
5074 // This is useful when we don't have the complete list of candidates to choose
5075 // from uniformly. In this case, we need to adjust the randomicity of the
5076 // selection, or else we will end up biasing the selection towards the latter
5077 // candidates.
5078 //
5079 // Quick back-envelope calculation shows that for the list of n candidates
5080 // the equal probability for the candidate to persist as "best" can be
5081 // achieved by replacing it with "next" k-th candidate with the probability
5082 // of 1/k. It can be easily shown that by the end of the run, the
5083 // probability for any candidate is converged to 1/n, thus giving the
5084 // uniform distribution among all the candidates.
5085 //
5086 // We don't care about the domain size as long as (RANDOMIZED_DOMAIN / count) is large.
5087 #define RANDOMIZED_DOMAIN_POW 29
5088 #define RANDOMIZED_DOMAIN (1 << RANDOMIZED_DOMAIN_POW)
5089 #define RANDOMIZED_DOMAIN_MASK ((1 << (RANDOMIZED_DOMAIN_POW + 1)) - 1)
5090 bool Compile::randomized_select(int count) {
5091 assert(count > 0, "only positive");
5092 return (random() & RANDOMIZED_DOMAIN_MASK) < (RANDOMIZED_DOMAIN / count);
5093 }
5094
5095 #ifdef ASSERT
5096 // Failures are geometrically distributed with probability 1/StressBailoutMean.
5097 bool Compile::fail_randomly() {
5098 if ((random() % StressBailoutMean) != 0) {
5099 return false;
5100 }
5101 record_failure("StressBailout");
5102 return true;
5103 }
5104
5105 bool Compile::failure_is_artificial() {
5106 return C->failure_reason_is("StressBailout");
5107 }
5108 #endif
5109
5110 CloneMap& Compile::clone_map() { return _clone_map; }
5111 void Compile::set_clone_map(Dict* d) { _clone_map._dict = d; }
5112
5113 void NodeCloneInfo::dump_on(outputStream* st) const {
5114 st->print(" {%d:%d} ", idx(), gen());
5115 }
5116
5117 void CloneMap::clone(Node* old, Node* nnn, int gen) {
5118 uint64_t val = value(old->_idx);
5119 NodeCloneInfo cio(val);
5120 assert(val != 0, "old node should be in the map");
5121 NodeCloneInfo cin(cio.idx(), gen + cio.gen());
5122 insert(nnn->_idx, cin.get());
5123 #ifndef PRODUCT
5124 if (is_debug()) {
5125 tty->print_cr("CloneMap::clone inserted node %d info {%d:%d} into CloneMap", nnn->_idx, cin.idx(), cin.gen());
5126 }
5127 #endif
5128 }
5129
5130 void CloneMap::verify_insert_and_clone(Node* old, Node* nnn, int gen) {
5131 NodeCloneInfo cio(value(old->_idx));
5132 if (cio.get() == 0) {
5133 cio.set(old->_idx, 0);
5134 insert(old->_idx, cio.get());
5135 #ifndef PRODUCT
5136 if (is_debug()) {
5137 tty->print_cr("CloneMap::verify_insert_and_clone inserted node %d info {%d:%d} into CloneMap", old->_idx, cio.idx(), cio.gen());
5138 }
5139 #endif
5140 }
5141 clone(old, nnn, gen);
5142 }
5143
5144 int CloneMap::max_gen() const {
5145 int g = 0;
5146 DictI di(_dict);
5147 for(; di.test(); ++di) {
5148 int t = gen(di._key);
5149 if (g < t) {
5150 g = t;
5151 #ifndef PRODUCT
5152 if (is_debug()) {
5153 tty->print_cr("CloneMap::max_gen() update max=%d from %d", g, _2_node_idx_t(di._key));
5154 }
5155 #endif
5156 }
5157 }
5158 return g;
5159 }
5160
5161 void CloneMap::dump(node_idx_t key, outputStream* st) const {
5162 uint64_t val = value(key);
5163 if (val != 0) {
5164 NodeCloneInfo ni(val);
5165 ni.dump_on(st);
5166 }
5167 }
5168
5169 void Compile::shuffle_macro_nodes() {
5170 shuffle_array(*C, _macro_nodes);
5171 }
5172
5173 // Move Allocate nodes to the start of the list
5174 void Compile::sort_macro_nodes() {
5175 int count = macro_count();
5176 int allocates = 0;
5177 for (int i = 0; i < count; i++) {
5178 Node* n = macro_node(i);
5179 if (n->is_Allocate()) {
5180 if (i != allocates) {
5181 Node* tmp = macro_node(allocates);
5182 _macro_nodes.at_put(allocates, n);
5183 _macro_nodes.at_put(i, tmp);
5184 }
5185 allocates++;
5186 }
5187 }
5188 }
5189
5190 void Compile::print_method(CompilerPhaseType compile_phase, int level, Node* n) {
5191 if (failing_internal()) { return; } // failing_internal to not stress bailouts from printing code.
5192 EventCompilerPhase event(UNTIMED);
5193 if (event.should_commit()) {
5194 CompilerEvent::PhaseEvent::post(event, C->_latest_stage_start_counter, compile_phase, C->_compile_id, level);
5195 }
5196 #ifndef PRODUCT
5197 ResourceMark rm;
5198 stringStream ss;
5199 ss.print_raw(CompilerPhaseTypeHelper::to_description(compile_phase));
5200 int iter = ++_igv_phase_iter[compile_phase];
5201 if (iter > 1) {
5202 ss.print(" %d", iter);
5203 }
5204 if (n != nullptr) {
5205 ss.print(": %d %s", n->_idx, NodeClassNames[n->Opcode()]);
5206 if (n->is_Call()) {
5207 CallNode* call = n->as_Call();
5208 if (call->_name != nullptr) {
5209 // E.g. uncommon traps etc.
5210 ss.print(" - %s", call->_name);
5211 } else if (call->is_CallJava()) {
5212 CallJavaNode* call_java = call->as_CallJava();
5213 if (call_java->method() != nullptr) {
5214 ss.print(" -");
5215 call_java->method()->print_short_name(&ss);
5216 }
5217 }
5218 }
5219 }
5220
5221 const char* name = ss.as_string();
5222 if (should_print_igv(level)) {
5223 _igv_printer->print_graph(name);
5224 }
5225 if (should_print_phase(level)) {
5226 print_phase(name);
5227 }
5228 if (should_print_ideal_phase(compile_phase)) {
5229 print_ideal_ir(CompilerPhaseTypeHelper::to_name(compile_phase));
5230 }
5231 #endif
5232 C->_latest_stage_start_counter.stamp();
5233 }
5234
5235 // Only used from CompileWrapper
5236 void Compile::begin_method() {
5237 #ifndef PRODUCT
5238 if (_method != nullptr && should_print_igv(1)) {
5239 _igv_printer->begin_method();
5240 }
5241 #endif
5242 C->_latest_stage_start_counter.stamp();
5243 }
5244
5245 // Only used from CompileWrapper
5246 void Compile::end_method() {
5247 EventCompilerPhase event(UNTIMED);
5248 if (event.should_commit()) {
5249 CompilerEvent::PhaseEvent::post(event, C->_latest_stage_start_counter, PHASE_END, C->_compile_id, 1);
5250 }
5251
5252 #ifndef PRODUCT
5253 if (_method != nullptr && should_print_igv(1)) {
5254 _igv_printer->end_method();
5255 }
5256 #endif
5257 }
5258
5259 #ifndef PRODUCT
5260 bool Compile::should_print_phase(const int level) const {
5261 return PrintPhaseLevel >= 0 && directive()->PhasePrintLevelOption >= level &&
5262 _method != nullptr; // Do not print phases for stubs.
5263 }
5264
5265 bool Compile::should_print_ideal_phase(CompilerPhaseType cpt) const {
5266 return _directive->should_print_ideal_phase(cpt);
5267 }
5268
5269 void Compile::init_igv() {
5270 if (_igv_printer == nullptr) {
5271 _igv_printer = IdealGraphPrinter::printer();
5272 _igv_printer->set_compile(this);
5273 }
5274 }
5275
5276 bool Compile::should_print_igv(const int level) {
5277 PRODUCT_RETURN_(return false;);
5278
5279 if (PrintIdealGraphLevel < 0) { // disabled by the user
5280 return false;
5281 }
5282
5283 bool need = directive()->IGVPrintLevelOption >= level;
5284 if (need) {
5285 Compile::init_igv();
5286 }
5287 return need;
5288 }
5289
5290 IdealGraphPrinter* Compile::_debug_file_printer = nullptr;
5291 IdealGraphPrinter* Compile::_debug_network_printer = nullptr;
5292
5293 // Called from debugger. Prints method to the default file with the default phase name.
5294 // This works regardless of any Ideal Graph Visualizer flags set or not.
5295 // Use in debugger (gdb/rr): p igv_print($sp, $fp, $pc).
5296 void igv_print(void* sp, void* fp, void* pc) {
5297 frame fr(sp, fp, pc);
5298 Compile::current()->igv_print_method_to_file(nullptr, false, &fr);
5299 }
5300
5301 // Same as igv_print() above but with a specified phase name.
5302 void igv_print(const char* phase_name, void* sp, void* fp, void* pc) {
5303 frame fr(sp, fp, pc);
5304 Compile::current()->igv_print_method_to_file(phase_name, false, &fr);
5305 }
5306
5307 // Called from debugger. Prints method with the default phase name to the default network or the one specified with
5308 // the network flags for the Ideal Graph Visualizer, or to the default file depending on the 'network' argument.
5309 // This works regardless of any Ideal Graph Visualizer flags set or not.
5310 // Use in debugger (gdb/rr): p igv_print(true, $sp, $fp, $pc).
5311 void igv_print(bool network, void* sp, void* fp, void* pc) {
5312 frame fr(sp, fp, pc);
5313 if (network) {
5314 Compile::current()->igv_print_method_to_network(nullptr, &fr);
5315 } else {
5316 Compile::current()->igv_print_method_to_file(nullptr, false, &fr);
5317 }
5318 }
5319
5320 // Same as igv_print(bool network, ...) above but with a specified phase name.
5321 // Use in debugger (gdb/rr): p igv_print(true, "MyPhase", $sp, $fp, $pc).
5322 void igv_print(bool network, const char* phase_name, void* sp, void* fp, void* pc) {
5323 frame fr(sp, fp, pc);
5324 if (network) {
5325 Compile::current()->igv_print_method_to_network(phase_name, &fr);
5326 } else {
5327 Compile::current()->igv_print_method_to_file(phase_name, false, &fr);
5328 }
5329 }
5330
5331 // Called from debugger. Normal write to the default _printer. Only works if Ideal Graph Visualizer printing flags are set.
5332 void igv_print_default() {
5333 Compile::current()->print_method(PHASE_DEBUG, 0);
5334 }
5335
5336 // Called from debugger, especially when replaying a trace in which the program state cannot be altered like with rr replay.
5337 // A method is appended to an existing default file with the default phase name. This means that igv_append() must follow
5338 // an earlier igv_print(*) call which sets up the file. This works regardless of any Ideal Graph Visualizer flags set or not.
5339 // Use in debugger (gdb/rr): p igv_append($sp, $fp, $pc).
5340 void igv_append(void* sp, void* fp, void* pc) {
5341 frame fr(sp, fp, pc);
5342 Compile::current()->igv_print_method_to_file(nullptr, true, &fr);
5343 }
5344
5345 // Same as igv_append(...) above but with a specified phase name.
5346 // Use in debugger (gdb/rr): p igv_append("MyPhase", $sp, $fp, $pc).
5347 void igv_append(const char* phase_name, void* sp, void* fp, void* pc) {
5348 frame fr(sp, fp, pc);
5349 Compile::current()->igv_print_method_to_file(phase_name, true, &fr);
5350 }
5351
5352 void Compile::igv_print_method_to_file(const char* phase_name, bool append, const frame* fr) {
5353 const char* file_name = "custom_debug.xml";
5354 if (_debug_file_printer == nullptr) {
5355 _debug_file_printer = new IdealGraphPrinter(C, file_name, append);
5356 } else {
5357 _debug_file_printer->update_compiled_method(C->method());
5358 }
5359 tty->print_cr("Method %s to %s", append ? "appended" : "printed", file_name);
5360 _debug_file_printer->print_graph(phase_name, fr);
5361 }
5362
5363 void Compile::igv_print_method_to_network(const char* phase_name, const frame* fr) {
5364 ResourceMark rm;
5365 GrowableArray<const Node*> empty_list;
5366 igv_print_graph_to_network(phase_name, empty_list, fr);
5367 }
5368
5369 void Compile::igv_print_graph_to_network(const char* name, GrowableArray<const Node*>& visible_nodes, const frame* fr) {
5370 if (_debug_network_printer == nullptr) {
5371 _debug_network_printer = new IdealGraphPrinter(C);
5372 } else {
5373 _debug_network_printer->update_compiled_method(C->method());
5374 }
5375 tty->print_cr("Method printed over network stream to IGV");
5376 _debug_network_printer->print(name, C->root(), visible_nodes, fr);
5377 }
5378 #endif // !PRODUCT
5379
5380 Node* Compile::narrow_value(BasicType bt, Node* value, const Type* type, PhaseGVN* phase, bool transform_res) {
5381 if (type != nullptr && phase->type(value)->higher_equal(type)) {
5382 return value;
5383 }
5384 Node* result = nullptr;
5385 if (bt == T_BYTE) {
5386 result = phase->transform(new LShiftINode(value, phase->intcon(24)));
5387 result = new RShiftINode(result, phase->intcon(24));
5388 } else if (bt == T_BOOLEAN) {
5389 result = new AndINode(value, phase->intcon(0xFF));
5390 } else if (bt == T_CHAR) {
5391 result = new AndINode(value,phase->intcon(0xFFFF));
5392 } else {
5393 assert(bt == T_SHORT, "unexpected narrow type");
5394 result = phase->transform(new LShiftINode(value, phase->intcon(16)));
5395 result = new RShiftINode(result, phase->intcon(16));
5396 }
5397 if (transform_res) {
5398 result = phase->transform(result);
5399 }
5400 return result;
5401 }
5402
5403 void Compile::record_method_not_compilable_oom() {
5404 record_method_not_compilable(CompilationMemoryStatistic::failure_reason_memlimit());
5405 }
5406
5407 #ifndef PRODUCT
5408 // Collects all the control inputs from nodes on the worklist and from their data dependencies
5409 static void find_candidate_control_inputs(Unique_Node_List& worklist, Unique_Node_List& candidates) {
5410 // Follow non-control edges until we reach CFG nodes
5411 for (uint i = 0; i < worklist.size(); i++) {
5412 const Node* n = worklist.at(i);
5413 for (uint j = 0; j < n->req(); j++) {
5414 Node* in = n->in(j);
5415 if (in == nullptr || in->is_Root()) {
5416 continue;
5417 }
5418 if (in->is_CFG()) {
5419 if (in->is_Call()) {
5420 // The return value of a call is only available if the call did not result in an exception
5421 Node* control_proj_use = in->as_Call()->proj_out(TypeFunc::Control)->unique_out();
5422 if (control_proj_use->is_Catch()) {
5423 Node* fall_through = control_proj_use->as_Catch()->proj_out(CatchProjNode::fall_through_index);
5424 candidates.push(fall_through);
5425 continue;
5426 }
5427 }
5428
5429 if (in->is_Multi()) {
5430 // We got here by following data inputs so we should only have one control use
5431 // (no IfNode, etc)
5432 assert(!n->is_MultiBranch(), "unexpected node type: %s", n->Name());
5433 candidates.push(in->as_Multi()->proj_out(TypeFunc::Control));
5434 } else {
5435 candidates.push(in);
5436 }
5437 } else {
5438 worklist.push(in);
5439 }
5440 }
5441 }
5442 }
5443
5444 // Returns the candidate node that is a descendant to all the other candidates
5445 static Node* pick_control(Unique_Node_List& candidates) {
5446 Unique_Node_List worklist;
5447 worklist.copy(candidates);
5448
5449 // Traverse backwards through the CFG
5450 for (uint i = 0; i < worklist.size(); i++) {
5451 const Node* n = worklist.at(i);
5452 if (n->is_Root()) {
5453 continue;
5454 }
5455 for (uint j = 0; j < n->req(); j++) {
5456 // Skip backedge of loops to avoid cycles
5457 if (n->is_Loop() && j == LoopNode::LoopBackControl) {
5458 continue;
5459 }
5460
5461 Node* pred = n->in(j);
5462 if (pred != nullptr && pred != n && pred->is_CFG()) {
5463 worklist.push(pred);
5464 // if pred is an ancestor of n, then pred is an ancestor to at least one candidate
5465 candidates.remove(pred);
5466 }
5467 }
5468 }
5469
5470 assert(candidates.size() == 1, "unexpected control flow");
5471 return candidates.at(0);
5472 }
5473
5474 // Initialize a parameter input for a debug print call, using a placeholder for jlong and jdouble
5475 static void debug_print_init_parm(Node* call, Node* parm, Node* half, int* pos) {
5476 call->init_req((*pos)++, parm);
5477 const BasicType bt = parm->bottom_type()->basic_type();
5478 if (bt == T_LONG || bt == T_DOUBLE) {
5479 call->init_req((*pos)++, half);
5480 }
5481 }
5482
5483 Node* Compile::make_debug_print_call(const char* str, address call_addr, PhaseGVN* gvn,
5484 Node* parm0, Node* parm1,
5485 Node* parm2, Node* parm3,
5486 Node* parm4, Node* parm5,
5487 Node* parm6) const {
5488 Node* str_node = gvn->transform(new ConPNode(TypeRawPtr::make(((address) str))));
5489 const TypeFunc* type = OptoRuntime::debug_print_Type(parm0, parm1, parm2, parm3, parm4, parm5, parm6);
5490 Node* call = new CallLeafNode(type, call_addr, "debug_print", TypeRawPtr::BOTTOM);
5491
5492 // find the most suitable control input
5493 Unique_Node_List worklist, candidates;
5494 if (parm0 != nullptr) { worklist.push(parm0);
5495 if (parm1 != nullptr) { worklist.push(parm1);
5496 if (parm2 != nullptr) { worklist.push(parm2);
5497 if (parm3 != nullptr) { worklist.push(parm3);
5498 if (parm4 != nullptr) { worklist.push(parm4);
5499 if (parm5 != nullptr) { worklist.push(parm5);
5500 if (parm6 != nullptr) { worklist.push(parm6);
5501 /* close each nested if ===> */ } } } } } } }
5502 find_candidate_control_inputs(worklist, candidates);
5503 Node* control = nullptr;
5504 if (candidates.size() == 0) {
5505 control = C->start()->proj_out(TypeFunc::Control);
5506 } else {
5507 control = pick_control(candidates);
5508 }
5509
5510 // find all the previous users of the control we picked
5511 GrowableArray<Node*> users_of_control;
5512 for (DUIterator_Fast kmax, i = control->fast_outs(kmax); i < kmax; i++) {
5513 Node* use = control->fast_out(i);
5514 if (use->is_CFG() && use != control) {
5515 users_of_control.push(use);
5516 }
5517 }
5518
5519 // we do not actually care about IO and memory as it uses neither
5520 call->init_req(TypeFunc::Control, control);
5521 call->init_req(TypeFunc::I_O, top());
5522 call->init_req(TypeFunc::Memory, top());
5523 call->init_req(TypeFunc::FramePtr, C->start()->proj_out(TypeFunc::FramePtr));
5524 call->init_req(TypeFunc::ReturnAdr, top());
5525
5526 int pos = TypeFunc::Parms;
5527 call->init_req(pos++, str_node);
5528 if (parm0 != nullptr) { debug_print_init_parm(call, parm0, top(), &pos);
5529 if (parm1 != nullptr) { debug_print_init_parm(call, parm1, top(), &pos);
5530 if (parm2 != nullptr) { debug_print_init_parm(call, parm2, top(), &pos);
5531 if (parm3 != nullptr) { debug_print_init_parm(call, parm3, top(), &pos);
5532 if (parm4 != nullptr) { debug_print_init_parm(call, parm4, top(), &pos);
5533 if (parm5 != nullptr) { debug_print_init_parm(call, parm5, top(), &pos);
5534 if (parm6 != nullptr) { debug_print_init_parm(call, parm6, top(), &pos);
5535 /* close each nested if ===> */ } } } } } } }
5536 assert(call->in(call->req()-1) != nullptr, "must initialize all parms");
5537
5538 call = gvn->transform(call);
5539 Node* call_control_proj = gvn->transform(new ProjNode(call, TypeFunc::Control));
5540
5541 // rewire previous users to have the new call as control instead
5542 PhaseIterGVN* igvn = gvn->is_IterGVN();
5543 for (int i = 0; i < users_of_control.length(); i++) {
5544 Node* use = users_of_control.at(i);
5545 for (uint j = 0; j < use->req(); j++) {
5546 if (use->in(j) == control) {
5547 if (igvn != nullptr) {
5548 igvn->replace_input_of(use, j, call_control_proj);
5549 } else {
5550 gvn->hash_delete(use);
5551 use->set_req(j, call_control_proj);
5552 gvn->hash_insert(use);
5553 }
5554 }
5555 }
5556 }
5557
5558 return call;
5559 }
5560 #endif // !PRODUCT