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