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