1 /*
2 * Copyright (c) 1998, 2018, 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 "ci/ciMethodData.hpp"
27 #include "classfile/systemDictionary.hpp"
28 #include "classfile/vmSymbols.hpp"
29 #include "compiler/compileLog.hpp"
30 #include "interpreter/linkResolver.hpp"
31 #include "memory/resourceArea.hpp"
32 #include "memory/universe.hpp"
33 #include "oops/oop.inline.hpp"
34 #include "opto/addnode.hpp"
35 #include "opto/castnode.hpp"
36 #include "opto/convertnode.hpp"
37 #include "opto/divnode.hpp"
38 #include "opto/idealGraphPrinter.hpp"
39 #include "opto/matcher.hpp"
40 #include "opto/memnode.hpp"
41 #include "opto/mulnode.hpp"
42 #include "opto/opaquenode.hpp"
43 #include "opto/parse.hpp"
44 #include "opto/runtime.hpp"
45 #include "runtime/deoptimization.hpp"
46 #include "runtime/sharedRuntime.hpp"
47
48 #ifndef PRODUCT
49 extern int explicit_null_checks_inserted,
50 explicit_null_checks_elided;
51 #endif
52
53 //---------------------------------array_load----------------------------------
array_load(BasicType bt)54 void Parse::array_load(BasicType bt) {
55 const Type* elemtype = Type::TOP;
56 bool big_val = bt == T_DOUBLE || bt == T_LONG;
57 Node* adr = array_addressing(bt, 0, elemtype);
58 if (stopped()) return; // guaranteed null or range check
59
60 pop(); // index (already used)
61 Node* array = pop(); // the array itself
62
63 if (elemtype == TypeInt::BOOL) {
64 bt = T_BOOLEAN;
65 }
66 const TypeAryPtr* adr_type = TypeAryPtr::get_array_body_type(bt);
67
68 Node* ld = access_load_at(array, adr, adr_type, elemtype, bt,
69 IN_HEAP | IS_ARRAY | C2_CONTROL_DEPENDENT_LOAD);
70 if (big_val) {
71 push_pair(ld);
72 } else {
73 push(ld);
74 }
75 }
76
77
78 //--------------------------------array_store----------------------------------
array_store(BasicType bt)79 void Parse::array_store(BasicType bt) {
80 const Type* elemtype = Type::TOP;
81 bool big_val = bt == T_DOUBLE || bt == T_LONG;
82 Node* adr = array_addressing(bt, big_val ? 2 : 1, elemtype);
83 if (stopped()) return; // guaranteed null or range check
84 if (bt == T_OBJECT) {
85 array_store_check();
86 }
87 Node* val; // Oop to store
88 if (big_val) {
89 val = pop_pair();
90 } else {
91 val = pop();
92 }
93 pop(); // index (already used)
94 Node* array = pop(); // the array itself
95
96 if (elemtype == TypeInt::BOOL) {
97 bt = T_BOOLEAN;
98 }
99 const TypeAryPtr* adr_type = TypeAryPtr::get_array_body_type(bt);
100
101 access_store_at(array, adr, adr_type, val, elemtype, bt, MO_UNORDERED | IN_HEAP | IS_ARRAY);
102 }
103
104
105 //------------------------------array_addressing-------------------------------
106 // Pull array and index from the stack. Compute pointer-to-element.
array_addressing(BasicType type,int vals,const Type * & elemtype)107 Node* Parse::array_addressing(BasicType type, int vals, const Type*& elemtype) {
108 Node *idx = peek(0+vals); // Get from stack without popping
109 Node *ary = peek(1+vals); // in case of exception
110
111 // Null check the array base, with correct stack contents
112 ary = null_check(ary, T_ARRAY);
113 // Compile-time detect of null-exception?
114 if (stopped()) return top();
115
116 const TypeAryPtr* arytype = _gvn.type(ary)->is_aryptr();
117 const TypeInt* sizetype = arytype->size();
118 elemtype = arytype->elem();
119
120 if (UseUniqueSubclasses) {
121 const Type* el = elemtype->make_ptr();
122 if (el && el->isa_instptr()) {
123 const TypeInstPtr* toop = el->is_instptr();
124 if (toop->klass()->as_instance_klass()->unique_concrete_subklass()) {
125 // If we load from "AbstractClass[]" we must see "ConcreteSubClass".
126 const Type* subklass = Type::get_const_type(toop->klass());
127 elemtype = subklass->join_speculative(el);
128 }
129 }
130 }
131
132 // Check for big class initializers with all constant offsets
133 // feeding into a known-size array.
134 const TypeInt* idxtype = _gvn.type(idx)->is_int();
135 // See if the highest idx value is less than the lowest array bound,
136 // and if the idx value cannot be negative:
137 bool need_range_check = true;
138 if (idxtype->_hi < sizetype->_lo && idxtype->_lo >= 0) {
139 need_range_check = false;
140 if (C->log() != NULL) C->log()->elem("observe that='!need_range_check'");
141 }
142
143 ciKlass * arytype_klass = arytype->klass();
144 if ((arytype_klass != NULL) && (!arytype_klass->is_loaded())) {
145 // Only fails for some -Xcomp runs
146 // The class is unloaded. We have to run this bytecode in the interpreter.
147 uncommon_trap(Deoptimization::Reason_unloaded,
148 Deoptimization::Action_reinterpret,
149 arytype->klass(), "!loaded array");
150 return top();
151 }
152
153 // Do the range check
154 if (GenerateRangeChecks && need_range_check) {
155 Node* tst;
156 if (sizetype->_hi <= 0) {
157 // The greatest array bound is negative, so we can conclude that we're
158 // compiling unreachable code, but the unsigned compare trick used below
159 // only works with non-negative lengths. Instead, hack "tst" to be zero so
160 // the uncommon_trap path will always be taken.
161 tst = _gvn.intcon(0);
162 } else {
163 // Range is constant in array-oop, so we can use the original state of mem
164 Node* len = load_array_length(ary);
165
166 // Test length vs index (standard trick using unsigned compare)
167 Node* chk = _gvn.transform( new CmpUNode(idx, len) );
168 BoolTest::mask btest = BoolTest::lt;
169 tst = _gvn.transform( new BoolNode(chk, btest) );
170 }
171 RangeCheckNode* rc = new RangeCheckNode(control(), tst, PROB_MAX, COUNT_UNKNOWN);
172 _gvn.set_type(rc, rc->Value(&_gvn));
173 if (!tst->is_Con()) {
174 record_for_igvn(rc);
175 }
176 set_control(_gvn.transform(new IfTrueNode(rc)));
177 // Branch to failure if out of bounds
178 {
179 PreserveJVMState pjvms(this);
180 set_control(_gvn.transform(new IfFalseNode(rc)));
181 if (C->allow_range_check_smearing()) {
182 // Do not use builtin_throw, since range checks are sometimes
183 // made more stringent by an optimistic transformation.
184 // This creates "tentative" range checks at this point,
185 // which are not guaranteed to throw exceptions.
186 // See IfNode::Ideal, is_range_check, adjust_check.
187 uncommon_trap(Deoptimization::Reason_range_check,
188 Deoptimization::Action_make_not_entrant,
189 NULL, "range_check");
190 } else {
191 // If we have already recompiled with the range-check-widening
192 // heroic optimization turned off, then we must really be throwing
193 // range check exceptions.
194 builtin_throw(Deoptimization::Reason_range_check, idx);
195 }
196 }
197 }
198 // Check for always knowing you are throwing a range-check exception
199 if (stopped()) return top();
200
201 // Make array address computation control dependent to prevent it
202 // from floating above the range check during loop optimizations.
203 Node* ptr = array_element_address(ary, idx, type, sizetype, control());
204 assert(ptr != top(), "top should go hand-in-hand with stopped");
205
206 return ptr;
207 }
208
209
210 // returns IfNode
jump_if_fork_int(Node * a,Node * b,BoolTest::mask mask,float prob,float cnt)211 IfNode* Parse::jump_if_fork_int(Node* a, Node* b, BoolTest::mask mask, float prob, float cnt) {
212 Node *cmp = _gvn.transform(new CmpINode(a, b)); // two cases: shiftcount > 32 and shiftcount <= 32
213 Node *tst = _gvn.transform(new BoolNode(cmp, mask));
214 IfNode *iff = create_and_map_if(control(), tst, prob, cnt);
215 return iff;
216 }
217
218 // return Region node
jump_if_join(Node * iffalse,Node * iftrue)219 Node* Parse::jump_if_join(Node* iffalse, Node* iftrue) {
220 Node *region = new RegionNode(3); // 2 results
221 record_for_igvn(region);
222 region->init_req(1, iffalse);
223 region->init_req(2, iftrue );
224 _gvn.set_type(region, Type::CONTROL);
225 region = _gvn.transform(region);
226 set_control (region);
227 return region;
228 }
229
230 // sentinel value for the target bci to mark never taken branches
231 // (according to profiling)
232 static const int never_reached = INT_MAX;
233
234 //------------------------------helper for tableswitch-------------------------
jump_if_true_fork(IfNode * iff,int dest_bci_if_true,int prof_table_index,bool unc)235 void Parse::jump_if_true_fork(IfNode *iff, int dest_bci_if_true, int prof_table_index, bool unc) {
236 // True branch, use existing map info
237 { PreserveJVMState pjvms(this);
238 Node *iftrue = _gvn.transform( new IfTrueNode (iff) );
239 set_control( iftrue );
240 if (unc) {
241 repush_if_args();
242 uncommon_trap(Deoptimization::Reason_unstable_if,
243 Deoptimization::Action_reinterpret,
244 NULL,
245 "taken always");
246 } else {
247 assert(dest_bci_if_true != never_reached, "inconsistent dest");
248 profile_switch_case(prof_table_index);
249 merge_new_path(dest_bci_if_true);
250 }
251 }
252
253 // False branch
254 Node *iffalse = _gvn.transform( new IfFalseNode(iff) );
255 set_control( iffalse );
256 }
257
jump_if_false_fork(IfNode * iff,int dest_bci_if_true,int prof_table_index,bool unc)258 void Parse::jump_if_false_fork(IfNode *iff, int dest_bci_if_true, int prof_table_index, bool unc) {
259 // True branch, use existing map info
260 { PreserveJVMState pjvms(this);
261 Node *iffalse = _gvn.transform( new IfFalseNode (iff) );
262 set_control( iffalse );
263 if (unc) {
264 repush_if_args();
265 uncommon_trap(Deoptimization::Reason_unstable_if,
266 Deoptimization::Action_reinterpret,
267 NULL,
268 "taken never");
269 } else {
270 assert(dest_bci_if_true != never_reached, "inconsistent dest");
271 profile_switch_case(prof_table_index);
272 merge_new_path(dest_bci_if_true);
273 }
274 }
275
276 // False branch
277 Node *iftrue = _gvn.transform( new IfTrueNode(iff) );
278 set_control( iftrue );
279 }
280
jump_if_always_fork(int dest_bci,int prof_table_index,bool unc)281 void Parse::jump_if_always_fork(int dest_bci, int prof_table_index, bool unc) {
282 // False branch, use existing map and control()
283 if (unc) {
284 repush_if_args();
285 uncommon_trap(Deoptimization::Reason_unstable_if,
286 Deoptimization::Action_reinterpret,
287 NULL,
288 "taken never");
289 } else {
290 assert(dest_bci != never_reached, "inconsistent dest");
291 profile_switch_case(prof_table_index);
292 merge_new_path(dest_bci);
293 }
294 }
295
296
297 extern "C" {
jint_cmp(const void * i,const void * j)298 static int jint_cmp(const void *i, const void *j) {
299 int a = *(jint *)i;
300 int b = *(jint *)j;
301 return a > b ? 1 : a < b ? -1 : 0;
302 }
303 }
304
305
306 // Default value for methodData switch indexing. Must be a negative value to avoid
307 // conflict with any legal switch index.
308 #define NullTableIndex -1
309
310 class SwitchRange : public StackObj {
311 // a range of integers coupled with a bci destination
312 jint _lo; // inclusive lower limit
313 jint _hi; // inclusive upper limit
314 int _dest;
315 int _table_index; // index into method data table
316 float _cnt; // how many times this range was hit according to profiling
317
318 public:
lo() const319 jint lo() const { return _lo; }
hi() const320 jint hi() const { return _hi; }
dest() const321 int dest() const { return _dest; }
table_index() const322 int table_index() const { return _table_index; }
is_singleton() const323 bool is_singleton() const { return _lo == _hi; }
cnt() const324 float cnt() const { return _cnt; }
325
setRange(jint lo,jint hi,int dest,int table_index,float cnt)326 void setRange(jint lo, jint hi, int dest, int table_index, float cnt) {
327 assert(lo <= hi, "must be a non-empty range");
328 _lo = lo, _hi = hi; _dest = dest; _table_index = table_index; _cnt = cnt;
329 assert(_cnt >= 0, "");
330 }
adjoinRange(jint lo,jint hi,int dest,int table_index,float cnt,bool trim_ranges)331 bool adjoinRange(jint lo, jint hi, int dest, int table_index, float cnt, bool trim_ranges) {
332 assert(lo <= hi, "must be a non-empty range");
333 if (lo == _hi+1 && table_index == _table_index) {
334 // see merge_ranges() comment below
335 if (trim_ranges) {
336 if (cnt == 0) {
337 if (_cnt != 0) {
338 return false;
339 }
340 if (dest != _dest) {
341 _dest = never_reached;
342 }
343 } else {
344 if (_cnt == 0) {
345 return false;
346 }
347 if (dest != _dest) {
348 return false;
349 }
350 }
351 } else {
352 if (dest != _dest) {
353 return false;
354 }
355 }
356 _hi = hi;
357 _cnt += cnt;
358 return true;
359 }
360 return false;
361 }
362
set(jint value,int dest,int table_index,float cnt)363 void set (jint value, int dest, int table_index, float cnt) {
364 setRange(value, value, dest, table_index, cnt);
365 }
adjoin(jint value,int dest,int table_index,float cnt,bool trim_ranges)366 bool adjoin(jint value, int dest, int table_index, float cnt, bool trim_ranges) {
367 return adjoinRange(value, value, dest, table_index, cnt, trim_ranges);
368 }
adjoin(SwitchRange & other)369 bool adjoin(SwitchRange& other) {
370 return adjoinRange(other._lo, other._hi, other._dest, other._table_index, other._cnt, false);
371 }
372
print()373 void print() {
374 if (is_singleton())
375 tty->print(" {%d}=>%d (cnt=%f)", lo(), dest(), cnt());
376 else if (lo() == min_jint)
377 tty->print(" {..%d}=>%d (cnt=%f)", hi(), dest(), cnt());
378 else if (hi() == max_jint)
379 tty->print(" {%d..}=>%d (cnt=%f)", lo(), dest(), cnt());
380 else
381 tty->print(" {%d..%d}=>%d (cnt=%f)", lo(), hi(), dest(), cnt());
382 }
383 };
384
385 // We try to minimize the number of ranges and the size of the taken
386 // ones using profiling data. When ranges are created,
387 // SwitchRange::adjoinRange() only allows 2 adjoining ranges to merge
388 // if both were never hit or both were hit to build longer unreached
389 // ranges. Here, we now merge adjoining ranges with the same
390 // destination and finally set destination of unreached ranges to the
391 // special value never_reached because it can help minimize the number
392 // of tests that are necessary.
393 //
394 // For instance:
395 // [0, 1] to target1 sometimes taken
396 // [1, 2] to target1 never taken
397 // [2, 3] to target2 never taken
398 // would lead to:
399 // [0, 1] to target1 sometimes taken
400 // [1, 3] never taken
401 //
402 // (first 2 ranges to target1 are not merged)
merge_ranges(SwitchRange * ranges,int & rp)403 static void merge_ranges(SwitchRange* ranges, int& rp) {
404 if (rp == 0) {
405 return;
406 }
407 int shift = 0;
408 for (int j = 0; j < rp; j++) {
409 SwitchRange& r1 = ranges[j-shift];
410 SwitchRange& r2 = ranges[j+1];
411 if (r1.adjoin(r2)) {
412 shift++;
413 } else if (shift > 0) {
414 ranges[j+1-shift] = r2;
415 }
416 }
417 rp -= shift;
418 for (int j = 0; j <= rp; j++) {
419 SwitchRange& r = ranges[j];
420 if (r.cnt() == 0 && r.dest() != never_reached) {
421 r.setRange(r.lo(), r.hi(), never_reached, r.table_index(), r.cnt());
422 }
423 }
424 }
425
426 //-------------------------------do_tableswitch--------------------------------
do_tableswitch()427 void Parse::do_tableswitch() {
428 Node* lookup = pop();
429 // Get information about tableswitch
430 int default_dest = iter().get_dest_table(0);
431 int lo_index = iter().get_int_table(1);
432 int hi_index = iter().get_int_table(2);
433 int len = hi_index - lo_index + 1;
434
435 if (len < 1) {
436 // If this is a backward branch, add safepoint
437 maybe_add_safepoint(default_dest);
438 merge(default_dest);
439 return;
440 }
441
442 ciMethodData* methodData = method()->method_data();
443 ciMultiBranchData* profile = NULL;
444 if (methodData->is_mature() && UseSwitchProfiling) {
445 ciProfileData* data = methodData->bci_to_data(bci());
446 if (data != NULL && data->is_MultiBranchData()) {
447 profile = (ciMultiBranchData*)data;
448 }
449 }
450 bool trim_ranges = !method_data_update() && !C->too_many_traps(method(), bci(), Deoptimization::Reason_unstable_if);
451
452 // generate decision tree, using trichotomy when possible
453 int rnum = len+2;
454 bool makes_backward_branch = false;
455 SwitchRange* ranges = NEW_RESOURCE_ARRAY(SwitchRange, rnum);
456 int rp = -1;
457 if (lo_index != min_jint) {
458 uint cnt = 1;
459 if (profile != NULL) {
460 cnt = profile->default_count() / (hi_index != max_jint ? 2 : 1);
461 }
462 ranges[++rp].setRange(min_jint, lo_index-1, default_dest, NullTableIndex, cnt);
463 }
464 for (int j = 0; j < len; j++) {
465 jint match_int = lo_index+j;
466 int dest = iter().get_dest_table(j+3);
467 makes_backward_branch |= (dest <= bci());
468 int table_index = method_data_update() ? j : NullTableIndex;
469 uint cnt = 1;
470 if (profile != NULL) {
471 cnt = profile->count_at(j);
472 }
473 if (rp < 0 || !ranges[rp].adjoin(match_int, dest, table_index, cnt, trim_ranges)) {
474 ranges[++rp].set(match_int, dest, table_index, cnt);
475 }
476 }
477 jint highest = lo_index+(len-1);
478 assert(ranges[rp].hi() == highest, "");
479 if (highest != max_jint) {
480 uint cnt = 1;
481 if (profile != NULL) {
482 cnt = profile->default_count() / (lo_index != min_jint ? 2 : 1);
483 }
484 if (!ranges[rp].adjoinRange(highest+1, max_jint, default_dest, NullTableIndex, cnt, trim_ranges)) {
485 ranges[++rp].setRange(highest+1, max_jint, default_dest, NullTableIndex, cnt);
486 }
487 }
488 assert(rp < len+2, "not too many ranges");
489
490 if (trim_ranges) {
491 merge_ranges(ranges, rp);
492 }
493
494 // Safepoint in case if backward branch observed
495 if( makes_backward_branch && UseLoopSafepoints )
496 add_safepoint();
497
498 jump_switch_ranges(lookup, &ranges[0], &ranges[rp]);
499 }
500
501
502 //------------------------------do_lookupswitch--------------------------------
do_lookupswitch()503 void Parse::do_lookupswitch() {
504 Node *lookup = pop(); // lookup value
505 // Get information about lookupswitch
506 int default_dest = iter().get_dest_table(0);
507 int len = iter().get_int_table(1);
508
509 if (len < 1) { // If this is a backward branch, add safepoint
510 maybe_add_safepoint(default_dest);
511 merge(default_dest);
512 return;
513 }
514
515 ciMethodData* methodData = method()->method_data();
516 ciMultiBranchData* profile = NULL;
517 if (methodData->is_mature() && UseSwitchProfiling) {
518 ciProfileData* data = methodData->bci_to_data(bci());
519 if (data != NULL && data->is_MultiBranchData()) {
520 profile = (ciMultiBranchData*)data;
521 }
522 }
523 bool trim_ranges = !method_data_update() && !C->too_many_traps(method(), bci(), Deoptimization::Reason_unstable_if);
524
525 // generate decision tree, using trichotomy when possible
526 jint* table = NEW_RESOURCE_ARRAY(jint, len*3);
527 {
528 for (int j = 0; j < len; j++) {
529 table[3*j+0] = iter().get_int_table(2+2*j);
530 table[3*j+1] = iter().get_dest_table(2+2*j+1);
531 table[3*j+2] = profile == NULL ? 1 : profile->count_at(j);
532 }
533 qsort(table, len, 3*sizeof(table[0]), jint_cmp);
534 }
535
536 float defaults = 0;
537 jint prev = min_jint;
538 for (int j = 0; j < len; j++) {
539 jint match_int = table[3*j+0];
540 if (match_int != prev) {
541 defaults += (float)match_int - prev;
542 }
543 prev = match_int+1;
544 }
545 if (prev-1 != max_jint) {
546 defaults += (float)max_jint - prev + 1;
547 }
548 float default_cnt = 1;
549 if (profile != NULL) {
550 default_cnt = profile->default_count()/defaults;
551 }
552
553 int rnum = len*2+1;
554 bool makes_backward_branch = false;
555 SwitchRange* ranges = NEW_RESOURCE_ARRAY(SwitchRange, rnum);
556 int rp = -1;
557 for (int j = 0; j < len; j++) {
558 jint match_int = table[3*j+0];
559 int dest = table[3*j+1];
560 int cnt = table[3*j+2];
561 int next_lo = rp < 0 ? min_jint : ranges[rp].hi()+1;
562 int table_index = method_data_update() ? j : NullTableIndex;
563 makes_backward_branch |= (dest <= bci());
564 float c = default_cnt * ((float)match_int - next_lo);
565 if (match_int != next_lo && (rp < 0 || !ranges[rp].adjoinRange(next_lo, match_int-1, default_dest, NullTableIndex, c, trim_ranges))) {
566 assert(default_dest != never_reached, "sentinel value for dead destinations");
567 ranges[++rp].setRange(next_lo, match_int-1, default_dest, NullTableIndex, c);
568 }
569 if (rp < 0 || !ranges[rp].adjoin(match_int, dest, table_index, cnt, trim_ranges)) {
570 assert(dest != never_reached, "sentinel value for dead destinations");
571 ranges[++rp].set(match_int, dest, table_index, cnt);
572 }
573 }
574 jint highest = table[3*(len-1)];
575 assert(ranges[rp].hi() == highest, "");
576 if (highest != max_jint &&
577 !ranges[rp].adjoinRange(highest+1, max_jint, default_dest, NullTableIndex, default_cnt * ((float)max_jint - highest), trim_ranges)) {
578 ranges[++rp].setRange(highest+1, max_jint, default_dest, NullTableIndex, default_cnt * ((float)max_jint - highest));
579 }
580 assert(rp < rnum, "not too many ranges");
581
582 if (trim_ranges) {
583 merge_ranges(ranges, rp);
584 }
585
586 // Safepoint in case backward branch observed
587 if (makes_backward_branch && UseLoopSafepoints)
588 add_safepoint();
589
590 jump_switch_ranges(lookup, &ranges[0], &ranges[rp]);
591 }
592
if_prob(float taken_cnt,float total_cnt)593 static float if_prob(float taken_cnt, float total_cnt) {
594 assert(taken_cnt <= total_cnt, "");
595 if (total_cnt == 0) {
596 return PROB_FAIR;
597 }
598 float p = taken_cnt / total_cnt;
599 return MIN2(MAX2(p, PROB_MIN), PROB_MAX);
600 }
601
if_cnt(float cnt)602 static float if_cnt(float cnt) {
603 if (cnt == 0) {
604 return COUNT_UNKNOWN;
605 }
606 return cnt;
607 }
608
sum_of_cnts(SwitchRange * lo,SwitchRange * hi)609 static float sum_of_cnts(SwitchRange *lo, SwitchRange *hi) {
610 float total_cnt = 0;
611 for (SwitchRange* sr = lo; sr <= hi; sr++) {
612 total_cnt += sr->cnt();
613 }
614 return total_cnt;
615 }
616
617 class SwitchRanges : public ResourceObj {
618 public:
619 SwitchRange* _lo;
620 SwitchRange* _hi;
621 SwitchRange* _mid;
622 float _cost;
623
624 enum {
625 Start,
626 LeftDone,
627 RightDone,
628 Done
629 } _state;
630
SwitchRanges(SwitchRange * lo,SwitchRange * hi)631 SwitchRanges(SwitchRange *lo, SwitchRange *hi)
632 : _lo(lo), _hi(hi), _mid(NULL),
633 _cost(0), _state(Start) {
634 }
635
SwitchRanges()636 SwitchRanges()
637 : _lo(NULL), _hi(NULL), _mid(NULL),
638 _cost(0), _state(Start) {}
639 };
640
641 // Estimate cost of performing a binary search on lo..hi
compute_tree_cost(SwitchRange * lo,SwitchRange * hi,float total_cnt)642 static float compute_tree_cost(SwitchRange *lo, SwitchRange *hi, float total_cnt) {
643 GrowableArray<SwitchRanges> tree;
644 SwitchRanges root(lo, hi);
645 tree.push(root);
646
647 float cost = 0;
648 do {
649 SwitchRanges& r = *tree.adr_at(tree.length()-1);
650 if (r._hi != r._lo) {
651 if (r._mid == NULL) {
652 float r_cnt = sum_of_cnts(r._lo, r._hi);
653
654 if (r_cnt == 0) {
655 tree.pop();
656 cost = 0;
657 continue;
658 }
659
660 SwitchRange* mid = NULL;
661 mid = r._lo;
662 for (float cnt = 0; ; ) {
663 assert(mid <= r._hi, "out of bounds");
664 cnt += mid->cnt();
665 if (cnt > r_cnt / 2) {
666 break;
667 }
668 mid++;
669 }
670 assert(mid <= r._hi, "out of bounds");
671 r._mid = mid;
672 r._cost = r_cnt / total_cnt;
673 }
674 r._cost += cost;
675 if (r._state < SwitchRanges::LeftDone && r._mid > r._lo) {
676 cost = 0;
677 r._state = SwitchRanges::LeftDone;
678 tree.push(SwitchRanges(r._lo, r._mid-1));
679 } else if (r._state < SwitchRanges::RightDone) {
680 cost = 0;
681 r._state = SwitchRanges::RightDone;
682 tree.push(SwitchRanges(r._mid == r._lo ? r._mid+1 : r._mid, r._hi));
683 } else {
684 tree.pop();
685 cost = r._cost;
686 }
687 } else {
688 tree.pop();
689 cost = r._cost;
690 }
691 } while (tree.length() > 0);
692
693
694 return cost;
695 }
696
697 // It sometimes pays off to test most common ranges before the binary search
linear_search_switch_ranges(Node * key_val,SwitchRange * & lo,SwitchRange * & hi)698 void Parse::linear_search_switch_ranges(Node* key_val, SwitchRange*& lo, SwitchRange*& hi) {
699 uint nr = hi - lo + 1;
700 float total_cnt = sum_of_cnts(lo, hi);
701
702 float min = compute_tree_cost(lo, hi, total_cnt);
703 float extra = 1;
704 float sub = 0;
705
706 SwitchRange* array1 = lo;
707 SwitchRange* array2 = NEW_RESOURCE_ARRAY(SwitchRange, nr);
708
709 SwitchRange* ranges = NULL;
710
711 while (nr >= 2) {
712 assert(lo == array1 || lo == array2, "one the 2 already allocated arrays");
713 ranges = (lo == array1) ? array2 : array1;
714
715 // Find highest frequency range
716 SwitchRange* candidate = lo;
717 for (SwitchRange* sr = lo+1; sr <= hi; sr++) {
718 if (sr->cnt() > candidate->cnt()) {
719 candidate = sr;
720 }
721 }
722 SwitchRange most_freq = *candidate;
723 if (most_freq.cnt() == 0) {
724 break;
725 }
726
727 // Copy remaining ranges into another array
728 int shift = 0;
729 for (uint i = 0; i < nr; i++) {
730 SwitchRange* sr = &lo[i];
731 if (sr != candidate) {
732 ranges[i-shift] = *sr;
733 } else {
734 shift++;
735 if (i > 0 && i < nr-1) {
736 SwitchRange prev = lo[i-1];
737 prev.setRange(prev.lo(), sr->hi(), prev.dest(), prev.table_index(), prev.cnt());
738 if (prev.adjoin(lo[i+1])) {
739 shift++;
740 i++;
741 }
742 ranges[i-shift] = prev;
743 }
744 }
745 }
746 nr -= shift;
747
748 // Evaluate cost of testing the most common range and performing a
749 // binary search on the other ranges
750 float cost = extra + compute_tree_cost(&ranges[0], &ranges[nr-1], total_cnt);
751 if (cost >= min) {
752 break;
753 }
754 // swap arrays
755 lo = &ranges[0];
756 hi = &ranges[nr-1];
757
758 // It pays off: emit the test for the most common range
759 assert(most_freq.cnt() > 0, "must be taken");
760 Node* val = _gvn.transform(new SubINode(key_val, _gvn.intcon(most_freq.lo())));
761 Node* cmp = _gvn.transform(new CmpUNode(val, _gvn.intcon(most_freq.hi() - most_freq.lo())));
762 Node* tst = _gvn.transform(new BoolNode(cmp, BoolTest::le));
763 IfNode* iff = create_and_map_if(control(), tst, if_prob(most_freq.cnt(), total_cnt), if_cnt(most_freq.cnt()));
764 jump_if_true_fork(iff, most_freq.dest(), most_freq.table_index(), false);
765
766 sub += most_freq.cnt() / total_cnt;
767 extra += 1 - sub;
768 min = cost;
769 }
770 }
771
772 //----------------------------create_jump_tables-------------------------------
create_jump_tables(Node * key_val,SwitchRange * lo,SwitchRange * hi)773 bool Parse::create_jump_tables(Node* key_val, SwitchRange* lo, SwitchRange* hi) {
774 // Are jumptables enabled
775 if (!UseJumpTables) return false;
776
777 // Are jumptables supported
778 if (!Matcher::has_match_rule(Op_Jump)) return false;
779
780 // Don't make jump table if profiling
781 if (method_data_update()) return false;
782
783 bool trim_ranges = !C->too_many_traps(method(), bci(), Deoptimization::Reason_unstable_if);
784
785 // Decide if a guard is needed to lop off big ranges at either (or
786 // both) end(s) of the input set. We'll call this the default target
787 // even though we can't be sure that it is the true "default".
788
789 bool needs_guard = false;
790 int default_dest;
791 int64_t total_outlier_size = 0;
792 int64_t hi_size = ((int64_t)hi->hi()) - ((int64_t)hi->lo()) + 1;
793 int64_t lo_size = ((int64_t)lo->hi()) - ((int64_t)lo->lo()) + 1;
794
795 if (lo->dest() == hi->dest()) {
796 total_outlier_size = hi_size + lo_size;
797 default_dest = lo->dest();
798 } else if (lo_size > hi_size) {
799 total_outlier_size = lo_size;
800 default_dest = lo->dest();
801 } else {
802 total_outlier_size = hi_size;
803 default_dest = hi->dest();
804 }
805
806 float total = sum_of_cnts(lo, hi);
807 float cost = compute_tree_cost(lo, hi, total);
808
809 // If a guard test will eliminate very sparse end ranges, then
810 // it is worth the cost of an extra jump.
811 float trimmed_cnt = 0;
812 if (total_outlier_size > (MaxJumpTableSparseness * 4)) {
813 needs_guard = true;
814 if (default_dest == lo->dest()) {
815 trimmed_cnt += lo->cnt();
816 lo++;
817 }
818 if (default_dest == hi->dest()) {
819 trimmed_cnt += hi->cnt();
820 hi--;
821 }
822 }
823
824 // Find the total number of cases and ranges
825 int64_t num_cases = ((int64_t)hi->hi()) - ((int64_t)lo->lo()) + 1;
826 int num_range = hi - lo + 1;
827
828 // Don't create table if: too large, too small, or too sparse.
829 if (num_cases > MaxJumpTableSize)
830 return false;
831 if (UseSwitchProfiling) {
832 // MinJumpTableSize is set so with a well balanced binary tree,
833 // when the number of ranges is MinJumpTableSize, it's cheaper to
834 // go through a JumpNode that a tree of IfNodes. Average cost of a
835 // tree of IfNodes with MinJumpTableSize is
836 // log2f(MinJumpTableSize) comparisons. So if the cost computed
837 // from profile data is less than log2f(MinJumpTableSize) then
838 // going with the binary search is cheaper.
839 if (cost < log2f(MinJumpTableSize)) {
840 return false;
841 }
842 } else {
843 if (num_cases < MinJumpTableSize)
844 return false;
845 }
846 if (num_cases > (MaxJumpTableSparseness * num_range))
847 return false;
848
849 // Normalize table lookups to zero
850 int lowval = lo->lo();
851 key_val = _gvn.transform( new SubINode(key_val, _gvn.intcon(lowval)) );
852
853 // Generate a guard to protect against input keyvals that aren't
854 // in the switch domain.
855 if (needs_guard) {
856 Node* size = _gvn.intcon(num_cases);
857 Node* cmp = _gvn.transform(new CmpUNode(key_val, size));
858 Node* tst = _gvn.transform(new BoolNode(cmp, BoolTest::ge));
859 IfNode* iff = create_and_map_if(control(), tst, if_prob(trimmed_cnt, total), if_cnt(trimmed_cnt));
860 jump_if_true_fork(iff, default_dest, NullTableIndex, trim_ranges && trimmed_cnt == 0);
861
862 total -= trimmed_cnt;
863 }
864
865 // Create an ideal node JumpTable that has projections
866 // of all possible ranges for a switch statement
867 // The key_val input must be converted to a pointer offset and scaled.
868 // Compare Parse::array_addressing above.
869
870 // Clean the 32-bit int into a real 64-bit offset.
871 // Otherwise, the jint value 0 might turn into an offset of 0x0800000000.
872 const TypeInt* ikeytype = TypeInt::make(0, num_cases, Type::WidenMin);
873 // Make I2L conversion control dependent to prevent it from
874 // floating above the range check during loop optimizations.
875 key_val = C->conv_I2X_index(&_gvn, key_val, ikeytype, control());
876
877 // Shift the value by wordsize so we have an index into the table, rather
878 // than a switch value
879 Node *shiftWord = _gvn.MakeConX(wordSize);
880 key_val = _gvn.transform( new MulXNode( key_val, shiftWord));
881
882 // Create the JumpNode
883 Arena* arena = C->comp_arena();
884 float* probs = (float*)arena->Amalloc(sizeof(float)*num_cases);
885 int i = 0;
886 if (total == 0) {
887 for (SwitchRange* r = lo; r <= hi; r++) {
888 for (int64_t j = r->lo(); j <= r->hi(); j++, i++) {
889 probs[i] = 1.0F / num_cases;
890 }
891 }
892 } else {
893 for (SwitchRange* r = lo; r <= hi; r++) {
894 float prob = r->cnt()/total;
895 for (int64_t j = r->lo(); j <= r->hi(); j++, i++) {
896 probs[i] = prob / (r->hi() - r->lo() + 1);
897 }
898 }
899 }
900
901 ciMethodData* methodData = method()->method_data();
902 ciMultiBranchData* profile = NULL;
903 if (methodData->is_mature()) {
904 ciProfileData* data = methodData->bci_to_data(bci());
905 if (data != NULL && data->is_MultiBranchData()) {
906 profile = (ciMultiBranchData*)data;
907 }
908 }
909
910 Node* jtn = _gvn.transform(new JumpNode(control(), key_val, num_cases, probs, profile == NULL ? COUNT_UNKNOWN : total));
911
912 // These are the switch destinations hanging off the jumpnode
913 i = 0;
914 for (SwitchRange* r = lo; r <= hi; r++) {
915 for (int64_t j = r->lo(); j <= r->hi(); j++, i++) {
916 Node* input = _gvn.transform(new JumpProjNode(jtn, i, r->dest(), (int)(j - lowval)));
917 {
918 PreserveJVMState pjvms(this);
919 set_control(input);
920 jump_if_always_fork(r->dest(), r->table_index(), trim_ranges && r->cnt() == 0);
921 }
922 }
923 }
924 assert(i == num_cases, "miscount of cases");
925 stop_and_kill_map(); // no more uses for this JVMS
926 return true;
927 }
928
929 //----------------------------jump_switch_ranges-------------------------------
jump_switch_ranges(Node * key_val,SwitchRange * lo,SwitchRange * hi,int switch_depth)930 void Parse::jump_switch_ranges(Node* key_val, SwitchRange *lo, SwitchRange *hi, int switch_depth) {
931 Block* switch_block = block();
932 bool trim_ranges = !method_data_update() && !C->too_many_traps(method(), bci(), Deoptimization::Reason_unstable_if);
933
934 if (switch_depth == 0) {
935 // Do special processing for the top-level call.
936 assert(lo->lo() == min_jint, "initial range must exhaust Type::INT");
937 assert(hi->hi() == max_jint, "initial range must exhaust Type::INT");
938
939 // Decrement pred-numbers for the unique set of nodes.
940 #ifdef ASSERT
941 if (!trim_ranges) {
942 // Ensure that the block's successors are a (duplicate-free) set.
943 int successors_counted = 0; // block occurrences in [hi..lo]
944 int unique_successors = switch_block->num_successors();
945 for (int i = 0; i < unique_successors; i++) {
946 Block* target = switch_block->successor_at(i);
947
948 // Check that the set of successors is the same in both places.
949 int successors_found = 0;
950 for (SwitchRange* p = lo; p <= hi; p++) {
951 if (p->dest() == target->start()) successors_found++;
952 }
953 assert(successors_found > 0, "successor must be known");
954 successors_counted += successors_found;
955 }
956 assert(successors_counted == (hi-lo)+1, "no unexpected successors");
957 }
958 #endif
959
960 // Maybe prune the inputs, based on the type of key_val.
961 jint min_val = min_jint;
962 jint max_val = max_jint;
963 const TypeInt* ti = key_val->bottom_type()->isa_int();
964 if (ti != NULL) {
965 min_val = ti->_lo;
966 max_val = ti->_hi;
967 assert(min_val <= max_val, "invalid int type");
968 }
969 while (lo->hi() < min_val) {
970 lo++;
971 }
972 if (lo->lo() < min_val) {
973 lo->setRange(min_val, lo->hi(), lo->dest(), lo->table_index(), lo->cnt());
974 }
975 while (hi->lo() > max_val) {
976 hi--;
977 }
978 if (hi->hi() > max_val) {
979 hi->setRange(hi->lo(), max_val, hi->dest(), hi->table_index(), hi->cnt());
980 }
981
982 linear_search_switch_ranges(key_val, lo, hi);
983 }
984
985 #ifndef PRODUCT
986 if (switch_depth == 0) {
987 _max_switch_depth = 0;
988 _est_switch_depth = log2_intptr((hi-lo+1)-1)+1;
989 }
990 #endif
991
992 assert(lo <= hi, "must be a non-empty set of ranges");
993 if (lo == hi) {
994 jump_if_always_fork(lo->dest(), lo->table_index(), trim_ranges && lo->cnt() == 0);
995 } else {
996 assert(lo->hi() == (lo+1)->lo()-1, "contiguous ranges");
997 assert(hi->lo() == (hi-1)->hi()+1, "contiguous ranges");
998
999 if (create_jump_tables(key_val, lo, hi)) return;
1000
1001 SwitchRange* mid = NULL;
1002 float total_cnt = sum_of_cnts(lo, hi);
1003
1004 int nr = hi - lo + 1;
1005 if (UseSwitchProfiling) {
1006 // Don't keep the binary search tree balanced: pick up mid point
1007 // that split frequencies in half.
1008 float cnt = 0;
1009 for (SwitchRange* sr = lo; sr <= hi; sr++) {
1010 cnt += sr->cnt();
1011 if (cnt >= total_cnt / 2) {
1012 mid = sr;
1013 break;
1014 }
1015 }
1016 } else {
1017 mid = lo + nr/2;
1018
1019 // if there is an easy choice, pivot at a singleton:
1020 if (nr > 3 && !mid->is_singleton() && (mid-1)->is_singleton()) mid--;
1021
1022 assert(lo < mid && mid <= hi, "good pivot choice");
1023 assert(nr != 2 || mid == hi, "should pick higher of 2");
1024 assert(nr != 3 || mid == hi-1, "should pick middle of 3");
1025 }
1026
1027
1028 Node *test_val = _gvn.intcon(mid == lo ? mid->hi() : mid->lo());
1029
1030 if (mid->is_singleton()) {
1031 IfNode *iff_ne = jump_if_fork_int(key_val, test_val, BoolTest::ne, 1-if_prob(mid->cnt(), total_cnt), if_cnt(mid->cnt()));
1032 jump_if_false_fork(iff_ne, mid->dest(), mid->table_index(), trim_ranges && mid->cnt() == 0);
1033
1034 // Special Case: If there are exactly three ranges, and the high
1035 // and low range each go to the same place, omit the "gt" test,
1036 // since it will not discriminate anything.
1037 bool eq_test_only = (hi == lo+2 && hi->dest() == lo->dest() && mid == hi-1) || mid == lo;
1038
1039 // if there is a higher range, test for it and process it:
1040 if (mid < hi && !eq_test_only) {
1041 // two comparisons of same values--should enable 1 test for 2 branches
1042 // Use BoolTest::lt instead of BoolTest::gt
1043 float cnt = sum_of_cnts(lo, mid-1);
1044 IfNode *iff_lt = jump_if_fork_int(key_val, test_val, BoolTest::lt, if_prob(cnt, total_cnt), if_cnt(cnt));
1045 Node *iftrue = _gvn.transform( new IfTrueNode(iff_lt) );
1046 Node *iffalse = _gvn.transform( new IfFalseNode(iff_lt) );
1047 { PreserveJVMState pjvms(this);
1048 set_control(iffalse);
1049 jump_switch_ranges(key_val, mid+1, hi, switch_depth+1);
1050 }
1051 set_control(iftrue);
1052 }
1053
1054 } else {
1055 // mid is a range, not a singleton, so treat mid..hi as a unit
1056 float cnt = sum_of_cnts(mid == lo ? mid+1 : mid, hi);
1057 IfNode *iff_ge = jump_if_fork_int(key_val, test_val, mid == lo ? BoolTest::gt : BoolTest::ge, if_prob(cnt, total_cnt), if_cnt(cnt));
1058
1059 // if there is a higher range, test for it and process it:
1060 if (mid == hi) {
1061 jump_if_true_fork(iff_ge, mid->dest(), mid->table_index(), trim_ranges && cnt == 0);
1062 } else {
1063 Node *iftrue = _gvn.transform( new IfTrueNode(iff_ge) );
1064 Node *iffalse = _gvn.transform( new IfFalseNode(iff_ge) );
1065 { PreserveJVMState pjvms(this);
1066 set_control(iftrue);
1067 jump_switch_ranges(key_val, mid == lo ? mid+1 : mid, hi, switch_depth+1);
1068 }
1069 set_control(iffalse);
1070 }
1071 }
1072
1073 // in any case, process the lower range
1074 if (mid == lo) {
1075 if (mid->is_singleton()) {
1076 jump_switch_ranges(key_val, lo+1, hi, switch_depth+1);
1077 } else {
1078 jump_if_always_fork(lo->dest(), lo->table_index(), trim_ranges && lo->cnt() == 0);
1079 }
1080 } else {
1081 jump_switch_ranges(key_val, lo, mid-1, switch_depth+1);
1082 }
1083 }
1084
1085 // Decrease pred_count for each successor after all is done.
1086 if (switch_depth == 0) {
1087 int unique_successors = switch_block->num_successors();
1088 for (int i = 0; i < unique_successors; i++) {
1089 Block* target = switch_block->successor_at(i);
1090 // Throw away the pre-allocated path for each unique successor.
1091 target->next_path_num();
1092 }
1093 }
1094
1095 #ifndef PRODUCT
1096 _max_switch_depth = MAX2(switch_depth, _max_switch_depth);
1097 if (TraceOptoParse && Verbose && WizardMode && switch_depth == 0) {
1098 SwitchRange* r;
1099 int nsing = 0;
1100 for( r = lo; r <= hi; r++ ) {
1101 if( r->is_singleton() ) nsing++;
1102 }
1103 tty->print(">>> ");
1104 _method->print_short_name();
1105 tty->print_cr(" switch decision tree");
1106 tty->print_cr(" %d ranges (%d singletons), max_depth=%d, est_depth=%d",
1107 (int) (hi-lo+1), nsing, _max_switch_depth, _est_switch_depth);
1108 if (_max_switch_depth > _est_switch_depth) {
1109 tty->print_cr("******** BAD SWITCH DEPTH ********");
1110 }
1111 tty->print(" ");
1112 for( r = lo; r <= hi; r++ ) {
1113 r->print();
1114 }
1115 tty->cr();
1116 }
1117 #endif
1118 }
1119
modf()1120 void Parse::modf() {
1121 Node *f2 = pop();
1122 Node *f1 = pop();
1123 Node* c = make_runtime_call(RC_LEAF, OptoRuntime::modf_Type(),
1124 CAST_FROM_FN_PTR(address, SharedRuntime::frem),
1125 "frem", NULL, //no memory effects
1126 f1, f2);
1127 Node* res = _gvn.transform(new ProjNode(c, TypeFunc::Parms + 0));
1128
1129 push(res);
1130 }
1131
modd()1132 void Parse::modd() {
1133 Node *d2 = pop_pair();
1134 Node *d1 = pop_pair();
1135 Node* c = make_runtime_call(RC_LEAF, OptoRuntime::Math_DD_D_Type(),
1136 CAST_FROM_FN_PTR(address, SharedRuntime::drem),
1137 "drem", NULL, //no memory effects
1138 d1, top(), d2, top());
1139 Node* res_d = _gvn.transform(new ProjNode(c, TypeFunc::Parms + 0));
1140
1141 #ifdef ASSERT
1142 Node* res_top = _gvn.transform(new ProjNode(c, TypeFunc::Parms + 1));
1143 assert(res_top == top(), "second value must be top");
1144 #endif
1145
1146 push_pair(res_d);
1147 }
1148
l2f()1149 void Parse::l2f() {
1150 Node* f2 = pop();
1151 Node* f1 = pop();
1152 Node* c = make_runtime_call(RC_LEAF, OptoRuntime::l2f_Type(),
1153 CAST_FROM_FN_PTR(address, SharedRuntime::l2f),
1154 "l2f", NULL, //no memory effects
1155 f1, f2);
1156 Node* res = _gvn.transform(new ProjNode(c, TypeFunc::Parms + 0));
1157
1158 push(res);
1159 }
1160
do_irem()1161 void Parse::do_irem() {
1162 // Must keep both values on the expression-stack during null-check
1163 zero_check_int(peek());
1164 // Compile-time detect of null-exception?
1165 if (stopped()) return;
1166
1167 Node* b = pop();
1168 Node* a = pop();
1169
1170 const Type *t = _gvn.type(b);
1171 if (t != Type::TOP) {
1172 const TypeInt *ti = t->is_int();
1173 if (ti->is_con()) {
1174 int divisor = ti->get_con();
1175 // check for positive power of 2
1176 if (divisor > 0 &&
1177 (divisor & ~(divisor-1)) == divisor) {
1178 // yes !
1179 Node *mask = _gvn.intcon((divisor - 1));
1180 // Sigh, must handle negative dividends
1181 Node *zero = _gvn.intcon(0);
1182 IfNode *ifff = jump_if_fork_int(a, zero, BoolTest::lt, PROB_FAIR, COUNT_UNKNOWN);
1183 Node *iff = _gvn.transform( new IfFalseNode(ifff) );
1184 Node *ift = _gvn.transform( new IfTrueNode (ifff) );
1185 Node *reg = jump_if_join(ift, iff);
1186 Node *phi = PhiNode::make(reg, NULL, TypeInt::INT);
1187 // Negative path; negate/and/negate
1188 Node *neg = _gvn.transform( new SubINode(zero, a) );
1189 Node *andn= _gvn.transform( new AndINode(neg, mask) );
1190 Node *negn= _gvn.transform( new SubINode(zero, andn) );
1191 phi->init_req(1, negn);
1192 // Fast positive case
1193 Node *andx = _gvn.transform( new AndINode(a, mask) );
1194 phi->init_req(2, andx);
1195 // Push the merge
1196 push( _gvn.transform(phi) );
1197 return;
1198 }
1199 }
1200 }
1201 // Default case
1202 push( _gvn.transform( new ModINode(control(),a,b) ) );
1203 }
1204
1205 // Handle jsr and jsr_w bytecode
do_jsr()1206 void Parse::do_jsr() {
1207 assert(bc() == Bytecodes::_jsr || bc() == Bytecodes::_jsr_w, "wrong bytecode");
1208
1209 // Store information about current state, tagged with new _jsr_bci
1210 int return_bci = iter().next_bci();
1211 int jsr_bci = (bc() == Bytecodes::_jsr) ? iter().get_dest() : iter().get_far_dest();
1212
1213 // Update method data
1214 profile_taken_branch(jsr_bci);
1215
1216 // The way we do things now, there is only one successor block
1217 // for the jsr, because the target code is cloned by ciTypeFlow.
1218 Block* target = successor_for_bci(jsr_bci);
1219
1220 // What got pushed?
1221 const Type* ret_addr = target->peek();
1222 assert(ret_addr->singleton(), "must be a constant (cloned jsr body)");
1223
1224 // Effect on jsr on stack
1225 push(_gvn.makecon(ret_addr));
1226
1227 // Flow to the jsr.
1228 merge(jsr_bci);
1229 }
1230
1231 // Handle ret bytecode
do_ret()1232 void Parse::do_ret() {
1233 // Find to whom we return.
1234 assert(block()->num_successors() == 1, "a ret can only go one place now");
1235 Block* target = block()->successor_at(0);
1236 assert(!target->is_ready(), "our arrival must be expected");
1237 profile_ret(target->flow()->start());
1238 int pnum = target->next_path_num();
1239 merge_common(target, pnum);
1240 }
1241
has_injected_profile(BoolTest::mask btest,Node * test,int & taken,int & not_taken)1242 static bool has_injected_profile(BoolTest::mask btest, Node* test, int& taken, int& not_taken) {
1243 if (btest != BoolTest::eq && btest != BoolTest::ne) {
1244 // Only ::eq and ::ne are supported for profile injection.
1245 return false;
1246 }
1247 if (test->is_Cmp() &&
1248 test->in(1)->Opcode() == Op_ProfileBoolean) {
1249 ProfileBooleanNode* profile = (ProfileBooleanNode*)test->in(1);
1250 int false_cnt = profile->false_count();
1251 int true_cnt = profile->true_count();
1252
1253 // Counts matching depends on the actual test operation (::eq or ::ne).
1254 // No need to scale the counts because profile injection was designed
1255 // to feed exact counts into VM.
1256 taken = (btest == BoolTest::eq) ? false_cnt : true_cnt;
1257 not_taken = (btest == BoolTest::eq) ? true_cnt : false_cnt;
1258
1259 profile->consume();
1260 return true;
1261 }
1262 return false;
1263 }
1264 //--------------------------dynamic_branch_prediction--------------------------
1265 // Try to gather dynamic branch prediction behavior. Return a probability
1266 // of the branch being taken and set the "cnt" field. Returns a -1.0
1267 // if we need to use static prediction for some reason.
dynamic_branch_prediction(float & cnt,BoolTest::mask btest,Node * test)1268 float Parse::dynamic_branch_prediction(float &cnt, BoolTest::mask btest, Node* test) {
1269 ResourceMark rm;
1270
1271 cnt = COUNT_UNKNOWN;
1272
1273 int taken = 0;
1274 int not_taken = 0;
1275
1276 bool use_mdo = !has_injected_profile(btest, test, taken, not_taken);
1277
1278 if (use_mdo) {
1279 // Use MethodData information if it is available
1280 // FIXME: free the ProfileData structure
1281 ciMethodData* methodData = method()->method_data();
1282 if (!methodData->is_mature()) return PROB_UNKNOWN;
1283 ciProfileData* data = methodData->bci_to_data(bci());
1284 if (data == NULL) {
1285 return PROB_UNKNOWN;
1286 }
1287 if (!data->is_JumpData()) return PROB_UNKNOWN;
1288
1289 // get taken and not taken values
1290 taken = data->as_JumpData()->taken();
1291 not_taken = 0;
1292 if (data->is_BranchData()) {
1293 not_taken = data->as_BranchData()->not_taken();
1294 }
1295
1296 // scale the counts to be commensurate with invocation counts:
1297 taken = method()->scale_count(taken);
1298 not_taken = method()->scale_count(not_taken);
1299 }
1300
1301 // Give up if too few (or too many, in which case the sum will overflow) counts to be meaningful.
1302 // We also check that individual counters are positive first, otherwise the sum can become positive.
1303 if (taken < 0 || not_taken < 0 || taken + not_taken < 40) {
1304 if (C->log() != NULL) {
1305 C->log()->elem("branch target_bci='%d' taken='%d' not_taken='%d'", iter().get_dest(), taken, not_taken);
1306 }
1307 return PROB_UNKNOWN;
1308 }
1309
1310 // Compute frequency that we arrive here
1311 float sum = taken + not_taken;
1312 // Adjust, if this block is a cloned private block but the
1313 // Jump counts are shared. Taken the private counts for
1314 // just this path instead of the shared counts.
1315 if( block()->count() > 0 )
1316 sum = block()->count();
1317 cnt = sum / FreqCountInvocations;
1318
1319 // Pin probability to sane limits
1320 float prob;
1321 if( !taken )
1322 prob = (0+PROB_MIN) / 2;
1323 else if( !not_taken )
1324 prob = (1+PROB_MAX) / 2;
1325 else { // Compute probability of true path
1326 prob = (float)taken / (float)(taken + not_taken);
1327 if (prob > PROB_MAX) prob = PROB_MAX;
1328 if (prob < PROB_MIN) prob = PROB_MIN;
1329 }
1330
1331 assert((cnt > 0.0f) && (prob > 0.0f),
1332 "Bad frequency assignment in if");
1333
1334 if (C->log() != NULL) {
1335 const char* prob_str = NULL;
1336 if (prob >= PROB_MAX) prob_str = (prob == PROB_MAX) ? "max" : "always";
1337 if (prob <= PROB_MIN) prob_str = (prob == PROB_MIN) ? "min" : "never";
1338 char prob_str_buf[30];
1339 if (prob_str == NULL) {
1340 jio_snprintf(prob_str_buf, sizeof(prob_str_buf), "%20.2f", prob);
1341 prob_str = prob_str_buf;
1342 }
1343 C->log()->elem("branch target_bci='%d' taken='%d' not_taken='%d' cnt='%f' prob='%s'",
1344 iter().get_dest(), taken, not_taken, cnt, prob_str);
1345 }
1346 return prob;
1347 }
1348
1349 //-----------------------------branch_prediction-------------------------------
branch_prediction(float & cnt,BoolTest::mask btest,int target_bci,Node * test)1350 float Parse::branch_prediction(float& cnt,
1351 BoolTest::mask btest,
1352 int target_bci,
1353 Node* test) {
1354 float prob = dynamic_branch_prediction(cnt, btest, test);
1355 // If prob is unknown, switch to static prediction
1356 if (prob != PROB_UNKNOWN) return prob;
1357
1358 prob = PROB_FAIR; // Set default value
1359 if (btest == BoolTest::eq) // Exactly equal test?
1360 prob = PROB_STATIC_INFREQUENT; // Assume its relatively infrequent
1361 else if (btest == BoolTest::ne)
1362 prob = PROB_STATIC_FREQUENT; // Assume its relatively frequent
1363
1364 // If this is a conditional test guarding a backwards branch,
1365 // assume its a loop-back edge. Make it a likely taken branch.
1366 if (target_bci < bci()) {
1367 if (is_osr_parse()) { // Could be a hot OSR'd loop; force deopt
1368 // Since it's an OSR, we probably have profile data, but since
1369 // branch_prediction returned PROB_UNKNOWN, the counts are too small.
1370 // Let's make a special check here for completely zero counts.
1371 ciMethodData* methodData = method()->method_data();
1372 if (!methodData->is_empty()) {
1373 ciProfileData* data = methodData->bci_to_data(bci());
1374 // Only stop for truly zero counts, which mean an unknown part
1375 // of the OSR-ed method, and we want to deopt to gather more stats.
1376 // If you have ANY counts, then this loop is simply 'cold' relative
1377 // to the OSR loop.
1378 if (data == NULL ||
1379 (data->as_BranchData()->taken() + data->as_BranchData()->not_taken() == 0)) {
1380 // This is the only way to return PROB_UNKNOWN:
1381 return PROB_UNKNOWN;
1382 }
1383 }
1384 }
1385 prob = PROB_STATIC_FREQUENT; // Likely to take backwards branch
1386 }
1387
1388 assert(prob != PROB_UNKNOWN, "must have some guess at this point");
1389 return prob;
1390 }
1391
1392 // The magic constants are chosen so as to match the output of
1393 // branch_prediction() when the profile reports a zero taken count.
1394 // It is important to distinguish zero counts unambiguously, because
1395 // some branches (e.g., _213_javac.Assembler.eliminate) validly produce
1396 // very small but nonzero probabilities, which if confused with zero
1397 // counts would keep the program recompiling indefinitely.
seems_never_taken(float prob) const1398 bool Parse::seems_never_taken(float prob) const {
1399 return prob < PROB_MIN;
1400 }
1401
1402 // True if the comparison seems to be the kind that will not change its
1403 // statistics from true to false. See comments in adjust_map_after_if.
1404 // This question is only asked along paths which are already
1405 // classifed as untaken (by seems_never_taken), so really,
1406 // if a path is never taken, its controlling comparison is
1407 // already acting in a stable fashion. If the comparison
1408 // seems stable, we will put an expensive uncommon trap
1409 // on the untaken path.
seems_stable_comparison() const1410 bool Parse::seems_stable_comparison() const {
1411 if (C->too_many_traps(method(), bci(), Deoptimization::Reason_unstable_if)) {
1412 return false;
1413 }
1414 return true;
1415 }
1416
1417 //-------------------------------repush_if_args--------------------------------
1418 // Push arguments of an "if" bytecode back onto the stack by adjusting _sp.
repush_if_args()1419 inline int Parse::repush_if_args() {
1420 if (PrintOpto && WizardMode) {
1421 tty->print("defending against excessive implicit null exceptions on %s @%d in ",
1422 Bytecodes::name(iter().cur_bc()), iter().cur_bci());
1423 method()->print_name(); tty->cr();
1424 }
1425 int bc_depth = - Bytecodes::depth(iter().cur_bc());
1426 assert(bc_depth == 1 || bc_depth == 2, "only two kinds of branches");
1427 DEBUG_ONLY(sync_jvms()); // argument(n) requires a synced jvms
1428 assert(argument(0) != NULL, "must exist");
1429 assert(bc_depth == 1 || argument(1) != NULL, "two must exist");
1430 inc_sp(bc_depth);
1431 return bc_depth;
1432 }
1433
1434 //----------------------------------do_ifnull----------------------------------
do_ifnull(BoolTest::mask btest,Node * c)1435 void Parse::do_ifnull(BoolTest::mask btest, Node *c) {
1436 int target_bci = iter().get_dest();
1437
1438 Block* branch_block = successor_for_bci(target_bci);
1439 Block* next_block = successor_for_bci(iter().next_bci());
1440
1441 float cnt;
1442 float prob = branch_prediction(cnt, btest, target_bci, c);
1443 if (prob == PROB_UNKNOWN) {
1444 // (An earlier version of do_ifnull omitted this trap for OSR methods.)
1445 if (PrintOpto && Verbose) {
1446 tty->print_cr("Never-taken edge stops compilation at bci %d", bci());
1447 }
1448 repush_if_args(); // to gather stats on loop
1449 // We need to mark this branch as taken so that if we recompile we will
1450 // see that it is possible. In the tiered system the interpreter doesn't
1451 // do profiling and by the time we get to the lower tier from the interpreter
1452 // the path may be cold again. Make sure it doesn't look untaken
1453 profile_taken_branch(target_bci, !ProfileInterpreter);
1454 uncommon_trap(Deoptimization::Reason_unreached,
1455 Deoptimization::Action_reinterpret,
1456 NULL, "cold");
1457 if (C->eliminate_boxing()) {
1458 // Mark the successor blocks as parsed
1459 branch_block->next_path_num();
1460 next_block->next_path_num();
1461 }
1462 return;
1463 }
1464
1465 NOT_PRODUCT(explicit_null_checks_inserted++);
1466
1467 // Generate real control flow
1468 Node *tst = _gvn.transform( new BoolNode( c, btest ) );
1469
1470 // Sanity check the probability value
1471 assert(prob > 0.0f,"Bad probability in Parser");
1472 // Need xform to put node in hash table
1473 IfNode *iff = create_and_xform_if( control(), tst, prob, cnt );
1474 assert(iff->_prob > 0.0f,"Optimizer made bad probability in parser");
1475 // True branch
1476 { PreserveJVMState pjvms(this);
1477 Node* iftrue = _gvn.transform( new IfTrueNode (iff) );
1478 set_control(iftrue);
1479
1480 if (stopped()) { // Path is dead?
1481 NOT_PRODUCT(explicit_null_checks_elided++);
1482 if (C->eliminate_boxing()) {
1483 // Mark the successor block as parsed
1484 branch_block->next_path_num();
1485 }
1486 } else { // Path is live.
1487 // Update method data
1488 profile_taken_branch(target_bci);
1489 adjust_map_after_if(btest, c, prob, branch_block, next_block);
1490 if (!stopped()) {
1491 merge(target_bci);
1492 }
1493 }
1494 }
1495
1496 // False branch
1497 Node* iffalse = _gvn.transform( new IfFalseNode(iff) );
1498 set_control(iffalse);
1499
1500 if (stopped()) { // Path is dead?
1501 NOT_PRODUCT(explicit_null_checks_elided++);
1502 if (C->eliminate_boxing()) {
1503 // Mark the successor block as parsed
1504 next_block->next_path_num();
1505 }
1506 } else { // Path is live.
1507 // Update method data
1508 profile_not_taken_branch();
1509 adjust_map_after_if(BoolTest(btest).negate(), c, 1.0-prob,
1510 next_block, branch_block);
1511 }
1512 }
1513
1514 //------------------------------------do_if------------------------------------
do_if(BoolTest::mask btest,Node * c)1515 void Parse::do_if(BoolTest::mask btest, Node* c) {
1516 int target_bci = iter().get_dest();
1517
1518 Block* branch_block = successor_for_bci(target_bci);
1519 Block* next_block = successor_for_bci(iter().next_bci());
1520
1521 float cnt;
1522 float prob = branch_prediction(cnt, btest, target_bci, c);
1523 float untaken_prob = 1.0 - prob;
1524
1525 if (prob == PROB_UNKNOWN) {
1526 if (PrintOpto && Verbose) {
1527 tty->print_cr("Never-taken edge stops compilation at bci %d", bci());
1528 }
1529 repush_if_args(); // to gather stats on loop
1530 // We need to mark this branch as taken so that if we recompile we will
1531 // see that it is possible. In the tiered system the interpreter doesn't
1532 // do profiling and by the time we get to the lower tier from the interpreter
1533 // the path may be cold again. Make sure it doesn't look untaken
1534 profile_taken_branch(target_bci, !ProfileInterpreter);
1535 uncommon_trap(Deoptimization::Reason_unreached,
1536 Deoptimization::Action_reinterpret,
1537 NULL, "cold");
1538 if (C->eliminate_boxing()) {
1539 // Mark the successor blocks as parsed
1540 branch_block->next_path_num();
1541 next_block->next_path_num();
1542 }
1543 return;
1544 }
1545
1546 // Sanity check the probability value
1547 assert(0.0f < prob && prob < 1.0f,"Bad probability in Parser");
1548
1549 bool taken_if_true = true;
1550 // Convert BoolTest to canonical form:
1551 if (!BoolTest(btest).is_canonical()) {
1552 btest = BoolTest(btest).negate();
1553 taken_if_true = false;
1554 // prob is NOT updated here; it remains the probability of the taken
1555 // path (as opposed to the prob of the path guarded by an 'IfTrueNode').
1556 }
1557 assert(btest != BoolTest::eq, "!= is the only canonical exact test");
1558
1559 Node* tst0 = new BoolNode(c, btest);
1560 Node* tst = _gvn.transform(tst0);
1561 BoolTest::mask taken_btest = BoolTest::illegal;
1562 BoolTest::mask untaken_btest = BoolTest::illegal;
1563
1564 if (tst->is_Bool()) {
1565 // Refresh c from the transformed bool node, since it may be
1566 // simpler than the original c. Also re-canonicalize btest.
1567 // This wins when (Bool ne (Conv2B p) 0) => (Bool ne (CmpP p NULL)).
1568 // That can arise from statements like: if (x instanceof C) ...
1569 if (tst != tst0) {
1570 // Canonicalize one more time since transform can change it.
1571 btest = tst->as_Bool()->_test._test;
1572 if (!BoolTest(btest).is_canonical()) {
1573 // Reverse edges one more time...
1574 tst = _gvn.transform( tst->as_Bool()->negate(&_gvn) );
1575 btest = tst->as_Bool()->_test._test;
1576 assert(BoolTest(btest).is_canonical(), "sanity");
1577 taken_if_true = !taken_if_true;
1578 }
1579 c = tst->in(1);
1580 }
1581 BoolTest::mask neg_btest = BoolTest(btest).negate();
1582 taken_btest = taken_if_true ? btest : neg_btest;
1583 untaken_btest = taken_if_true ? neg_btest : btest;
1584 }
1585
1586 // Generate real control flow
1587 float true_prob = (taken_if_true ? prob : untaken_prob);
1588 IfNode* iff = create_and_map_if(control(), tst, true_prob, cnt);
1589 assert(iff->_prob > 0.0f,"Optimizer made bad probability in parser");
1590 Node* taken_branch = new IfTrueNode(iff);
1591 Node* untaken_branch = new IfFalseNode(iff);
1592 if (!taken_if_true) { // Finish conversion to canonical form
1593 Node* tmp = taken_branch;
1594 taken_branch = untaken_branch;
1595 untaken_branch = tmp;
1596 }
1597
1598 // Branch is taken:
1599 { PreserveJVMState pjvms(this);
1600 taken_branch = _gvn.transform(taken_branch);
1601 set_control(taken_branch);
1602
1603 if (stopped()) {
1604 if (C->eliminate_boxing()) {
1605 // Mark the successor block as parsed
1606 branch_block->next_path_num();
1607 }
1608 } else {
1609 // Update method data
1610 profile_taken_branch(target_bci);
1611 adjust_map_after_if(taken_btest, c, prob, branch_block, next_block);
1612 if (!stopped()) {
1613 merge(target_bci);
1614 }
1615 }
1616 }
1617
1618 untaken_branch = _gvn.transform(untaken_branch);
1619 set_control(untaken_branch);
1620
1621 // Branch not taken.
1622 if (stopped()) {
1623 if (C->eliminate_boxing()) {
1624 // Mark the successor block as parsed
1625 next_block->next_path_num();
1626 }
1627 } else {
1628 // Update method data
1629 profile_not_taken_branch();
1630 adjust_map_after_if(untaken_btest, c, untaken_prob,
1631 next_block, branch_block);
1632 }
1633 }
1634
path_is_suitable_for_uncommon_trap(float prob) const1635 bool Parse::path_is_suitable_for_uncommon_trap(float prob) const {
1636 // Don't want to speculate on uncommon traps when running with -Xcomp
1637 if (!UseInterpreter) {
1638 return false;
1639 }
1640 return (seems_never_taken(prob) && seems_stable_comparison());
1641 }
1642
maybe_add_predicate_after_if(Block * path)1643 void Parse::maybe_add_predicate_after_if(Block* path) {
1644 if (path->is_SEL_head() && path->preds_parsed() == 0) {
1645 // Add predicates at bci of if dominating the loop so traps can be
1646 // recorded on the if's profile data
1647 int bc_depth = repush_if_args();
1648 add_predicate();
1649 dec_sp(bc_depth);
1650 path->set_has_predicates();
1651 }
1652 }
1653
1654
1655 //----------------------------adjust_map_after_if------------------------------
1656 // Adjust the JVM state to reflect the result of taking this path.
1657 // Basically, it means inspecting the CmpNode controlling this
1658 // branch, seeing how it constrains a tested value, and then
1659 // deciding if it's worth our while to encode this constraint
1660 // as graph nodes in the current abstract interpretation map.
adjust_map_after_if(BoolTest::mask btest,Node * c,float prob,Block * path,Block * other_path)1661 void Parse::adjust_map_after_if(BoolTest::mask btest, Node* c, float prob,
1662 Block* path, Block* other_path) {
1663 if (!c->is_Cmp()) {
1664 maybe_add_predicate_after_if(path);
1665 return;
1666 }
1667
1668 if (stopped() || btest == BoolTest::illegal) {
1669 return; // nothing to do
1670 }
1671
1672 bool is_fallthrough = (path == successor_for_bci(iter().next_bci()));
1673
1674 if (path_is_suitable_for_uncommon_trap(prob)) {
1675 repush_if_args();
1676 uncommon_trap(Deoptimization::Reason_unstable_if,
1677 Deoptimization::Action_reinterpret,
1678 NULL,
1679 (is_fallthrough ? "taken always" : "taken never"));
1680 return;
1681 }
1682
1683 Node* val = c->in(1);
1684 Node* con = c->in(2);
1685 const Type* tcon = _gvn.type(con);
1686 const Type* tval = _gvn.type(val);
1687 bool have_con = tcon->singleton();
1688 if (tval->singleton()) {
1689 if (!have_con) {
1690 // Swap, so constant is in con.
1691 con = val;
1692 tcon = tval;
1693 val = c->in(2);
1694 tval = _gvn.type(val);
1695 btest = BoolTest(btest).commute();
1696 have_con = true;
1697 } else {
1698 // Do we have two constants? Then leave well enough alone.
1699 have_con = false;
1700 }
1701 }
1702 if (!have_con) { // remaining adjustments need a con
1703 maybe_add_predicate_after_if(path);
1704 return;
1705 }
1706
1707 sharpen_type_after_if(btest, con, tcon, val, tval);
1708 maybe_add_predicate_after_if(path);
1709 }
1710
1711
extract_obj_from_klass_load(PhaseGVN * gvn,Node * n)1712 static Node* extract_obj_from_klass_load(PhaseGVN* gvn, Node* n) {
1713 Node* ldk;
1714 if (n->is_DecodeNKlass()) {
1715 if (n->in(1)->Opcode() != Op_LoadNKlass) {
1716 return NULL;
1717 } else {
1718 ldk = n->in(1);
1719 }
1720 } else if (n->Opcode() != Op_LoadKlass) {
1721 return NULL;
1722 } else {
1723 ldk = n;
1724 }
1725 assert(ldk != NULL && ldk->is_Load(), "should have found a LoadKlass or LoadNKlass node");
1726
1727 Node* adr = ldk->in(MemNode::Address);
1728 intptr_t off = 0;
1729 Node* obj = AddPNode::Ideal_base_and_offset(adr, gvn, off);
1730 if (obj == NULL || off != oopDesc::klass_offset_in_bytes()) // loading oopDesc::_klass?
1731 return NULL;
1732 const TypePtr* tp = gvn->type(obj)->is_ptr();
1733 if (tp == NULL || !(tp->isa_instptr() || tp->isa_aryptr())) // is obj a Java object ptr?
1734 return NULL;
1735
1736 return obj;
1737 }
1738
sharpen_type_after_if(BoolTest::mask btest,Node * con,const Type * tcon,Node * val,const Type * tval)1739 void Parse::sharpen_type_after_if(BoolTest::mask btest,
1740 Node* con, const Type* tcon,
1741 Node* val, const Type* tval) {
1742 // Look for opportunities to sharpen the type of a node
1743 // whose klass is compared with a constant klass.
1744 if (btest == BoolTest::eq && tcon->isa_klassptr()) {
1745 Node* obj = extract_obj_from_klass_load(&_gvn, val);
1746 const TypeOopPtr* con_type = tcon->isa_klassptr()->as_instance_type();
1747 if (obj != NULL && (con_type->isa_instptr() || con_type->isa_aryptr())) {
1748 // Found:
1749 // Bool(CmpP(LoadKlass(obj._klass), ConP(Foo.klass)), [eq])
1750 // or the narrowOop equivalent.
1751 const Type* obj_type = _gvn.type(obj);
1752 const TypeOopPtr* tboth = obj_type->join_speculative(con_type)->isa_oopptr();
1753 if (tboth != NULL && tboth->klass_is_exact() && tboth != obj_type &&
1754 tboth->higher_equal(obj_type)) {
1755 // obj has to be of the exact type Foo if the CmpP succeeds.
1756 int obj_in_map = map()->find_edge(obj);
1757 JVMState* jvms = this->jvms();
1758 if (obj_in_map >= 0 &&
1759 (jvms->is_loc(obj_in_map) || jvms->is_stk(obj_in_map))) {
1760 TypeNode* ccast = new CheckCastPPNode(control(), obj, tboth);
1761 const Type* tcc = ccast->as_Type()->type();
1762 assert(tcc != obj_type && tcc->higher_equal(obj_type), "must improve");
1763 // Delay transform() call to allow recovery of pre-cast value
1764 // at the control merge.
1765 _gvn.set_type_bottom(ccast);
1766 record_for_igvn(ccast);
1767 // Here's the payoff.
1768 replace_in_map(obj, ccast);
1769 }
1770 }
1771 }
1772 }
1773
1774 int val_in_map = map()->find_edge(val);
1775 if (val_in_map < 0) return; // replace_in_map would be useless
1776 {
1777 JVMState* jvms = this->jvms();
1778 if (!(jvms->is_loc(val_in_map) ||
1779 jvms->is_stk(val_in_map)))
1780 return; // again, it would be useless
1781 }
1782
1783 // Check for a comparison to a constant, and "know" that the compared
1784 // value is constrained on this path.
1785 assert(tcon->singleton(), "");
1786 ConstraintCastNode* ccast = NULL;
1787 Node* cast = NULL;
1788
1789 switch (btest) {
1790 case BoolTest::eq: // Constant test?
1791 {
1792 const Type* tboth = tcon->join_speculative(tval);
1793 if (tboth == tval) break; // Nothing to gain.
1794 if (tcon->isa_int()) {
1795 ccast = new CastIINode(val, tboth);
1796 } else if (tcon == TypePtr::NULL_PTR) {
1797 // Cast to null, but keep the pointer identity temporarily live.
1798 ccast = new CastPPNode(val, tboth);
1799 } else {
1800 const TypeF* tf = tcon->isa_float_constant();
1801 const TypeD* td = tcon->isa_double_constant();
1802 // Exclude tests vs float/double 0 as these could be
1803 // either +0 or -0. Just because you are equal to +0
1804 // doesn't mean you ARE +0!
1805 // Note, following code also replaces Long and Oop values.
1806 if ((!tf || tf->_f != 0.0) &&
1807 (!td || td->_d != 0.0))
1808 cast = con; // Replace non-constant val by con.
1809 }
1810 }
1811 break;
1812
1813 case BoolTest::ne:
1814 if (tcon == TypePtr::NULL_PTR) {
1815 cast = cast_not_null(val, false);
1816 }
1817 break;
1818
1819 default:
1820 // (At this point we could record int range types with CastII.)
1821 break;
1822 }
1823
1824 if (ccast != NULL) {
1825 const Type* tcc = ccast->as_Type()->type();
1826 assert(tcc != tval && tcc->higher_equal(tval), "must improve");
1827 // Delay transform() call to allow recovery of pre-cast value
1828 // at the control merge.
1829 ccast->set_req(0, control());
1830 _gvn.set_type_bottom(ccast);
1831 record_for_igvn(ccast);
1832 cast = ccast;
1833 }
1834
1835 if (cast != NULL) { // Here's the payoff.
1836 replace_in_map(val, cast);
1837 }
1838 }
1839
1840 /**
1841 * Use speculative type to optimize CmpP node: if comparison is
1842 * against the low level class, cast the object to the speculative
1843 * type if any. CmpP should then go away.
1844 *
1845 * @param c expected CmpP node
1846 * @return result of CmpP on object casted to speculative type
1847 *
1848 */
optimize_cmp_with_klass(Node * c)1849 Node* Parse::optimize_cmp_with_klass(Node* c) {
1850 // If this is transformed by the _gvn to a comparison with the low
1851 // level klass then we may be able to use speculation
1852 if (c->Opcode() == Op_CmpP &&
1853 (c->in(1)->Opcode() == Op_LoadKlass || c->in(1)->Opcode() == Op_DecodeNKlass) &&
1854 c->in(2)->is_Con()) {
1855 Node* load_klass = NULL;
1856 Node* decode = NULL;
1857 if (c->in(1)->Opcode() == Op_DecodeNKlass) {
1858 decode = c->in(1);
1859 load_klass = c->in(1)->in(1);
1860 } else {
1861 load_klass = c->in(1);
1862 }
1863 if (load_klass->in(2)->is_AddP()) {
1864 Node* addp = load_klass->in(2);
1865 Node* obj = addp->in(AddPNode::Address);
1866 const TypeOopPtr* obj_type = _gvn.type(obj)->is_oopptr();
1867 if (obj_type->speculative_type_not_null() != NULL) {
1868 ciKlass* k = obj_type->speculative_type();
1869 inc_sp(2);
1870 obj = maybe_cast_profiled_obj(obj, k);
1871 dec_sp(2);
1872 // Make the CmpP use the casted obj
1873 addp = basic_plus_adr(obj, addp->in(AddPNode::Offset));
1874 load_klass = load_klass->clone();
1875 load_klass->set_req(2, addp);
1876 load_klass = _gvn.transform(load_klass);
1877 if (decode != NULL) {
1878 decode = decode->clone();
1879 decode->set_req(1, load_klass);
1880 load_klass = _gvn.transform(decode);
1881 }
1882 c = c->clone();
1883 c->set_req(1, load_klass);
1884 c = _gvn.transform(c);
1885 }
1886 }
1887 }
1888 return c;
1889 }
1890
1891 //------------------------------do_one_bytecode--------------------------------
1892 // Parse this bytecode, and alter the Parsers JVM->Node mapping
do_one_bytecode()1893 void Parse::do_one_bytecode() {
1894 Node *a, *b, *c, *d; // Handy temps
1895 BoolTest::mask btest;
1896 int i;
1897
1898 assert(!has_exceptions(), "bytecode entry state must be clear of throws");
1899
1900 if (C->check_node_count(NodeLimitFudgeFactor * 5,
1901 "out of nodes parsing method")) {
1902 return;
1903 }
1904
1905 #ifdef ASSERT
1906 // for setting breakpoints
1907 if (TraceOptoParse) {
1908 tty->print(" @");
1909 dump_bci(bci());
1910 tty->cr();
1911 }
1912 #endif
1913
1914 switch (bc()) {
1915 case Bytecodes::_nop:
1916 // do nothing
1917 break;
1918 case Bytecodes::_lconst_0:
1919 push_pair(longcon(0));
1920 break;
1921
1922 case Bytecodes::_lconst_1:
1923 push_pair(longcon(1));
1924 break;
1925
1926 case Bytecodes::_fconst_0:
1927 push(zerocon(T_FLOAT));
1928 break;
1929
1930 case Bytecodes::_fconst_1:
1931 push(makecon(TypeF::ONE));
1932 break;
1933
1934 case Bytecodes::_fconst_2:
1935 push(makecon(TypeF::make(2.0f)));
1936 break;
1937
1938 case Bytecodes::_dconst_0:
1939 push_pair(zerocon(T_DOUBLE));
1940 break;
1941
1942 case Bytecodes::_dconst_1:
1943 push_pair(makecon(TypeD::ONE));
1944 break;
1945
1946 case Bytecodes::_iconst_m1:push(intcon(-1)); break;
1947 case Bytecodes::_iconst_0: push(intcon( 0)); break;
1948 case Bytecodes::_iconst_1: push(intcon( 1)); break;
1949 case Bytecodes::_iconst_2: push(intcon( 2)); break;
1950 case Bytecodes::_iconst_3: push(intcon( 3)); break;
1951 case Bytecodes::_iconst_4: push(intcon( 4)); break;
1952 case Bytecodes::_iconst_5: push(intcon( 5)); break;
1953 case Bytecodes::_bipush: push(intcon(iter().get_constant_u1())); break;
1954 case Bytecodes::_sipush: push(intcon(iter().get_constant_u2())); break;
1955 case Bytecodes::_aconst_null: push(null()); break;
1956 case Bytecodes::_ldc:
1957 case Bytecodes::_ldc_w:
1958 case Bytecodes::_ldc2_w:
1959 // If the constant is unresolved, run this BC once in the interpreter.
1960 {
1961 ciConstant constant = iter().get_constant();
1962 if (!constant.is_valid() ||
1963 (constant.basic_type() == T_OBJECT &&
1964 !constant.as_object()->is_loaded())) {
1965 int index = iter().get_constant_pool_index();
1966 constantTag tag = iter().get_constant_pool_tag(index);
1967 uncommon_trap(Deoptimization::make_trap_request
1968 (Deoptimization::Reason_unloaded,
1969 Deoptimization::Action_reinterpret,
1970 index),
1971 NULL, tag.internal_name());
1972 break;
1973 }
1974 assert(constant.basic_type() != T_OBJECT || constant.as_object()->is_instance(),
1975 "must be java_mirror of klass");
1976 const Type* con_type = Type::make_from_constant(constant);
1977 if (con_type != NULL) {
1978 push_node(con_type->basic_type(), makecon(con_type));
1979 }
1980 }
1981
1982 break;
1983
1984 case Bytecodes::_aload_0:
1985 push( local(0) );
1986 break;
1987 case Bytecodes::_aload_1:
1988 push( local(1) );
1989 break;
1990 case Bytecodes::_aload_2:
1991 push( local(2) );
1992 break;
1993 case Bytecodes::_aload_3:
1994 push( local(3) );
1995 break;
1996 case Bytecodes::_aload:
1997 push( local(iter().get_index()) );
1998 break;
1999
2000 case Bytecodes::_fload_0:
2001 case Bytecodes::_iload_0:
2002 push( local(0) );
2003 break;
2004 case Bytecodes::_fload_1:
2005 case Bytecodes::_iload_1:
2006 push( local(1) );
2007 break;
2008 case Bytecodes::_fload_2:
2009 case Bytecodes::_iload_2:
2010 push( local(2) );
2011 break;
2012 case Bytecodes::_fload_3:
2013 case Bytecodes::_iload_3:
2014 push( local(3) );
2015 break;
2016 case Bytecodes::_fload:
2017 case Bytecodes::_iload:
2018 push( local(iter().get_index()) );
2019 break;
2020 case Bytecodes::_lload_0:
2021 push_pair_local( 0 );
2022 break;
2023 case Bytecodes::_lload_1:
2024 push_pair_local( 1 );
2025 break;
2026 case Bytecodes::_lload_2:
2027 push_pair_local( 2 );
2028 break;
2029 case Bytecodes::_lload_3:
2030 push_pair_local( 3 );
2031 break;
2032 case Bytecodes::_lload:
2033 push_pair_local( iter().get_index() );
2034 break;
2035
2036 case Bytecodes::_dload_0:
2037 push_pair_local(0);
2038 break;
2039 case Bytecodes::_dload_1:
2040 push_pair_local(1);
2041 break;
2042 case Bytecodes::_dload_2:
2043 push_pair_local(2);
2044 break;
2045 case Bytecodes::_dload_3:
2046 push_pair_local(3);
2047 break;
2048 case Bytecodes::_dload:
2049 push_pair_local(iter().get_index());
2050 break;
2051 case Bytecodes::_fstore_0:
2052 case Bytecodes::_istore_0:
2053 case Bytecodes::_astore_0:
2054 set_local( 0, pop() );
2055 break;
2056 case Bytecodes::_fstore_1:
2057 case Bytecodes::_istore_1:
2058 case Bytecodes::_astore_1:
2059 set_local( 1, pop() );
2060 break;
2061 case Bytecodes::_fstore_2:
2062 case Bytecodes::_istore_2:
2063 case Bytecodes::_astore_2:
2064 set_local( 2, pop() );
2065 break;
2066 case Bytecodes::_fstore_3:
2067 case Bytecodes::_istore_3:
2068 case Bytecodes::_astore_3:
2069 set_local( 3, pop() );
2070 break;
2071 case Bytecodes::_fstore:
2072 case Bytecodes::_istore:
2073 case Bytecodes::_astore:
2074 set_local( iter().get_index(), pop() );
2075 break;
2076 // long stores
2077 case Bytecodes::_lstore_0:
2078 set_pair_local( 0, pop_pair() );
2079 break;
2080 case Bytecodes::_lstore_1:
2081 set_pair_local( 1, pop_pair() );
2082 break;
2083 case Bytecodes::_lstore_2:
2084 set_pair_local( 2, pop_pair() );
2085 break;
2086 case Bytecodes::_lstore_3:
2087 set_pair_local( 3, pop_pair() );
2088 break;
2089 case Bytecodes::_lstore:
2090 set_pair_local( iter().get_index(), pop_pair() );
2091 break;
2092
2093 // double stores
2094 case Bytecodes::_dstore_0:
2095 set_pair_local( 0, dstore_rounding(pop_pair()) );
2096 break;
2097 case Bytecodes::_dstore_1:
2098 set_pair_local( 1, dstore_rounding(pop_pair()) );
2099 break;
2100 case Bytecodes::_dstore_2:
2101 set_pair_local( 2, dstore_rounding(pop_pair()) );
2102 break;
2103 case Bytecodes::_dstore_3:
2104 set_pair_local( 3, dstore_rounding(pop_pair()) );
2105 break;
2106 case Bytecodes::_dstore:
2107 set_pair_local( iter().get_index(), dstore_rounding(pop_pair()) );
2108 break;
2109
2110 case Bytecodes::_pop: dec_sp(1); break;
2111 case Bytecodes::_pop2: dec_sp(2); break;
2112 case Bytecodes::_swap:
2113 a = pop();
2114 b = pop();
2115 push(a);
2116 push(b);
2117 break;
2118 case Bytecodes::_dup:
2119 a = pop();
2120 push(a);
2121 push(a);
2122 break;
2123 case Bytecodes::_dup_x1:
2124 a = pop();
2125 b = pop();
2126 push( a );
2127 push( b );
2128 push( a );
2129 break;
2130 case Bytecodes::_dup_x2:
2131 a = pop();
2132 b = pop();
2133 c = pop();
2134 push( a );
2135 push( c );
2136 push( b );
2137 push( a );
2138 break;
2139 case Bytecodes::_dup2:
2140 a = pop();
2141 b = pop();
2142 push( b );
2143 push( a );
2144 push( b );
2145 push( a );
2146 break;
2147
2148 case Bytecodes::_dup2_x1:
2149 // before: .. c, b, a
2150 // after: .. b, a, c, b, a
2151 // not tested
2152 a = pop();
2153 b = pop();
2154 c = pop();
2155 push( b );
2156 push( a );
2157 push( c );
2158 push( b );
2159 push( a );
2160 break;
2161 case Bytecodes::_dup2_x2:
2162 // before: .. d, c, b, a
2163 // after: .. b, a, d, c, b, a
2164 // not tested
2165 a = pop();
2166 b = pop();
2167 c = pop();
2168 d = pop();
2169 push( b );
2170 push( a );
2171 push( d );
2172 push( c );
2173 push( b );
2174 push( a );
2175 break;
2176
2177 case Bytecodes::_arraylength: {
2178 // Must do null-check with value on expression stack
2179 Node *ary = null_check(peek(), T_ARRAY);
2180 // Compile-time detect of null-exception?
2181 if (stopped()) return;
2182 a = pop();
2183 push(load_array_length(a));
2184 break;
2185 }
2186
2187 case Bytecodes::_baload: array_load(T_BYTE); break;
2188 case Bytecodes::_caload: array_load(T_CHAR); break;
2189 case Bytecodes::_iaload: array_load(T_INT); break;
2190 case Bytecodes::_saload: array_load(T_SHORT); break;
2191 case Bytecodes::_faload: array_load(T_FLOAT); break;
2192 case Bytecodes::_aaload: array_load(T_OBJECT); break;
2193 case Bytecodes::_laload: array_load(T_LONG); break;
2194 case Bytecodes::_daload: array_load(T_DOUBLE); break;
2195 case Bytecodes::_bastore: array_store(T_BYTE); break;
2196 case Bytecodes::_castore: array_store(T_CHAR); break;
2197 case Bytecodes::_iastore: array_store(T_INT); break;
2198 case Bytecodes::_sastore: array_store(T_SHORT); break;
2199 case Bytecodes::_fastore: array_store(T_FLOAT); break;
2200 case Bytecodes::_aastore: array_store(T_OBJECT); break;
2201 case Bytecodes::_lastore: array_store(T_LONG); break;
2202 case Bytecodes::_dastore: array_store(T_DOUBLE); break;
2203
2204 case Bytecodes::_getfield:
2205 do_getfield();
2206 break;
2207
2208 case Bytecodes::_getstatic:
2209 do_getstatic();
2210 break;
2211
2212 case Bytecodes::_putfield:
2213 do_putfield();
2214 break;
2215
2216 case Bytecodes::_putstatic:
2217 do_putstatic();
2218 break;
2219
2220 case Bytecodes::_irem:
2221 do_irem();
2222 break;
2223 case Bytecodes::_idiv:
2224 // Must keep both values on the expression-stack during null-check
2225 zero_check_int(peek());
2226 // Compile-time detect of null-exception?
2227 if (stopped()) return;
2228 b = pop();
2229 a = pop();
2230 push( _gvn.transform( new DivINode(control(),a,b) ) );
2231 break;
2232 case Bytecodes::_imul:
2233 b = pop(); a = pop();
2234 push( _gvn.transform( new MulINode(a,b) ) );
2235 break;
2236 case Bytecodes::_iadd:
2237 b = pop(); a = pop();
2238 push( _gvn.transform( new AddINode(a,b) ) );
2239 break;
2240 case Bytecodes::_ineg:
2241 a = pop();
2242 push( _gvn.transform( new SubINode(_gvn.intcon(0),a)) );
2243 break;
2244 case Bytecodes::_isub:
2245 b = pop(); a = pop();
2246 push( _gvn.transform( new SubINode(a,b) ) );
2247 break;
2248 case Bytecodes::_iand:
2249 b = pop(); a = pop();
2250 push( _gvn.transform( new AndINode(a,b) ) );
2251 break;
2252 case Bytecodes::_ior:
2253 b = pop(); a = pop();
2254 push( _gvn.transform( new OrINode(a,b) ) );
2255 break;
2256 case Bytecodes::_ixor:
2257 b = pop(); a = pop();
2258 push( _gvn.transform( new XorINode(a,b) ) );
2259 break;
2260 case Bytecodes::_ishl:
2261 b = pop(); a = pop();
2262 push( _gvn.transform( new LShiftINode(a,b) ) );
2263 break;
2264 case Bytecodes::_ishr:
2265 b = pop(); a = pop();
2266 push( _gvn.transform( new RShiftINode(a,b) ) );
2267 break;
2268 case Bytecodes::_iushr:
2269 b = pop(); a = pop();
2270 push( _gvn.transform( new URShiftINode(a,b) ) );
2271 break;
2272
2273 case Bytecodes::_fneg:
2274 a = pop();
2275 b = _gvn.transform(new NegFNode (a));
2276 push(b);
2277 break;
2278
2279 case Bytecodes::_fsub:
2280 b = pop();
2281 a = pop();
2282 c = _gvn.transform( new SubFNode(a,b) );
2283 d = precision_rounding(c);
2284 push( d );
2285 break;
2286
2287 case Bytecodes::_fadd:
2288 b = pop();
2289 a = pop();
2290 c = _gvn.transform( new AddFNode(a,b) );
2291 d = precision_rounding(c);
2292 push( d );
2293 break;
2294
2295 case Bytecodes::_fmul:
2296 b = pop();
2297 a = pop();
2298 c = _gvn.transform( new MulFNode(a,b) );
2299 d = precision_rounding(c);
2300 push( d );
2301 break;
2302
2303 case Bytecodes::_fdiv:
2304 b = pop();
2305 a = pop();
2306 c = _gvn.transform( new DivFNode(0,a,b) );
2307 d = precision_rounding(c);
2308 push( d );
2309 break;
2310
2311 case Bytecodes::_frem:
2312 if (Matcher::has_match_rule(Op_ModF)) {
2313 // Generate a ModF node.
2314 b = pop();
2315 a = pop();
2316 c = _gvn.transform( new ModFNode(0,a,b) );
2317 d = precision_rounding(c);
2318 push( d );
2319 }
2320 else {
2321 // Generate a call.
2322 modf();
2323 }
2324 break;
2325
2326 case Bytecodes::_fcmpl:
2327 b = pop();
2328 a = pop();
2329 c = _gvn.transform( new CmpF3Node( a, b));
2330 push(c);
2331 break;
2332 case Bytecodes::_fcmpg:
2333 b = pop();
2334 a = pop();
2335
2336 // Same as fcmpl but need to flip the unordered case. Swap the inputs,
2337 // which negates the result sign except for unordered. Flip the unordered
2338 // as well by using CmpF3 which implements unordered-lesser instead of
2339 // unordered-greater semantics. Finally, commute the result bits. Result
2340 // is same as using a CmpF3Greater except we did it with CmpF3 alone.
2341 c = _gvn.transform( new CmpF3Node( b, a));
2342 c = _gvn.transform( new SubINode(_gvn.intcon(0),c) );
2343 push(c);
2344 break;
2345
2346 case Bytecodes::_f2i:
2347 a = pop();
2348 push(_gvn.transform(new ConvF2INode(a)));
2349 break;
2350
2351 case Bytecodes::_d2i:
2352 a = pop_pair();
2353 b = _gvn.transform(new ConvD2INode(a));
2354 push( b );
2355 break;
2356
2357 case Bytecodes::_f2d:
2358 a = pop();
2359 b = _gvn.transform( new ConvF2DNode(a));
2360 push_pair( b );
2361 break;
2362
2363 case Bytecodes::_d2f:
2364 a = pop_pair();
2365 b = _gvn.transform( new ConvD2FNode(a));
2366 // This breaks _227_mtrt (speed & correctness) and _222_mpegaudio (speed)
2367 //b = _gvn.transform(new RoundFloatNode(0, b) );
2368 push( b );
2369 break;
2370
2371 case Bytecodes::_l2f:
2372 if (Matcher::convL2FSupported()) {
2373 a = pop_pair();
2374 b = _gvn.transform( new ConvL2FNode(a));
2375 // For i486.ad, FILD doesn't restrict precision to 24 or 53 bits.
2376 // Rather than storing the result into an FP register then pushing
2377 // out to memory to round, the machine instruction that implements
2378 // ConvL2D is responsible for rounding.
2379 // c = precision_rounding(b);
2380 c = _gvn.transform(b);
2381 push(c);
2382 } else {
2383 l2f();
2384 }
2385 break;
2386
2387 case Bytecodes::_l2d:
2388 a = pop_pair();
2389 b = _gvn.transform( new ConvL2DNode(a));
2390 // For i486.ad, rounding is always necessary (see _l2f above).
2391 // c = dprecision_rounding(b);
2392 c = _gvn.transform(b);
2393 push_pair(c);
2394 break;
2395
2396 case Bytecodes::_f2l:
2397 a = pop();
2398 b = _gvn.transform( new ConvF2LNode(a));
2399 push_pair(b);
2400 break;
2401
2402 case Bytecodes::_d2l:
2403 a = pop_pair();
2404 b = _gvn.transform( new ConvD2LNode(a));
2405 push_pair(b);
2406 break;
2407
2408 case Bytecodes::_dsub:
2409 b = pop_pair();
2410 a = pop_pair();
2411 c = _gvn.transform( new SubDNode(a,b) );
2412 d = dprecision_rounding(c);
2413 push_pair( d );
2414 break;
2415
2416 case Bytecodes::_dadd:
2417 b = pop_pair();
2418 a = pop_pair();
2419 c = _gvn.transform( new AddDNode(a,b) );
2420 d = dprecision_rounding(c);
2421 push_pair( d );
2422 break;
2423
2424 case Bytecodes::_dmul:
2425 b = pop_pair();
2426 a = pop_pair();
2427 c = _gvn.transform( new MulDNode(a,b) );
2428 d = dprecision_rounding(c);
2429 push_pair( d );
2430 break;
2431
2432 case Bytecodes::_ddiv:
2433 b = pop_pair();
2434 a = pop_pair();
2435 c = _gvn.transform( new DivDNode(0,a,b) );
2436 d = dprecision_rounding(c);
2437 push_pair( d );
2438 break;
2439
2440 case Bytecodes::_dneg:
2441 a = pop_pair();
2442 b = _gvn.transform(new NegDNode (a));
2443 push_pair(b);
2444 break;
2445
2446 case Bytecodes::_drem:
2447 if (Matcher::has_match_rule(Op_ModD)) {
2448 // Generate a ModD node.
2449 b = pop_pair();
2450 a = pop_pair();
2451 // a % b
2452
2453 c = _gvn.transform( new ModDNode(0,a,b) );
2454 d = dprecision_rounding(c);
2455 push_pair( d );
2456 }
2457 else {
2458 // Generate a call.
2459 modd();
2460 }
2461 break;
2462
2463 case Bytecodes::_dcmpl:
2464 b = pop_pair();
2465 a = pop_pair();
2466 c = _gvn.transform( new CmpD3Node( a, b));
2467 push(c);
2468 break;
2469
2470 case Bytecodes::_dcmpg:
2471 b = pop_pair();
2472 a = pop_pair();
2473 // Same as dcmpl but need to flip the unordered case.
2474 // Commute the inputs, which negates the result sign except for unordered.
2475 // Flip the unordered as well by using CmpD3 which implements
2476 // unordered-lesser instead of unordered-greater semantics.
2477 // Finally, negate the result bits. Result is same as using a
2478 // CmpD3Greater except we did it with CmpD3 alone.
2479 c = _gvn.transform( new CmpD3Node( b, a));
2480 c = _gvn.transform( new SubINode(_gvn.intcon(0),c) );
2481 push(c);
2482 break;
2483
2484
2485 // Note for longs -> lo word is on TOS, hi word is on TOS - 1
2486 case Bytecodes::_land:
2487 b = pop_pair();
2488 a = pop_pair();
2489 c = _gvn.transform( new AndLNode(a,b) );
2490 push_pair(c);
2491 break;
2492 case Bytecodes::_lor:
2493 b = pop_pair();
2494 a = pop_pair();
2495 c = _gvn.transform( new OrLNode(a,b) );
2496 push_pair(c);
2497 break;
2498 case Bytecodes::_lxor:
2499 b = pop_pair();
2500 a = pop_pair();
2501 c = _gvn.transform( new XorLNode(a,b) );
2502 push_pair(c);
2503 break;
2504
2505 case Bytecodes::_lshl:
2506 b = pop(); // the shift count
2507 a = pop_pair(); // value to be shifted
2508 c = _gvn.transform( new LShiftLNode(a,b) );
2509 push_pair(c);
2510 break;
2511 case Bytecodes::_lshr:
2512 b = pop(); // the shift count
2513 a = pop_pair(); // value to be shifted
2514 c = _gvn.transform( new RShiftLNode(a,b) );
2515 push_pair(c);
2516 break;
2517 case Bytecodes::_lushr:
2518 b = pop(); // the shift count
2519 a = pop_pair(); // value to be shifted
2520 c = _gvn.transform( new URShiftLNode(a,b) );
2521 push_pair(c);
2522 break;
2523 case Bytecodes::_lmul:
2524 b = pop_pair();
2525 a = pop_pair();
2526 c = _gvn.transform( new MulLNode(a,b) );
2527 push_pair(c);
2528 break;
2529
2530 case Bytecodes::_lrem:
2531 // Must keep both values on the expression-stack during null-check
2532 assert(peek(0) == top(), "long word order");
2533 zero_check_long(peek(1));
2534 // Compile-time detect of null-exception?
2535 if (stopped()) return;
2536 b = pop_pair();
2537 a = pop_pair();
2538 c = _gvn.transform( new ModLNode(control(),a,b) );
2539 push_pair(c);
2540 break;
2541
2542 case Bytecodes::_ldiv:
2543 // Must keep both values on the expression-stack during null-check
2544 assert(peek(0) == top(), "long word order");
2545 zero_check_long(peek(1));
2546 // Compile-time detect of null-exception?
2547 if (stopped()) return;
2548 b = pop_pair();
2549 a = pop_pair();
2550 c = _gvn.transform( new DivLNode(control(),a,b) );
2551 push_pair(c);
2552 break;
2553
2554 case Bytecodes::_ladd:
2555 b = pop_pair();
2556 a = pop_pair();
2557 c = _gvn.transform( new AddLNode(a,b) );
2558 push_pair(c);
2559 break;
2560 case Bytecodes::_lsub:
2561 b = pop_pair();
2562 a = pop_pair();
2563 c = _gvn.transform( new SubLNode(a,b) );
2564 push_pair(c);
2565 break;
2566 case Bytecodes::_lcmp:
2567 // Safepoints are now inserted _before_ branches. The long-compare
2568 // bytecode painfully produces a 3-way value (-1,0,+1) which requires a
2569 // slew of control flow. These are usually followed by a CmpI vs zero and
2570 // a branch; this pattern then optimizes to the obvious long-compare and
2571 // branch. However, if the branch is backwards there's a Safepoint
2572 // inserted. The inserted Safepoint captures the JVM state at the
2573 // pre-branch point, i.e. it captures the 3-way value. Thus if a
2574 // long-compare is used to control a loop the debug info will force
2575 // computation of the 3-way value, even though the generated code uses a
2576 // long-compare and branch. We try to rectify the situation by inserting
2577 // a SafePoint here and have it dominate and kill the safepoint added at a
2578 // following backwards branch. At this point the JVM state merely holds 2
2579 // longs but not the 3-way value.
2580 if( UseLoopSafepoints ) {
2581 switch( iter().next_bc() ) {
2582 case Bytecodes::_ifgt:
2583 case Bytecodes::_iflt:
2584 case Bytecodes::_ifge:
2585 case Bytecodes::_ifle:
2586 case Bytecodes::_ifne:
2587 case Bytecodes::_ifeq:
2588 // If this is a backwards branch in the bytecodes, add Safepoint
2589 maybe_add_safepoint(iter().next_get_dest());
2590 default:
2591 break;
2592 }
2593 }
2594 b = pop_pair();
2595 a = pop_pair();
2596 c = _gvn.transform( new CmpL3Node( a, b ));
2597 push(c);
2598 break;
2599
2600 case Bytecodes::_lneg:
2601 a = pop_pair();
2602 b = _gvn.transform( new SubLNode(longcon(0),a));
2603 push_pair(b);
2604 break;
2605 case Bytecodes::_l2i:
2606 a = pop_pair();
2607 push( _gvn.transform( new ConvL2INode(a)));
2608 break;
2609 case Bytecodes::_i2l:
2610 a = pop();
2611 b = _gvn.transform( new ConvI2LNode(a));
2612 push_pair(b);
2613 break;
2614 case Bytecodes::_i2b:
2615 // Sign extend
2616 a = pop();
2617 a = _gvn.transform( new LShiftINode(a,_gvn.intcon(24)) );
2618 a = _gvn.transform( new RShiftINode(a,_gvn.intcon(24)) );
2619 push( a );
2620 break;
2621 case Bytecodes::_i2s:
2622 a = pop();
2623 a = _gvn.transform( new LShiftINode(a,_gvn.intcon(16)) );
2624 a = _gvn.transform( new RShiftINode(a,_gvn.intcon(16)) );
2625 push( a );
2626 break;
2627 case Bytecodes::_i2c:
2628 a = pop();
2629 push( _gvn.transform( new AndINode(a,_gvn.intcon(0xFFFF)) ) );
2630 break;
2631
2632 case Bytecodes::_i2f:
2633 a = pop();
2634 b = _gvn.transform( new ConvI2FNode(a) ) ;
2635 c = precision_rounding(b);
2636 push (b);
2637 break;
2638
2639 case Bytecodes::_i2d:
2640 a = pop();
2641 b = _gvn.transform( new ConvI2DNode(a));
2642 push_pair(b);
2643 break;
2644
2645 case Bytecodes::_iinc: // Increment local
2646 i = iter().get_index(); // Get local index
2647 set_local( i, _gvn.transform( new AddINode( _gvn.intcon(iter().get_iinc_con()), local(i) ) ) );
2648 break;
2649
2650 // Exit points of synchronized methods must have an unlock node
2651 case Bytecodes::_return:
2652 return_current(NULL);
2653 break;
2654
2655 case Bytecodes::_ireturn:
2656 case Bytecodes::_areturn:
2657 case Bytecodes::_freturn:
2658 return_current(pop());
2659 break;
2660 case Bytecodes::_lreturn:
2661 return_current(pop_pair());
2662 break;
2663 case Bytecodes::_dreturn:
2664 return_current(pop_pair());
2665 break;
2666
2667 case Bytecodes::_athrow:
2668 // null exception oop throws NULL pointer exception
2669 null_check(peek());
2670 if (stopped()) return;
2671 // Hook the thrown exception directly to subsequent handlers.
2672 if (BailoutToInterpreterForThrows) {
2673 // Keep method interpreted from now on.
2674 uncommon_trap(Deoptimization::Reason_unhandled,
2675 Deoptimization::Action_make_not_compilable);
2676 return;
2677 }
2678 if (env()->jvmti_can_post_on_exceptions()) {
2679 // check if we must post exception events, take uncommon trap if so (with must_throw = false)
2680 uncommon_trap_if_should_post_on_exceptions(Deoptimization::Reason_unhandled, false);
2681 }
2682 // Here if either can_post_on_exceptions or should_post_on_exceptions is false
2683 add_exception_state(make_exception_state(peek()));
2684 break;
2685
2686 case Bytecodes::_goto: // fall through
2687 case Bytecodes::_goto_w: {
2688 int target_bci = (bc() == Bytecodes::_goto) ? iter().get_dest() : iter().get_far_dest();
2689
2690 // If this is a backwards branch in the bytecodes, add Safepoint
2691 maybe_add_safepoint(target_bci);
2692
2693 // Update method data
2694 profile_taken_branch(target_bci);
2695
2696 // Merge the current control into the target basic block
2697 merge(target_bci);
2698
2699 // See if we can get some profile data and hand it off to the next block
2700 Block *target_block = block()->successor_for_bci(target_bci);
2701 if (target_block->pred_count() != 1) break;
2702 ciMethodData* methodData = method()->method_data();
2703 if (!methodData->is_mature()) break;
2704 ciProfileData* data = methodData->bci_to_data(bci());
2705 assert(data != NULL && data->is_JumpData(), "need JumpData for taken branch");
2706 int taken = ((ciJumpData*)data)->taken();
2707 taken = method()->scale_count(taken);
2708 target_block->set_count(taken);
2709 break;
2710 }
2711
2712 case Bytecodes::_ifnull: btest = BoolTest::eq; goto handle_if_null;
2713 case Bytecodes::_ifnonnull: btest = BoolTest::ne; goto handle_if_null;
2714 handle_if_null:
2715 // If this is a backwards branch in the bytecodes, add Safepoint
2716 maybe_add_safepoint(iter().get_dest());
2717 a = null();
2718 b = pop();
2719 if (!_gvn.type(b)->speculative_maybe_null() &&
2720 !too_many_traps(Deoptimization::Reason_speculate_null_check)) {
2721 inc_sp(1);
2722 Node* null_ctl = top();
2723 b = null_check_oop(b, &null_ctl, true, true, true);
2724 assert(null_ctl->is_top(), "no null control here");
2725 dec_sp(1);
2726 } else if (_gvn.type(b)->speculative_always_null() &&
2727 !too_many_traps(Deoptimization::Reason_speculate_null_assert)) {
2728 inc_sp(1);
2729 b = null_assert(b);
2730 dec_sp(1);
2731 }
2732 c = _gvn.transform( new CmpPNode(b, a) );
2733 do_ifnull(btest, c);
2734 break;
2735
2736 case Bytecodes::_if_acmpeq: btest = BoolTest::eq; goto handle_if_acmp;
2737 case Bytecodes::_if_acmpne: btest = BoolTest::ne; goto handle_if_acmp;
2738 handle_if_acmp:
2739 // If this is a backwards branch in the bytecodes, add Safepoint
2740 maybe_add_safepoint(iter().get_dest());
2741 a = access_resolve(pop(), 0);
2742 b = access_resolve(pop(), 0);
2743 c = _gvn.transform( new CmpPNode(b, a) );
2744 c = optimize_cmp_with_klass(c);
2745 do_if(btest, c);
2746 break;
2747
2748 case Bytecodes::_ifeq: btest = BoolTest::eq; goto handle_ifxx;
2749 case Bytecodes::_ifne: btest = BoolTest::ne; goto handle_ifxx;
2750 case Bytecodes::_iflt: btest = BoolTest::lt; goto handle_ifxx;
2751 case Bytecodes::_ifle: btest = BoolTest::le; goto handle_ifxx;
2752 case Bytecodes::_ifgt: btest = BoolTest::gt; goto handle_ifxx;
2753 case Bytecodes::_ifge: btest = BoolTest::ge; goto handle_ifxx;
2754 handle_ifxx:
2755 // If this is a backwards branch in the bytecodes, add Safepoint
2756 maybe_add_safepoint(iter().get_dest());
2757 a = _gvn.intcon(0);
2758 b = pop();
2759 c = _gvn.transform( new CmpINode(b, a) );
2760 do_if(btest, c);
2761 break;
2762
2763 case Bytecodes::_if_icmpeq: btest = BoolTest::eq; goto handle_if_icmp;
2764 case Bytecodes::_if_icmpne: btest = BoolTest::ne; goto handle_if_icmp;
2765 case Bytecodes::_if_icmplt: btest = BoolTest::lt; goto handle_if_icmp;
2766 case Bytecodes::_if_icmple: btest = BoolTest::le; goto handle_if_icmp;
2767 case Bytecodes::_if_icmpgt: btest = BoolTest::gt; goto handle_if_icmp;
2768 case Bytecodes::_if_icmpge: btest = BoolTest::ge; goto handle_if_icmp;
2769 handle_if_icmp:
2770 // If this is a backwards branch in the bytecodes, add Safepoint
2771 maybe_add_safepoint(iter().get_dest());
2772 a = pop();
2773 b = pop();
2774 c = _gvn.transform( new CmpINode( b, a ) );
2775 do_if(btest, c);
2776 break;
2777
2778 case Bytecodes::_tableswitch:
2779 do_tableswitch();
2780 break;
2781
2782 case Bytecodes::_lookupswitch:
2783 do_lookupswitch();
2784 break;
2785
2786 case Bytecodes::_invokestatic:
2787 case Bytecodes::_invokedynamic:
2788 case Bytecodes::_invokespecial:
2789 case Bytecodes::_invokevirtual:
2790 case Bytecodes::_invokeinterface:
2791 do_call();
2792 break;
2793 case Bytecodes::_checkcast:
2794 do_checkcast();
2795 break;
2796 case Bytecodes::_instanceof:
2797 do_instanceof();
2798 break;
2799 case Bytecodes::_anewarray:
2800 do_anewarray();
2801 break;
2802 case Bytecodes::_newarray:
2803 do_newarray((BasicType)iter().get_index());
2804 break;
2805 case Bytecodes::_multianewarray:
2806 do_multianewarray();
2807 break;
2808 case Bytecodes::_new:
2809 do_new();
2810 break;
2811
2812 case Bytecodes::_jsr:
2813 case Bytecodes::_jsr_w:
2814 do_jsr();
2815 break;
2816
2817 case Bytecodes::_ret:
2818 do_ret();
2819 break;
2820
2821
2822 case Bytecodes::_monitorenter:
2823 do_monitor_enter();
2824 break;
2825
2826 case Bytecodes::_monitorexit:
2827 do_monitor_exit();
2828 break;
2829
2830 case Bytecodes::_breakpoint:
2831 // Breakpoint set concurrently to compile
2832 // %%% use an uncommon trap?
2833 C->record_failure("breakpoint in method");
2834 return;
2835
2836 default:
2837 #ifndef PRODUCT
2838 map()->dump(99);
2839 #endif
2840 tty->print("\nUnhandled bytecode %s\n", Bytecodes::name(bc()) );
2841 ShouldNotReachHere();
2842 }
2843
2844 #ifndef PRODUCT
2845 IdealGraphPrinter *printer = C->printer();
2846 if (printer && printer->should_print(1)) {
2847 char buffer[256];
2848 jio_snprintf(buffer, sizeof(buffer), "Bytecode %d: %s", bci(), Bytecodes::name(bc()));
2849 bool old = printer->traverse_outs();
2850 printer->set_traverse_outs(true);
2851 printer->print_method(buffer, 4);
2852 printer->set_traverse_outs(old);
2853 }
2854 #endif
2855 }
2856