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