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