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