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