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