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