Fri, 15 Oct 2010 09:38:20 +0200
6991577: add IfOp optimization to C1
Summary: Ifop optimization for c1
Reviewed-by: never, phh, iveresov
1 /*
2 * Copyright (c) 1999, 2010, 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 */
25 #include "incls/_precompiled.incl"
26 #include "incls/_c1_Optimizer.cpp.incl"
28 define_array(ValueSetArray, ValueSet*);
29 define_stack(ValueSetList, ValueSetArray);
32 Optimizer::Optimizer(IR* ir) {
33 assert(ir->is_valid(), "IR must be valid");
34 _ir = ir;
35 }
37 class CE_Eliminator: public BlockClosure {
38 private:
39 IR* _hir;
40 int _cee_count; // the number of CEs successfully eliminated
41 int _ifop_count; // the number of IfOps successfully simplified
42 int _has_substitution;
44 public:
45 CE_Eliminator(IR* hir) : _cee_count(0), _ifop_count(0), _hir(hir) {
46 _has_substitution = false;
47 _hir->iterate_preorder(this);
48 if (_has_substitution) {
49 // substituted some ifops/phis, so resolve the substitution
50 SubstitutionResolver sr(_hir);
51 }
52 }
53 int cee_count() const { return _cee_count; }
54 int ifop_count() const { return _ifop_count; }
56 void adjust_exception_edges(BlockBegin* block, BlockBegin* sux) {
57 int e = sux->number_of_exception_handlers();
58 for (int i = 0; i < e; i++) {
59 BlockBegin* xhandler = sux->exception_handler_at(i);
60 block->add_exception_handler(xhandler);
62 assert(xhandler->is_predecessor(sux), "missing predecessor");
63 if (sux->number_of_preds() == 0) {
64 // sux is disconnected from graph so disconnect from exception handlers
65 xhandler->remove_predecessor(sux);
66 }
67 if (!xhandler->is_predecessor(block)) {
68 xhandler->add_predecessor(block);
69 }
70 }
71 }
73 virtual void block_do(BlockBegin* block);
75 private:
76 Value make_ifop(Value x, Instruction::Condition cond, Value y, Value tval, Value fval);
77 };
79 void CE_Eliminator::block_do(BlockBegin* block) {
80 // 1) find conditional expression
81 // check if block ends with an If
82 If* if_ = block->end()->as_If();
83 if (if_ == NULL) return;
85 // check if If works on int or object types
86 // (we cannot handle If's working on long, float or doubles yet,
87 // since IfOp doesn't support them - these If's show up if cmp
88 // operations followed by If's are eliminated)
89 ValueType* if_type = if_->x()->type();
90 if (!if_type->is_int() && !if_type->is_object()) return;
92 BlockBegin* t_block = if_->tsux();
93 BlockBegin* f_block = if_->fsux();
94 Instruction* t_cur = t_block->next();
95 Instruction* f_cur = f_block->next();
97 // one Constant may be present between BlockBegin and BlockEnd
98 Value t_const = NULL;
99 Value f_const = NULL;
100 if (t_cur->as_Constant() != NULL && !t_cur->can_trap()) {
101 t_const = t_cur;
102 t_cur = t_cur->next();
103 }
104 if (f_cur->as_Constant() != NULL && !f_cur->can_trap()) {
105 f_const = f_cur;
106 f_cur = f_cur->next();
107 }
109 // check if both branches end with a goto
110 Goto* t_goto = t_cur->as_Goto();
111 if (t_goto == NULL) return;
112 Goto* f_goto = f_cur->as_Goto();
113 if (f_goto == NULL) return;
115 // check if both gotos merge into the same block
116 BlockBegin* sux = t_goto->default_sux();
117 if (sux != f_goto->default_sux()) return;
119 // check if at least one word was pushed on sux_state
120 ValueStack* sux_state = sux->state();
121 if (sux_state->stack_size() <= if_->state()->stack_size()) return;
123 // check if phi function is present at end of successor stack and that
124 // only this phi was pushed on the stack
125 Value sux_phi = sux_state->stack_at(if_->state()->stack_size());
126 if (sux_phi == NULL || sux_phi->as_Phi() == NULL || sux_phi->as_Phi()->block() != sux) return;
127 if (sux_phi->type()->size() != sux_state->stack_size() - if_->state()->stack_size()) return;
129 // get the values that were pushed in the true- and false-branch
130 Value t_value = t_goto->state()->stack_at(if_->state()->stack_size());
131 Value f_value = f_goto->state()->stack_at(if_->state()->stack_size());
133 // backend does not support floats
134 assert(t_value->type()->base() == f_value->type()->base(), "incompatible types");
135 if (t_value->type()->is_float_kind()) return;
137 // check that successor has no other phi functions but sux_phi
138 // this can happen when t_block or f_block contained additonal stores to local variables
139 // that are no longer represented by explicit instructions
140 for_each_phi_fun(sux, phi,
141 if (phi != sux_phi) return;
142 );
143 // true and false blocks can't have phis
144 for_each_phi_fun(t_block, phi, return; );
145 for_each_phi_fun(f_block, phi, return; );
147 // 2) substitute conditional expression
148 // with an IfOp followed by a Goto
149 // cut if_ away and get node before
150 Instruction* cur_end = if_->prev(block);
152 // append constants of true- and false-block if necessary
153 // clone constants because original block must not be destroyed
154 assert((t_value != f_const && f_value != t_const) || t_const == f_const, "mismatch");
155 if (t_value == t_const) {
156 t_value = new Constant(t_const->type());
157 NOT_PRODUCT(t_value->set_printable_bci(if_->printable_bci()));
158 cur_end = cur_end->set_next(t_value);
159 }
160 if (f_value == f_const) {
161 f_value = new Constant(f_const->type());
162 NOT_PRODUCT(f_value->set_printable_bci(if_->printable_bci()));
163 cur_end = cur_end->set_next(f_value);
164 }
166 Value result = make_ifop(if_->x(), if_->cond(), if_->y(), t_value, f_value);
167 assert(result != NULL, "make_ifop must return a non-null instruction");
168 if (!result->is_linked() && result->can_be_linked()) {
169 NOT_PRODUCT(result->set_printable_bci(if_->printable_bci()));
170 cur_end = cur_end->set_next(result);
171 }
173 // append Goto to successor
174 ValueStack* state_before = if_->is_safepoint() ? if_->state_before() : NULL;
175 Goto* goto_ = new Goto(sux, state_before, if_->is_safepoint() || t_goto->is_safepoint() || f_goto->is_safepoint());
177 // prepare state for Goto
178 ValueStack* goto_state = if_->state();
179 while (sux_state->scope() != goto_state->scope()) {
180 goto_state = goto_state->caller_state();
181 assert(goto_state != NULL, "states do not match up");
182 }
183 goto_state = goto_state->copy(ValueStack::StateAfter, goto_state->bci());
184 goto_state->push(result->type(), result);
185 assert(goto_state->is_same(sux_state), "states must match now");
186 goto_->set_state(goto_state);
188 cur_end = cur_end->set_next(goto_, goto_state->bci());
190 // Adjust control flow graph
191 BlockBegin::disconnect_edge(block, t_block);
192 BlockBegin::disconnect_edge(block, f_block);
193 if (t_block->number_of_preds() == 0) {
194 BlockBegin::disconnect_edge(t_block, sux);
195 }
196 adjust_exception_edges(block, t_block);
197 if (f_block->number_of_preds() == 0) {
198 BlockBegin::disconnect_edge(f_block, sux);
199 }
200 adjust_exception_edges(block, f_block);
202 // update block end
203 block->set_end(goto_);
205 // substitute the phi if possible
206 if (sux_phi->as_Phi()->operand_count() == 1) {
207 assert(sux_phi->as_Phi()->operand_at(0) == result, "screwed up phi");
208 sux_phi->set_subst(result);
209 _has_substitution = true;
210 }
212 // 3) successfully eliminated a conditional expression
213 _cee_count++;
214 if (PrintCEE) {
215 tty->print_cr("%d. CEE in B%d (B%d B%d)", cee_count(), block->block_id(), t_block->block_id(), f_block->block_id());
216 tty->print_cr("%d. IfOp in B%d", ifop_count(), block->block_id());
217 }
219 _hir->verify();
220 }
222 Value CE_Eliminator::make_ifop(Value x, Instruction::Condition cond, Value y, Value tval, Value fval) {
223 if (!OptimizeIfOps) {
224 return new IfOp(x, cond, y, tval, fval);
225 }
227 tval = tval->subst();
228 fval = fval->subst();
229 if (tval == fval) {
230 _ifop_count++;
231 return tval;
232 }
234 x = x->subst();
235 y = y->subst();
237 Constant* y_const = y->as_Constant();
238 if (y_const != NULL) {
239 IfOp* x_ifop = x->as_IfOp();
240 if (x_ifop != NULL) { // x is an ifop, y is a constant
241 Constant* x_tval_const = x_ifop->tval()->subst()->as_Constant();
242 Constant* x_fval_const = x_ifop->fval()->subst()->as_Constant();
244 if (x_tval_const != NULL && x_fval_const != NULL) {
245 Instruction::Condition x_ifop_cond = x_ifop->cond();
247 Constant::CompareResult t_compare_res = x_tval_const->compare(cond, y_const);
248 Constant::CompareResult f_compare_res = x_fval_const->compare(cond, y_const);
250 guarantee(t_compare_res != Constant::not_comparable && f_compare_res != Constant::not_comparable, "incomparable constants in IfOp");
252 Value new_tval = t_compare_res == Constant::cond_true ? tval : fval;
253 Value new_fval = f_compare_res == Constant::cond_true ? tval : fval;
255 _ifop_count++;
256 if (new_tval == new_fval) {
257 return new_tval;
258 } else {
259 return new IfOp(x_ifop->x(), x_ifop_cond, x_ifop->y(), new_tval, new_fval);
260 }
261 }
262 } else {
263 Constant* x_const = x->as_Constant();
264 if (x_const != NULL) { // x and y are constants
265 Constant::CompareResult x_compare_res = x_const->compare(cond, y_const);
266 guarantee(x_compare_res != Constant::not_comparable, "incomparable constants in IfOp");
268 _ifop_count++;
269 return x_compare_res == Constant::cond_true ? tval : fval;
270 }
271 }
272 }
273 return new IfOp(x, cond, y, tval, fval);
274 }
276 void Optimizer::eliminate_conditional_expressions() {
277 // find conditional expressions & replace them with IfOps
278 CE_Eliminator ce(ir());
279 }
281 class BlockMerger: public BlockClosure {
282 private:
283 IR* _hir;
284 int _merge_count; // the number of block pairs successfully merged
286 public:
287 BlockMerger(IR* hir)
288 : _hir(hir)
289 , _merge_count(0)
290 {
291 _hir->iterate_preorder(this);
292 }
294 bool try_merge(BlockBegin* block) {
295 BlockEnd* end = block->end();
296 if (end->as_Goto() != NULL) {
297 assert(end->number_of_sux() == 1, "end must have exactly one successor");
298 // Note: It would be sufficient to check for the number of successors (= 1)
299 // in order to decide if this block can be merged potentially. That
300 // would then also include switch statements w/ only a default case.
301 // However, in that case we would need to make sure the switch tag
302 // expression is executed if it can produce observable side effects.
303 // We should probably have the canonicalizer simplifying such switch
304 // statements and then we are sure we don't miss these merge opportunities
305 // here (was bug - gri 7/7/99).
306 BlockBegin* sux = end->default_sux();
307 if (sux->number_of_preds() == 1 && !sux->is_entry_block() && !end->is_safepoint()) {
308 // merge the two blocks
310 #ifdef ASSERT
311 // verify that state at the end of block and at the beginning of sux are equal
312 // no phi functions must be present at beginning of sux
313 ValueStack* sux_state = sux->state();
314 ValueStack* end_state = end->state();
316 assert(end_state->scope() == sux_state->scope(), "scopes must match");
317 assert(end_state->stack_size() == sux_state->stack_size(), "stack not equal");
318 assert(end_state->locals_size() == sux_state->locals_size(), "locals not equal");
320 int index;
321 Value sux_value;
322 for_each_stack_value(sux_state, index, sux_value) {
323 assert(sux_value == end_state->stack_at(index), "stack not equal");
324 }
325 for_each_local_value(sux_state, index, sux_value) {
326 assert(sux_value == end_state->local_at(index), "locals not equal");
327 }
328 assert(sux_state->caller_state() == end_state->caller_state(), "caller not equal");
329 #endif
331 // find instruction before end & append first instruction of sux block
332 Instruction* prev = end->prev(block);
333 Instruction* next = sux->next();
334 assert(prev->as_BlockEnd() == NULL, "must not be a BlockEnd");
335 prev->set_next(next);
336 sux->disconnect_from_graph();
337 block->set_end(sux->end());
338 // add exception handlers of deleted block, if any
339 for (int k = 0; k < sux->number_of_exception_handlers(); k++) {
340 BlockBegin* xhandler = sux->exception_handler_at(k);
341 block->add_exception_handler(xhandler);
343 // also substitute predecessor of exception handler
344 assert(xhandler->is_predecessor(sux), "missing predecessor");
345 xhandler->remove_predecessor(sux);
346 if (!xhandler->is_predecessor(block)) {
347 xhandler->add_predecessor(block);
348 }
349 }
351 // debugging output
352 _merge_count++;
353 if (PrintBlockElimination) {
354 tty->print_cr("%d. merged B%d & B%d (stack size = %d)",
355 _merge_count, block->block_id(), sux->block_id(), sux->state()->stack_size());
356 }
358 _hir->verify();
360 If* if_ = block->end()->as_If();
361 if (if_) {
362 IfOp* ifop = if_->x()->as_IfOp();
363 Constant* con = if_->y()->as_Constant();
364 bool swapped = false;
365 if (!con || !ifop) {
366 ifop = if_->y()->as_IfOp();
367 con = if_->x()->as_Constant();
368 swapped = true;
369 }
370 if (con && ifop) {
371 Constant* tval = ifop->tval()->as_Constant();
372 Constant* fval = ifop->fval()->as_Constant();
373 if (tval && fval) {
374 // Find the instruction before if_, starting with ifop.
375 // When if_ and ifop are not in the same block, prev
376 // becomes NULL In such (rare) cases it is not
377 // profitable to perform the optimization.
378 Value prev = ifop;
379 while (prev != NULL && prev->next() != if_) {
380 prev = prev->next();
381 }
383 if (prev != NULL) {
384 Instruction::Condition cond = if_->cond();
385 BlockBegin* tsux = if_->tsux();
386 BlockBegin* fsux = if_->fsux();
387 if (swapped) {
388 cond = Instruction::mirror(cond);
389 }
391 BlockBegin* tblock = tval->compare(cond, con, tsux, fsux);
392 BlockBegin* fblock = fval->compare(cond, con, tsux, fsux);
393 if (tblock != fblock && !if_->is_safepoint()) {
394 If* newif = new If(ifop->x(), ifop->cond(), false, ifop->y(),
395 tblock, fblock, if_->state_before(), if_->is_safepoint());
396 newif->set_state(if_->state()->copy());
398 assert(prev->next() == if_, "must be guaranteed by above search");
399 NOT_PRODUCT(newif->set_printable_bci(if_->printable_bci()));
400 prev->set_next(newif);
401 block->set_end(newif);
403 _merge_count++;
404 if (PrintBlockElimination) {
405 tty->print_cr("%d. replaced If and IfOp at end of B%d with single If", _merge_count, block->block_id());
406 }
408 _hir->verify();
409 }
410 }
411 }
412 }
413 }
415 return true;
416 }
417 }
418 return false;
419 }
421 virtual void block_do(BlockBegin* block) {
422 _hir->verify();
423 // repeat since the same block may merge again
424 while (try_merge(block)) {
425 _hir->verify();
426 }
427 }
428 };
431 void Optimizer::eliminate_blocks() {
432 // merge blocks if possible
433 BlockMerger bm(ir());
434 }
437 class NullCheckEliminator;
438 class NullCheckVisitor: public InstructionVisitor {
439 private:
440 NullCheckEliminator* _nce;
441 NullCheckEliminator* nce() { return _nce; }
443 public:
444 NullCheckVisitor() {}
446 void set_eliminator(NullCheckEliminator* nce) { _nce = nce; }
448 void do_Phi (Phi* x);
449 void do_Local (Local* x);
450 void do_Constant (Constant* x);
451 void do_LoadField (LoadField* x);
452 void do_StoreField (StoreField* x);
453 void do_ArrayLength (ArrayLength* x);
454 void do_LoadIndexed (LoadIndexed* x);
455 void do_StoreIndexed (StoreIndexed* x);
456 void do_NegateOp (NegateOp* x);
457 void do_ArithmeticOp (ArithmeticOp* x);
458 void do_ShiftOp (ShiftOp* x);
459 void do_LogicOp (LogicOp* x);
460 void do_CompareOp (CompareOp* x);
461 void do_IfOp (IfOp* x);
462 void do_Convert (Convert* x);
463 void do_NullCheck (NullCheck* x);
464 void do_Invoke (Invoke* x);
465 void do_NewInstance (NewInstance* x);
466 void do_NewTypeArray (NewTypeArray* x);
467 void do_NewObjectArray (NewObjectArray* x);
468 void do_NewMultiArray (NewMultiArray* x);
469 void do_CheckCast (CheckCast* x);
470 void do_InstanceOf (InstanceOf* x);
471 void do_MonitorEnter (MonitorEnter* x);
472 void do_MonitorExit (MonitorExit* x);
473 void do_Intrinsic (Intrinsic* x);
474 void do_BlockBegin (BlockBegin* x);
475 void do_Goto (Goto* x);
476 void do_If (If* x);
477 void do_IfInstanceOf (IfInstanceOf* x);
478 void do_TableSwitch (TableSwitch* x);
479 void do_LookupSwitch (LookupSwitch* x);
480 void do_Return (Return* x);
481 void do_Throw (Throw* x);
482 void do_Base (Base* x);
483 void do_OsrEntry (OsrEntry* x);
484 void do_ExceptionObject(ExceptionObject* x);
485 void do_RoundFP (RoundFP* x);
486 void do_UnsafeGetRaw (UnsafeGetRaw* x);
487 void do_UnsafePutRaw (UnsafePutRaw* x);
488 void do_UnsafeGetObject(UnsafeGetObject* x);
489 void do_UnsafePutObject(UnsafePutObject* x);
490 void do_UnsafePrefetchRead (UnsafePrefetchRead* x);
491 void do_UnsafePrefetchWrite(UnsafePrefetchWrite* x);
492 void do_ProfileCall (ProfileCall* x);
493 void do_ProfileInvoke (ProfileInvoke* x);
494 };
497 // Because of a static contained within (for the purpose of iteration
498 // over instructions), it is only valid to have one of these active at
499 // a time
500 class NullCheckEliminator: public ValueVisitor {
501 private:
502 Optimizer* _opt;
504 ValueSet* _visitable_instructions; // Visit each instruction only once per basic block
505 BlockList* _work_list; // Basic blocks to visit
507 bool visitable(Value x) {
508 assert(_visitable_instructions != NULL, "check");
509 return _visitable_instructions->contains(x);
510 }
511 void mark_visited(Value x) {
512 assert(_visitable_instructions != NULL, "check");
513 _visitable_instructions->remove(x);
514 }
515 void mark_visitable(Value x) {
516 assert(_visitable_instructions != NULL, "check");
517 _visitable_instructions->put(x);
518 }
519 void clear_visitable_state() {
520 assert(_visitable_instructions != NULL, "check");
521 _visitable_instructions->clear();
522 }
524 ValueSet* _set; // current state, propagated to subsequent BlockBegins
525 ValueSetList _block_states; // BlockBegin null-check states for all processed blocks
526 NullCheckVisitor _visitor;
527 NullCheck* _last_explicit_null_check;
529 bool set_contains(Value x) { assert(_set != NULL, "check"); return _set->contains(x); }
530 void set_put (Value x) { assert(_set != NULL, "check"); _set->put(x); }
531 void set_remove (Value x) { assert(_set != NULL, "check"); _set->remove(x); }
533 BlockList* work_list() { return _work_list; }
535 void iterate_all();
536 void iterate_one(BlockBegin* block);
538 ValueSet* state() { return _set; }
539 void set_state_from (ValueSet* state) { _set->set_from(state); }
540 ValueSet* state_for (BlockBegin* block) { return _block_states[block->block_id()]; }
541 void set_state_for (BlockBegin* block, ValueSet* stack) { _block_states[block->block_id()] = stack; }
542 // Returns true if caused a change in the block's state.
543 bool merge_state_for(BlockBegin* block,
544 ValueSet* incoming_state);
546 public:
547 // constructor
548 NullCheckEliminator(Optimizer* opt)
549 : _opt(opt)
550 , _set(new ValueSet())
551 , _last_explicit_null_check(NULL)
552 , _block_states(BlockBegin::number_of_blocks(), NULL)
553 , _work_list(new BlockList()) {
554 _visitable_instructions = new ValueSet();
555 _visitor.set_eliminator(this);
556 }
558 Optimizer* opt() { return _opt; }
559 IR* ir () { return opt()->ir(); }
561 // Process a graph
562 void iterate(BlockBegin* root);
564 void visit(Value* f);
566 // In some situations (like NullCheck(x); getfield(x)) the debug
567 // information from the explicit NullCheck can be used to populate
568 // the getfield, even if the two instructions are in different
569 // scopes; this allows implicit null checks to be used but the
570 // correct exception information to be generated. We must clear the
571 // last-traversed NullCheck when we reach a potentially-exception-
572 // throwing instruction, as well as in some other cases.
573 void set_last_explicit_null_check(NullCheck* check) { _last_explicit_null_check = check; }
574 NullCheck* last_explicit_null_check() { return _last_explicit_null_check; }
575 Value last_explicit_null_check_obj() { return (_last_explicit_null_check
576 ? _last_explicit_null_check->obj()
577 : NULL); }
578 NullCheck* consume_last_explicit_null_check() {
579 _last_explicit_null_check->unpin(Instruction::PinExplicitNullCheck);
580 _last_explicit_null_check->set_can_trap(false);
581 return _last_explicit_null_check;
582 }
583 void clear_last_explicit_null_check() { _last_explicit_null_check = NULL; }
585 // Handlers for relevant instructions
586 // (separated out from NullCheckVisitor for clarity)
588 // The basic contract is that these must leave the instruction in
589 // the desired state; must not assume anything about the state of
590 // the instruction. We make multiple passes over some basic blocks
591 // and the last pass is the only one whose result is valid.
592 void handle_AccessField (AccessField* x);
593 void handle_ArrayLength (ArrayLength* x);
594 void handle_LoadIndexed (LoadIndexed* x);
595 void handle_StoreIndexed (StoreIndexed* x);
596 void handle_NullCheck (NullCheck* x);
597 void handle_Invoke (Invoke* x);
598 void handle_NewInstance (NewInstance* x);
599 void handle_NewArray (NewArray* x);
600 void handle_AccessMonitor (AccessMonitor* x);
601 void handle_Intrinsic (Intrinsic* x);
602 void handle_ExceptionObject (ExceptionObject* x);
603 void handle_Phi (Phi* x);
604 };
607 // NEEDS_CLEANUP
608 // There may be other instructions which need to clear the last
609 // explicit null check. Anything across which we can not hoist the
610 // debug information for a NullCheck instruction must clear it. It
611 // might be safer to pattern match "NullCheck ; {AccessField,
612 // ArrayLength, LoadIndexed}" but it is more easily structured this way.
613 // Should test to see performance hit of clearing it for all handlers
614 // with empty bodies below. If it is negligible then we should leave
615 // that in for safety, otherwise should think more about it.
616 void NullCheckVisitor::do_Phi (Phi* x) { nce()->handle_Phi(x); }
617 void NullCheckVisitor::do_Local (Local* x) {}
618 void NullCheckVisitor::do_Constant (Constant* x) { /* FIXME: handle object constants */ }
619 void NullCheckVisitor::do_LoadField (LoadField* x) { nce()->handle_AccessField(x); }
620 void NullCheckVisitor::do_StoreField (StoreField* x) { nce()->handle_AccessField(x); }
621 void NullCheckVisitor::do_ArrayLength (ArrayLength* x) { nce()->handle_ArrayLength(x); }
622 void NullCheckVisitor::do_LoadIndexed (LoadIndexed* x) { nce()->handle_LoadIndexed(x); }
623 void NullCheckVisitor::do_StoreIndexed (StoreIndexed* x) { nce()->handle_StoreIndexed(x); }
624 void NullCheckVisitor::do_NegateOp (NegateOp* x) {}
625 void NullCheckVisitor::do_ArithmeticOp (ArithmeticOp* x) { if (x->can_trap()) nce()->clear_last_explicit_null_check(); }
626 void NullCheckVisitor::do_ShiftOp (ShiftOp* x) {}
627 void NullCheckVisitor::do_LogicOp (LogicOp* x) {}
628 void NullCheckVisitor::do_CompareOp (CompareOp* x) {}
629 void NullCheckVisitor::do_IfOp (IfOp* x) {}
630 void NullCheckVisitor::do_Convert (Convert* x) {}
631 void NullCheckVisitor::do_NullCheck (NullCheck* x) { nce()->handle_NullCheck(x); }
632 void NullCheckVisitor::do_Invoke (Invoke* x) { nce()->handle_Invoke(x); }
633 void NullCheckVisitor::do_NewInstance (NewInstance* x) { nce()->handle_NewInstance(x); }
634 void NullCheckVisitor::do_NewTypeArray (NewTypeArray* x) { nce()->handle_NewArray(x); }
635 void NullCheckVisitor::do_NewObjectArray (NewObjectArray* x) { nce()->handle_NewArray(x); }
636 void NullCheckVisitor::do_NewMultiArray (NewMultiArray* x) { nce()->handle_NewArray(x); }
637 void NullCheckVisitor::do_CheckCast (CheckCast* x) {}
638 void NullCheckVisitor::do_InstanceOf (InstanceOf* x) {}
639 void NullCheckVisitor::do_MonitorEnter (MonitorEnter* x) { nce()->handle_AccessMonitor(x); }
640 void NullCheckVisitor::do_MonitorExit (MonitorExit* x) { nce()->handle_AccessMonitor(x); }
641 void NullCheckVisitor::do_Intrinsic (Intrinsic* x) { nce()->clear_last_explicit_null_check(); }
642 void NullCheckVisitor::do_BlockBegin (BlockBegin* x) {}
643 void NullCheckVisitor::do_Goto (Goto* x) {}
644 void NullCheckVisitor::do_If (If* x) {}
645 void NullCheckVisitor::do_IfInstanceOf (IfInstanceOf* x) {}
646 void NullCheckVisitor::do_TableSwitch (TableSwitch* x) {}
647 void NullCheckVisitor::do_LookupSwitch (LookupSwitch* x) {}
648 void NullCheckVisitor::do_Return (Return* x) {}
649 void NullCheckVisitor::do_Throw (Throw* x) { nce()->clear_last_explicit_null_check(); }
650 void NullCheckVisitor::do_Base (Base* x) {}
651 void NullCheckVisitor::do_OsrEntry (OsrEntry* x) {}
652 void NullCheckVisitor::do_ExceptionObject(ExceptionObject* x) { nce()->handle_ExceptionObject(x); }
653 void NullCheckVisitor::do_RoundFP (RoundFP* x) {}
654 void NullCheckVisitor::do_UnsafeGetRaw (UnsafeGetRaw* x) {}
655 void NullCheckVisitor::do_UnsafePutRaw (UnsafePutRaw* x) {}
656 void NullCheckVisitor::do_UnsafeGetObject(UnsafeGetObject* x) {}
657 void NullCheckVisitor::do_UnsafePutObject(UnsafePutObject* x) {}
658 void NullCheckVisitor::do_UnsafePrefetchRead (UnsafePrefetchRead* x) {}
659 void NullCheckVisitor::do_UnsafePrefetchWrite(UnsafePrefetchWrite* x) {}
660 void NullCheckVisitor::do_ProfileCall (ProfileCall* x) { nce()->clear_last_explicit_null_check(); }
661 void NullCheckVisitor::do_ProfileInvoke (ProfileInvoke* x) {}
664 void NullCheckEliminator::visit(Value* p) {
665 assert(*p != NULL, "should not find NULL instructions");
666 if (visitable(*p)) {
667 mark_visited(*p);
668 (*p)->visit(&_visitor);
669 }
670 }
672 bool NullCheckEliminator::merge_state_for(BlockBegin* block, ValueSet* incoming_state) {
673 ValueSet* state = state_for(block);
674 if (state == NULL) {
675 state = incoming_state->copy();
676 set_state_for(block, state);
677 return true;
678 } else {
679 bool changed = state->set_intersect(incoming_state);
680 if (PrintNullCheckElimination && changed) {
681 tty->print_cr("Block %d's null check state changed", block->block_id());
682 }
683 return changed;
684 }
685 }
688 void NullCheckEliminator::iterate_all() {
689 while (work_list()->length() > 0) {
690 iterate_one(work_list()->pop());
691 }
692 }
695 void NullCheckEliminator::iterate_one(BlockBegin* block) {
696 clear_visitable_state();
697 // clear out an old explicit null checks
698 set_last_explicit_null_check(NULL);
700 if (PrintNullCheckElimination) {
701 tty->print_cr(" ...iterating block %d in null check elimination for %s::%s%s",
702 block->block_id(),
703 ir()->method()->holder()->name()->as_utf8(),
704 ir()->method()->name()->as_utf8(),
705 ir()->method()->signature()->as_symbol()->as_utf8());
706 }
708 // Create new state if none present (only happens at root)
709 if (state_for(block) == NULL) {
710 ValueSet* tmp_state = new ValueSet();
711 set_state_for(block, tmp_state);
712 // Initial state is that local 0 (receiver) is non-null for
713 // non-static methods
714 ValueStack* stack = block->state();
715 IRScope* scope = stack->scope();
716 ciMethod* method = scope->method();
717 if (!method->is_static()) {
718 Local* local0 = stack->local_at(0)->as_Local();
719 assert(local0 != NULL, "must be");
720 assert(local0->type() == objectType, "invalid type of receiver");
722 if (local0 != NULL) {
723 // Local 0 is used in this scope
724 tmp_state->put(local0);
725 if (PrintNullCheckElimination) {
726 tty->print_cr("Local 0 (value %d) proven non-null upon entry", local0->id());
727 }
728 }
729 }
730 }
732 // Must copy block's state to avoid mutating it during iteration
733 // through the block -- otherwise "not-null" states can accidentally
734 // propagate "up" through the block during processing of backward
735 // branches and algorithm is incorrect (and does not converge)
736 set_state_from(state_for(block));
738 // allow visiting of Phis belonging to this block
739 for_each_phi_fun(block, phi,
740 mark_visitable(phi);
741 );
743 BlockEnd* e = block->end();
744 assert(e != NULL, "incomplete graph");
745 int i;
747 // Propagate the state before this block into the exception
748 // handlers. They aren't true successors since we aren't guaranteed
749 // to execute the whole block before executing them. Also putting
750 // them on first seems to help reduce the amount of iteration to
751 // reach a fixed point.
752 for (i = 0; i < block->number_of_exception_handlers(); i++) {
753 BlockBegin* next = block->exception_handler_at(i);
754 if (merge_state_for(next, state())) {
755 if (!work_list()->contains(next)) {
756 work_list()->push(next);
757 }
758 }
759 }
761 // Iterate through block, updating state.
762 for (Instruction* instr = block; instr != NULL; instr = instr->next()) {
763 // Mark instructions in this block as visitable as they are seen
764 // in the instruction list. This keeps the iteration from
765 // visiting instructions which are references in other blocks or
766 // visiting instructions more than once.
767 mark_visitable(instr);
768 if (instr->is_pinned() || instr->can_trap() || (instr->as_NullCheck() != NULL)) {
769 mark_visited(instr);
770 instr->input_values_do(this);
771 instr->visit(&_visitor);
772 }
773 }
775 // Propagate state to successors if necessary
776 for (i = 0; i < e->number_of_sux(); i++) {
777 BlockBegin* next = e->sux_at(i);
778 if (merge_state_for(next, state())) {
779 if (!work_list()->contains(next)) {
780 work_list()->push(next);
781 }
782 }
783 }
784 }
787 void NullCheckEliminator::iterate(BlockBegin* block) {
788 work_list()->push(block);
789 iterate_all();
790 }
792 void NullCheckEliminator::handle_AccessField(AccessField* x) {
793 if (x->is_static()) {
794 if (x->as_LoadField() != NULL) {
795 // If the field is a non-null static final object field (as is
796 // often the case for sun.misc.Unsafe), put this LoadField into
797 // the non-null map
798 ciField* field = x->field();
799 if (field->is_constant()) {
800 ciConstant field_val = field->constant_value();
801 BasicType field_type = field_val.basic_type();
802 if (field_type == T_OBJECT || field_type == T_ARRAY) {
803 ciObject* obj_val = field_val.as_object();
804 if (!obj_val->is_null_object()) {
805 if (PrintNullCheckElimination) {
806 tty->print_cr("AccessField %d proven non-null by static final non-null oop check",
807 x->id());
808 }
809 set_put(x);
810 }
811 }
812 }
813 }
814 // Be conservative
815 clear_last_explicit_null_check();
816 return;
817 }
819 Value obj = x->obj();
820 if (set_contains(obj)) {
821 // Value is non-null => update AccessField
822 if (last_explicit_null_check_obj() == obj && !x->needs_patching()) {
823 x->set_explicit_null_check(consume_last_explicit_null_check());
824 x->set_needs_null_check(true);
825 if (PrintNullCheckElimination) {
826 tty->print_cr("Folded NullCheck %d into AccessField %d's null check for value %d",
827 x->explicit_null_check()->id(), x->id(), obj->id());
828 }
829 } else {
830 x->set_explicit_null_check(NULL);
831 x->set_needs_null_check(false);
832 if (PrintNullCheckElimination) {
833 tty->print_cr("Eliminated AccessField %d's null check for value %d", x->id(), obj->id());
834 }
835 }
836 } else {
837 set_put(obj);
838 if (PrintNullCheckElimination) {
839 tty->print_cr("AccessField %d of value %d proves value to be non-null", x->id(), obj->id());
840 }
841 // Ensure previous passes do not cause wrong state
842 x->set_needs_null_check(true);
843 x->set_explicit_null_check(NULL);
844 }
845 clear_last_explicit_null_check();
846 }
849 void NullCheckEliminator::handle_ArrayLength(ArrayLength* x) {
850 Value array = x->array();
851 if (set_contains(array)) {
852 // Value is non-null => update AccessArray
853 if (last_explicit_null_check_obj() == array) {
854 x->set_explicit_null_check(consume_last_explicit_null_check());
855 x->set_needs_null_check(true);
856 if (PrintNullCheckElimination) {
857 tty->print_cr("Folded NullCheck %d into ArrayLength %d's null check for value %d",
858 x->explicit_null_check()->id(), x->id(), array->id());
859 }
860 } else {
861 x->set_explicit_null_check(NULL);
862 x->set_needs_null_check(false);
863 if (PrintNullCheckElimination) {
864 tty->print_cr("Eliminated ArrayLength %d's null check for value %d", x->id(), array->id());
865 }
866 }
867 } else {
868 set_put(array);
869 if (PrintNullCheckElimination) {
870 tty->print_cr("ArrayLength %d of value %d proves value to be non-null", x->id(), array->id());
871 }
872 // Ensure previous passes do not cause wrong state
873 x->set_needs_null_check(true);
874 x->set_explicit_null_check(NULL);
875 }
876 clear_last_explicit_null_check();
877 }
880 void NullCheckEliminator::handle_LoadIndexed(LoadIndexed* x) {
881 Value array = x->array();
882 if (set_contains(array)) {
883 // Value is non-null => update AccessArray
884 if (last_explicit_null_check_obj() == array) {
885 x->set_explicit_null_check(consume_last_explicit_null_check());
886 x->set_needs_null_check(true);
887 if (PrintNullCheckElimination) {
888 tty->print_cr("Folded NullCheck %d into LoadIndexed %d's null check for value %d",
889 x->explicit_null_check()->id(), x->id(), array->id());
890 }
891 } else {
892 x->set_explicit_null_check(NULL);
893 x->set_needs_null_check(false);
894 if (PrintNullCheckElimination) {
895 tty->print_cr("Eliminated LoadIndexed %d's null check for value %d", x->id(), array->id());
896 }
897 }
898 } else {
899 set_put(array);
900 if (PrintNullCheckElimination) {
901 tty->print_cr("LoadIndexed %d of value %d proves value to be non-null", x->id(), array->id());
902 }
903 // Ensure previous passes do not cause wrong state
904 x->set_needs_null_check(true);
905 x->set_explicit_null_check(NULL);
906 }
907 clear_last_explicit_null_check();
908 }
911 void NullCheckEliminator::handle_StoreIndexed(StoreIndexed* x) {
912 Value array = x->array();
913 if (set_contains(array)) {
914 // Value is non-null => update AccessArray
915 if (PrintNullCheckElimination) {
916 tty->print_cr("Eliminated StoreIndexed %d's null check for value %d", x->id(), array->id());
917 }
918 x->set_needs_null_check(false);
919 } else {
920 set_put(array);
921 if (PrintNullCheckElimination) {
922 tty->print_cr("StoreIndexed %d of value %d proves value to be non-null", x->id(), array->id());
923 }
924 // Ensure previous passes do not cause wrong state
925 x->set_needs_null_check(true);
926 }
927 clear_last_explicit_null_check();
928 }
931 void NullCheckEliminator::handle_NullCheck(NullCheck* x) {
932 Value obj = x->obj();
933 if (set_contains(obj)) {
934 // Already proven to be non-null => this NullCheck is useless
935 if (PrintNullCheckElimination) {
936 tty->print_cr("Eliminated NullCheck %d for value %d", x->id(), obj->id());
937 }
938 // Don't unpin since that may shrink obj's live range and make it unavailable for debug info.
939 // The code generator won't emit LIR for a NullCheck that cannot trap.
940 x->set_can_trap(false);
941 } else {
942 // May be null => add to map and set last explicit NullCheck
943 x->set_can_trap(true);
944 // make sure it's pinned if it can trap
945 x->pin(Instruction::PinExplicitNullCheck);
946 set_put(obj);
947 set_last_explicit_null_check(x);
948 if (PrintNullCheckElimination) {
949 tty->print_cr("NullCheck %d of value %d proves value to be non-null", x->id(), obj->id());
950 }
951 }
952 }
955 void NullCheckEliminator::handle_Invoke(Invoke* x) {
956 if (!x->has_receiver()) {
957 // Be conservative
958 clear_last_explicit_null_check();
959 return;
960 }
962 Value recv = x->receiver();
963 if (!set_contains(recv)) {
964 set_put(recv);
965 if (PrintNullCheckElimination) {
966 tty->print_cr("Invoke %d of value %d proves value to be non-null", x->id(), recv->id());
967 }
968 }
969 clear_last_explicit_null_check();
970 }
973 void NullCheckEliminator::handle_NewInstance(NewInstance* x) {
974 set_put(x);
975 if (PrintNullCheckElimination) {
976 tty->print_cr("NewInstance %d is non-null", x->id());
977 }
978 }
981 void NullCheckEliminator::handle_NewArray(NewArray* x) {
982 set_put(x);
983 if (PrintNullCheckElimination) {
984 tty->print_cr("NewArray %d is non-null", x->id());
985 }
986 }
989 void NullCheckEliminator::handle_ExceptionObject(ExceptionObject* x) {
990 set_put(x);
991 if (PrintNullCheckElimination) {
992 tty->print_cr("ExceptionObject %d is non-null", x->id());
993 }
994 }
997 void NullCheckEliminator::handle_AccessMonitor(AccessMonitor* x) {
998 Value obj = x->obj();
999 if (set_contains(obj)) {
1000 // Value is non-null => update AccessMonitor
1001 if (PrintNullCheckElimination) {
1002 tty->print_cr("Eliminated AccessMonitor %d's null check for value %d", x->id(), obj->id());
1003 }
1004 x->set_needs_null_check(false);
1005 } else {
1006 set_put(obj);
1007 if (PrintNullCheckElimination) {
1008 tty->print_cr("AccessMonitor %d of value %d proves value to be non-null", x->id(), obj->id());
1009 }
1010 // Ensure previous passes do not cause wrong state
1011 x->set_needs_null_check(true);
1012 }
1013 clear_last_explicit_null_check();
1014 }
1017 void NullCheckEliminator::handle_Intrinsic(Intrinsic* x) {
1018 if (!x->has_receiver()) {
1019 // Be conservative
1020 clear_last_explicit_null_check();
1021 return;
1022 }
1024 Value recv = x->receiver();
1025 if (set_contains(recv)) {
1026 // Value is non-null => update Intrinsic
1027 if (PrintNullCheckElimination) {
1028 tty->print_cr("Eliminated Intrinsic %d's null check for value %d", x->id(), recv->id());
1029 }
1030 x->set_needs_null_check(false);
1031 } else {
1032 set_put(recv);
1033 if (PrintNullCheckElimination) {
1034 tty->print_cr("Intrinsic %d of value %d proves value to be non-null", x->id(), recv->id());
1035 }
1036 // Ensure previous passes do not cause wrong state
1037 x->set_needs_null_check(true);
1038 }
1039 clear_last_explicit_null_check();
1040 }
1043 void NullCheckEliminator::handle_Phi(Phi* x) {
1044 int i;
1045 bool all_non_null = true;
1046 if (x->is_illegal()) {
1047 all_non_null = false;
1048 } else {
1049 for (i = 0; i < x->operand_count(); i++) {
1050 Value input = x->operand_at(i);
1051 if (!set_contains(input)) {
1052 all_non_null = false;
1053 }
1054 }
1055 }
1057 if (all_non_null) {
1058 // Value is non-null => update Phi
1059 if (PrintNullCheckElimination) {
1060 tty->print_cr("Eliminated Phi %d's null check for phifun because all inputs are non-null", x->id());
1061 }
1062 x->set_needs_null_check(false);
1063 } else if (set_contains(x)) {
1064 set_remove(x);
1065 }
1066 }
1069 void Optimizer::eliminate_null_checks() {
1070 ResourceMark rm;
1072 NullCheckEliminator nce(this);
1074 if (PrintNullCheckElimination) {
1075 tty->print_cr("Starting null check elimination for method %s::%s%s",
1076 ir()->method()->holder()->name()->as_utf8(),
1077 ir()->method()->name()->as_utf8(),
1078 ir()->method()->signature()->as_symbol()->as_utf8());
1079 }
1081 // Apply to graph
1082 nce.iterate(ir()->start());
1084 // walk over the graph looking for exception
1085 // handlers and iterate over them as well
1086 int nblocks = BlockBegin::number_of_blocks();
1087 BlockList blocks(nblocks);
1088 boolArray visited_block(nblocks, false);
1090 blocks.push(ir()->start());
1091 visited_block[ir()->start()->block_id()] = true;
1092 for (int i = 0; i < blocks.length(); i++) {
1093 BlockBegin* b = blocks[i];
1094 // exception handlers need to be treated as additional roots
1095 for (int e = b->number_of_exception_handlers(); e-- > 0; ) {
1096 BlockBegin* excp = b->exception_handler_at(e);
1097 int id = excp->block_id();
1098 if (!visited_block[id]) {
1099 blocks.push(excp);
1100 visited_block[id] = true;
1101 nce.iterate(excp);
1102 }
1103 }
1104 // traverse successors
1105 BlockEnd *end = b->end();
1106 for (int s = end->number_of_sux(); s-- > 0; ) {
1107 BlockBegin* next = end->sux_at(s);
1108 int id = next->block_id();
1109 if (!visited_block[id]) {
1110 blocks.push(next);
1111 visited_block[id] = true;
1112 }
1113 }
1114 }
1117 if (PrintNullCheckElimination) {
1118 tty->print_cr("Done with null check elimination for method %s::%s%s",
1119 ir()->method()->holder()->name()->as_utf8(),
1120 ir()->method()->name()->as_utf8(),
1121 ir()->method()->signature()->as_symbol()->as_utf8());
1122 }
1123 }