Tue, 11 Nov 2014 11:05:41 +0100
8056071: compiler/whitebox/IsMethodCompilableTest.java fails with 'method() is not compilable after 3 iterations'
Summary: Always use MDO if valid and always compile trivial methods with C1 if available.
Reviewed-by: kvn, iveresov
1 /*
2 * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 *
23 */
25 #include "precompiled.hpp"
26 #include "interpreter/bytecodeStream.hpp"
27 #include "oops/generateOopMap.hpp"
28 #include "oops/oop.inline.hpp"
29 #include "oops/symbol.hpp"
30 #include "runtime/handles.inline.hpp"
31 #include "runtime/java.hpp"
32 #include "runtime/relocator.hpp"
33 #include "utilities/bitMap.inline.hpp"
34 #include "prims/methodHandles.hpp"
36 //
37 //
38 // Compute stack layouts for each instruction in method.
39 //
40 // Problems:
41 // - What to do about jsr with different types of local vars?
42 // Need maps that are conditional on jsr path?
43 // - Jsr and exceptions should be done more efficiently (the retAddr stuff)
44 //
45 // Alternative:
46 // - Could extend verifier to provide this information.
47 // For: one fewer abstract interpreter to maintain. Against: the verifier
48 // solves a bigger problem so slower (undesirable to force verification of
49 // everything?).
50 //
51 // Algorithm:
52 // Partition bytecodes into basic blocks
53 // For each basic block: store entry state (vars, stack). For instructions
54 // inside basic blocks we do not store any state (instead we recompute it
55 // from state produced by previous instruction).
56 //
57 // Perform abstract interpretation of bytecodes over this lattice:
58 //
59 // _--'#'--_
60 // / / \ \
61 // / / \ \
62 // / | | \
63 // 'r' 'v' 'p' ' '
64 // \ | | /
65 // \ \ / /
66 // \ \ / /
67 // -- '@' --
68 //
69 // '#' top, result of conflict merge
70 // 'r' reference type
71 // 'v' value type
72 // 'p' pc type for jsr/ret
73 // ' ' uninitialized; never occurs on operand stack in Java
74 // '@' bottom/unexecuted; initial state each bytecode.
75 //
76 // Basic block headers are the only merge points. We use this iteration to
77 // compute the information:
78 //
79 // find basic blocks;
80 // initialize them with uninitialized state;
81 // initialize first BB according to method signature;
82 // mark first BB changed
83 // while (some BB is changed) do {
84 // perform abstract interpration of all bytecodes in BB;
85 // merge exit state of BB into entry state of all successor BBs,
86 // noting if any of these change;
87 // }
88 //
89 // One additional complication is necessary. The jsr instruction pushes
90 // a return PC on the stack (a 'p' type in the abstract interpretation).
91 // To be able to process "ret" bytecodes, we keep track of these return
92 // PC's in a 'retAddrs' structure in abstract interpreter context (when
93 // processing a "ret" bytecodes, it is not sufficient to know that it gets
94 // an argument of the right type 'p'; we need to know which address it
95 // returns to).
96 //
97 // (Note this comment is borrowed form the original author of the algorithm)
99 // ComputeCallStack
100 //
101 // Specialization of SignatureIterator - compute the effects of a call
102 //
103 class ComputeCallStack : public SignatureIterator {
104 CellTypeState *_effect;
105 int _idx;
107 void setup();
108 void set(CellTypeState state) { _effect[_idx++] = state; }
109 int length() { return _idx; };
111 virtual void do_bool () { set(CellTypeState::value); };
112 virtual void do_char () { set(CellTypeState::value); };
113 virtual void do_float () { set(CellTypeState::value); };
114 virtual void do_byte () { set(CellTypeState::value); };
115 virtual void do_short () { set(CellTypeState::value); };
116 virtual void do_int () { set(CellTypeState::value); };
117 virtual void do_void () { set(CellTypeState::bottom);};
118 virtual void do_object(int begin, int end) { set(CellTypeState::ref); };
119 virtual void do_array (int begin, int end) { set(CellTypeState::ref); };
121 void do_double() { set(CellTypeState::value);
122 set(CellTypeState::value); }
123 void do_long () { set(CellTypeState::value);
124 set(CellTypeState::value); }
126 public:
127 ComputeCallStack(Symbol* signature) : SignatureIterator(signature) {};
129 // Compute methods
130 int compute_for_parameters(bool is_static, CellTypeState *effect) {
131 _idx = 0;
132 _effect = effect;
134 if (!is_static)
135 effect[_idx++] = CellTypeState::ref;
137 iterate_parameters();
139 return length();
140 };
142 int compute_for_returntype(CellTypeState *effect) {
143 _idx = 0;
144 _effect = effect;
145 iterate_returntype();
146 set(CellTypeState::bottom); // Always terminate with a bottom state, so ppush works
148 return length();
149 }
150 };
152 //=========================================================================================
153 // ComputeEntryStack
154 //
155 // Specialization of SignatureIterator - in order to set up first stack frame
156 //
157 class ComputeEntryStack : public SignatureIterator {
158 CellTypeState *_effect;
159 int _idx;
161 void setup();
162 void set(CellTypeState state) { _effect[_idx++] = state; }
163 int length() { return _idx; };
165 virtual void do_bool () { set(CellTypeState::value); };
166 virtual void do_char () { set(CellTypeState::value); };
167 virtual void do_float () { set(CellTypeState::value); };
168 virtual void do_byte () { set(CellTypeState::value); };
169 virtual void do_short () { set(CellTypeState::value); };
170 virtual void do_int () { set(CellTypeState::value); };
171 virtual void do_void () { set(CellTypeState::bottom);};
172 virtual void do_object(int begin, int end) { set(CellTypeState::make_slot_ref(_idx)); }
173 virtual void do_array (int begin, int end) { set(CellTypeState::make_slot_ref(_idx)); }
175 void do_double() { set(CellTypeState::value);
176 set(CellTypeState::value); }
177 void do_long () { set(CellTypeState::value);
178 set(CellTypeState::value); }
180 public:
181 ComputeEntryStack(Symbol* signature) : SignatureIterator(signature) {};
183 // Compute methods
184 int compute_for_parameters(bool is_static, CellTypeState *effect) {
185 _idx = 0;
186 _effect = effect;
188 if (!is_static)
189 effect[_idx++] = CellTypeState::make_slot_ref(0);
191 iterate_parameters();
193 return length();
194 };
196 int compute_for_returntype(CellTypeState *effect) {
197 _idx = 0;
198 _effect = effect;
199 iterate_returntype();
200 set(CellTypeState::bottom); // Always terminate with a bottom state, so ppush works
202 return length();
203 }
204 };
206 //=====================================================================================
207 //
208 // Implementation of RetTable/RetTableEntry
209 //
210 // Contains function to itereate through all bytecodes
211 // and find all return entry points
212 //
213 int RetTable::_init_nof_entries = 10;
214 int RetTableEntry::_init_nof_jsrs = 5;
216 void RetTableEntry::add_delta(int bci, int delta) {
217 if (_target_bci > bci) _target_bci += delta;
219 for (int k = 0; k < _jsrs->length(); k++) {
220 int jsr = _jsrs->at(k);
221 if (jsr > bci) _jsrs->at_put(k, jsr+delta);
222 }
223 }
225 void RetTable::compute_ret_table(methodHandle method) {
226 BytecodeStream i(method);
227 Bytecodes::Code bytecode;
229 while( (bytecode = i.next()) >= 0) {
230 switch (bytecode) {
231 case Bytecodes::_jsr:
232 add_jsr(i.next_bci(), i.dest());
233 break;
234 case Bytecodes::_jsr_w:
235 add_jsr(i.next_bci(), i.dest_w());
236 break;
237 }
238 }
239 }
241 void RetTable::add_jsr(int return_bci, int target_bci) {
242 RetTableEntry* entry = _first;
244 // Scan table for entry
245 for (;entry && entry->target_bci() != target_bci; entry = entry->next());
247 if (!entry) {
248 // Allocate new entry and put in list
249 entry = new RetTableEntry(target_bci, _first);
250 _first = entry;
251 }
253 // Now "entry" is set. Make sure that the entry is initialized
254 // and has room for the new jsr.
255 entry->add_jsr(return_bci);
256 }
258 RetTableEntry* RetTable::find_jsrs_for_target(int targBci) {
259 RetTableEntry *cur = _first;
261 while(cur) {
262 assert(cur->target_bci() != -1, "sanity check");
263 if (cur->target_bci() == targBci) return cur;
264 cur = cur->next();
265 }
266 ShouldNotReachHere();
267 return NULL;
268 }
270 // The instruction at bci is changing size by "delta". Update the return map.
271 void RetTable::update_ret_table(int bci, int delta) {
272 RetTableEntry *cur = _first;
273 while(cur) {
274 cur->add_delta(bci, delta);
275 cur = cur->next();
276 }
277 }
279 //
280 // Celltype state
281 //
283 CellTypeState CellTypeState::bottom = CellTypeState::make_bottom();
284 CellTypeState CellTypeState::uninit = CellTypeState::make_any(uninit_value);
285 CellTypeState CellTypeState::ref = CellTypeState::make_any(ref_conflict);
286 CellTypeState CellTypeState::value = CellTypeState::make_any(val_value);
287 CellTypeState CellTypeState::refUninit = CellTypeState::make_any(ref_conflict | uninit_value);
288 CellTypeState CellTypeState::top = CellTypeState::make_top();
289 CellTypeState CellTypeState::addr = CellTypeState::make_any(addr_conflict);
291 // Commonly used constants
292 static CellTypeState epsilonCTS[1] = { CellTypeState::bottom };
293 static CellTypeState refCTS = CellTypeState::ref;
294 static CellTypeState valCTS = CellTypeState::value;
295 static CellTypeState vCTS[2] = { CellTypeState::value, CellTypeState::bottom };
296 static CellTypeState rCTS[2] = { CellTypeState::ref, CellTypeState::bottom };
297 static CellTypeState rrCTS[3] = { CellTypeState::ref, CellTypeState::ref, CellTypeState::bottom };
298 static CellTypeState vrCTS[3] = { CellTypeState::value, CellTypeState::ref, CellTypeState::bottom };
299 static CellTypeState vvCTS[3] = { CellTypeState::value, CellTypeState::value, CellTypeState::bottom };
300 static CellTypeState rvrCTS[4] = { CellTypeState::ref, CellTypeState::value, CellTypeState::ref, CellTypeState::bottom };
301 static CellTypeState vvrCTS[4] = { CellTypeState::value, CellTypeState::value, CellTypeState::ref, CellTypeState::bottom };
302 static CellTypeState vvvCTS[4] = { CellTypeState::value, CellTypeState::value, CellTypeState::value, CellTypeState::bottom };
303 static CellTypeState vvvrCTS[5] = { CellTypeState::value, CellTypeState::value, CellTypeState::value, CellTypeState::ref, CellTypeState::bottom };
304 static CellTypeState vvvvCTS[5] = { CellTypeState::value, CellTypeState::value, CellTypeState::value, CellTypeState::value, CellTypeState::bottom };
306 char CellTypeState::to_char() const {
307 if (can_be_reference()) {
308 if (can_be_value() || can_be_address())
309 return '#'; // Conflict that needs to be rewritten
310 else
311 return 'r';
312 } else if (can_be_value())
313 return 'v';
314 else if (can_be_address())
315 return 'p';
316 else if (can_be_uninit())
317 return ' ';
318 else
319 return '@';
320 }
323 // Print a detailed CellTypeState. Indicate all bits that are set. If
324 // the CellTypeState represents an address or a reference, print the
325 // value of the additional information.
326 void CellTypeState::print(outputStream *os) {
327 if (can_be_address()) {
328 os->print("(p");
329 } else {
330 os->print("( ");
331 }
332 if (can_be_reference()) {
333 os->print("r");
334 } else {
335 os->print(" ");
336 }
337 if (can_be_value()) {
338 os->print("v");
339 } else {
340 os->print(" ");
341 }
342 if (can_be_uninit()) {
343 os->print("u|");
344 } else {
345 os->print(" |");
346 }
347 if (is_info_top()) {
348 os->print("Top)");
349 } else if (is_info_bottom()) {
350 os->print("Bot)");
351 } else {
352 if (is_reference()) {
353 int info = get_info();
354 int data = info & ~(ref_not_lock_bit | ref_slot_bit);
355 if (info & ref_not_lock_bit) {
356 // Not a monitor lock reference.
357 if (info & ref_slot_bit) {
358 // slot
359 os->print("slot%d)", data);
360 } else {
361 // line
362 os->print("line%d)", data);
363 }
364 } else {
365 // lock
366 os->print("lock%d)", data);
367 }
368 } else {
369 os->print("%d)", get_info());
370 }
371 }
372 }
374 //
375 // Basicblock handling methods
376 //
378 void GenerateOopMap ::initialize_bb() {
379 _gc_points = 0;
380 _bb_count = 0;
381 _bb_hdr_bits.clear();
382 _bb_hdr_bits.resize(method()->code_size());
383 }
385 void GenerateOopMap::bb_mark_fct(GenerateOopMap *c, int bci, int *data) {
386 assert(bci>= 0 && bci < c->method()->code_size(), "index out of bounds");
387 if (c->is_bb_header(bci))
388 return;
390 if (TraceNewOopMapGeneration) {
391 tty->print_cr("Basicblock#%d begins at: %d", c->_bb_count, bci);
392 }
393 c->set_bbmark_bit(bci);
394 c->_bb_count++;
395 }
398 void GenerateOopMap::mark_bbheaders_and_count_gc_points() {
399 initialize_bb();
401 bool fellThrough = false; // False to get first BB marked.
403 // First mark all exception handlers as start of a basic-block
404 ExceptionTable excps(method());
405 for(int i = 0; i < excps.length(); i ++) {
406 bb_mark_fct(this, excps.handler_pc(i), NULL);
407 }
409 // Then iterate through the code
410 BytecodeStream bcs(_method);
411 Bytecodes::Code bytecode;
413 while( (bytecode = bcs.next()) >= 0) {
414 int bci = bcs.bci();
416 if (!fellThrough)
417 bb_mark_fct(this, bci, NULL);
419 fellThrough = jump_targets_do(&bcs, &GenerateOopMap::bb_mark_fct, NULL);
421 /* We will also mark successors of jsr's as basic block headers. */
422 switch (bytecode) {
423 case Bytecodes::_jsr:
424 assert(!fellThrough, "should not happen");
425 bb_mark_fct(this, bci + Bytecodes::length_for(bytecode), NULL);
426 break;
427 case Bytecodes::_jsr_w:
428 assert(!fellThrough, "should not happen");
429 bb_mark_fct(this, bci + Bytecodes::length_for(bytecode), NULL);
430 break;
431 }
433 if (possible_gc_point(&bcs))
434 _gc_points++;
435 }
436 }
438 void GenerateOopMap::reachable_basicblock(GenerateOopMap *c, int bci, int *data) {
439 assert(bci>= 0 && bci < c->method()->code_size(), "index out of bounds");
440 BasicBlock* bb = c->get_basic_block_at(bci);
441 if (bb->is_dead()) {
442 bb->mark_as_alive();
443 *data = 1; // Mark basicblock as changed
444 }
445 }
448 void GenerateOopMap::mark_reachable_code() {
449 int change = 1; // int to get function pointers to work
451 // Mark entry basic block as alive and all exception handlers
452 _basic_blocks[0].mark_as_alive();
453 ExceptionTable excps(method());
454 for(int i = 0; i < excps.length(); i++) {
455 BasicBlock *bb = get_basic_block_at(excps.handler_pc(i));
456 // If block is not already alive (due to multiple exception handlers to same bb), then
457 // make it alive
458 if (bb->is_dead()) bb->mark_as_alive();
459 }
461 BytecodeStream bcs(_method);
463 // Iterate through all basic blocks until we reach a fixpoint
464 while (change) {
465 change = 0;
467 for (int i = 0; i < _bb_count; i++) {
468 BasicBlock *bb = &_basic_blocks[i];
469 if (bb->is_alive()) {
470 // Position bytecodestream at last bytecode in basicblock
471 bcs.set_start(bb->_end_bci);
472 bcs.next();
473 Bytecodes::Code bytecode = bcs.code();
474 int bci = bcs.bci();
475 assert(bci == bb->_end_bci, "wrong bci");
477 bool fell_through = jump_targets_do(&bcs, &GenerateOopMap::reachable_basicblock, &change);
479 // We will also mark successors of jsr's as alive.
480 switch (bytecode) {
481 case Bytecodes::_jsr:
482 case Bytecodes::_jsr_w:
483 assert(!fell_through, "should not happen");
484 reachable_basicblock(this, bci + Bytecodes::length_for(bytecode), &change);
485 break;
486 }
487 if (fell_through) {
488 // Mark successor as alive
489 if (bb[1].is_dead()) {
490 bb[1].mark_as_alive();
491 change = 1;
492 }
493 }
494 }
495 }
496 }
497 }
499 /* If the current instruction in "c" has no effect on control flow,
500 returns "true". Otherwise, calls "jmpFct" one or more times, with
501 "c", an appropriate "pcDelta", and "data" as arguments, then
502 returns "false". There is one exception: if the current
503 instruction is a "ret", returns "false" without calling "jmpFct".
504 Arrangements for tracking the control flow of a "ret" must be made
505 externally. */
506 bool GenerateOopMap::jump_targets_do(BytecodeStream *bcs, jmpFct_t jmpFct, int *data) {
507 int bci = bcs->bci();
509 switch (bcs->code()) {
510 case Bytecodes::_ifeq:
511 case Bytecodes::_ifne:
512 case Bytecodes::_iflt:
513 case Bytecodes::_ifge:
514 case Bytecodes::_ifgt:
515 case Bytecodes::_ifle:
516 case Bytecodes::_if_icmpeq:
517 case Bytecodes::_if_icmpne:
518 case Bytecodes::_if_icmplt:
519 case Bytecodes::_if_icmpge:
520 case Bytecodes::_if_icmpgt:
521 case Bytecodes::_if_icmple:
522 case Bytecodes::_if_acmpeq:
523 case Bytecodes::_if_acmpne:
524 case Bytecodes::_ifnull:
525 case Bytecodes::_ifnonnull:
526 (*jmpFct)(this, bcs->dest(), data);
527 (*jmpFct)(this, bci + 3, data);
528 break;
530 case Bytecodes::_goto:
531 (*jmpFct)(this, bcs->dest(), data);
532 break;
533 case Bytecodes::_goto_w:
534 (*jmpFct)(this, bcs->dest_w(), data);
535 break;
536 case Bytecodes::_tableswitch:
537 { Bytecode_tableswitch tableswitch(method(), bcs->bcp());
538 int len = tableswitch.length();
540 (*jmpFct)(this, bci + tableswitch.default_offset(), data); /* Default. jump address */
541 while (--len >= 0) {
542 (*jmpFct)(this, bci + tableswitch.dest_offset_at(len), data);
543 }
544 break;
545 }
547 case Bytecodes::_lookupswitch:
548 { Bytecode_lookupswitch lookupswitch(method(), bcs->bcp());
549 int npairs = lookupswitch.number_of_pairs();
550 (*jmpFct)(this, bci + lookupswitch.default_offset(), data); /* Default. */
551 while(--npairs >= 0) {
552 LookupswitchPair pair = lookupswitch.pair_at(npairs);
553 (*jmpFct)(this, bci + pair.offset(), data);
554 }
555 break;
556 }
557 case Bytecodes::_jsr:
558 assert(bcs->is_wide()==false, "sanity check");
559 (*jmpFct)(this, bcs->dest(), data);
563 break;
564 case Bytecodes::_jsr_w:
565 (*jmpFct)(this, bcs->dest_w(), data);
566 break;
567 case Bytecodes::_wide:
568 ShouldNotReachHere();
569 return true;
570 break;
571 case Bytecodes::_athrow:
572 case Bytecodes::_ireturn:
573 case Bytecodes::_lreturn:
574 case Bytecodes::_freturn:
575 case Bytecodes::_dreturn:
576 case Bytecodes::_areturn:
577 case Bytecodes::_return:
578 case Bytecodes::_ret:
579 break;
580 default:
581 return true;
582 }
583 return false;
584 }
586 /* Requires "pc" to be the head of a basic block; returns that basic
587 block. */
588 BasicBlock *GenerateOopMap::get_basic_block_at(int bci) const {
589 BasicBlock* bb = get_basic_block_containing(bci);
590 assert(bb->_bci == bci, "should have found BB");
591 return bb;
592 }
594 // Requires "pc" to be the start of an instruction; returns the basic
595 // block containing that instruction. */
596 BasicBlock *GenerateOopMap::get_basic_block_containing(int bci) const {
597 BasicBlock *bbs = _basic_blocks;
598 int lo = 0, hi = _bb_count - 1;
600 while (lo <= hi) {
601 int m = (lo + hi) / 2;
602 int mbci = bbs[m]._bci;
603 int nbci;
605 if ( m == _bb_count-1) {
606 assert( bci >= mbci && bci < method()->code_size(), "sanity check failed");
607 return bbs+m;
608 } else {
609 nbci = bbs[m+1]._bci;
610 }
612 if ( mbci <= bci && bci < nbci) {
613 return bbs+m;
614 } else if (mbci < bci) {
615 lo = m + 1;
616 } else {
617 assert(mbci > bci, "sanity check");
618 hi = m - 1;
619 }
620 }
622 fatal("should have found BB");
623 return NULL;
624 }
626 void GenerateOopMap::restore_state(BasicBlock *bb)
627 {
628 memcpy(_state, bb->_state, _state_len*sizeof(CellTypeState));
629 _stack_top = bb->_stack_top;
630 _monitor_top = bb->_monitor_top;
631 }
633 int GenerateOopMap::next_bb_start_pc(BasicBlock *bb) {
634 int bbNum = bb - _basic_blocks + 1;
635 if (bbNum == _bb_count)
636 return method()->code_size();
638 return _basic_blocks[bbNum]._bci;
639 }
641 //
642 // CellType handling methods
643 //
645 // Allocate memory and throw LinkageError if failure.
646 #define ALLOC_RESOURCE_ARRAY(var, type, count) \
647 var = NEW_RESOURCE_ARRAY_RETURN_NULL(type, count); \
648 if (var == NULL) { \
649 report_error("Cannot reserve enough memory to analyze this method"); \
650 return; \
651 }
654 void GenerateOopMap::init_state() {
655 _state_len = _max_locals + _max_stack + _max_monitors;
656 ALLOC_RESOURCE_ARRAY(_state, CellTypeState, _state_len);
657 memset(_state, 0, _state_len * sizeof(CellTypeState));
658 int count = MAX3(_max_locals, _max_stack, _max_monitors) + 1/*for null terminator char */;
659 ALLOC_RESOURCE_ARRAY(_state_vec_buf, char, count);
660 }
662 void GenerateOopMap::make_context_uninitialized() {
663 CellTypeState* vs = vars();
665 for (int i = 0; i < _max_locals; i++)
666 vs[i] = CellTypeState::uninit;
668 _stack_top = 0;
669 _monitor_top = 0;
670 }
672 int GenerateOopMap::methodsig_to_effect(Symbol* signature, bool is_static, CellTypeState* effect) {
673 ComputeEntryStack ces(signature);
674 return ces.compute_for_parameters(is_static, effect);
675 }
677 // Return result of merging cts1 and cts2.
678 CellTypeState CellTypeState::merge(CellTypeState cts, int slot) const {
679 CellTypeState result;
681 assert(!is_bottom() && !cts.is_bottom(),
682 "merge of bottom values is handled elsewhere");
684 result._state = _state | cts._state;
686 // If the top bit is set, we don't need to do any more work.
687 if (!result.is_info_top()) {
688 assert((result.can_be_address() || result.can_be_reference()),
689 "only addresses and references have non-top info");
691 if (!equal(cts)) {
692 // The two values being merged are different. Raise to top.
693 if (result.is_reference()) {
694 result = CellTypeState::make_slot_ref(slot);
695 } else {
696 result._state |= info_conflict;
697 }
698 }
699 }
700 assert(result.is_valid_state(), "checking that CTS merge maintains legal state");
702 return result;
703 }
705 // Merge the variable state for locals and stack from cts into bbts.
706 bool GenerateOopMap::merge_local_state_vectors(CellTypeState* cts,
707 CellTypeState* bbts) {
708 int i;
709 int len = _max_locals + _stack_top;
710 bool change = false;
712 for (i = len - 1; i >= 0; i--) {
713 CellTypeState v = cts[i].merge(bbts[i], i);
714 change = change || !v.equal(bbts[i]);
715 bbts[i] = v;
716 }
718 return change;
719 }
721 // Merge the monitor stack state from cts into bbts.
722 bool GenerateOopMap::merge_monitor_state_vectors(CellTypeState* cts,
723 CellTypeState* bbts) {
724 bool change = false;
725 if (_max_monitors > 0 && _monitor_top != bad_monitors) {
726 // If there are no monitors in the program, or there has been
727 // a monitor matching error before this point in the program,
728 // then we do not merge in the monitor state.
730 int base = _max_locals + _max_stack;
731 int len = base + _monitor_top;
732 for (int i = len - 1; i >= base; i--) {
733 CellTypeState v = cts[i].merge(bbts[i], i);
735 // Can we prove that, when there has been a change, it will already
736 // have been detected at this point? That would make this equal
737 // check here unnecessary.
738 change = change || !v.equal(bbts[i]);
739 bbts[i] = v;
740 }
741 }
743 return change;
744 }
746 void GenerateOopMap::copy_state(CellTypeState *dst, CellTypeState *src) {
747 int len = _max_locals + _stack_top;
748 for (int i = 0; i < len; i++) {
749 if (src[i].is_nonlock_reference()) {
750 dst[i] = CellTypeState::make_slot_ref(i);
751 } else {
752 dst[i] = src[i];
753 }
754 }
755 if (_max_monitors > 0 && _monitor_top != bad_monitors) {
756 int base = _max_locals + _max_stack;
757 len = base + _monitor_top;
758 for (int i = base; i < len; i++) {
759 dst[i] = src[i];
760 }
761 }
762 }
765 // Merge the states for the current block and the next. As long as a
766 // block is reachable the locals and stack must be merged. If the
767 // stack heights don't match then this is a verification error and
768 // it's impossible to interpret the code. Simultaneously monitor
769 // states are being check to see if they nest statically. If monitor
770 // depths match up then their states are merged. Otherwise the
771 // mismatch is simply recorded and interpretation continues since
772 // monitor matching is purely informational and doesn't say anything
773 // about the correctness of the code.
774 void GenerateOopMap::merge_state_into_bb(BasicBlock *bb) {
775 guarantee(bb != NULL, "null basicblock");
776 assert(bb->is_alive(), "merging state into a dead basicblock");
778 if (_stack_top == bb->_stack_top) {
779 // always merge local state even if monitors don't match.
780 if (merge_local_state_vectors(_state, bb->_state)) {
781 bb->set_changed(true);
782 }
783 if (_monitor_top == bb->_monitor_top) {
784 // monitors still match so continue merging monitor states.
785 if (merge_monitor_state_vectors(_state, bb->_state)) {
786 bb->set_changed(true);
787 }
788 } else {
789 if (TraceMonitorMismatch) {
790 report_monitor_mismatch("monitor stack height merge conflict");
791 }
792 // When the monitor stacks are not matched, we set _monitor_top to
793 // bad_monitors. This signals that, from here on, the monitor stack cannot
794 // be trusted. In particular, monitorexit bytecodes may throw
795 // exceptions. We mark this block as changed so that the change
796 // propagates properly.
797 bb->_monitor_top = bad_monitors;
798 bb->set_changed(true);
799 _monitor_safe = false;
800 }
801 } else if (!bb->is_reachable()) {
802 // First time we look at this BB
803 copy_state(bb->_state, _state);
804 bb->_stack_top = _stack_top;
805 bb->_monitor_top = _monitor_top;
806 bb->set_changed(true);
807 } else {
808 verify_error("stack height conflict: %d vs. %d", _stack_top, bb->_stack_top);
809 }
810 }
812 void GenerateOopMap::merge_state(GenerateOopMap *gom, int bci, int* data) {
813 gom->merge_state_into_bb(gom->get_basic_block_at(bci));
814 }
816 void GenerateOopMap::set_var(int localNo, CellTypeState cts) {
817 assert(cts.is_reference() || cts.is_value() || cts.is_address(),
818 "wrong celltypestate");
819 if (localNo < 0 || localNo > _max_locals) {
820 verify_error("variable write error: r%d", localNo);
821 return;
822 }
823 vars()[localNo] = cts;
824 }
826 CellTypeState GenerateOopMap::get_var(int localNo) {
827 assert(localNo < _max_locals + _nof_refval_conflicts, "variable read error");
828 if (localNo < 0 || localNo > _max_locals) {
829 verify_error("variable read error: r%d", localNo);
830 return valCTS; // just to pick something;
831 }
832 return vars()[localNo];
833 }
835 CellTypeState GenerateOopMap::pop() {
836 if ( _stack_top <= 0) {
837 verify_error("stack underflow");
838 return valCTS; // just to pick something
839 }
840 return stack()[--_stack_top];
841 }
843 void GenerateOopMap::push(CellTypeState cts) {
844 if ( _stack_top >= _max_stack) {
845 verify_error("stack overflow");
846 return;
847 }
848 stack()[_stack_top++] = cts;
849 }
851 CellTypeState GenerateOopMap::monitor_pop() {
852 assert(_monitor_top != bad_monitors, "monitor_pop called on error monitor stack");
853 if (_monitor_top == 0) {
854 // We have detected a pop of an empty monitor stack.
855 _monitor_safe = false;
856 _monitor_top = bad_monitors;
858 if (TraceMonitorMismatch) {
859 report_monitor_mismatch("monitor stack underflow");
860 }
861 return CellTypeState::ref; // just to keep the analysis going.
862 }
863 return monitors()[--_monitor_top];
864 }
866 void GenerateOopMap::monitor_push(CellTypeState cts) {
867 assert(_monitor_top != bad_monitors, "monitor_push called on error monitor stack");
868 if (_monitor_top >= _max_monitors) {
869 // Some monitorenter is being executed more than once.
870 // This means that the monitor stack cannot be simulated.
871 _monitor_safe = false;
872 _monitor_top = bad_monitors;
874 if (TraceMonitorMismatch) {
875 report_monitor_mismatch("monitor stack overflow");
876 }
877 return;
878 }
879 monitors()[_monitor_top++] = cts;
880 }
882 //
883 // Interpretation handling methods
884 //
886 void GenerateOopMap::do_interpretation()
887 {
888 // "i" is just for debugging, so we can detect cases where this loop is
889 // iterated more than once.
890 int i = 0;
891 do {
892 #ifndef PRODUCT
893 if (TraceNewOopMapGeneration) {
894 tty->print("\n\nIteration #%d of do_interpretation loop, method:\n", i);
895 method()->print_name(tty);
896 tty->print("\n\n");
897 }
898 #endif
899 _conflict = false;
900 _monitor_safe = true;
901 // init_state is now called from init_basic_blocks. The length of a
902 // state vector cannot be determined until we have made a pass through
903 // the bytecodes counting the possible monitor entries.
904 if (!_got_error) init_basic_blocks();
905 if (!_got_error) setup_method_entry_state();
906 if (!_got_error) interp_all();
907 if (!_got_error) rewrite_refval_conflicts();
908 i++;
909 } while (_conflict && !_got_error);
910 }
912 void GenerateOopMap::init_basic_blocks() {
913 // Note: Could consider reserving only the needed space for each BB's state
914 // (entry stack may not be of maximal height for every basic block).
915 // But cumbersome since we don't know the stack heights yet. (Nor the
916 // monitor stack heights...)
918 ALLOC_RESOURCE_ARRAY(_basic_blocks, BasicBlock, _bb_count);
920 // Make a pass through the bytecodes. Count the number of monitorenters.
921 // This can be used an upper bound on the monitor stack depth in programs
922 // which obey stack discipline with their monitor usage. Initialize the
923 // known information about basic blocks.
924 BytecodeStream j(_method);
925 Bytecodes::Code bytecode;
927 int bbNo = 0;
928 int monitor_count = 0;
929 int prev_bci = -1;
930 while( (bytecode = j.next()) >= 0) {
931 if (j.code() == Bytecodes::_monitorenter) {
932 monitor_count++;
933 }
935 int bci = j.bci();
936 if (is_bb_header(bci)) {
937 // Initialize the basicblock structure
938 BasicBlock *bb = _basic_blocks + bbNo;
939 bb->_bci = bci;
940 bb->_max_locals = _max_locals;
941 bb->_max_stack = _max_stack;
942 bb->set_changed(false);
943 bb->_stack_top = BasicBlock::_dead_basic_block; // Initialize all basicblocks are dead.
944 bb->_monitor_top = bad_monitors;
946 if (bbNo > 0) {
947 _basic_blocks[bbNo - 1]._end_bci = prev_bci;
948 }
950 bbNo++;
951 }
952 // Remember prevous bci.
953 prev_bci = bci;
954 }
955 // Set
956 _basic_blocks[bbNo-1]._end_bci = prev_bci;
959 // Check that the correct number of basicblocks was found
960 if (bbNo !=_bb_count) {
961 if (bbNo < _bb_count) {
962 verify_error("jump into the middle of instruction?");
963 return;
964 } else {
965 verify_error("extra basic blocks - should not happen?");
966 return;
967 }
968 }
970 _max_monitors = monitor_count;
972 // Now that we have a bound on the depth of the monitor stack, we can
973 // initialize the CellTypeState-related information.
974 init_state();
976 // We allocate space for all state-vectors for all basicblocks in one huge
977 // chunk. Then in the next part of the code, we set a pointer in each
978 // _basic_block that points to each piece.
980 // The product of bbNo and _state_len can get large if there are lots of
981 // basic blocks and stack/locals/monitors. Need to check to make sure
982 // we don't overflow the capacity of a pointer.
983 if ((unsigned)bbNo > UINTPTR_MAX / sizeof(CellTypeState) / _state_len) {
984 report_error("The amount of memory required to analyze this method "
985 "exceeds addressable range");
986 return;
987 }
989 CellTypeState *basicBlockState;
990 ALLOC_RESOURCE_ARRAY(basicBlockState, CellTypeState, bbNo * _state_len);
991 memset(basicBlockState, 0, bbNo * _state_len * sizeof(CellTypeState));
993 // Make a pass over the basicblocks and assign their state vectors.
994 for (int blockNum=0; blockNum < bbNo; blockNum++) {
995 BasicBlock *bb = _basic_blocks + blockNum;
996 bb->_state = basicBlockState + blockNum * _state_len;
998 #ifdef ASSERT
999 if (blockNum + 1 < bbNo) {
1000 address bcp = _method->bcp_from(bb->_end_bci);
1001 int bc_len = Bytecodes::java_length_at(_method(), bcp);
1002 assert(bb->_end_bci + bc_len == bb[1]._bci, "unmatched bci info in basicblock");
1003 }
1004 #endif
1005 }
1006 #ifdef ASSERT
1007 { BasicBlock *bb = &_basic_blocks[bbNo-1];
1008 address bcp = _method->bcp_from(bb->_end_bci);
1009 int bc_len = Bytecodes::java_length_at(_method(), bcp);
1010 assert(bb->_end_bci + bc_len == _method->code_size(), "wrong end bci");
1011 }
1012 #endif
1014 // Mark all alive blocks
1015 mark_reachable_code();
1016 }
1018 void GenerateOopMap::setup_method_entry_state() {
1020 // Initialize all locals to 'uninit' and set stack-height to 0
1021 make_context_uninitialized();
1023 // Initialize CellState type of arguments
1024 methodsig_to_effect(method()->signature(), method()->is_static(), vars());
1026 // If some references must be pre-assigned to null, then set that up
1027 initialize_vars();
1029 // This is the start state
1030 merge_state_into_bb(&_basic_blocks[0]);
1032 assert(_basic_blocks[0].changed(), "we are not getting off the ground");
1033 }
1035 // The instruction at bci is changing size by "delta". Update the basic blocks.
1036 void GenerateOopMap::update_basic_blocks(int bci, int delta,
1037 int new_method_size) {
1038 assert(new_method_size >= method()->code_size() + delta,
1039 "new method size is too small");
1041 BitMap::bm_word_t* new_bb_hdr_bits =
1042 NEW_RESOURCE_ARRAY(BitMap::bm_word_t,
1043 BitMap::word_align_up(new_method_size));
1044 _bb_hdr_bits.set_map(new_bb_hdr_bits);
1045 _bb_hdr_bits.set_size(new_method_size);
1046 _bb_hdr_bits.clear();
1049 for(int k = 0; k < _bb_count; k++) {
1050 if (_basic_blocks[k]._bci > bci) {
1051 _basic_blocks[k]._bci += delta;
1052 _basic_blocks[k]._end_bci += delta;
1053 }
1054 _bb_hdr_bits.at_put(_basic_blocks[k]._bci, true);
1055 }
1056 }
1058 //
1059 // Initvars handling
1060 //
1062 void GenerateOopMap::initialize_vars() {
1063 for (int k = 0; k < _init_vars->length(); k++)
1064 _state[_init_vars->at(k)] = CellTypeState::make_slot_ref(k);
1065 }
1067 void GenerateOopMap::add_to_ref_init_set(int localNo) {
1069 if (TraceNewOopMapGeneration)
1070 tty->print_cr("Added init vars: %d", localNo);
1072 // Is it already in the set?
1073 if (_init_vars->contains(localNo) )
1074 return;
1076 _init_vars->append(localNo);
1077 }
1079 //
1080 // Interpreration code
1081 //
1083 void GenerateOopMap::interp_all() {
1084 bool change = true;
1086 while (change && !_got_error) {
1087 change = false;
1088 for (int i = 0; i < _bb_count && !_got_error; i++) {
1089 BasicBlock *bb = &_basic_blocks[i];
1090 if (bb->changed()) {
1091 if (_got_error) return;
1092 change = true;
1093 bb->set_changed(false);
1094 interp_bb(bb);
1095 }
1096 }
1097 }
1098 }
1100 void GenerateOopMap::interp_bb(BasicBlock *bb) {
1102 // We do not want to do anything in case the basic-block has not been initialized. This
1103 // will happen in the case where there is dead-code hang around in a method.
1104 assert(bb->is_reachable(), "should be reachable or deadcode exist");
1105 restore_state(bb);
1107 BytecodeStream itr(_method);
1109 // Set iterator interval to be the current basicblock
1110 int lim_bci = next_bb_start_pc(bb);
1111 itr.set_interval(bb->_bci, lim_bci);
1112 assert(lim_bci != bb->_bci, "must be at least one instruction in a basicblock");
1113 itr.next(); // read first instruction
1115 // Iterates through all bytecodes except the last in a basic block.
1116 // We handle the last one special, since there is controlflow change.
1117 while(itr.next_bci() < lim_bci && !_got_error) {
1118 if (_has_exceptions || _monitor_top != 0) {
1119 // We do not need to interpret the results of exceptional
1120 // continuation from this instruction when the method has no
1121 // exception handlers and the monitor stack is currently
1122 // empty.
1123 do_exception_edge(&itr);
1124 }
1125 interp1(&itr);
1126 itr.next();
1127 }
1129 // Handle last instruction.
1130 if (!_got_error) {
1131 assert(itr.next_bci() == lim_bci, "must point to end");
1132 if (_has_exceptions || _monitor_top != 0) {
1133 do_exception_edge(&itr);
1134 }
1135 interp1(&itr);
1137 bool fall_through = jump_targets_do(&itr, GenerateOopMap::merge_state, NULL);
1138 if (_got_error) return;
1140 if (itr.code() == Bytecodes::_ret) {
1141 assert(!fall_through, "cannot be set if ret instruction");
1142 // Automatically handles 'wide' ret indicies
1143 ret_jump_targets_do(&itr, GenerateOopMap::merge_state, itr.get_index(), NULL);
1144 } else if (fall_through) {
1145 // Hit end of BB, but the instr. was a fall-through instruction,
1146 // so perform transition as if the BB ended in a "jump".
1147 if (lim_bci != bb[1]._bci) {
1148 verify_error("bytecodes fell through last instruction");
1149 return;
1150 }
1151 merge_state_into_bb(bb + 1);
1152 }
1153 }
1154 }
1156 void GenerateOopMap::do_exception_edge(BytecodeStream* itr) {
1157 // Only check exception edge, if bytecode can trap
1158 if (!Bytecodes::can_trap(itr->code())) return;
1159 switch (itr->code()) {
1160 case Bytecodes::_aload_0:
1161 // These bytecodes can trap for rewriting. We need to assume that
1162 // they do not throw exceptions to make the monitor analysis work.
1163 return;
1165 case Bytecodes::_ireturn:
1166 case Bytecodes::_lreturn:
1167 case Bytecodes::_freturn:
1168 case Bytecodes::_dreturn:
1169 case Bytecodes::_areturn:
1170 case Bytecodes::_return:
1171 // If the monitor stack height is not zero when we leave the method,
1172 // then we are either exiting with a non-empty stack or we have
1173 // found monitor trouble earlier in our analysis. In either case,
1174 // assume an exception could be taken here.
1175 if (_monitor_top == 0) {
1176 return;
1177 }
1178 break;
1180 case Bytecodes::_monitorexit:
1181 // If the monitor stack height is bad_monitors, then we have detected a
1182 // monitor matching problem earlier in the analysis. If the
1183 // monitor stack height is 0, we are about to pop a monitor
1184 // off of an empty stack. In either case, the bytecode
1185 // could throw an exception.
1186 if (_monitor_top != bad_monitors && _monitor_top != 0) {
1187 return;
1188 }
1189 break;
1190 }
1192 if (_has_exceptions) {
1193 int bci = itr->bci();
1194 ExceptionTable exct(method());
1195 for(int i = 0; i< exct.length(); i++) {
1196 int start_pc = exct.start_pc(i);
1197 int end_pc = exct.end_pc(i);
1198 int handler_pc = exct.handler_pc(i);
1199 int catch_type = exct.catch_type_index(i);
1201 if (start_pc <= bci && bci < end_pc) {
1202 BasicBlock *excBB = get_basic_block_at(handler_pc);
1203 guarantee(excBB != NULL, "no basic block for exception");
1204 CellTypeState *excStk = excBB->stack();
1205 CellTypeState *cOpStck = stack();
1206 CellTypeState cOpStck_0 = cOpStck[0];
1207 int cOpStackTop = _stack_top;
1209 // Exception stacks are always the same.
1210 assert(method()->max_stack() > 0, "sanity check");
1212 // We remembered the size and first element of "cOpStck"
1213 // above; now we temporarily set them to the appropriate
1214 // values for an exception handler. */
1215 cOpStck[0] = CellTypeState::make_slot_ref(_max_locals);
1216 _stack_top = 1;
1218 merge_state_into_bb(excBB);
1220 // Now undo the temporary change.
1221 cOpStck[0] = cOpStck_0;
1222 _stack_top = cOpStackTop;
1224 // If this is a "catch all" handler, then we do not need to
1225 // consider any additional handlers.
1226 if (catch_type == 0) {
1227 return;
1228 }
1229 }
1230 }
1231 }
1233 // It is possible that none of the exception handlers would have caught
1234 // the exception. In this case, we will exit the method. We must
1235 // ensure that the monitor stack is empty in this case.
1236 if (_monitor_top == 0) {
1237 return;
1238 }
1240 // We pessimistically assume that this exception can escape the
1241 // method. (It is possible that it will always be caught, but
1242 // we don't care to analyse the types of the catch clauses.)
1244 // We don't set _monitor_top to bad_monitors because there are no successors
1245 // to this exceptional exit.
1247 if (TraceMonitorMismatch && _monitor_safe) {
1248 // We check _monitor_safe so that we only report the first mismatched
1249 // exceptional exit.
1250 report_monitor_mismatch("non-empty monitor stack at exceptional exit");
1251 }
1252 _monitor_safe = false;
1254 }
1256 void GenerateOopMap::report_monitor_mismatch(const char *msg) {
1257 #ifndef PRODUCT
1258 tty->print(" Monitor mismatch in method ");
1259 method()->print_short_name(tty);
1260 tty->print_cr(": %s", msg);
1261 #endif
1262 }
1264 void GenerateOopMap::print_states(outputStream *os,
1265 CellTypeState* vec, int num) {
1266 for (int i = 0; i < num; i++) {
1267 vec[i].print(tty);
1268 }
1269 }
1271 // Print the state values at the current bytecode.
1272 void GenerateOopMap::print_current_state(outputStream *os,
1273 BytecodeStream *currentBC,
1274 bool detailed) {
1276 if (detailed) {
1277 os->print(" %4d vars = ", currentBC->bci());
1278 print_states(os, vars(), _max_locals);
1279 os->print(" %s", Bytecodes::name(currentBC->code()));
1280 switch(currentBC->code()) {
1281 case Bytecodes::_invokevirtual:
1282 case Bytecodes::_invokespecial:
1283 case Bytecodes::_invokestatic:
1284 case Bytecodes::_invokedynamic:
1285 case Bytecodes::_invokeinterface:
1286 int idx = currentBC->has_index_u4() ? currentBC->get_index_u4() : currentBC->get_index_u2_cpcache();
1287 ConstantPool* cp = method()->constants();
1288 int nameAndTypeIdx = cp->name_and_type_ref_index_at(idx);
1289 int signatureIdx = cp->signature_ref_index_at(nameAndTypeIdx);
1290 Symbol* signature = cp->symbol_at(signatureIdx);
1291 os->print("%s", signature->as_C_string());
1292 }
1293 os->cr();
1294 os->print(" stack = ");
1295 print_states(os, stack(), _stack_top);
1296 os->cr();
1297 if (_monitor_top != bad_monitors) {
1298 os->print(" monitors = ");
1299 print_states(os, monitors(), _monitor_top);
1300 } else {
1301 os->print(" [bad monitor stack]");
1302 }
1303 os->cr();
1304 } else {
1305 os->print(" %4d vars = '%s' ", currentBC->bci(), state_vec_to_string(vars(), _max_locals));
1306 os->print(" stack = '%s' ", state_vec_to_string(stack(), _stack_top));
1307 if (_monitor_top != bad_monitors) {
1308 os->print(" monitors = '%s' \t%s", state_vec_to_string(monitors(), _monitor_top), Bytecodes::name(currentBC->code()));
1309 } else {
1310 os->print(" [bad monitor stack]");
1311 }
1312 switch(currentBC->code()) {
1313 case Bytecodes::_invokevirtual:
1314 case Bytecodes::_invokespecial:
1315 case Bytecodes::_invokestatic:
1316 case Bytecodes::_invokedynamic:
1317 case Bytecodes::_invokeinterface:
1318 int idx = currentBC->has_index_u4() ? currentBC->get_index_u4() : currentBC->get_index_u2_cpcache();
1319 ConstantPool* cp = method()->constants();
1320 int nameAndTypeIdx = cp->name_and_type_ref_index_at(idx);
1321 int signatureIdx = cp->signature_ref_index_at(nameAndTypeIdx);
1322 Symbol* signature = cp->symbol_at(signatureIdx);
1323 os->print("%s", signature->as_C_string());
1324 }
1325 os->cr();
1326 }
1327 }
1329 // Sets the current state to be the state after executing the
1330 // current instruction, starting in the current state.
1331 void GenerateOopMap::interp1(BytecodeStream *itr) {
1332 if (TraceNewOopMapGeneration) {
1333 print_current_state(tty, itr, TraceNewOopMapGenerationDetailed);
1334 }
1336 // Should we report the results? Result is reported *before* the instruction at the current bci is executed.
1337 // However, not for calls. For calls we do not want to include the arguments, so we postpone the reporting until
1338 // they have been popped (in method ppl).
1339 if (_report_result == true) {
1340 switch(itr->code()) {
1341 case Bytecodes::_invokevirtual:
1342 case Bytecodes::_invokespecial:
1343 case Bytecodes::_invokestatic:
1344 case Bytecodes::_invokedynamic:
1345 case Bytecodes::_invokeinterface:
1346 _itr_send = itr;
1347 _report_result_for_send = true;
1348 break;
1349 default:
1350 fill_stackmap_for_opcodes(itr, vars(), stack(), _stack_top);
1351 break;
1352 }
1353 }
1355 // abstract interpretation of current opcode
1356 switch(itr->code()) {
1357 case Bytecodes::_nop: break;
1358 case Bytecodes::_goto: break;
1359 case Bytecodes::_goto_w: break;
1360 case Bytecodes::_iinc: break;
1361 case Bytecodes::_return: do_return_monitor_check();
1362 break;
1364 case Bytecodes::_aconst_null:
1365 case Bytecodes::_new: ppush1(CellTypeState::make_line_ref(itr->bci()));
1366 break;
1368 case Bytecodes::_iconst_m1:
1369 case Bytecodes::_iconst_0:
1370 case Bytecodes::_iconst_1:
1371 case Bytecodes::_iconst_2:
1372 case Bytecodes::_iconst_3:
1373 case Bytecodes::_iconst_4:
1374 case Bytecodes::_iconst_5:
1375 case Bytecodes::_fconst_0:
1376 case Bytecodes::_fconst_1:
1377 case Bytecodes::_fconst_2:
1378 case Bytecodes::_bipush:
1379 case Bytecodes::_sipush: ppush1(valCTS); break;
1381 case Bytecodes::_lconst_0:
1382 case Bytecodes::_lconst_1:
1383 case Bytecodes::_dconst_0:
1384 case Bytecodes::_dconst_1: ppush(vvCTS); break;
1386 case Bytecodes::_ldc2_w: ppush(vvCTS); break;
1388 case Bytecodes::_ldc: // fall through:
1389 case Bytecodes::_ldc_w: do_ldc(itr->bci()); break;
1391 case Bytecodes::_iload:
1392 case Bytecodes::_fload: ppload(vCTS, itr->get_index()); break;
1394 case Bytecodes::_lload:
1395 case Bytecodes::_dload: ppload(vvCTS,itr->get_index()); break;
1397 case Bytecodes::_aload: ppload(rCTS, itr->get_index()); break;
1399 case Bytecodes::_iload_0:
1400 case Bytecodes::_fload_0: ppload(vCTS, 0); break;
1401 case Bytecodes::_iload_1:
1402 case Bytecodes::_fload_1: ppload(vCTS, 1); break;
1403 case Bytecodes::_iload_2:
1404 case Bytecodes::_fload_2: ppload(vCTS, 2); break;
1405 case Bytecodes::_iload_3:
1406 case Bytecodes::_fload_3: ppload(vCTS, 3); break;
1408 case Bytecodes::_lload_0:
1409 case Bytecodes::_dload_0: ppload(vvCTS, 0); break;
1410 case Bytecodes::_lload_1:
1411 case Bytecodes::_dload_1: ppload(vvCTS, 1); break;
1412 case Bytecodes::_lload_2:
1413 case Bytecodes::_dload_2: ppload(vvCTS, 2); break;
1414 case Bytecodes::_lload_3:
1415 case Bytecodes::_dload_3: ppload(vvCTS, 3); break;
1417 case Bytecodes::_aload_0: ppload(rCTS, 0); break;
1418 case Bytecodes::_aload_1: ppload(rCTS, 1); break;
1419 case Bytecodes::_aload_2: ppload(rCTS, 2); break;
1420 case Bytecodes::_aload_3: ppload(rCTS, 3); break;
1422 case Bytecodes::_iaload:
1423 case Bytecodes::_faload:
1424 case Bytecodes::_baload:
1425 case Bytecodes::_caload:
1426 case Bytecodes::_saload: pp(vrCTS, vCTS); break;
1428 case Bytecodes::_laload: pp(vrCTS, vvCTS); break;
1429 case Bytecodes::_daload: pp(vrCTS, vvCTS); break;
1431 case Bytecodes::_aaload: pp_new_ref(vrCTS, itr->bci()); break;
1433 case Bytecodes::_istore:
1434 case Bytecodes::_fstore: ppstore(vCTS, itr->get_index()); break;
1436 case Bytecodes::_lstore:
1437 case Bytecodes::_dstore: ppstore(vvCTS, itr->get_index()); break;
1439 case Bytecodes::_astore: do_astore(itr->get_index()); break;
1441 case Bytecodes::_istore_0:
1442 case Bytecodes::_fstore_0: ppstore(vCTS, 0); break;
1443 case Bytecodes::_istore_1:
1444 case Bytecodes::_fstore_1: ppstore(vCTS, 1); break;
1445 case Bytecodes::_istore_2:
1446 case Bytecodes::_fstore_2: ppstore(vCTS, 2); break;
1447 case Bytecodes::_istore_3:
1448 case Bytecodes::_fstore_3: ppstore(vCTS, 3); break;
1450 case Bytecodes::_lstore_0:
1451 case Bytecodes::_dstore_0: ppstore(vvCTS, 0); break;
1452 case Bytecodes::_lstore_1:
1453 case Bytecodes::_dstore_1: ppstore(vvCTS, 1); break;
1454 case Bytecodes::_lstore_2:
1455 case Bytecodes::_dstore_2: ppstore(vvCTS, 2); break;
1456 case Bytecodes::_lstore_3:
1457 case Bytecodes::_dstore_3: ppstore(vvCTS, 3); break;
1459 case Bytecodes::_astore_0: do_astore(0); break;
1460 case Bytecodes::_astore_1: do_astore(1); break;
1461 case Bytecodes::_astore_2: do_astore(2); break;
1462 case Bytecodes::_astore_3: do_astore(3); break;
1464 case Bytecodes::_iastore:
1465 case Bytecodes::_fastore:
1466 case Bytecodes::_bastore:
1467 case Bytecodes::_castore:
1468 case Bytecodes::_sastore: ppop(vvrCTS); break;
1469 case Bytecodes::_lastore:
1470 case Bytecodes::_dastore: ppop(vvvrCTS); break;
1471 case Bytecodes::_aastore: ppop(rvrCTS); break;
1473 case Bytecodes::_pop: ppop_any(1); break;
1474 case Bytecodes::_pop2: ppop_any(2); break;
1476 case Bytecodes::_dup: ppdupswap(1, "11"); break;
1477 case Bytecodes::_dup_x1: ppdupswap(2, "121"); break;
1478 case Bytecodes::_dup_x2: ppdupswap(3, "1321"); break;
1479 case Bytecodes::_dup2: ppdupswap(2, "2121"); break;
1480 case Bytecodes::_dup2_x1: ppdupswap(3, "21321"); break;
1481 case Bytecodes::_dup2_x2: ppdupswap(4, "214321"); break;
1482 case Bytecodes::_swap: ppdupswap(2, "12"); break;
1484 case Bytecodes::_iadd:
1485 case Bytecodes::_fadd:
1486 case Bytecodes::_isub:
1487 case Bytecodes::_fsub:
1488 case Bytecodes::_imul:
1489 case Bytecodes::_fmul:
1490 case Bytecodes::_idiv:
1491 case Bytecodes::_fdiv:
1492 case Bytecodes::_irem:
1493 case Bytecodes::_frem:
1494 case Bytecodes::_ishl:
1495 case Bytecodes::_ishr:
1496 case Bytecodes::_iushr:
1497 case Bytecodes::_iand:
1498 case Bytecodes::_ior:
1499 case Bytecodes::_ixor:
1500 case Bytecodes::_l2f:
1501 case Bytecodes::_l2i:
1502 case Bytecodes::_d2f:
1503 case Bytecodes::_d2i:
1504 case Bytecodes::_fcmpl:
1505 case Bytecodes::_fcmpg: pp(vvCTS, vCTS); break;
1507 case Bytecodes::_ladd:
1508 case Bytecodes::_dadd:
1509 case Bytecodes::_lsub:
1510 case Bytecodes::_dsub:
1511 case Bytecodes::_lmul:
1512 case Bytecodes::_dmul:
1513 case Bytecodes::_ldiv:
1514 case Bytecodes::_ddiv:
1515 case Bytecodes::_lrem:
1516 case Bytecodes::_drem:
1517 case Bytecodes::_land:
1518 case Bytecodes::_lor:
1519 case Bytecodes::_lxor: pp(vvvvCTS, vvCTS); break;
1521 case Bytecodes::_ineg:
1522 case Bytecodes::_fneg:
1523 case Bytecodes::_i2f:
1524 case Bytecodes::_f2i:
1525 case Bytecodes::_i2c:
1526 case Bytecodes::_i2s:
1527 case Bytecodes::_i2b: pp(vCTS, vCTS); break;
1529 case Bytecodes::_lneg:
1530 case Bytecodes::_dneg:
1531 case Bytecodes::_l2d:
1532 case Bytecodes::_d2l: pp(vvCTS, vvCTS); break;
1534 case Bytecodes::_lshl:
1535 case Bytecodes::_lshr:
1536 case Bytecodes::_lushr: pp(vvvCTS, vvCTS); break;
1538 case Bytecodes::_i2l:
1539 case Bytecodes::_i2d:
1540 case Bytecodes::_f2l:
1541 case Bytecodes::_f2d: pp(vCTS, vvCTS); break;
1543 case Bytecodes::_lcmp: pp(vvvvCTS, vCTS); break;
1544 case Bytecodes::_dcmpl:
1545 case Bytecodes::_dcmpg: pp(vvvvCTS, vCTS); break;
1547 case Bytecodes::_ifeq:
1548 case Bytecodes::_ifne:
1549 case Bytecodes::_iflt:
1550 case Bytecodes::_ifge:
1551 case Bytecodes::_ifgt:
1552 case Bytecodes::_ifle:
1553 case Bytecodes::_tableswitch: ppop1(valCTS);
1554 break;
1555 case Bytecodes::_ireturn:
1556 case Bytecodes::_freturn: do_return_monitor_check();
1557 ppop1(valCTS);
1558 break;
1559 case Bytecodes::_if_icmpeq:
1560 case Bytecodes::_if_icmpne:
1561 case Bytecodes::_if_icmplt:
1562 case Bytecodes::_if_icmpge:
1563 case Bytecodes::_if_icmpgt:
1564 case Bytecodes::_if_icmple: ppop(vvCTS);
1565 break;
1567 case Bytecodes::_lreturn: do_return_monitor_check();
1568 ppop(vvCTS);
1569 break;
1571 case Bytecodes::_dreturn: do_return_monitor_check();
1572 ppop(vvCTS);
1573 break;
1575 case Bytecodes::_if_acmpeq:
1576 case Bytecodes::_if_acmpne: ppop(rrCTS); break;
1578 case Bytecodes::_jsr: do_jsr(itr->dest()); break;
1579 case Bytecodes::_jsr_w: do_jsr(itr->dest_w()); break;
1581 case Bytecodes::_getstatic: do_field(true, true, itr->get_index_u2_cpcache(), itr->bci()); break;
1582 case Bytecodes::_putstatic: do_field(false, true, itr->get_index_u2_cpcache(), itr->bci()); break;
1583 case Bytecodes::_getfield: do_field(true, false, itr->get_index_u2_cpcache(), itr->bci()); break;
1584 case Bytecodes::_putfield: do_field(false, false, itr->get_index_u2_cpcache(), itr->bci()); break;
1586 case Bytecodes::_invokevirtual:
1587 case Bytecodes::_invokespecial: do_method(false, false, itr->get_index_u2_cpcache(), itr->bci()); break;
1588 case Bytecodes::_invokestatic: do_method(true, false, itr->get_index_u2_cpcache(), itr->bci()); break;
1589 case Bytecodes::_invokedynamic: do_method(true, false, itr->get_index_u4(), itr->bci()); break;
1590 case Bytecodes::_invokeinterface: do_method(false, true, itr->get_index_u2_cpcache(), itr->bci()); break;
1591 case Bytecodes::_newarray:
1592 case Bytecodes::_anewarray: pp_new_ref(vCTS, itr->bci()); break;
1593 case Bytecodes::_checkcast: do_checkcast(); break;
1594 case Bytecodes::_arraylength:
1595 case Bytecodes::_instanceof: pp(rCTS, vCTS); break;
1596 case Bytecodes::_monitorenter: do_monitorenter(itr->bci()); break;
1597 case Bytecodes::_monitorexit: do_monitorexit(itr->bci()); break;
1599 case Bytecodes::_athrow: // handled by do_exception_edge() BUT ...
1600 // vlh(apple): do_exception_edge() does not get
1601 // called if method has no exception handlers
1602 if ((!_has_exceptions) && (_monitor_top > 0)) {
1603 _monitor_safe = false;
1604 }
1605 break;
1607 case Bytecodes::_areturn: do_return_monitor_check();
1608 ppop1(refCTS);
1609 break;
1610 case Bytecodes::_ifnull:
1611 case Bytecodes::_ifnonnull: ppop1(refCTS); break;
1612 case Bytecodes::_multianewarray: do_multianewarray(*(itr->bcp()+3), itr->bci()); break;
1614 case Bytecodes::_wide: fatal("Iterator should skip this bytecode"); break;
1615 case Bytecodes::_ret: break;
1617 // Java opcodes
1618 case Bytecodes::_lookupswitch: ppop1(valCTS); break;
1620 default:
1621 tty->print("unexpected opcode: %d\n", itr->code());
1622 ShouldNotReachHere();
1623 break;
1624 }
1625 }
1627 void GenerateOopMap::check_type(CellTypeState expected, CellTypeState actual) {
1628 if (!expected.equal_kind(actual)) {
1629 verify_error("wrong type on stack (found: %c expected: %c)", actual.to_char(), expected.to_char());
1630 }
1631 }
1633 void GenerateOopMap::ppstore(CellTypeState *in, int loc_no) {
1634 while(!(*in).is_bottom()) {
1635 CellTypeState expected =*in++;
1636 CellTypeState actual = pop();
1637 check_type(expected, actual);
1638 assert(loc_no >= 0, "sanity check");
1639 set_var(loc_no++, actual);
1640 }
1641 }
1643 void GenerateOopMap::ppload(CellTypeState *out, int loc_no) {
1644 while(!(*out).is_bottom()) {
1645 CellTypeState out1 = *out++;
1646 CellTypeState vcts = get_var(loc_no);
1647 assert(out1.can_be_reference() || out1.can_be_value(),
1648 "can only load refs. and values.");
1649 if (out1.is_reference()) {
1650 assert(loc_no>=0, "sanity check");
1651 if (!vcts.is_reference()) {
1652 // We were asked to push a reference, but the type of the
1653 // variable can be something else
1654 _conflict = true;
1655 if (vcts.can_be_uninit()) {
1656 // It is a ref-uninit conflict (at least). If there are other
1657 // problems, we'll get them in the next round
1658 add_to_ref_init_set(loc_no);
1659 vcts = out1;
1660 } else {
1661 // It wasn't a ref-uninit conflict. So must be a
1662 // ref-val or ref-pc conflict. Split the variable.
1663 record_refval_conflict(loc_no);
1664 vcts = out1;
1665 }
1666 push(out1); // recover...
1667 } else {
1668 push(vcts); // preserve reference.
1669 }
1670 // Otherwise it is a conflict, but one that verification would
1671 // have caught if illegal. In particular, it can't be a topCTS
1672 // resulting from mergeing two difference pcCTS's since the verifier
1673 // would have rejected any use of such a merge.
1674 } else {
1675 push(out1); // handle val/init conflict
1676 }
1677 loc_no++;
1678 }
1679 }
1681 void GenerateOopMap::ppdupswap(int poplen, const char *out) {
1682 CellTypeState actual[5];
1683 assert(poplen < 5, "this must be less than length of actual vector");
1685 // pop all arguments
1686 for(int i = 0; i < poplen; i++) actual[i] = pop();
1688 // put them back
1689 char push_ch = *out++;
1690 while (push_ch != '\0') {
1691 int idx = push_ch - '1';
1692 assert(idx >= 0 && idx < poplen, "wrong arguments");
1693 push(actual[idx]);
1694 push_ch = *out++;
1695 }
1696 }
1698 void GenerateOopMap::ppop1(CellTypeState out) {
1699 CellTypeState actual = pop();
1700 check_type(out, actual);
1701 }
1703 void GenerateOopMap::ppop(CellTypeState *out) {
1704 while (!(*out).is_bottom()) {
1705 ppop1(*out++);
1706 }
1707 }
1709 void GenerateOopMap::ppush1(CellTypeState in) {
1710 assert(in.is_reference() | in.is_value(), "sanity check");
1711 push(in);
1712 }
1714 void GenerateOopMap::ppush(CellTypeState *in) {
1715 while (!(*in).is_bottom()) {
1716 ppush1(*in++);
1717 }
1718 }
1720 void GenerateOopMap::pp(CellTypeState *in, CellTypeState *out) {
1721 ppop(in);
1722 ppush(out);
1723 }
1725 void GenerateOopMap::pp_new_ref(CellTypeState *in, int bci) {
1726 ppop(in);
1727 ppush1(CellTypeState::make_line_ref(bci));
1728 }
1730 void GenerateOopMap::ppop_any(int poplen) {
1731 if (_stack_top >= poplen) {
1732 _stack_top -= poplen;
1733 } else {
1734 verify_error("stack underflow");
1735 }
1736 }
1738 // Replace all occurences of the state 'match' with the state 'replace'
1739 // in our current state vector.
1740 void GenerateOopMap::replace_all_CTS_matches(CellTypeState match,
1741 CellTypeState replace) {
1742 int i;
1743 int len = _max_locals + _stack_top;
1744 bool change = false;
1746 for (i = len - 1; i >= 0; i--) {
1747 if (match.equal(_state[i])) {
1748 _state[i] = replace;
1749 }
1750 }
1752 if (_monitor_top > 0) {
1753 int base = _max_locals + _max_stack;
1754 len = base + _monitor_top;
1755 for (i = len - 1; i >= base; i--) {
1756 if (match.equal(_state[i])) {
1757 _state[i] = replace;
1758 }
1759 }
1760 }
1761 }
1763 void GenerateOopMap::do_checkcast() {
1764 CellTypeState actual = pop();
1765 check_type(refCTS, actual);
1766 push(actual);
1767 }
1769 void GenerateOopMap::do_monitorenter(int bci) {
1770 CellTypeState actual = pop();
1771 if (_monitor_top == bad_monitors) {
1772 return;
1773 }
1775 // Bail out when we get repeated locks on an identical monitor. This case
1776 // isn't too hard to handle and can be made to work if supporting nested
1777 // redundant synchronized statements becomes a priority.
1778 //
1779 // See also "Note" in do_monitorexit(), below.
1780 if (actual.is_lock_reference()) {
1781 _monitor_top = bad_monitors;
1782 _monitor_safe = false;
1784 if (TraceMonitorMismatch) {
1785 report_monitor_mismatch("nested redundant lock -- bailout...");
1786 }
1787 return;
1788 }
1790 CellTypeState lock = CellTypeState::make_lock_ref(bci);
1791 check_type(refCTS, actual);
1792 if (!actual.is_info_top()) {
1793 replace_all_CTS_matches(actual, lock);
1794 monitor_push(lock);
1795 }
1796 }
1798 void GenerateOopMap::do_monitorexit(int bci) {
1799 CellTypeState actual = pop();
1800 if (_monitor_top == bad_monitors) {
1801 return;
1802 }
1803 check_type(refCTS, actual);
1804 CellTypeState expected = monitor_pop();
1805 if (!actual.is_lock_reference() || !expected.equal(actual)) {
1806 // The monitor we are exiting is not verifiably the one
1807 // on the top of our monitor stack. This causes a monitor
1808 // mismatch.
1809 _monitor_top = bad_monitors;
1810 _monitor_safe = false;
1812 // We need to mark this basic block as changed so that
1813 // this monitorexit will be visited again. We need to
1814 // do this to ensure that we have accounted for the
1815 // possibility that this bytecode will throw an
1816 // exception.
1817 BasicBlock* bb = get_basic_block_containing(bci);
1818 guarantee(bb != NULL, "no basic block for bci");
1819 bb->set_changed(true);
1820 bb->_monitor_top = bad_monitors;
1822 if (TraceMonitorMismatch) {
1823 report_monitor_mismatch("improper monitor pair");
1824 }
1825 } else {
1826 // This code is a fix for the case where we have repeated
1827 // locking of the same object in straightline code. We clear
1828 // out the lock when it is popped from the monitor stack
1829 // and replace it with an unobtrusive reference value that can
1830 // be locked again.
1831 //
1832 // Note: when generateOopMap is fixed to properly handle repeated,
1833 // nested, redundant locks on the same object, then this
1834 // fix will need to be removed at that time.
1835 replace_all_CTS_matches(actual, CellTypeState::make_line_ref(bci));
1836 }
1837 }
1839 void GenerateOopMap::do_return_monitor_check() {
1840 if (_monitor_top > 0) {
1841 // The monitor stack must be empty when we leave the method
1842 // for the monitors to be properly matched.
1843 _monitor_safe = false;
1845 // Since there are no successors to the *return bytecode, it
1846 // isn't necessary to set _monitor_top to bad_monitors.
1848 if (TraceMonitorMismatch) {
1849 report_monitor_mismatch("non-empty monitor stack at return");
1850 }
1851 }
1852 }
1854 void GenerateOopMap::do_jsr(int targ_bci) {
1855 push(CellTypeState::make_addr(targ_bci));
1856 }
1860 void GenerateOopMap::do_ldc(int bci) {
1861 Bytecode_loadconstant ldc(method(), bci);
1862 ConstantPool* cp = method()->constants();
1863 constantTag tag = cp->tag_at(ldc.pool_index()); // idx is index in resolved_references
1864 BasicType bt = ldc.result_type();
1865 CellTypeState cts;
1866 if (tag.basic_type() == T_OBJECT) {
1867 assert(!tag.is_string_index() && !tag.is_klass_index(), "Unexpected index tag");
1868 assert(bt == T_OBJECT, "Guard is incorrect");
1869 cts = CellTypeState::make_line_ref(bci);
1870 } else {
1871 assert(bt != T_OBJECT, "Guard is incorrect");
1872 cts = valCTS;
1873 }
1874 ppush1(cts);
1875 }
1877 void GenerateOopMap::do_multianewarray(int dims, int bci) {
1878 assert(dims >= 1, "sanity check");
1879 for(int i = dims -1; i >=0; i--) {
1880 ppop1(valCTS);
1881 }
1882 ppush1(CellTypeState::make_line_ref(bci));
1883 }
1885 void GenerateOopMap::do_astore(int idx) {
1886 CellTypeState r_or_p = pop();
1887 if (!r_or_p.is_address() && !r_or_p.is_reference()) {
1888 // We actually expected ref or pc, but we only report that we expected a ref. It does not
1889 // really matter (at least for now)
1890 verify_error("wrong type on stack (found: %c, expected: {pr})", r_or_p.to_char());
1891 return;
1892 }
1893 set_var(idx, r_or_p);
1894 }
1896 // Copies bottom/zero terminated CTS string from "src" into "dst".
1897 // Does NOT terminate with a bottom. Returns the number of cells copied.
1898 int GenerateOopMap::copy_cts(CellTypeState *dst, CellTypeState *src) {
1899 int idx = 0;
1900 while (!src[idx].is_bottom()) {
1901 dst[idx] = src[idx];
1902 idx++;
1903 }
1904 return idx;
1905 }
1907 void GenerateOopMap::do_field(int is_get, int is_static, int idx, int bci) {
1908 // Dig up signature for field in constant pool
1909 ConstantPool* cp = method()->constants();
1910 int nameAndTypeIdx = cp->name_and_type_ref_index_at(idx);
1911 int signatureIdx = cp->signature_ref_index_at(nameAndTypeIdx);
1912 Symbol* signature = cp->symbol_at(signatureIdx);
1914 // Parse signature (espcially simple for fields)
1915 assert(signature->utf8_length() > 0, "field signatures cannot have zero length");
1916 // The signature is UFT8 encoded, but the first char is always ASCII for signatures.
1917 char sigch = (char)*(signature->base());
1918 CellTypeState temp[4];
1919 CellTypeState *eff = sigchar_to_effect(sigch, bci, temp);
1921 CellTypeState in[4];
1922 CellTypeState *out;
1923 int i = 0;
1925 if (is_get) {
1926 out = eff;
1927 } else {
1928 out = epsilonCTS;
1929 i = copy_cts(in, eff);
1930 }
1931 if (!is_static) in[i++] = CellTypeState::ref;
1932 in[i] = CellTypeState::bottom;
1933 assert(i<=3, "sanity check");
1934 pp(in, out);
1935 }
1937 void GenerateOopMap::do_method(int is_static, int is_interface, int idx, int bci) {
1938 // Dig up signature for field in constant pool
1939 ConstantPool* cp = _method->constants();
1940 Symbol* signature = cp->signature_ref_at(idx);
1942 // Parse method signature
1943 CellTypeState out[4];
1944 CellTypeState in[MAXARGSIZE+1]; // Includes result
1945 ComputeCallStack cse(signature);
1947 // Compute return type
1948 int res_length= cse.compute_for_returntype(out);
1950 // Temporary hack.
1951 if (out[0].equal(CellTypeState::ref) && out[1].equal(CellTypeState::bottom)) {
1952 out[0] = CellTypeState::make_line_ref(bci);
1953 }
1955 assert(res_length<=4, "max value should be vv");
1957 // Compute arguments
1958 int arg_length = cse.compute_for_parameters(is_static != 0, in);
1959 assert(arg_length<=MAXARGSIZE, "too many locals");
1961 // Pop arguments
1962 for (int i = arg_length - 1; i >= 0; i--) ppop1(in[i]);// Do args in reverse order.
1964 // Report results
1965 if (_report_result_for_send == true) {
1966 fill_stackmap_for_opcodes(_itr_send, vars(), stack(), _stack_top);
1967 _report_result_for_send = false;
1968 }
1970 // Push return address
1971 ppush(out);
1972 }
1974 // This is used to parse the signature for fields, since they are very simple...
1975 CellTypeState *GenerateOopMap::sigchar_to_effect(char sigch, int bci, CellTypeState *out) {
1976 // Object and array
1977 if (sigch=='L' || sigch=='[') {
1978 out[0] = CellTypeState::make_line_ref(bci);
1979 out[1] = CellTypeState::bottom;
1980 return out;
1981 }
1982 if (sigch == 'J' || sigch == 'D' ) return vvCTS; // Long and Double
1983 if (sigch == 'V' ) return epsilonCTS; // Void
1984 return vCTS; // Otherwise
1985 }
1987 long GenerateOopMap::_total_byte_count = 0;
1988 elapsedTimer GenerateOopMap::_total_oopmap_time;
1990 // This function assumes "bcs" is at a "ret" instruction and that the vars
1991 // state is valid for that instruction. Furthermore, the ret instruction
1992 // must be the last instruction in "bb" (we store information about the
1993 // "ret" in "bb").
1994 void GenerateOopMap::ret_jump_targets_do(BytecodeStream *bcs, jmpFct_t jmpFct, int varNo, int *data) {
1995 CellTypeState ra = vars()[varNo];
1996 if (!ra.is_good_address()) {
1997 verify_error("ret returns from two jsr subroutines?");
1998 return;
1999 }
2000 int target = ra.get_info();
2002 RetTableEntry* rtEnt = _rt.find_jsrs_for_target(target);
2003 int bci = bcs->bci();
2004 for (int i = 0; i < rtEnt->nof_jsrs(); i++) {
2005 int target_bci = rtEnt->jsrs(i);
2006 // Make sure a jrtRet does not set the changed bit for dead basicblock.
2007 BasicBlock* jsr_bb = get_basic_block_containing(target_bci - 1);
2008 debug_only(BasicBlock* target_bb = &jsr_bb[1];)
2009 assert(target_bb == get_basic_block_at(target_bci), "wrong calc. of successor basicblock");
2010 bool alive = jsr_bb->is_alive();
2011 if (TraceNewOopMapGeneration) {
2012 tty->print("pc = %d, ret -> %d alive: %s\n", bci, target_bci, alive ? "true" : "false");
2013 }
2014 if (alive) jmpFct(this, target_bci, data);
2015 }
2016 }
2018 //
2019 // Debug method
2020 //
2021 char* GenerateOopMap::state_vec_to_string(CellTypeState* vec, int len) {
2022 #ifdef ASSERT
2023 int checklen = MAX3(_max_locals, _max_stack, _max_monitors) + 1;
2024 assert(len < checklen, "state_vec_buf overflow");
2025 #endif
2026 for (int i = 0; i < len; i++) _state_vec_buf[i] = vec[i].to_char();
2027 _state_vec_buf[len] = 0;
2028 return _state_vec_buf;
2029 }
2031 void GenerateOopMap::print_time() {
2032 tty->print_cr ("Accumulated oopmap times:");
2033 tty->print_cr ("---------------------------");
2034 tty->print_cr (" Total : %3.3f sec.", GenerateOopMap::_total_oopmap_time.seconds());
2035 tty->print_cr (" (%3.0f bytecodes per sec) ",
2036 GenerateOopMap::_total_byte_count / GenerateOopMap::_total_oopmap_time.seconds());
2037 }
2039 //
2040 // ============ Main Entry Point ===========
2041 //
2042 GenerateOopMap::GenerateOopMap(methodHandle method) {
2043 // We have to initialize all variables here, that can be queried directly
2044 _method = method;
2045 _max_locals=0;
2046 _init_vars = NULL;
2048 #ifndef PRODUCT
2049 // If we are doing a detailed trace, include the regular trace information.
2050 if (TraceNewOopMapGenerationDetailed) {
2051 TraceNewOopMapGeneration = true;
2052 }
2053 #endif
2054 }
2056 void GenerateOopMap::compute_map(TRAPS) {
2057 #ifndef PRODUCT
2058 if (TimeOopMap2) {
2059 method()->print_short_name(tty);
2060 tty->print(" ");
2061 }
2062 if (TimeOopMap) {
2063 _total_byte_count += method()->code_size();
2064 }
2065 #endif
2066 TraceTime t_single("oopmap time", TimeOopMap2);
2067 TraceTime t_all(NULL, &_total_oopmap_time, TimeOopMap);
2069 // Initialize values
2070 _got_error = false;
2071 _conflict = false;
2072 _max_locals = method()->max_locals();
2073 _max_stack = method()->max_stack();
2074 _has_exceptions = (method()->has_exception_handler());
2075 _nof_refval_conflicts = 0;
2076 _init_vars = new GrowableArray<intptr_t>(5); // There are seldom more than 5 init_vars
2077 _report_result = false;
2078 _report_result_for_send = false;
2079 _new_var_map = NULL;
2080 _ret_adr_tos = new GrowableArray<intptr_t>(5); // 5 seems like a good number;
2081 _did_rewriting = false;
2082 _did_relocation = false;
2084 if (TraceNewOopMapGeneration) {
2085 tty->print("Method name: %s\n", method()->name()->as_C_string());
2086 if (Verbose) {
2087 _method->print_codes();
2088 tty->print_cr("Exception table:");
2089 ExceptionTable excps(method());
2090 for(int i = 0; i < excps.length(); i ++) {
2091 tty->print_cr("[%d - %d] -> %d",
2092 excps.start_pc(i), excps.end_pc(i), excps.handler_pc(i));
2093 }
2094 }
2095 }
2097 // if no code - do nothing
2098 // compiler needs info
2099 if (method()->code_size() == 0 || _max_locals + method()->max_stack() == 0) {
2100 fill_stackmap_prolog(0);
2101 fill_stackmap_epilog();
2102 return;
2103 }
2104 // Step 1: Compute all jump targets and their return value
2105 if (!_got_error)
2106 _rt.compute_ret_table(_method);
2108 // Step 2: Find all basic blocks and count GC points
2109 if (!_got_error)
2110 mark_bbheaders_and_count_gc_points();
2112 // Step 3: Calculate stack maps
2113 if (!_got_error)
2114 do_interpretation();
2116 // Step 4:Return results
2117 if (!_got_error && report_results())
2118 report_result();
2120 if (_got_error) {
2121 THROW_HANDLE(_exception);
2122 }
2123 }
2125 // Error handling methods
2126 // These methods create an exception for the current thread which is thrown
2127 // at the bottom of the call stack, when it returns to compute_map(). The
2128 // _got_error flag controls execution. NOT TODO: The VM exception propagation
2129 // mechanism using TRAPS/CHECKs could be used here instead but it would need
2130 // to be added as a parameter to every function and checked for every call.
2131 // The tons of extra code it would generate didn't seem worth the change.
2132 //
2133 void GenerateOopMap::error_work(const char *format, va_list ap) {
2134 _got_error = true;
2135 char msg_buffer[512];
2136 vsnprintf(msg_buffer, sizeof(msg_buffer), format, ap);
2137 // Append method name
2138 char msg_buffer2[512];
2139 jio_snprintf(msg_buffer2, sizeof(msg_buffer2), "%s in method %s", msg_buffer, method()->name()->as_C_string());
2140 _exception = Exceptions::new_exception(Thread::current(),
2141 vmSymbols::java_lang_LinkageError(), msg_buffer2);
2142 }
2144 void GenerateOopMap::report_error(const char *format, ...) {
2145 va_list ap;
2146 va_start(ap, format);
2147 error_work(format, ap);
2148 }
2150 void GenerateOopMap::verify_error(const char *format, ...) {
2151 // We do not distinguish between different types of errors for verification
2152 // errors. Let the verifier give a better message.
2153 const char *msg = "Illegal class file encountered. Try running with -Xverify:all";
2154 _got_error = true;
2155 // Append method name
2156 char msg_buffer2[512];
2157 jio_snprintf(msg_buffer2, sizeof(msg_buffer2), "%s in method %s", msg,
2158 method()->name()->as_C_string());
2159 _exception = Exceptions::new_exception(Thread::current(),
2160 vmSymbols::java_lang_LinkageError(), msg_buffer2);
2161 }
2163 //
2164 // Report result opcodes
2165 //
2166 void GenerateOopMap::report_result() {
2168 if (TraceNewOopMapGeneration) tty->print_cr("Report result pass");
2170 // We now want to report the result of the parse
2171 _report_result = true;
2173 // Prolog code
2174 fill_stackmap_prolog(_gc_points);
2176 // Mark everything changed, then do one interpretation pass.
2177 for (int i = 0; i<_bb_count; i++) {
2178 if (_basic_blocks[i].is_reachable()) {
2179 _basic_blocks[i].set_changed(true);
2180 interp_bb(&_basic_blocks[i]);
2181 }
2182 }
2184 // Note: Since we are skipping dead-code when we are reporting results, then
2185 // the no. of encountered gc-points might be fewer than the previously number
2186 // we have counted. (dead-code is a pain - it should be removed before we get here)
2187 fill_stackmap_epilog();
2189 // Report initvars
2190 fill_init_vars(_init_vars);
2192 _report_result = false;
2193 }
2195 void GenerateOopMap::result_for_basicblock(int bci) {
2196 if (TraceNewOopMapGeneration) tty->print_cr("Report result pass for basicblock");
2198 // We now want to report the result of the parse
2199 _report_result = true;
2201 // Find basicblock and report results
2202 BasicBlock* bb = get_basic_block_containing(bci);
2203 guarantee(bb != NULL, "no basic block for bci");
2204 assert(bb->is_reachable(), "getting result from unreachable basicblock");
2205 bb->set_changed(true);
2206 interp_bb(bb);
2207 }
2209 //
2210 // Conflict handling code
2211 //
2213 void GenerateOopMap::record_refval_conflict(int varNo) {
2214 assert(varNo>=0 && varNo< _max_locals, "index out of range");
2216 if (TraceOopMapRewrites) {
2217 tty->print("### Conflict detected (local no: %d)\n", varNo);
2218 }
2220 if (!_new_var_map) {
2221 _new_var_map = NEW_RESOURCE_ARRAY(int, _max_locals);
2222 for (int k = 0; k < _max_locals; k++) _new_var_map[k] = k;
2223 }
2225 if ( _new_var_map[varNo] == varNo) {
2226 // Check if max. number of locals has been reached
2227 if (_max_locals + _nof_refval_conflicts >= MAX_LOCAL_VARS) {
2228 report_error("Rewriting exceeded local variable limit");
2229 return;
2230 }
2231 _new_var_map[varNo] = _max_locals + _nof_refval_conflicts;
2232 _nof_refval_conflicts++;
2233 }
2234 }
2236 void GenerateOopMap::rewrite_refval_conflicts()
2237 {
2238 // We can get here two ways: Either a rewrite conflict was detected, or
2239 // an uninitialize reference was detected. In the second case, we do not
2240 // do any rewriting, we just want to recompute the reference set with the
2241 // new information
2243 int nof_conflicts = 0; // Used for debugging only
2245 if ( _nof_refval_conflicts == 0 )
2246 return;
2248 // Check if rewrites are allowed in this parse.
2249 if (!allow_rewrites() && !IgnoreRewrites) {
2250 fatal("Rewriting method not allowed at this stage");
2251 }
2254 // This following flag is to tempoary supress rewrites. The locals that might conflict will
2255 // all be set to contain values. This is UNSAFE - however, until the rewriting has been completely
2256 // tested it is nice to have.
2257 if (IgnoreRewrites) {
2258 if (Verbose) {
2259 tty->print("rewrites suppressed for local no. ");
2260 for (int l = 0; l < _max_locals; l++) {
2261 if (_new_var_map[l] != l) {
2262 tty->print("%d ", l);
2263 vars()[l] = CellTypeState::value;
2264 }
2265 }
2266 tty->cr();
2267 }
2269 // That was that...
2270 _new_var_map = NULL;
2271 _nof_refval_conflicts = 0;
2272 _conflict = false;
2274 return;
2275 }
2277 // Tracing flag
2278 _did_rewriting = true;
2280 if (TraceOopMapRewrites) {
2281 tty->print_cr("ref/value conflict for method %s - bytecodes are getting rewritten", method()->name()->as_C_string());
2282 method()->print();
2283 method()->print_codes();
2284 }
2286 assert(_new_var_map!=NULL, "nothing to rewrite");
2287 assert(_conflict==true, "We should not be here");
2289 compute_ret_adr_at_TOS();
2290 if (!_got_error) {
2291 for (int k = 0; k < _max_locals && !_got_error; k++) {
2292 if (_new_var_map[k] != k) {
2293 if (TraceOopMapRewrites) {
2294 tty->print_cr("Rewriting: %d -> %d", k, _new_var_map[k]);
2295 }
2296 rewrite_refval_conflict(k, _new_var_map[k]);
2297 if (_got_error) return;
2298 nof_conflicts++;
2299 }
2300 }
2301 }
2303 assert(nof_conflicts == _nof_refval_conflicts, "sanity check");
2305 // Adjust the number of locals
2306 method()->set_max_locals(_max_locals+_nof_refval_conflicts);
2307 _max_locals += _nof_refval_conflicts;
2309 // That was that...
2310 _new_var_map = NULL;
2311 _nof_refval_conflicts = 0;
2312 }
2314 void GenerateOopMap::rewrite_refval_conflict(int from, int to) {
2315 bool startOver;
2316 do {
2317 // Make sure that the BytecodeStream is constructed in the loop, since
2318 // during rewriting a new method oop is going to be used, and the next time
2319 // around we want to use that.
2320 BytecodeStream bcs(_method);
2321 startOver = false;
2323 while( !startOver && !_got_error &&
2324 // test bcs in case method changed and it became invalid
2325 bcs.next() >=0) {
2326 startOver = rewrite_refval_conflict_inst(&bcs, from, to);
2327 }
2328 } while (startOver && !_got_error);
2329 }
2331 /* If the current instruction is one that uses local variable "from"
2332 in a ref way, change it to use "to". There's a subtle reason why we
2333 renumber the ref uses and not the non-ref uses: non-ref uses may be
2334 2 slots wide (double, long) which would necessitate keeping track of
2335 whether we should add one or two variables to the method. If the change
2336 affected the width of some instruction, returns "TRUE"; otherwise, returns "FALSE".
2337 Another reason for moving ref's value is for solving (addr, ref) conflicts, which
2338 both uses aload/astore methods.
2339 */
2340 bool GenerateOopMap::rewrite_refval_conflict_inst(BytecodeStream *itr, int from, int to) {
2341 Bytecodes::Code bc = itr->code();
2342 int index;
2343 int bci = itr->bci();
2345 if (is_aload(itr, &index) && index == from) {
2346 if (TraceOopMapRewrites) {
2347 tty->print_cr("Rewriting aload at bci: %d", bci);
2348 }
2349 return rewrite_load_or_store(itr, Bytecodes::_aload, Bytecodes::_aload_0, to);
2350 }
2352 if (is_astore(itr, &index) && index == from) {
2353 if (!stack_top_holds_ret_addr(bci)) {
2354 if (TraceOopMapRewrites) {
2355 tty->print_cr("Rewriting astore at bci: %d", bci);
2356 }
2357 return rewrite_load_or_store(itr, Bytecodes::_astore, Bytecodes::_astore_0, to);
2358 } else {
2359 if (TraceOopMapRewrites) {
2360 tty->print_cr("Supress rewriting of astore at bci: %d", bci);
2361 }
2362 }
2363 }
2365 return false;
2366 }
2368 // The argument to this method is:
2369 // bc : Current bytecode
2370 // bcN : either _aload or _astore
2371 // bc0 : either _aload_0 or _astore_0
2372 bool GenerateOopMap::rewrite_load_or_store(BytecodeStream *bcs, Bytecodes::Code bcN, Bytecodes::Code bc0, unsigned int varNo) {
2373 assert(bcN == Bytecodes::_astore || bcN == Bytecodes::_aload, "wrong argument (bcN)");
2374 assert(bc0 == Bytecodes::_astore_0 || bc0 == Bytecodes::_aload_0, "wrong argument (bc0)");
2375 int ilen = Bytecodes::length_at(_method(), bcs->bcp());
2376 int newIlen;
2378 if (ilen == 4) {
2379 // Original instruction was wide; keep it wide for simplicity
2380 newIlen = 4;
2381 } else if (varNo < 4)
2382 newIlen = 1;
2383 else if (varNo >= 256)
2384 newIlen = 4;
2385 else
2386 newIlen = 2;
2388 // If we need to relocate in order to patch the byte, we
2389 // do the patching in a temp. buffer, that is passed to the reloc.
2390 // The patching of the bytecode stream is then done by the Relocator.
2391 // This is neccesary, since relocating the instruction at a certain bci, might
2392 // also relocate that instruction, e.g., if a _goto before it gets widen to a _goto_w.
2393 // Hence, we do not know which bci to patch after relocation.
2395 assert(newIlen <= 4, "sanity check");
2396 u_char inst_buffer[4]; // Max. instruction size is 4.
2397 address bcp;
2399 if (newIlen != ilen) {
2400 // Relocation needed do patching in temp. buffer
2401 bcp = (address)inst_buffer;
2402 } else {
2403 bcp = _method->bcp_from(bcs->bci());
2404 }
2406 // Patch either directly in Method* or in temp. buffer
2407 if (newIlen == 1) {
2408 assert(varNo < 4, "varNo too large");
2409 *bcp = bc0 + varNo;
2410 } else if (newIlen == 2) {
2411 assert(varNo < 256, "2-byte index needed!");
2412 *(bcp + 0) = bcN;
2413 *(bcp + 1) = varNo;
2414 } else {
2415 assert(newIlen == 4, "Wrong instruction length");
2416 *(bcp + 0) = Bytecodes::_wide;
2417 *(bcp + 1) = bcN;
2418 Bytes::put_Java_u2(bcp+2, varNo);
2419 }
2421 if (newIlen != ilen) {
2422 expand_current_instr(bcs->bci(), ilen, newIlen, inst_buffer);
2423 }
2426 return (newIlen != ilen);
2427 }
2429 class RelocCallback : public RelocatorListener {
2430 private:
2431 GenerateOopMap* _gom;
2432 public:
2433 RelocCallback(GenerateOopMap* gom) { _gom = gom; };
2435 // Callback method
2436 virtual void relocated(int bci, int delta, int new_code_length) {
2437 _gom->update_basic_blocks (bci, delta, new_code_length);
2438 _gom->update_ret_adr_at_TOS(bci, delta);
2439 _gom->_rt.update_ret_table (bci, delta);
2440 }
2441 };
2443 // Returns true if expanding was succesful. Otherwise, reports an error and
2444 // returns false.
2445 void GenerateOopMap::expand_current_instr(int bci, int ilen, int newIlen, u_char inst_buffer[]) {
2446 Thread *THREAD = Thread::current(); // Could really have TRAPS argument.
2447 RelocCallback rcb(this);
2448 Relocator rc(_method, &rcb);
2449 methodHandle m= rc.insert_space_at(bci, newIlen, inst_buffer, THREAD);
2450 if (m.is_null() || HAS_PENDING_EXCEPTION) {
2451 report_error("could not rewrite method - exception occurred or bytecode buffer overflow");
2452 return;
2453 }
2455 // Relocator returns a new method oop.
2456 _did_relocation = true;
2457 _method = m;
2458 }
2461 bool GenerateOopMap::is_astore(BytecodeStream *itr, int *index) {
2462 Bytecodes::Code bc = itr->code();
2463 switch(bc) {
2464 case Bytecodes::_astore_0:
2465 case Bytecodes::_astore_1:
2466 case Bytecodes::_astore_2:
2467 case Bytecodes::_astore_3:
2468 *index = bc - Bytecodes::_astore_0;
2469 return true;
2470 case Bytecodes::_astore:
2471 *index = itr->get_index();
2472 return true;
2473 }
2474 return false;
2475 }
2477 bool GenerateOopMap::is_aload(BytecodeStream *itr, int *index) {
2478 Bytecodes::Code bc = itr->code();
2479 switch(bc) {
2480 case Bytecodes::_aload_0:
2481 case Bytecodes::_aload_1:
2482 case Bytecodes::_aload_2:
2483 case Bytecodes::_aload_3:
2484 *index = bc - Bytecodes::_aload_0;
2485 return true;
2487 case Bytecodes::_aload:
2488 *index = itr->get_index();
2489 return true;
2490 }
2491 return false;
2492 }
2495 // Return true iff the top of the operand stack holds a return address at
2496 // the current instruction
2497 bool GenerateOopMap::stack_top_holds_ret_addr(int bci) {
2498 for(int i = 0; i < _ret_adr_tos->length(); i++) {
2499 if (_ret_adr_tos->at(i) == bci)
2500 return true;
2501 }
2503 return false;
2504 }
2506 void GenerateOopMap::compute_ret_adr_at_TOS() {
2507 assert(_ret_adr_tos != NULL, "must be initialized");
2508 _ret_adr_tos->clear();
2510 for (int i = 0; i < bb_count(); i++) {
2511 BasicBlock* bb = &_basic_blocks[i];
2513 // Make sure to only check basicblocks that are reachable
2514 if (bb->is_reachable()) {
2516 // For each Basic block we check all instructions
2517 BytecodeStream bcs(_method);
2518 bcs.set_interval(bb->_bci, next_bb_start_pc(bb));
2520 restore_state(bb);
2522 while (bcs.next()>=0 && !_got_error) {
2523 // TDT: should this be is_good_address() ?
2524 if (_stack_top > 0 && stack()[_stack_top-1].is_address()) {
2525 _ret_adr_tos->append(bcs.bci());
2526 if (TraceNewOopMapGeneration) {
2527 tty->print_cr("Ret_adr TOS at bci: %d", bcs.bci());
2528 }
2529 }
2530 interp1(&bcs);
2531 }
2532 }
2533 }
2534 }
2536 void GenerateOopMap::update_ret_adr_at_TOS(int bci, int delta) {
2537 for(int i = 0; i < _ret_adr_tos->length(); i++) {
2538 int v = _ret_adr_tos->at(i);
2539 if (v > bci) _ret_adr_tos->at_put(i, v + delta);
2540 }
2541 }
2543 // ===================================================================
2545 #ifndef PRODUCT
2546 int ResolveOopMapConflicts::_nof_invocations = 0;
2547 int ResolveOopMapConflicts::_nof_rewrites = 0;
2548 int ResolveOopMapConflicts::_nof_relocations = 0;
2549 #endif
2551 methodHandle ResolveOopMapConflicts::do_potential_rewrite(TRAPS) {
2552 compute_map(CHECK_(methodHandle()));
2554 #ifndef PRODUCT
2555 // Tracking and statistics
2556 if (PrintRewrites) {
2557 _nof_invocations++;
2558 if (did_rewriting()) {
2559 _nof_rewrites++;
2560 if (did_relocation()) _nof_relocations++;
2561 tty->print("Method was rewritten %s: ", (did_relocation()) ? "and relocated" : "");
2562 method()->print_value(); tty->cr();
2563 tty->print_cr("Cand.: %d rewrts: %d (%d%%) reloc.: %d (%d%%)",
2564 _nof_invocations,
2565 _nof_rewrites, (_nof_rewrites * 100) / _nof_invocations,
2566 _nof_relocations, (_nof_relocations * 100) / _nof_invocations);
2567 }
2568 }
2569 #endif
2570 return methodHandle(THREAD, method());
2571 }