1 /*
   2  * Copyright (c) 2000, 2015, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "ci/ciConstant.hpp"
  27 #include "ci/ciField.hpp"
  28 #include "ci/ciMethod.hpp"
  29 #include "ci/ciMethodData.hpp"
  30 #include "ci/ciObjArrayKlass.hpp"
  31 #include "ci/ciStreams.hpp"
  32 #include "ci/ciTypeArrayKlass.hpp"
  33 #include "ci/ciTypeFlow.hpp"
  34 #include "compiler/compileLog.hpp"
  35 #include "interpreter/bytecode.hpp"
  36 #include "interpreter/bytecodes.hpp"
  37 #include "memory/allocation.inline.hpp"
  38 #include "oops/oop.inline.hpp"
  39 #include "opto/compile.hpp"
  40 #include "opto/node.hpp"
  41 #include "runtime/deoptimization.hpp"
  42 #include "utilities/growableArray.hpp"
  43 
  44 // ciTypeFlow::JsrSet
  45 //
  46 // A JsrSet represents some set of JsrRecords.  This class
  47 // is used to record a set of all jsr routines which we permit
  48 // execution to return (ret) from.
  49 //
  50 // During abstract interpretation, JsrSets are used to determine
  51 // whether two paths which reach a given block are unique, and
  52 // should be cloned apart, or are compatible, and should merge
  53 // together.
  54 
  55 // ------------------------------------------------------------------
  56 // ciTypeFlow::JsrSet::JsrSet
  57 ciTypeFlow::JsrSet::JsrSet(Arena* arena, int default_len) {
  58   if (arena != NULL) {
  59     // Allocate growable array in Arena.
  60     _set = new (arena) GrowableArray<JsrRecord*>(arena, default_len, 0, NULL);
  61   } else {
  62     // Allocate growable array in current ResourceArea.
  63     _set = new GrowableArray<JsrRecord*>(4, 0, NULL, false);
  64   }
  65 }
  66 
  67 // ------------------------------------------------------------------
  68 // ciTypeFlow::JsrSet::copy_into
  69 void ciTypeFlow::JsrSet::copy_into(JsrSet* jsrs) {
  70   int len = size();
  71   jsrs->_set->clear();
  72   for (int i = 0; i < len; i++) {
  73     jsrs->_set->append(_set->at(i));
  74   }
  75 }
  76 
  77 // ------------------------------------------------------------------
  78 // ciTypeFlow::JsrSet::is_compatible_with
  79 //
  80 // !!!! MISGIVINGS ABOUT THIS... disregard
  81 //
  82 // Is this JsrSet compatible with some other JsrSet?
  83 //
  84 // In set-theoretic terms, a JsrSet can be viewed as a partial function
  85 // from entry addresses to return addresses.  Two JsrSets A and B are
  86 // compatible iff
  87 //
  88 //   For any x,
  89 //   A(x) defined and B(x) defined implies A(x) == B(x)
  90 //
  91 // Less formally, two JsrSets are compatible when they have identical
  92 // return addresses for any entry addresses they share in common.
  93 bool ciTypeFlow::JsrSet::is_compatible_with(JsrSet* other) {
  94   // Walk through both sets in parallel.  If the same entry address
  95   // appears in both sets, then the return address must match for
  96   // the sets to be compatible.
  97   int size1 = size();
  98   int size2 = other->size();
  99 
 100   // Special case.  If nothing is on the jsr stack, then there can
 101   // be no ret.
 102   if (size2 == 0) {
 103     return true;
 104   } else if (size1 != size2) {
 105     return false;
 106   } else {
 107     for (int i = 0; i < size1; i++) {
 108       JsrRecord* record1 = record_at(i);
 109       JsrRecord* record2 = other->record_at(i);
 110       if (record1->entry_address() != record2->entry_address() ||
 111           record1->return_address() != record2->return_address()) {
 112         return false;
 113       }
 114     }
 115     return true;
 116   }
 117 
 118 #if 0
 119   int pos1 = 0;
 120   int pos2 = 0;
 121   int size1 = size();
 122   int size2 = other->size();
 123   while (pos1 < size1 && pos2 < size2) {
 124     JsrRecord* record1 = record_at(pos1);
 125     JsrRecord* record2 = other->record_at(pos2);
 126     int entry1 = record1->entry_address();
 127     int entry2 = record2->entry_address();
 128     if (entry1 < entry2) {
 129       pos1++;
 130     } else if (entry1 > entry2) {
 131       pos2++;
 132     } else {
 133       if (record1->return_address() == record2->return_address()) {
 134         pos1++;
 135         pos2++;
 136       } else {
 137         // These two JsrSets are incompatible.
 138         return false;
 139       }
 140     }
 141   }
 142   // The two JsrSets agree.
 143   return true;
 144 #endif
 145 }
 146 
 147 // ------------------------------------------------------------------
 148 // ciTypeFlow::JsrSet::insert_jsr_record
 149 //
 150 // Insert the given JsrRecord into the JsrSet, maintaining the order
 151 // of the set and replacing any element with the same entry address.
 152 void ciTypeFlow::JsrSet::insert_jsr_record(JsrRecord* record) {
 153   int len = size();
 154   int entry = record->entry_address();
 155   int pos = 0;
 156   for ( ; pos < len; pos++) {
 157     JsrRecord* current = record_at(pos);
 158     if (entry == current->entry_address()) {
 159       // Stomp over this entry.
 160       _set->at_put(pos, record);
 161       assert(size() == len, "must be same size");
 162       return;
 163     } else if (entry < current->entry_address()) {
 164       break;
 165     }
 166   }
 167 
 168   // Insert the record into the list.
 169   JsrRecord* swap = record;
 170   JsrRecord* temp = NULL;
 171   for ( ; pos < len; pos++) {
 172     temp = _set->at(pos);
 173     _set->at_put(pos, swap);
 174     swap = temp;
 175   }
 176   _set->append(swap);
 177   assert(size() == len+1, "must be larger");
 178 }
 179 
 180 // ------------------------------------------------------------------
 181 // ciTypeFlow::JsrSet::remove_jsr_record
 182 //
 183 // Remove the JsrRecord with the given return address from the JsrSet.
 184 void ciTypeFlow::JsrSet::remove_jsr_record(int return_address) {
 185   int len = size();
 186   for (int i = 0; i < len; i++) {
 187     if (record_at(i)->return_address() == return_address) {
 188       // We have found the proper entry.  Remove it from the
 189       // JsrSet and exit.
 190       for (int j = i+1; j < len ; j++) {
 191         _set->at_put(j-1, _set->at(j));
 192       }
 193       _set->trunc_to(len-1);
 194       assert(size() == len-1, "must be smaller");
 195       return;
 196     }
 197   }
 198   assert(false, "verify: returning from invalid subroutine");
 199 }
 200 
 201 // ------------------------------------------------------------------
 202 // ciTypeFlow::JsrSet::apply_control
 203 //
 204 // Apply the effect of a control-flow bytecode on the JsrSet.  The
 205 // only bytecodes that modify the JsrSet are jsr and ret.
 206 void ciTypeFlow::JsrSet::apply_control(ciTypeFlow* analyzer,
 207                                        ciBytecodeStream* str,
 208                                        ciTypeFlow::StateVector* state) {
 209   Bytecodes::Code code = str->cur_bc();
 210   if (code == Bytecodes::_jsr) {
 211     JsrRecord* record =
 212       analyzer->make_jsr_record(str->get_dest(), str->next_bci());
 213     insert_jsr_record(record);
 214   } else if (code == Bytecodes::_jsr_w) {
 215     JsrRecord* record =
 216       analyzer->make_jsr_record(str->get_far_dest(), str->next_bci());
 217     insert_jsr_record(record);
 218   } else if (code == Bytecodes::_ret) {
 219     Cell local = state->local(str->get_index());
 220     ciType* return_address = state->type_at(local);
 221     assert(return_address->is_return_address(), "verify: wrong type");
 222     if (size() == 0) {
 223       // Ret-state underflow:  Hit a ret w/o any previous jsrs.  Bail out.
 224       // This can happen when a loop is inside a finally clause (4614060).
 225       analyzer->record_failure("OSR in finally clause");
 226       return;
 227     }
 228     remove_jsr_record(return_address->as_return_address()->bci());
 229   }
 230 }
 231 
 232 #ifndef PRODUCT
 233 // ------------------------------------------------------------------
 234 // ciTypeFlow::JsrSet::print_on
 235 void ciTypeFlow::JsrSet::print_on(outputStream* st) const {
 236   st->print("{ ");
 237   int num_elements = size();
 238   if (num_elements > 0) {
 239     int i = 0;
 240     for( ; i < num_elements - 1; i++) {
 241       _set->at(i)->print_on(st);
 242       st->print(", ");
 243     }
 244     _set->at(i)->print_on(st);
 245     st->print(" ");
 246   }
 247   st->print("}");
 248 }
 249 #endif
 250 
 251 // ciTypeFlow::StateVector
 252 //
 253 // A StateVector summarizes the type information at some point in
 254 // the program.
 255 
 256 // ------------------------------------------------------------------
 257 // ciTypeFlow::StateVector::type_meet
 258 //
 259 // Meet two types.
 260 //
 261 // The semi-lattice of types use by this analysis are modeled on those
 262 // of the verifier.  The lattice is as follows:
 263 //
 264 //        top_type() >= all non-extremal types >= bottom_type
 265 //                             and
 266 //   Every primitive type is comparable only with itself.  The meet of
 267 //   reference types is determined by their kind: instance class,
 268 //   interface, or array class.  The meet of two types of the same
 269 //   kind is their least common ancestor.  The meet of two types of
 270 //   different kinds is always java.lang.Object.
 271 ciType* ciTypeFlow::StateVector::type_meet_internal(ciType* t1, ciType* t2, ciTypeFlow* analyzer) {
 272   assert(t1 != t2, "checked in caller");
 273   if (t1->equals(top_type())) {
 274     return t2;
 275   } else if (t2->equals(top_type())) {
 276     return t1;
 277   } else if (t1->is_primitive_type() || t2->is_primitive_type()) {
 278     // Special case null_type.  null_type meet any reference type T
 279     // is T.  null_type meet null_type is null_type.
 280     if (t1->equals(null_type())) {
 281       if (!t2->is_primitive_type() || t2->equals(null_type())) {
 282         return t2;
 283       }
 284     } else if (t2->equals(null_type())) {
 285       if (!t1->is_primitive_type()) {
 286         return t1;
 287       }
 288     }
 289 
 290     // At least one of the two types is a non-top primitive type.
 291     // The other type is not equal to it.  Fall to bottom.
 292     return bottom_type();
 293   } else {
 294     // Both types are non-top non-primitive types.  That is,
 295     // both types are either instanceKlasses or arrayKlasses.
 296     ciKlass* object_klass = analyzer->env()->Object_klass();
 297     ciKlass* k1 = t1->as_klass();
 298     ciKlass* k2 = t2->as_klass();
 299     if (k1->equals(object_klass) || k2->equals(object_klass)) {
 300       return object_klass;
 301     } else if (!k1->is_loaded() || !k2->is_loaded()) {
 302       // Unloaded classes fall to java.lang.Object at a merge.
 303       return object_klass;
 304     } else if (k1->is_interface() != k2->is_interface()) {
 305       // When an interface meets a non-interface, we get Object;
 306       // This is what the verifier does.
 307       return object_klass;
 308     } else if (k1->is_array_klass() || k2->is_array_klass()) {
 309       // When an array meets a non-array, we get Object.
 310       // When objArray meets typeArray, we also get Object.
 311       // And when typeArray meets different typeArray, we again get Object.
 312       // But when objArray meets objArray, we look carefully at element types.
 313       if (k1->is_obj_array_klass() && k2->is_obj_array_klass()) {
 314         // Meet the element types, then construct the corresponding array type.
 315         ciKlass* elem1 = k1->as_obj_array_klass()->element_klass();
 316         ciKlass* elem2 = k2->as_obj_array_klass()->element_klass();
 317         ciKlass* elem  = type_meet_internal(elem1, elem2, analyzer)->as_klass();
 318         // Do an easy shortcut if one type is a super of the other.
 319         if (elem == elem1) {
 320           assert(k1 == ciObjArrayKlass::make(elem), "shortcut is OK");
 321           return k1;
 322         } else if (elem == elem2) {
 323           assert(k2 == ciObjArrayKlass::make(elem), "shortcut is OK");
 324           return k2;
 325         } else {
 326           return ciObjArrayKlass::make(elem);
 327         }
 328       } else {
 329         return object_klass;
 330       }
 331     } else {
 332       // Must be two plain old instance klasses.
 333       assert(k1->is_instance_klass(), "previous cases handle non-instances");
 334       assert(k2->is_instance_klass(), "previous cases handle non-instances");
 335       return k1->least_common_ancestor(k2);
 336     }
 337   }
 338 }
 339 
 340 
 341 // ------------------------------------------------------------------
 342 // ciTypeFlow::StateVector::StateVector
 343 //
 344 // Build a new state vector
 345 ciTypeFlow::StateVector::StateVector(ciTypeFlow* analyzer) {
 346   _outer = analyzer;
 347   _stack_size = -1;
 348   _monitor_count = -1;
 349   // Allocate the _types array
 350   int max_cells = analyzer->max_cells();
 351   _types = (ciType**)analyzer->arena()->Amalloc(sizeof(ciType*) * max_cells);
 352   for (int i=0; i<max_cells; i++) {
 353     _types[i] = top_type();
 354   }
 355   _trap_bci = -1;
 356   _trap_index = 0;
 357   _def_locals.clear();
 358 }
 359 
 360 
 361 // ------------------------------------------------------------------
 362 // ciTypeFlow::get_start_state
 363 //
 364 // Set this vector to the method entry state.
 365 const ciTypeFlow::StateVector* ciTypeFlow::get_start_state() {
 366   StateVector* state = new StateVector(this);
 367   if (is_osr_flow()) {
 368     ciTypeFlow* non_osr_flow = method()->get_flow_analysis();
 369     if (non_osr_flow->failing()) {
 370       record_failure(non_osr_flow->failure_reason());
 371       return NULL;
 372     }
 373     JsrSet* jsrs = new JsrSet(NULL, 16);
 374     Block* non_osr_block = non_osr_flow->existing_block_at(start_bci(), jsrs);
 375     if (non_osr_block == NULL) {
 376       record_failure("cannot reach OSR point");
 377       return NULL;
 378     }
 379     // load up the non-OSR state at this point
 380     non_osr_block->copy_state_into(state);
 381     int non_osr_start = non_osr_block->start();
 382     if (non_osr_start != start_bci()) {
 383       // must flow forward from it
 384       if (CITraceTypeFlow) {
 385         tty->print_cr(">> Interpreting pre-OSR block %d:", non_osr_start);
 386       }
 387       Block* block = block_at(non_osr_start, jsrs);
 388       assert(block->limit() == start_bci(), "must flow forward to start");
 389       flow_block(block, state, jsrs);
 390     }
 391     return state;
 392     // Note:  The code below would be an incorrect for an OSR flow,
 393     // even if it were possible for an OSR entry point to be at bci zero.
 394   }
 395   // "Push" the method signature into the first few locals.
 396   state->set_stack_size(-max_locals());
 397   if (!method()->is_static()) {
 398     state->push(method()->holder());
 399     assert(state->tos() == state->local(0), "");
 400   }
 401   for (ciSignatureStream str(method()->signature());
 402        !str.at_return_type();
 403        str.next()) {
 404     state->push_translate(str.type());
 405   }
 406   // Set the rest of the locals to bottom.
 407   Cell cell = state->next_cell(state->tos());
 408   state->set_stack_size(0);
 409   int limit = state->limit_cell();
 410   for (; cell < limit; cell = state->next_cell(cell)) {
 411     state->set_type_at(cell, state->bottom_type());
 412   }
 413   // Lock an object, if necessary.
 414   state->set_monitor_count(method()->is_synchronized() ? 1 : 0);
 415   return state;
 416 }
 417 
 418 // ------------------------------------------------------------------
 419 // ciTypeFlow::StateVector::copy_into
 420 //
 421 // Copy our value into some other StateVector
 422 void ciTypeFlow::StateVector::copy_into(ciTypeFlow::StateVector* copy)
 423 const {
 424   copy->set_stack_size(stack_size());
 425   copy->set_monitor_count(monitor_count());
 426   Cell limit = limit_cell();
 427   for (Cell c = start_cell(); c < limit; c = next_cell(c)) {
 428     copy->set_type_at(c, type_at(c));
 429   }
 430 }
 431 
 432 // ------------------------------------------------------------------
 433 // ciTypeFlow::StateVector::meet
 434 //
 435 // Meets this StateVector with another, destructively modifying this
 436 // one.  Returns true if any modification takes place.
 437 bool ciTypeFlow::StateVector::meet(const ciTypeFlow::StateVector* incoming) {
 438   if (monitor_count() == -1) {
 439     set_monitor_count(incoming->monitor_count());
 440   }
 441   assert(monitor_count() == incoming->monitor_count(), "monitors must match");
 442 
 443   if (stack_size() == -1) {
 444     set_stack_size(incoming->stack_size());
 445     Cell limit = limit_cell();
 446     #ifdef ASSERT
 447     { for (Cell c = start_cell(); c < limit; c = next_cell(c)) {
 448         assert(type_at(c) == top_type(), "");
 449     } }
 450     #endif
 451     // Make a simple copy of the incoming state.
 452     for (Cell c = start_cell(); c < limit; c = next_cell(c)) {
 453       set_type_at(c, incoming->type_at(c));
 454     }
 455     return true;  // it is always different the first time
 456   }
 457 #ifdef ASSERT
 458   if (stack_size() != incoming->stack_size()) {
 459     _outer->method()->print_codes();
 460     tty->print_cr("!!!! Stack size conflict");
 461     tty->print_cr("Current state:");
 462     print_on(tty);
 463     tty->print_cr("Incoming state:");
 464     ((StateVector*)incoming)->print_on(tty);
 465   }
 466 #endif
 467   assert(stack_size() == incoming->stack_size(), "sanity");
 468 
 469   bool different = false;
 470   Cell limit = limit_cell();
 471   for (Cell c = start_cell(); c < limit; c = next_cell(c)) {
 472     ciType* t1 = type_at(c);
 473     ciType* t2 = incoming->type_at(c);
 474     if (!t1->equals(t2)) {
 475       ciType* new_type = type_meet(t1, t2);
 476       if (!t1->equals(new_type)) {
 477         set_type_at(c, new_type);
 478         different = true;
 479       }
 480     }
 481   }
 482   return different;
 483 }
 484 
 485 // ------------------------------------------------------------------
 486 // ciTypeFlow::StateVector::meet_exception
 487 //
 488 // Meets this StateVector with another, destructively modifying this
 489 // one.  The incoming state is coming via an exception.  Returns true
 490 // if any modification takes place.
 491 bool ciTypeFlow::StateVector::meet_exception(ciInstanceKlass* exc,
 492                                      const ciTypeFlow::StateVector* incoming) {
 493   if (monitor_count() == -1) {
 494     set_monitor_count(incoming->monitor_count());
 495   }
 496   assert(monitor_count() == incoming->monitor_count(), "monitors must match");
 497 
 498   if (stack_size() == -1) {
 499     set_stack_size(1);
 500   }
 501 
 502   assert(stack_size() ==  1, "must have one-element stack");
 503 
 504   bool different = false;
 505 
 506   // Meet locals from incoming array.
 507   Cell limit = local(_outer->max_locals()-1);
 508   for (Cell c = start_cell(); c <= limit; c = next_cell(c)) {
 509     ciType* t1 = type_at(c);
 510     ciType* t2 = incoming->type_at(c);
 511     if (!t1->equals(t2)) {
 512       ciType* new_type = type_meet(t1, t2);
 513       if (!t1->equals(new_type)) {
 514         set_type_at(c, new_type);
 515         different = true;
 516       }
 517     }
 518   }
 519 
 520   // Handle stack separately.  When an exception occurs, the
 521   // only stack entry is the exception instance.
 522   ciType* tos_type = type_at_tos();
 523   if (!tos_type->equals(exc)) {
 524     ciType* new_type = type_meet(tos_type, exc);
 525     if (!tos_type->equals(new_type)) {
 526       set_type_at_tos(new_type);
 527       different = true;
 528     }
 529   }
 530 
 531   return different;
 532 }
 533 
 534 // ------------------------------------------------------------------
 535 // ciTypeFlow::StateVector::push_translate
 536 void ciTypeFlow::StateVector::push_translate(ciType* type) {
 537   BasicType basic_type = type->basic_type();
 538   if (basic_type == T_BOOLEAN || basic_type == T_CHAR ||
 539       basic_type == T_BYTE    || basic_type == T_SHORT) {
 540     push_int();
 541   } else {
 542     push(type);
 543     if (type->is_two_word()) {
 544       push(half_type(type));
 545     }
 546   }
 547 }
 548 
 549 // ------------------------------------------------------------------
 550 // ciTypeFlow::StateVector::do_aaload
 551 void ciTypeFlow::StateVector::do_aaload(ciBytecodeStream* str) {
 552   pop_int();
 553   ciObjArrayKlass* array_klass = pop_objArray();
 554   if (array_klass == NULL) {
 555     // Did aaload on a null reference; push a null and ignore the exception.
 556     // This instruction will never continue normally.  All we have to do
 557     // is report a value that will meet correctly with any downstream
 558     // reference types on paths that will truly be executed.  This null type
 559     // meets with any reference type to yield that same reference type.
 560     // (The compiler will generate an unconditional exception here.)
 561     push(null_type());
 562     return;
 563   }
 564   if (!array_klass->is_loaded()) {
 565     // Only fails for some -Xcomp runs
 566     trap(str, array_klass,
 567          Deoptimization::make_trap_request
 568          (Deoptimization::Reason_unloaded,
 569           Deoptimization::Action_reinterpret));
 570     return;
 571   }
 572   ciKlass* element_klass = array_klass->element_klass();
 573   if (!element_klass->is_loaded() && element_klass->is_instance_klass()) {
 574     Untested("unloaded array element class in ciTypeFlow");
 575     trap(str, element_klass,
 576          Deoptimization::make_trap_request
 577          (Deoptimization::Reason_unloaded,
 578           Deoptimization::Action_reinterpret));
 579   } else {
 580     push_object(element_klass);
 581   }
 582 }
 583 
 584 
 585 // ------------------------------------------------------------------
 586 // ciTypeFlow::StateVector::do_checkcast
 587 void ciTypeFlow::StateVector::do_checkcast(ciBytecodeStream* str) {
 588   bool will_link;
 589   ciKlass* klass = str->get_klass(will_link);
 590   if (!will_link) {
 591     // VM's interpreter will not load 'klass' if object is NULL.
 592     // Type flow after this block may still be needed in two situations:
 593     // 1) C2 uses do_null_assert() and continues compilation for later blocks
 594     // 2) C2 does an OSR compile in a later block (see bug 4778368).
 595     pop_object();
 596     do_null_assert(klass);
 597   } else {
 598     pop_object();
 599     push_object(klass);
 600   }
 601 }
 602 
 603 // ------------------------------------------------------------------
 604 // ciTypeFlow::StateVector::do_getfield
 605 void ciTypeFlow::StateVector::do_getfield(ciBytecodeStream* str) {
 606   // could add assert here for type of object.
 607   pop_object();
 608   do_getstatic(str);
 609 }
 610 
 611 // ------------------------------------------------------------------
 612 // ciTypeFlow::StateVector::do_getstatic
 613 void ciTypeFlow::StateVector::do_getstatic(ciBytecodeStream* str) {
 614   bool will_link;
 615   ciField* field = str->get_field(will_link);
 616   if (!will_link) {
 617     trap(str, field->holder(), str->get_field_holder_index());
 618   } else {
 619     ciType* field_type = field->type();
 620     if (!field_type->is_loaded()) {
 621       // Normally, we need the field's type to be loaded if we are to
 622       // do anything interesting with its value.
 623       // We used to do this:  trap(str, str->get_field_signature_index());
 624       //
 625       // There is one good reason not to trap here.  Execution can
 626       // get past this "getfield" or "getstatic" if the value of
 627       // the field is null.  As long as the value is null, the class
 628       // does not need to be loaded!  The compiler must assume that
 629       // the value of the unloaded class reference is null; if the code
 630       // ever sees a non-null value, loading has occurred.
 631       //
 632       // This actually happens often enough to be annoying.  If the
 633       // compiler throws an uncommon trap at this bytecode, you can
 634       // get an endless loop of recompilations, when all the code
 635       // needs to do is load a series of null values.  Also, a trap
 636       // here can make an OSR entry point unreachable, triggering the
 637       // assert on non_osr_block in ciTypeFlow::get_start_state.
 638       // (See bug 4379915.)
 639       do_null_assert(field_type->as_klass());
 640     } else {
 641       push_translate(field_type);
 642     }
 643   }
 644 }
 645 
 646 // ------------------------------------------------------------------
 647 // ciTypeFlow::StateVector::do_invoke
 648 void ciTypeFlow::StateVector::do_invoke(ciBytecodeStream* str,
 649                                         bool has_receiver) {
 650   bool will_link;
 651   ciSignature* declared_signature = NULL;
 652   ciMethod* callee = str->get_method(will_link, &declared_signature);
 653   assert(declared_signature != NULL, "cannot be null");
 654   if (!will_link) {
 655     // We weren't able to find the method.
 656     if (str->cur_bc() == Bytecodes::_invokedynamic) {
 657       trap(str, NULL,
 658            Deoptimization::make_trap_request
 659            (Deoptimization::Reason_uninitialized,
 660             Deoptimization::Action_reinterpret));
 661     } else {
 662       ciKlass* unloaded_holder = callee->holder();
 663       trap(str, unloaded_holder, str->get_method_holder_index());
 664     }
 665   } else {
 666     // We are using the declared signature here because it might be
 667     // different from the callee signature (Cf. invokedynamic and
 668     // invokehandle).
 669     ciSignatureStream sigstr(declared_signature);
 670     const int arg_size = declared_signature->size();
 671     const int stack_base = stack_size() - arg_size;
 672     int i = 0;
 673     for( ; !sigstr.at_return_type(); sigstr.next()) {
 674       ciType* type = sigstr.type();
 675       ciType* stack_type = type_at(stack(stack_base + i++));
 676       // Do I want to check this type?
 677       // assert(stack_type->is_subtype_of(type), "bad type for field value");
 678       if (type->is_two_word()) {
 679         ciType* stack_type2 = type_at(stack(stack_base + i++));
 680         assert(stack_type2->equals(half_type(type)), "must be 2nd half");
 681       }
 682     }
 683     assert(arg_size == i, "must match");
 684     for (int j = 0; j < arg_size; j++) {
 685       pop();
 686     }
 687     if (has_receiver) {
 688       // Check this?
 689       pop_object();
 690     }
 691     assert(!sigstr.is_done(), "must have return type");
 692     ciType* return_type = sigstr.type();
 693     if (!return_type->is_void()) {
 694       if (!return_type->is_loaded()) {
 695         // As in do_getstatic(), generally speaking, we need the return type to
 696         // be loaded if we are to do anything interesting with its value.
 697         // We used to do this:  trap(str, str->get_method_signature_index());
 698         //
 699         // We do not trap here since execution can get past this invoke if
 700         // the return value is null.  As long as the value is null, the class
 701         // does not need to be loaded!  The compiler must assume that
 702         // the value of the unloaded class reference is null; if the code
 703         // ever sees a non-null value, loading has occurred.
 704         //
 705         // See do_getstatic() for similar explanation, as well as bug 4684993.
 706         do_null_assert(return_type->as_klass());
 707       } else {
 708         push_translate(return_type);
 709       }
 710     }
 711   }
 712 }
 713 
 714 // ------------------------------------------------------------------
 715 // ciTypeFlow::StateVector::do_jsr
 716 void ciTypeFlow::StateVector::do_jsr(ciBytecodeStream* str) {
 717   push(ciReturnAddress::make(str->next_bci()));
 718 }
 719 
 720 // ------------------------------------------------------------------
 721 // ciTypeFlow::StateVector::do_ldc
 722 void ciTypeFlow::StateVector::do_ldc(ciBytecodeStream* str) {
 723   ciConstant con = str->get_constant();
 724   BasicType basic_type = con.basic_type();
 725   if (basic_type == T_ILLEGAL) {
 726     // OutOfMemoryError in the CI while loading constant
 727     push_null();
 728     outer()->record_failure("ldc did not link");
 729     return;
 730   }
 731   if (basic_type == T_OBJECT || basic_type == T_ARRAY) {
 732     ciObject* obj = con.as_object();
 733     if (obj->is_null_object()) {
 734       push_null();
 735     } else {
 736       assert(obj->is_instance() || obj->is_array(), "must be java_mirror of klass");
 737       push_object(obj->klass());
 738     }
 739   } else {
 740     push_translate(ciType::make(basic_type));
 741   }
 742 }
 743 
 744 // ------------------------------------------------------------------
 745 // ciTypeFlow::StateVector::do_multianewarray
 746 void ciTypeFlow::StateVector::do_multianewarray(ciBytecodeStream* str) {
 747   int dimensions = str->get_dimensions();
 748   bool will_link;
 749   ciArrayKlass* array_klass = str->get_klass(will_link)->as_array_klass();
 750   if (!will_link) {
 751     trap(str, array_klass, str->get_klass_index());
 752   } else {
 753     for (int i = 0; i < dimensions; i++) {
 754       pop_int();
 755     }
 756     push_object(array_klass);
 757   }
 758 }
 759 
 760 // ------------------------------------------------------------------
 761 // ciTypeFlow::StateVector::do_new
 762 void ciTypeFlow::StateVector::do_new(ciBytecodeStream* str) {
 763   bool will_link;
 764   ciKlass* klass = str->get_klass(will_link);
 765   if (!will_link || str->is_unresolved_klass()) {
 766     trap(str, klass, str->get_klass_index());
 767   } else {
 768     push_object(klass);
 769   }
 770 }
 771 
 772 // ------------------------------------------------------------------
 773 // ciTypeFlow::StateVector::do_vnew
 774 void ciTypeFlow::StateVector::do_vnew(ciBytecodeStream* str) {
 775   // This assumes that vnew is only valid in a static value type constructor
 776   ciInstanceKlass* klass = str->method()->holder();
 777   // TODO add additional verification (see InterpreterRuntime::_vnew)
 778   assert(klass->is_valuetype(), "should be value type");
 779   // TODO do check for unresolved?
 780   // TODO value types should not be handled as objects
 781   push_object(klass);
 782 }
 783 
 784 // ------------------------------------------------------------------
 785 // ciTypeFlow::StateVector::do_newarray
 786 void ciTypeFlow::StateVector::do_newarray(ciBytecodeStream* str) {
 787   pop_int();
 788   ciKlass* klass = ciTypeArrayKlass::make((BasicType)str->get_index());
 789   push_object(klass);
 790 }
 791 
 792 // ------------------------------------------------------------------
 793 // ciTypeFlow::StateVector::do_putfield
 794 void ciTypeFlow::StateVector::do_putfield(ciBytecodeStream* str) {
 795   do_putstatic(str);
 796   if (_trap_bci != -1)  return;  // unloaded field holder, etc.
 797   // could add assert here for type of object.
 798   pop_object();
 799 }
 800 
 801 // ------------------------------------------------------------------
 802 // ciTypeFlow::StateVector::do_putstatic
 803 void ciTypeFlow::StateVector::do_putstatic(ciBytecodeStream* str) {
 804   bool will_link;
 805   ciField* field = str->get_field(will_link);
 806   if (!will_link) {
 807     trap(str, field->holder(), str->get_field_holder_index());
 808   } else {
 809     ciType* field_type = field->type();
 810     ciType* type = pop_value();
 811     // Do I want to check this type?
 812     //      assert(type->is_subtype_of(field_type), "bad type for field value");
 813     if (field_type->is_two_word()) {
 814       ciType* type2 = pop_value();
 815       assert(type2->is_two_word(), "must be 2nd half");
 816       assert(type == half_type(type2), "must be 2nd half");
 817     }
 818   }
 819 }
 820 
 821 // ------------------------------------------------------------------
 822 // ciTypeFlow::StateVector::do_ret
 823 void ciTypeFlow::StateVector::do_ret(ciBytecodeStream* str) {
 824   Cell index = local(str->get_index());
 825 
 826   ciType* address = type_at(index);
 827   assert(address->is_return_address(), "bad return address");
 828   set_type_at(index, bottom_type());
 829 }
 830 
 831 // ------------------------------------------------------------------
 832 // ciTypeFlow::StateVector::trap
 833 //
 834 // Stop interpretation of this path with a trap.
 835 void ciTypeFlow::StateVector::trap(ciBytecodeStream* str, ciKlass* klass, int index) {
 836   _trap_bci = str->cur_bci();
 837   _trap_index = index;
 838 
 839   // Log information about this trap:
 840   CompileLog* log = outer()->env()->log();
 841   if (log != NULL) {
 842     int mid = log->identify(outer()->method());
 843     int kid = (klass == NULL)? -1: log->identify(klass);
 844     log->begin_elem("uncommon_trap method='%d' bci='%d'", mid, str->cur_bci());
 845     char buf[100];
 846     log->print(" %s", Deoptimization::format_trap_request(buf, sizeof(buf),
 847                                                           index));
 848     if (kid >= 0)
 849       log->print(" klass='%d'", kid);
 850     log->end_elem();
 851   }
 852 }
 853 
 854 // ------------------------------------------------------------------
 855 // ciTypeFlow::StateVector::do_null_assert
 856 // Corresponds to graphKit::do_null_assert.
 857 void ciTypeFlow::StateVector::do_null_assert(ciKlass* unloaded_klass) {
 858   if (unloaded_klass->is_loaded()) {
 859     // We failed to link, but we can still compute with this class,
 860     // since it is loaded somewhere.  The compiler will uncommon_trap
 861     // if the object is not null, but the typeflow pass can not assume
 862     // that the object will be null, otherwise it may incorrectly tell
 863     // the parser that an object is known to be null. 4761344, 4807707
 864     push_object(unloaded_klass);
 865   } else {
 866     // The class is not loaded anywhere.  It is safe to model the
 867     // null in the typestates, because we can compile in a null check
 868     // which will deoptimize us if someone manages to load the
 869     // class later.
 870     push_null();
 871   }
 872 }
 873 
 874 
 875 // ------------------------------------------------------------------
 876 // ciTypeFlow::StateVector::apply_one_bytecode
 877 //
 878 // Apply the effect of one bytecode to this StateVector
 879 bool ciTypeFlow::StateVector::apply_one_bytecode(ciBytecodeStream* str) {
 880   _trap_bci = -1;
 881   _trap_index = 0;
 882 
 883   if (CITraceTypeFlow) {
 884     tty->print_cr(">> Interpreting bytecode %d:%s", str->cur_bci(),
 885                   Bytecodes::name(str->cur_bc()));
 886   }
 887 
 888   switch(str->cur_bc()) {
 889   case Bytecodes::_aaload: do_aaload(str);                       break;
 890 
 891   case Bytecodes::_aastore:
 892     {
 893       pop_object();
 894       pop_int();
 895       pop_objArray();
 896       break;
 897     }
 898   case Bytecodes::_aconst_null:
 899     {
 900       push_null();
 901       break;
 902     }
 903   case Bytecodes::_vload:
 904   case Bytecodes::_aload:   load_local_object(str->get_index());    break;
 905   case Bytecodes::_aload_0: load_local_object(0);                   break;
 906   case Bytecodes::_aload_1: load_local_object(1);                   break;
 907   case Bytecodes::_aload_2: load_local_object(2);                   break;
 908   case Bytecodes::_aload_3: load_local_object(3);                   break;
 909 
 910   case Bytecodes::_anewarray:
 911     {
 912       pop_int();
 913       bool will_link;
 914       ciKlass* element_klass = str->get_klass(will_link);
 915       if (!will_link) {
 916         trap(str, element_klass, str->get_klass_index());
 917       } else {
 918         push_object(ciObjArrayKlass::make(element_klass));
 919       }
 920       break;
 921     }
 922   case Bytecodes::_areturn:
 923   case Bytecodes::_vreturn:
 924   case Bytecodes::_ifnonnull:
 925   case Bytecodes::_ifnull:
 926     {
 927       pop_object();
 928       break;
 929     }
 930   case Bytecodes::_monitorenter:
 931     {
 932       pop_object();
 933       set_monitor_count(monitor_count() + 1);
 934       break;
 935     }
 936   case Bytecodes::_monitorexit:
 937     {
 938       pop_object();
 939       assert(monitor_count() > 0, "must be a monitor to exit from");
 940       set_monitor_count(monitor_count() - 1);
 941       break;
 942     }
 943   case Bytecodes::_arraylength:
 944     {
 945       pop_array();
 946       push_int();
 947       break;
 948     }
 949   case Bytecodes::_vstore:
 950   case Bytecodes::_astore:   store_local_object(str->get_index());  break;
 951   case Bytecodes::_astore_0: store_local_object(0);                 break;
 952   case Bytecodes::_astore_1: store_local_object(1);                 break;
 953   case Bytecodes::_astore_2: store_local_object(2);                 break;
 954   case Bytecodes::_astore_3: store_local_object(3);                 break;
 955 
 956   case Bytecodes::_athrow:
 957     {
 958       NEEDS_CLEANUP;
 959       pop_object();
 960       break;
 961     }
 962   case Bytecodes::_baload:
 963   case Bytecodes::_caload:
 964   case Bytecodes::_iaload:
 965   case Bytecodes::_saload:
 966     {
 967       pop_int();
 968       ciTypeArrayKlass* array_klass = pop_typeArray();
 969       // Put assert here for right type?
 970       push_int();
 971       break;
 972     }
 973   case Bytecodes::_bastore:
 974   case Bytecodes::_castore:
 975   case Bytecodes::_iastore:
 976   case Bytecodes::_sastore:
 977     {
 978       pop_int();
 979       pop_int();
 980       pop_typeArray();
 981       // assert here?
 982       break;
 983     }
 984   case Bytecodes::_bipush:
 985   case Bytecodes::_iconst_m1:
 986   case Bytecodes::_iconst_0:
 987   case Bytecodes::_iconst_1:
 988   case Bytecodes::_iconst_2:
 989   case Bytecodes::_iconst_3:
 990   case Bytecodes::_iconst_4:
 991   case Bytecodes::_iconst_5:
 992   case Bytecodes::_sipush:
 993     {
 994       push_int();
 995       break;
 996     }
 997   case Bytecodes::_checkcast: do_checkcast(str);                  break;
 998 
 999   case Bytecodes::_d2f:
1000     {
1001       pop_double();
1002       push_float();
1003       break;
1004     }
1005   case Bytecodes::_d2i:
1006     {
1007       pop_double();
1008       push_int();
1009       break;
1010     }
1011   case Bytecodes::_d2l:
1012     {
1013       pop_double();
1014       push_long();
1015       break;
1016     }
1017   case Bytecodes::_dadd:
1018   case Bytecodes::_ddiv:
1019   case Bytecodes::_dmul:
1020   case Bytecodes::_drem:
1021   case Bytecodes::_dsub:
1022     {
1023       pop_double();
1024       pop_double();
1025       push_double();
1026       break;
1027     }
1028   case Bytecodes::_daload:
1029     {
1030       pop_int();
1031       ciTypeArrayKlass* array_klass = pop_typeArray();
1032       // Put assert here for right type?
1033       push_double();
1034       break;
1035     }
1036   case Bytecodes::_dastore:
1037     {
1038       pop_double();
1039       pop_int();
1040       pop_typeArray();
1041       // assert here?
1042       break;
1043     }
1044   case Bytecodes::_dcmpg:
1045   case Bytecodes::_dcmpl:
1046     {
1047       pop_double();
1048       pop_double();
1049       push_int();
1050       break;
1051     }
1052   case Bytecodes::_dconst_0:
1053   case Bytecodes::_dconst_1:
1054     {
1055       push_double();
1056       break;
1057     }
1058   case Bytecodes::_dload:   load_local_double(str->get_index());    break;
1059   case Bytecodes::_dload_0: load_local_double(0);                   break;
1060   case Bytecodes::_dload_1: load_local_double(1);                   break;
1061   case Bytecodes::_dload_2: load_local_double(2);                   break;
1062   case Bytecodes::_dload_3: load_local_double(3);                   break;
1063 
1064   case Bytecodes::_dneg:
1065     {
1066       pop_double();
1067       push_double();
1068       break;
1069     }
1070   case Bytecodes::_dreturn:
1071     {
1072       pop_double();
1073       break;
1074     }
1075   case Bytecodes::_dstore:   store_local_double(str->get_index());  break;
1076   case Bytecodes::_dstore_0: store_local_double(0);                 break;
1077   case Bytecodes::_dstore_1: store_local_double(1);                 break;
1078   case Bytecodes::_dstore_2: store_local_double(2);                 break;
1079   case Bytecodes::_dstore_3: store_local_double(3);                 break;
1080 
1081   case Bytecodes::_dup:
1082     {
1083       push(type_at_tos());
1084       break;
1085     }
1086   case Bytecodes::_dup_x1:
1087     {
1088       ciType* value1 = pop_value();
1089       ciType* value2 = pop_value();
1090       push(value1);
1091       push(value2);
1092       push(value1);
1093       break;
1094     }
1095   case Bytecodes::_dup_x2:
1096     {
1097       ciType* value1 = pop_value();
1098       ciType* value2 = pop_value();
1099       ciType* value3 = pop_value();
1100       push(value1);
1101       push(value3);
1102       push(value2);
1103       push(value1);
1104       break;
1105     }
1106   case Bytecodes::_dup2:
1107     {
1108       ciType* value1 = pop_value();
1109       ciType* value2 = pop_value();
1110       push(value2);
1111       push(value1);
1112       push(value2);
1113       push(value1);
1114       break;
1115     }
1116   case Bytecodes::_dup2_x1:
1117     {
1118       ciType* value1 = pop_value();
1119       ciType* value2 = pop_value();
1120       ciType* value3 = pop_value();
1121       push(value2);
1122       push(value1);
1123       push(value3);
1124       push(value2);
1125       push(value1);
1126       break;
1127     }
1128   case Bytecodes::_dup2_x2:
1129     {
1130       ciType* value1 = pop_value();
1131       ciType* value2 = pop_value();
1132       ciType* value3 = pop_value();
1133       ciType* value4 = pop_value();
1134       push(value2);
1135       push(value1);
1136       push(value4);
1137       push(value3);
1138       push(value2);
1139       push(value1);
1140       break;
1141     }
1142   case Bytecodes::_f2d:
1143     {
1144       pop_float();
1145       push_double();
1146       break;
1147     }
1148   case Bytecodes::_f2i:
1149     {
1150       pop_float();
1151       push_int();
1152       break;
1153     }
1154   case Bytecodes::_f2l:
1155     {
1156       pop_float();
1157       push_long();
1158       break;
1159     }
1160   case Bytecodes::_fadd:
1161   case Bytecodes::_fdiv:
1162   case Bytecodes::_fmul:
1163   case Bytecodes::_frem:
1164   case Bytecodes::_fsub:
1165     {
1166       pop_float();
1167       pop_float();
1168       push_float();
1169       break;
1170     }
1171   case Bytecodes::_faload:
1172     {
1173       pop_int();
1174       ciTypeArrayKlass* array_klass = pop_typeArray();
1175       // Put assert here.
1176       push_float();
1177       break;
1178     }
1179   case Bytecodes::_fastore:
1180     {
1181       pop_float();
1182       pop_int();
1183       ciTypeArrayKlass* array_klass = pop_typeArray();
1184       // Put assert here.
1185       break;
1186     }
1187   case Bytecodes::_fcmpg:
1188   case Bytecodes::_fcmpl:
1189     {
1190       pop_float();
1191       pop_float();
1192       push_int();
1193       break;
1194     }
1195   case Bytecodes::_fconst_0:
1196   case Bytecodes::_fconst_1:
1197   case Bytecodes::_fconst_2:
1198     {
1199       push_float();
1200       break;
1201     }
1202   case Bytecodes::_fload:   load_local_float(str->get_index());     break;
1203   case Bytecodes::_fload_0: load_local_float(0);                    break;
1204   case Bytecodes::_fload_1: load_local_float(1);                    break;
1205   case Bytecodes::_fload_2: load_local_float(2);                    break;
1206   case Bytecodes::_fload_3: load_local_float(3);                    break;
1207 
1208   case Bytecodes::_fneg:
1209     {
1210       pop_float();
1211       push_float();
1212       break;
1213     }
1214   case Bytecodes::_freturn:
1215     {
1216       pop_float();
1217       break;
1218     }
1219   case Bytecodes::_fstore:    store_local_float(str->get_index());   break;
1220   case Bytecodes::_fstore_0:  store_local_float(0);                  break;
1221   case Bytecodes::_fstore_1:  store_local_float(1);                  break;
1222   case Bytecodes::_fstore_2:  store_local_float(2);                  break;
1223   case Bytecodes::_fstore_3:  store_local_float(3);                  break;
1224 
1225   case Bytecodes::_vgetfield:
1226   case Bytecodes::_getfield:  do_getfield(str);                      break;
1227   case Bytecodes::_getstatic: do_getstatic(str);                     break;
1228 
1229   case Bytecodes::_goto:
1230   case Bytecodes::_goto_w:
1231   case Bytecodes::_nop:
1232   case Bytecodes::_return:
1233     {
1234       // do nothing.
1235       break;
1236     }
1237   case Bytecodes::_i2b:
1238   case Bytecodes::_i2c:
1239   case Bytecodes::_i2s:
1240   case Bytecodes::_ineg:
1241     {
1242       pop_int();
1243       push_int();
1244       break;
1245     }
1246   case Bytecodes::_i2d:
1247     {
1248       pop_int();
1249       push_double();
1250       break;
1251     }
1252   case Bytecodes::_i2f:
1253     {
1254       pop_int();
1255       push_float();
1256       break;
1257     }
1258   case Bytecodes::_i2l:
1259     {
1260       pop_int();
1261       push_long();
1262       break;
1263     }
1264   case Bytecodes::_iadd:
1265   case Bytecodes::_iand:
1266   case Bytecodes::_idiv:
1267   case Bytecodes::_imul:
1268   case Bytecodes::_ior:
1269   case Bytecodes::_irem:
1270   case Bytecodes::_ishl:
1271   case Bytecodes::_ishr:
1272   case Bytecodes::_isub:
1273   case Bytecodes::_iushr:
1274   case Bytecodes::_ixor:
1275     {
1276       pop_int();
1277       pop_int();
1278       push_int();
1279       break;
1280     }
1281   case Bytecodes::_if_acmpeq:
1282   case Bytecodes::_if_acmpne:
1283     {
1284       pop_object();
1285       pop_object();
1286       break;
1287     }
1288   case Bytecodes::_if_icmpeq:
1289   case Bytecodes::_if_icmpge:
1290   case Bytecodes::_if_icmpgt:
1291   case Bytecodes::_if_icmple:
1292   case Bytecodes::_if_icmplt:
1293   case Bytecodes::_if_icmpne:
1294     {
1295       pop_int();
1296       pop_int();
1297       break;
1298     }
1299   case Bytecodes::_ifeq:
1300   case Bytecodes::_ifle:
1301   case Bytecodes::_iflt:
1302   case Bytecodes::_ifge:
1303   case Bytecodes::_ifgt:
1304   case Bytecodes::_ifne:
1305   case Bytecodes::_ireturn:
1306   case Bytecodes::_lookupswitch:
1307   case Bytecodes::_tableswitch:
1308     {
1309       pop_int();
1310       break;
1311     }
1312   case Bytecodes::_iinc:
1313     {
1314       int lnum = str->get_index();
1315       check_int(local(lnum));
1316       store_to_local(lnum);
1317       break;
1318     }
1319   case Bytecodes::_iload:   load_local_int(str->get_index()); break;
1320   case Bytecodes::_iload_0: load_local_int(0);                      break;
1321   case Bytecodes::_iload_1: load_local_int(1);                      break;
1322   case Bytecodes::_iload_2: load_local_int(2);                      break;
1323   case Bytecodes::_iload_3: load_local_int(3);                      break;
1324 
1325   case Bytecodes::_instanceof:
1326     {
1327       // Check for uncommon trap:
1328       do_checkcast(str);
1329       pop_object();
1330       push_int();
1331       break;
1332     }
1333   case Bytecodes::_invokeinterface: do_invoke(str, true);           break;
1334   case Bytecodes::_invokespecial:   do_invoke(str, true);           break;
1335   case Bytecodes::_invokestatic:    do_invoke(str, false);          break;
1336   case Bytecodes::_invokedirect:
1337   case Bytecodes::_invokevirtual:   do_invoke(str, true);           break;
1338   case Bytecodes::_invokedynamic:   do_invoke(str, false);          break;
1339 
1340   case Bytecodes::_istore:   store_local_int(str->get_index());     break;
1341   case Bytecodes::_istore_0: store_local_int(0);                    break;
1342   case Bytecodes::_istore_1: store_local_int(1);                    break;
1343   case Bytecodes::_istore_2: store_local_int(2);                    break;
1344   case Bytecodes::_istore_3: store_local_int(3);                    break;
1345 
1346   case Bytecodes::_jsr:
1347   case Bytecodes::_jsr_w: do_jsr(str);                              break;
1348 
1349   case Bytecodes::_l2d:
1350     {
1351       pop_long();
1352       push_double();
1353       break;
1354     }
1355   case Bytecodes::_l2f:
1356     {
1357       pop_long();
1358       push_float();
1359       break;
1360     }
1361   case Bytecodes::_l2i:
1362     {
1363       pop_long();
1364       push_int();
1365       break;
1366     }
1367   case Bytecodes::_ladd:
1368   case Bytecodes::_land:
1369   case Bytecodes::_ldiv:
1370   case Bytecodes::_lmul:
1371   case Bytecodes::_lor:
1372   case Bytecodes::_lrem:
1373   case Bytecodes::_lsub:
1374   case Bytecodes::_lxor:
1375     {
1376       pop_long();
1377       pop_long();
1378       push_long();
1379       break;
1380     }
1381   case Bytecodes::_laload:
1382     {
1383       pop_int();
1384       ciTypeArrayKlass* array_klass = pop_typeArray();
1385       // Put assert here for right type?
1386       push_long();
1387       break;
1388     }
1389   case Bytecodes::_lastore:
1390     {
1391       pop_long();
1392       pop_int();
1393       pop_typeArray();
1394       // assert here?
1395       break;
1396     }
1397   case Bytecodes::_lcmp:
1398     {
1399       pop_long();
1400       pop_long();
1401       push_int();
1402       break;
1403     }
1404   case Bytecodes::_lconst_0:
1405   case Bytecodes::_lconst_1:
1406     {
1407       push_long();
1408       break;
1409     }
1410   case Bytecodes::_ldc:
1411   case Bytecodes::_ldc_w:
1412   case Bytecodes::_ldc2_w:
1413     {
1414       do_ldc(str);
1415       break;
1416     }
1417 
1418   case Bytecodes::_lload:   load_local_long(str->get_index());      break;
1419   case Bytecodes::_lload_0: load_local_long(0);                     break;
1420   case Bytecodes::_lload_1: load_local_long(1);                     break;
1421   case Bytecodes::_lload_2: load_local_long(2);                     break;
1422   case Bytecodes::_lload_3: load_local_long(3);                     break;
1423 
1424   case Bytecodes::_lneg:
1425     {
1426       pop_long();
1427       push_long();
1428       break;
1429     }
1430   case Bytecodes::_lreturn:
1431     {
1432       pop_long();
1433       break;
1434     }
1435   case Bytecodes::_lshl:
1436   case Bytecodes::_lshr:
1437   case Bytecodes::_lushr:
1438     {
1439       pop_int();
1440       pop_long();
1441       push_long();
1442       break;
1443     }
1444   case Bytecodes::_lstore:   store_local_long(str->get_index());    break;
1445   case Bytecodes::_lstore_0: store_local_long(0);                   break;
1446   case Bytecodes::_lstore_1: store_local_long(1);                   break;
1447   case Bytecodes::_lstore_2: store_local_long(2);                   break;
1448   case Bytecodes::_lstore_3: store_local_long(3);                   break;
1449 
1450   case Bytecodes::_multianewarray: do_multianewarray(str);          break;
1451   case Bytecodes::_new:      do_new(str);                           break;
1452   case Bytecodes::_vnew:     do_vnew(str);                          break;
1453 
1454   case Bytecodes::_newarray: do_newarray(str);                      break;
1455 
1456   case Bytecodes::_pop:
1457     {
1458       pop();
1459       break;
1460     }
1461   case Bytecodes::_pop2:
1462     {
1463       pop();
1464       pop();
1465       break;
1466     }
1467 
1468   case Bytecodes::_putfield:       do_putfield(str);                 break;
1469   case Bytecodes::_putstatic:      do_putstatic(str);                break;
1470 
1471   case Bytecodes::_ret: do_ret(str);                                 break;
1472 
1473   case Bytecodes::_swap:
1474     {
1475       ciType* value1 = pop_value();
1476       ciType* value2 = pop_value();
1477       push(value1);
1478       push(value2);
1479       break;
1480     }
1481   case Bytecodes::_wide:
1482   default:
1483     {
1484       // The iterator should skip this.
1485       ShouldNotReachHere();
1486       break;
1487     }
1488   }
1489 
1490   if (CITraceTypeFlow) {
1491     print_on(tty);
1492   }
1493 
1494   return (_trap_bci != -1);
1495 }
1496 
1497 #ifndef PRODUCT
1498 // ------------------------------------------------------------------
1499 // ciTypeFlow::StateVector::print_cell_on
1500 void ciTypeFlow::StateVector::print_cell_on(outputStream* st, Cell c) const {
1501   ciType* type = type_at(c);
1502   if (type == top_type()) {
1503     st->print("top");
1504   } else if (type == bottom_type()) {
1505     st->print("bottom");
1506   } else if (type == null_type()) {
1507     st->print("null");
1508   } else if (type == long2_type()) {
1509     st->print("long2");
1510   } else if (type == double2_type()) {
1511     st->print("double2");
1512   } else if (is_int(type)) {
1513     st->print("int");
1514   } else if (is_long(type)) {
1515     st->print("long");
1516   } else if (is_float(type)) {
1517     st->print("float");
1518   } else if (is_double(type)) {
1519     st->print("double");
1520   } else if (type->is_return_address()) {
1521     st->print("address(%d)", type->as_return_address()->bci());
1522   } else {
1523     if (type->is_klass()) {
1524       type->as_klass()->name()->print_symbol_on(st);
1525     } else {
1526       st->print("UNEXPECTED TYPE");
1527       type->print();
1528     }
1529   }
1530 }
1531 
1532 // ------------------------------------------------------------------
1533 // ciTypeFlow::StateVector::print_on
1534 void ciTypeFlow::StateVector::print_on(outputStream* st) const {
1535   int num_locals   = _outer->max_locals();
1536   int num_stack    = stack_size();
1537   int num_monitors = monitor_count();
1538   st->print_cr("  State : locals %d, stack %d, monitors %d", num_locals, num_stack, num_monitors);
1539   if (num_stack >= 0) {
1540     int i;
1541     for (i = 0; i < num_locals; i++) {
1542       st->print("    local %2d : ", i);
1543       print_cell_on(st, local(i));
1544       st->cr();
1545     }
1546     for (i = 0; i < num_stack; i++) {
1547       st->print("    stack %2d : ", i);
1548       print_cell_on(st, stack(i));
1549       st->cr();
1550     }
1551   }
1552 }
1553 #endif
1554 
1555 
1556 // ------------------------------------------------------------------
1557 // ciTypeFlow::SuccIter::next
1558 //
1559 void ciTypeFlow::SuccIter::next() {
1560   int succ_ct = _pred->successors()->length();
1561   int next = _index + 1;
1562   if (next < succ_ct) {
1563     _index = next;
1564     _succ = _pred->successors()->at(next);
1565     return;
1566   }
1567   for (int i = next - succ_ct; i < _pred->exceptions()->length(); i++) {
1568     // Do not compile any code for unloaded exception types.
1569     // Following compiler passes are responsible for doing this also.
1570     ciInstanceKlass* exception_klass = _pred->exc_klasses()->at(i);
1571     if (exception_klass->is_loaded()) {
1572       _index = next;
1573       _succ = _pred->exceptions()->at(i);
1574       return;
1575     }
1576     next++;
1577   }
1578   _index = -1;
1579   _succ = NULL;
1580 }
1581 
1582 // ------------------------------------------------------------------
1583 // ciTypeFlow::SuccIter::set_succ
1584 //
1585 void ciTypeFlow::SuccIter::set_succ(Block* succ) {
1586   int succ_ct = _pred->successors()->length();
1587   if (_index < succ_ct) {
1588     _pred->successors()->at_put(_index, succ);
1589   } else {
1590     int idx = _index - succ_ct;
1591     _pred->exceptions()->at_put(idx, succ);
1592   }
1593 }
1594 
1595 // ciTypeFlow::Block
1596 //
1597 // A basic block.
1598 
1599 // ------------------------------------------------------------------
1600 // ciTypeFlow::Block::Block
1601 ciTypeFlow::Block::Block(ciTypeFlow* outer,
1602                          ciBlock *ciblk,
1603                          ciTypeFlow::JsrSet* jsrs) {
1604   _ciblock = ciblk;
1605   _exceptions = NULL;
1606   _exc_klasses = NULL;
1607   _successors = NULL;
1608   _predecessors = new (outer->arena()) GrowableArray<Block*>(outer->arena(), 1, 0, NULL);
1609   _state = new (outer->arena()) StateVector(outer);
1610   JsrSet* new_jsrs =
1611     new (outer->arena()) JsrSet(outer->arena(), jsrs->size());
1612   jsrs->copy_into(new_jsrs);
1613   _jsrs = new_jsrs;
1614   _next = NULL;
1615   _on_work_list = false;
1616   _backedge_copy = false;
1617   _has_monitorenter = false;
1618   _trap_bci = -1;
1619   _trap_index = 0;
1620   df_init();
1621 
1622   if (CITraceTypeFlow) {
1623     tty->print_cr(">> Created new block");
1624     print_on(tty);
1625   }
1626 
1627   assert(this->outer() == outer, "outer link set up");
1628   assert(!outer->have_block_count(), "must not have mapped blocks yet");
1629 }
1630 
1631 // ------------------------------------------------------------------
1632 // ciTypeFlow::Block::df_init
1633 void ciTypeFlow::Block::df_init() {
1634   _pre_order = -1; assert(!has_pre_order(), "");
1635   _post_order = -1; assert(!has_post_order(), "");
1636   _loop = NULL;
1637   _irreducible_entry = false;
1638   _rpo_next = NULL;
1639 }
1640 
1641 // ------------------------------------------------------------------
1642 // ciTypeFlow::Block::successors
1643 //
1644 // Get the successors for this Block.
1645 GrowableArray<ciTypeFlow::Block*>*
1646 ciTypeFlow::Block::successors(ciBytecodeStream* str,
1647                               ciTypeFlow::StateVector* state,
1648                               ciTypeFlow::JsrSet* jsrs) {
1649   if (_successors == NULL) {
1650     if (CITraceTypeFlow) {
1651       tty->print(">> Computing successors for block ");
1652       print_value_on(tty);
1653       tty->cr();
1654     }
1655 
1656     ciTypeFlow* analyzer = outer();
1657     Arena* arena = analyzer->arena();
1658     Block* block = NULL;
1659     bool has_successor = !has_trap() &&
1660                          (control() != ciBlock::fall_through_bci || limit() < analyzer->code_size());
1661     if (!has_successor) {
1662       _successors =
1663         new (arena) GrowableArray<Block*>(arena, 1, 0, NULL);
1664       // No successors
1665     } else if (control() == ciBlock::fall_through_bci) {
1666       assert(str->cur_bci() == limit(), "bad block end");
1667       // This block simply falls through to the next.
1668       _successors =
1669         new (arena) GrowableArray<Block*>(arena, 1, 0, NULL);
1670 
1671       Block* block = analyzer->block_at(limit(), _jsrs);
1672       assert(_successors->length() == FALL_THROUGH, "");
1673       _successors->append(block);
1674     } else {
1675       int current_bci = str->cur_bci();
1676       int next_bci = str->next_bci();
1677       int branch_bci = -1;
1678       Block* target = NULL;
1679       assert(str->next_bci() == limit(), "bad block end");
1680       // This block is not a simple fall-though.  Interpret
1681       // the current bytecode to find our successors.
1682       switch (str->cur_bc()) {
1683       case Bytecodes::_ifeq:         case Bytecodes::_ifne:
1684       case Bytecodes::_iflt:         case Bytecodes::_ifge:
1685       case Bytecodes::_ifgt:         case Bytecodes::_ifle:
1686       case Bytecodes::_if_icmpeq:    case Bytecodes::_if_icmpne:
1687       case Bytecodes::_if_icmplt:    case Bytecodes::_if_icmpge:
1688       case Bytecodes::_if_icmpgt:    case Bytecodes::_if_icmple:
1689       case Bytecodes::_if_acmpeq:    case Bytecodes::_if_acmpne:
1690       case Bytecodes::_ifnull:       case Bytecodes::_ifnonnull:
1691         // Our successors are the branch target and the next bci.
1692         branch_bci = str->get_dest();
1693         _successors =
1694           new (arena) GrowableArray<Block*>(arena, 2, 0, NULL);
1695         assert(_successors->length() == IF_NOT_TAKEN, "");
1696         _successors->append(analyzer->block_at(next_bci, jsrs));
1697         assert(_successors->length() == IF_TAKEN, "");
1698         _successors->append(analyzer->block_at(branch_bci, jsrs));
1699         break;
1700 
1701       case Bytecodes::_goto:
1702         branch_bci = str->get_dest();
1703         _successors =
1704           new (arena) GrowableArray<Block*>(arena, 1, 0, NULL);
1705         assert(_successors->length() == GOTO_TARGET, "");
1706         _successors->append(analyzer->block_at(branch_bci, jsrs));
1707         break;
1708 
1709       case Bytecodes::_jsr:
1710         branch_bci = str->get_dest();
1711         _successors =
1712           new (arena) GrowableArray<Block*>(arena, 1, 0, NULL);
1713         assert(_successors->length() == GOTO_TARGET, "");
1714         _successors->append(analyzer->block_at(branch_bci, jsrs));
1715         break;
1716 
1717       case Bytecodes::_goto_w:
1718       case Bytecodes::_jsr_w:
1719         _successors =
1720           new (arena) GrowableArray<Block*>(arena, 1, 0, NULL);
1721         assert(_successors->length() == GOTO_TARGET, "");
1722         _successors->append(analyzer->block_at(str->get_far_dest(), jsrs));
1723         break;
1724 
1725       case Bytecodes::_tableswitch:  {
1726         Bytecode_tableswitch tableswitch(str);
1727 
1728         int len = tableswitch.length();
1729         _successors =
1730           new (arena) GrowableArray<Block*>(arena, len+1, 0, NULL);
1731         int bci = current_bci + tableswitch.default_offset();
1732         Block* block = analyzer->block_at(bci, jsrs);
1733         assert(_successors->length() == SWITCH_DEFAULT, "");
1734         _successors->append(block);
1735         while (--len >= 0) {
1736           int bci = current_bci + tableswitch.dest_offset_at(len);
1737           block = analyzer->block_at(bci, jsrs);
1738           assert(_successors->length() >= SWITCH_CASES, "");
1739           _successors->append_if_missing(block);
1740         }
1741         break;
1742       }
1743 
1744       case Bytecodes::_lookupswitch: {
1745         Bytecode_lookupswitch lookupswitch(str);
1746 
1747         int npairs = lookupswitch.number_of_pairs();
1748         _successors =
1749           new (arena) GrowableArray<Block*>(arena, npairs+1, 0, NULL);
1750         int bci = current_bci + lookupswitch.default_offset();
1751         Block* block = analyzer->block_at(bci, jsrs);
1752         assert(_successors->length() == SWITCH_DEFAULT, "");
1753         _successors->append(block);
1754         while(--npairs >= 0) {
1755           LookupswitchPair pair = lookupswitch.pair_at(npairs);
1756           int bci = current_bci + pair.offset();
1757           Block* block = analyzer->block_at(bci, jsrs);
1758           assert(_successors->length() >= SWITCH_CASES, "");
1759           _successors->append_if_missing(block);
1760         }
1761         break;
1762       }
1763 
1764       case Bytecodes::_athrow:
1765       case Bytecodes::_ireturn:
1766       case Bytecodes::_lreturn:
1767       case Bytecodes::_freturn:
1768       case Bytecodes::_dreturn:
1769       case Bytecodes::_areturn:
1770       case Bytecodes::_vreturn:
1771       case Bytecodes::_return:
1772         _successors =
1773           new (arena) GrowableArray<Block*>(arena, 1, 0, NULL);
1774         // No successors
1775         break;
1776 
1777       case Bytecodes::_ret: {
1778         _successors =
1779           new (arena) GrowableArray<Block*>(arena, 1, 0, NULL);
1780 
1781         Cell local = state->local(str->get_index());
1782         ciType* return_address = state->type_at(local);
1783         assert(return_address->is_return_address(), "verify: wrong type");
1784         int bci = return_address->as_return_address()->bci();
1785         assert(_successors->length() == GOTO_TARGET, "");
1786         _successors->append(analyzer->block_at(bci, jsrs));
1787         break;
1788       }
1789 
1790       case Bytecodes::_wide:
1791       default:
1792         ShouldNotReachHere();
1793         break;
1794       }
1795     }
1796 
1797     // Set predecessor information
1798     for (int i = 0; i < _successors->length(); i++) {
1799       Block* block = _successors->at(i);
1800       block->predecessors()->append(this);
1801     }
1802   }
1803   return _successors;
1804 }
1805 
1806 // ------------------------------------------------------------------
1807 // ciTypeFlow::Block:compute_exceptions
1808 //
1809 // Compute the exceptional successors and types for this Block.
1810 void ciTypeFlow::Block::compute_exceptions() {
1811   assert(_exceptions == NULL && _exc_klasses == NULL, "repeat");
1812 
1813   if (CITraceTypeFlow) {
1814     tty->print(">> Computing exceptions for block ");
1815     print_value_on(tty);
1816     tty->cr();
1817   }
1818 
1819   ciTypeFlow* analyzer = outer();
1820   Arena* arena = analyzer->arena();
1821 
1822   // Any bci in the block will do.
1823   ciExceptionHandlerStream str(analyzer->method(), start());
1824 
1825   // Allocate our growable arrays.
1826   int exc_count = str.count();
1827   _exceptions = new (arena) GrowableArray<Block*>(arena, exc_count, 0, NULL);
1828   _exc_klasses = new (arena) GrowableArray<ciInstanceKlass*>(arena, exc_count,
1829                                                              0, NULL);
1830 
1831   for ( ; !str.is_done(); str.next()) {
1832     ciExceptionHandler* handler = str.handler();
1833     int bci = handler->handler_bci();
1834     ciInstanceKlass* klass = NULL;
1835     if (bci == -1) {
1836       // There is no catch all.  It is possible to exit the method.
1837       break;
1838     }
1839     if (handler->is_catch_all()) {
1840       klass = analyzer->env()->Throwable_klass();
1841     } else {
1842       klass = handler->catch_klass();
1843     }
1844     Block* block = analyzer->block_at(bci, _jsrs);
1845     _exceptions->append(block);
1846     block->predecessors()->append(this);
1847     _exc_klasses->append(klass);
1848   }
1849 }
1850 
1851 // ------------------------------------------------------------------
1852 // ciTypeFlow::Block::set_backedge_copy
1853 // Use this only to make a pre-existing public block into a backedge copy.
1854 void ciTypeFlow::Block::set_backedge_copy(bool z) {
1855   assert(z || (z == is_backedge_copy()), "cannot make a backedge copy public");
1856   _backedge_copy = z;
1857 }
1858 
1859 // ------------------------------------------------------------------
1860 // ciTypeFlow::Block::is_clonable_exit
1861 //
1862 // At most 2 normal successors, one of which continues looping,
1863 // and all exceptional successors must exit.
1864 bool ciTypeFlow::Block::is_clonable_exit(ciTypeFlow::Loop* lp) {
1865   int normal_cnt  = 0;
1866   int in_loop_cnt = 0;
1867   for (SuccIter iter(this); !iter.done(); iter.next()) {
1868     Block* succ = iter.succ();
1869     if (iter.is_normal_ctrl()) {
1870       if (++normal_cnt > 2) return false;
1871       if (lp->contains(succ->loop())) {
1872         if (++in_loop_cnt > 1) return false;
1873       }
1874     } else {
1875       if (lp->contains(succ->loop())) return false;
1876     }
1877   }
1878   return in_loop_cnt == 1;
1879 }
1880 
1881 // ------------------------------------------------------------------
1882 // ciTypeFlow::Block::looping_succ
1883 //
1884 ciTypeFlow::Block* ciTypeFlow::Block::looping_succ(ciTypeFlow::Loop* lp) {
1885   assert(successors()->length() <= 2, "at most 2 normal successors");
1886   for (SuccIter iter(this); !iter.done(); iter.next()) {
1887     Block* succ = iter.succ();
1888     if (lp->contains(succ->loop())) {
1889       return succ;
1890     }
1891   }
1892   return NULL;
1893 }
1894 
1895 #ifndef PRODUCT
1896 // ------------------------------------------------------------------
1897 // ciTypeFlow::Block::print_value_on
1898 void ciTypeFlow::Block::print_value_on(outputStream* st) const {
1899   if (has_pre_order()) st->print("#%-2d ", pre_order());
1900   if (has_rpo())       st->print("rpo#%-2d ", rpo());
1901   st->print("[%d - %d)", start(), limit());
1902   if (is_loop_head()) st->print(" lphd");
1903   if (is_irreducible_entry()) st->print(" irred");
1904   if (_jsrs->size() > 0) { st->print("/");  _jsrs->print_on(st); }
1905   if (is_backedge_copy())  st->print("/backedge_copy");
1906 }
1907 
1908 // ------------------------------------------------------------------
1909 // ciTypeFlow::Block::print_on
1910 void ciTypeFlow::Block::print_on(outputStream* st) const {
1911   if ((Verbose || WizardMode) && (limit() >= 0)) {
1912     // Don't print 'dummy' blocks (i.e. blocks with limit() '-1')
1913     outer()->method()->print_codes_on(start(), limit(), st);
1914   }
1915   st->print_cr("  ====================================================  ");
1916   st->print ("  ");
1917   print_value_on(st);
1918   st->print(" Stored locals: "); def_locals()->print_on(st, outer()->method()->max_locals()); tty->cr();
1919   if (loop() && loop()->parent() != NULL) {
1920     st->print(" loops:");
1921     Loop* lp = loop();
1922     do {
1923       st->print(" %d<-%d", lp->head()->pre_order(),lp->tail()->pre_order());
1924       if (lp->is_irreducible()) st->print("(ir)");
1925       lp = lp->parent();
1926     } while (lp->parent() != NULL);
1927   }
1928   st->cr();
1929   _state->print_on(st);
1930   if (_successors == NULL) {
1931     st->print_cr("  No successor information");
1932   } else {
1933     int num_successors = _successors->length();
1934     st->print_cr("  Successors : %d", num_successors);
1935     for (int i = 0; i < num_successors; i++) {
1936       Block* successor = _successors->at(i);
1937       st->print("    ");
1938       successor->print_value_on(st);
1939       st->cr();
1940     }
1941   }
1942   if (_predecessors == NULL) {
1943     st->print_cr("  No predecessor information");
1944   } else {
1945     int num_predecessors = _predecessors->length();
1946     st->print_cr("  Predecessors : %d", num_predecessors);
1947     for (int i = 0; i < num_predecessors; i++) {
1948       Block* predecessor = _predecessors->at(i);
1949       st->print("    ");
1950       predecessor->print_value_on(st);
1951       st->cr();
1952     }
1953   }
1954   if (_exceptions == NULL) {
1955     st->print_cr("  No exception information");
1956   } else {
1957     int num_exceptions = _exceptions->length();
1958     st->print_cr("  Exceptions : %d", num_exceptions);
1959     for (int i = 0; i < num_exceptions; i++) {
1960       Block* exc_succ = _exceptions->at(i);
1961       ciInstanceKlass* exc_klass = _exc_klasses->at(i);
1962       st->print("    ");
1963       exc_succ->print_value_on(st);
1964       st->print(" -- ");
1965       exc_klass->name()->print_symbol_on(st);
1966       st->cr();
1967     }
1968   }
1969   if (has_trap()) {
1970     st->print_cr("  Traps on %d with trap index %d", trap_bci(), trap_index());
1971   }
1972   st->print_cr("  ====================================================  ");
1973 }
1974 #endif
1975 
1976 #ifndef PRODUCT
1977 // ------------------------------------------------------------------
1978 // ciTypeFlow::LocalSet::print_on
1979 void ciTypeFlow::LocalSet::print_on(outputStream* st, int limit) const {
1980   st->print("{");
1981   for (int i = 0; i < max; i++) {
1982     if (test(i)) st->print(" %d", i);
1983   }
1984   if (limit > max) {
1985     st->print(" %d..%d ", max, limit);
1986   }
1987   st->print(" }");
1988 }
1989 #endif
1990 
1991 // ciTypeFlow
1992 //
1993 // This is a pass over the bytecodes which computes the following:
1994 //   basic block structure
1995 //   interpreter type-states (a la the verifier)
1996 
1997 // ------------------------------------------------------------------
1998 // ciTypeFlow::ciTypeFlow
1999 ciTypeFlow::ciTypeFlow(ciEnv* env, ciMethod* method, int osr_bci) {
2000   _env = env;
2001   _method = method;
2002   _methodBlocks = method->get_method_blocks();
2003   _max_locals = method->max_locals();
2004   _max_stack = method->max_stack();
2005   _code_size = method->code_size();
2006   _has_irreducible_entry = false;
2007   _osr_bci = osr_bci;
2008   _failure_reason = NULL;
2009   assert(0 <= start_bci() && start_bci() < code_size() , "correct osr_bci argument: 0 <= %d < %d", start_bci(), code_size());
2010   _work_list = NULL;
2011 
2012   _ciblock_count = _methodBlocks->num_blocks();
2013   _idx_to_blocklist = NEW_ARENA_ARRAY(arena(), GrowableArray<Block*>*, _ciblock_count);
2014   for (int i = 0; i < _ciblock_count; i++) {
2015     _idx_to_blocklist[i] = NULL;
2016   }
2017   _block_map = NULL;  // until all blocks are seen
2018   _jsr_count = 0;
2019   _jsr_records = NULL;
2020 }
2021 
2022 // ------------------------------------------------------------------
2023 // ciTypeFlow::work_list_next
2024 //
2025 // Get the next basic block from our work list.
2026 ciTypeFlow::Block* ciTypeFlow::work_list_next() {
2027   assert(!work_list_empty(), "work list must not be empty");
2028   Block* next_block = _work_list;
2029   _work_list = next_block->next();
2030   next_block->set_next(NULL);
2031   next_block->set_on_work_list(false);
2032   return next_block;
2033 }
2034 
2035 // ------------------------------------------------------------------
2036 // ciTypeFlow::add_to_work_list
2037 //
2038 // Add a basic block to our work list.
2039 // List is sorted by decreasing postorder sort (same as increasing RPO)
2040 void ciTypeFlow::add_to_work_list(ciTypeFlow::Block* block) {
2041   assert(!block->is_on_work_list(), "must not already be on work list");
2042 
2043   if (CITraceTypeFlow) {
2044     tty->print(">> Adding block ");
2045     block->print_value_on(tty);
2046     tty->print_cr(" to the work list : ");
2047   }
2048 
2049   block->set_on_work_list(true);
2050 
2051   // decreasing post order sort
2052 
2053   Block* prev = NULL;
2054   Block* current = _work_list;
2055   int po = block->post_order();
2056   while (current != NULL) {
2057     if (!current->has_post_order() || po > current->post_order())
2058       break;
2059     prev = current;
2060     current = current->next();
2061   }
2062   if (prev == NULL) {
2063     block->set_next(_work_list);
2064     _work_list = block;
2065   } else {
2066     block->set_next(current);
2067     prev->set_next(block);
2068   }
2069 
2070   if (CITraceTypeFlow) {
2071     tty->cr();
2072   }
2073 }
2074 
2075 // ------------------------------------------------------------------
2076 // ciTypeFlow::block_at
2077 //
2078 // Return the block beginning at bci which has a JsrSet compatible
2079 // with jsrs.
2080 ciTypeFlow::Block* ciTypeFlow::block_at(int bci, ciTypeFlow::JsrSet* jsrs, CreateOption option) {
2081   // First find the right ciBlock.
2082   if (CITraceTypeFlow) {
2083     tty->print(">> Requesting block for %d/", bci);
2084     jsrs->print_on(tty);
2085     tty->cr();
2086   }
2087 
2088   ciBlock* ciblk = _methodBlocks->block_containing(bci);
2089   assert(ciblk->start_bci() == bci, "bad ciBlock boundaries");
2090   Block* block = get_block_for(ciblk->index(), jsrs, option);
2091 
2092   assert(block == NULL? (option == no_create): block->is_backedge_copy() == (option == create_backedge_copy), "create option consistent with result");
2093 
2094   if (CITraceTypeFlow) {
2095     if (block != NULL) {
2096       tty->print(">> Found block ");
2097       block->print_value_on(tty);
2098       tty->cr();
2099     } else {
2100       tty->print_cr(">> No such block.");
2101     }
2102   }
2103 
2104   return block;
2105 }
2106 
2107 // ------------------------------------------------------------------
2108 // ciTypeFlow::make_jsr_record
2109 //
2110 // Make a JsrRecord for a given (entry, return) pair, if such a record
2111 // does not already exist.
2112 ciTypeFlow::JsrRecord* ciTypeFlow::make_jsr_record(int entry_address,
2113                                                    int return_address) {
2114   if (_jsr_records == NULL) {
2115     _jsr_records = new (arena()) GrowableArray<JsrRecord*>(arena(),
2116                                                            _jsr_count,
2117                                                            0,
2118                                                            NULL);
2119   }
2120   JsrRecord* record = NULL;
2121   int len = _jsr_records->length();
2122   for (int i = 0; i < len; i++) {
2123     JsrRecord* record = _jsr_records->at(i);
2124     if (record->entry_address() == entry_address &&
2125         record->return_address() == return_address) {
2126       return record;
2127     }
2128   }
2129 
2130   record = new (arena()) JsrRecord(entry_address, return_address);
2131   _jsr_records->append(record);
2132   return record;
2133 }
2134 
2135 // ------------------------------------------------------------------
2136 // ciTypeFlow::flow_exceptions
2137 //
2138 // Merge the current state into all exceptional successors at the
2139 // current point in the code.
2140 void ciTypeFlow::flow_exceptions(GrowableArray<ciTypeFlow::Block*>* exceptions,
2141                                  GrowableArray<ciInstanceKlass*>* exc_klasses,
2142                                  ciTypeFlow::StateVector* state) {
2143   int len = exceptions->length();
2144   assert(exc_klasses->length() == len, "must have same length");
2145   for (int i = 0; i < len; i++) {
2146     Block* block = exceptions->at(i);
2147     ciInstanceKlass* exception_klass = exc_klasses->at(i);
2148 
2149     if (!exception_klass->is_loaded()) {
2150       // Do not compile any code for unloaded exception types.
2151       // Following compiler passes are responsible for doing this also.
2152       continue;
2153     }
2154 
2155     if (block->meet_exception(exception_klass, state)) {
2156       // Block was modified and has PO.  Add it to the work list.
2157       if (block->has_post_order() &&
2158           !block->is_on_work_list()) {
2159         add_to_work_list(block);
2160       }
2161     }
2162   }
2163 }
2164 
2165 // ------------------------------------------------------------------
2166 // ciTypeFlow::flow_successors
2167 //
2168 // Merge the current state into all successors at the current point
2169 // in the code.
2170 void ciTypeFlow::flow_successors(GrowableArray<ciTypeFlow::Block*>* successors,
2171                                  ciTypeFlow::StateVector* state) {
2172   int len = successors->length();
2173   for (int i = 0; i < len; i++) {
2174     Block* block = successors->at(i);
2175     if (block->meet(state)) {
2176       // Block was modified and has PO.  Add it to the work list.
2177       if (block->has_post_order() &&
2178           !block->is_on_work_list()) {
2179         add_to_work_list(block);
2180       }
2181     }
2182   }
2183 }
2184 
2185 // ------------------------------------------------------------------
2186 // ciTypeFlow::can_trap
2187 //
2188 // Tells if a given instruction is able to generate an exception edge.
2189 bool ciTypeFlow::can_trap(ciBytecodeStream& str) {
2190   // Cf. GenerateOopMap::do_exception_edge.
2191   if (!Bytecodes::can_trap(str.cur_bc()))  return false;
2192 
2193   switch (str.cur_bc()) {
2194     // %%% FIXME: ldc of Class can generate an exception
2195     case Bytecodes::_ldc:
2196     case Bytecodes::_ldc_w:
2197     case Bytecodes::_ldc2_w:
2198     case Bytecodes::_aload_0:
2199       // These bytecodes can trap for rewriting.  We need to assume that
2200       // they do not throw exceptions to make the monitor analysis work.
2201       return false;
2202 
2203     case Bytecodes::_ireturn:
2204     case Bytecodes::_lreturn:
2205     case Bytecodes::_freturn:
2206     case Bytecodes::_dreturn:
2207     case Bytecodes::_areturn:
2208     case Bytecodes::_vreturn:
2209     case Bytecodes::_return:
2210       // We can assume the monitor stack is empty in this analysis.
2211       return false;
2212 
2213     case Bytecodes::_monitorexit:
2214       // We can assume monitors are matched in this analysis.
2215       return false;
2216   }
2217 
2218   return true;
2219 }
2220 
2221 // ------------------------------------------------------------------
2222 // ciTypeFlow::clone_loop_heads
2223 //
2224 // Clone the loop heads
2225 bool ciTypeFlow::clone_loop_heads(Loop* lp, StateVector* temp_vector, JsrSet* temp_set) {
2226   bool rslt = false;
2227   for (PreorderLoops iter(loop_tree_root()); !iter.done(); iter.next()) {
2228     lp = iter.current();
2229     Block* head = lp->head();
2230     if (lp == loop_tree_root() ||
2231         lp->is_irreducible() ||
2232         !head->is_clonable_exit(lp))
2233       continue;
2234 
2235     // Avoid BoxLock merge.
2236     if (EliminateNestedLocks && head->has_monitorenter())
2237       continue;
2238 
2239     // check not already cloned
2240     if (head->backedge_copy_count() != 0)
2241       continue;
2242 
2243     // Don't clone head of OSR loop to get correct types in start block.
2244     if (is_osr_flow() && head->start() == start_bci())
2245       continue;
2246 
2247     // check _no_ shared head below us
2248     Loop* ch;
2249     for (ch = lp->child(); ch != NULL && ch->head() != head; ch = ch->sibling());
2250     if (ch != NULL)
2251       continue;
2252 
2253     // Clone head
2254     Block* new_head = head->looping_succ(lp);
2255     Block* clone = clone_loop_head(lp, temp_vector, temp_set);
2256     // Update lp's info
2257     clone->set_loop(lp);
2258     lp->set_head(new_head);
2259     lp->set_tail(clone);
2260     // And move original head into outer loop
2261     head->set_loop(lp->parent());
2262 
2263     rslt = true;
2264   }
2265   return rslt;
2266 }
2267 
2268 // ------------------------------------------------------------------
2269 // ciTypeFlow::clone_loop_head
2270 //
2271 // Clone lp's head and replace tail's successors with clone.
2272 //
2273 //  |
2274 //  v
2275 // head <-> body
2276 //  |
2277 //  v
2278 // exit
2279 //
2280 // new_head
2281 //
2282 //  |
2283 //  v
2284 // head ----------\
2285 //  |             |
2286 //  |             v
2287 //  |  clone <-> body
2288 //  |    |
2289 //  | /--/
2290 //  | |
2291 //  v v
2292 // exit
2293 //
2294 ciTypeFlow::Block* ciTypeFlow::clone_loop_head(Loop* lp, StateVector* temp_vector, JsrSet* temp_set) {
2295   Block* head = lp->head();
2296   Block* tail = lp->tail();
2297   if (CITraceTypeFlow) {
2298     tty->print(">> Requesting clone of loop head "); head->print_value_on(tty);
2299     tty->print("  for predecessor ");                tail->print_value_on(tty);
2300     tty->cr();
2301   }
2302   Block* clone = block_at(head->start(), head->jsrs(), create_backedge_copy);
2303   assert(clone->backedge_copy_count() == 1, "one backedge copy for all back edges");
2304 
2305   assert(!clone->has_pre_order(), "just created");
2306   clone->set_next_pre_order();
2307 
2308   // Insert clone after (orig) tail in reverse post order
2309   clone->set_rpo_next(tail->rpo_next());
2310   tail->set_rpo_next(clone);
2311 
2312   // tail->head becomes tail->clone
2313   for (SuccIter iter(tail); !iter.done(); iter.next()) {
2314     if (iter.succ() == head) {
2315       iter.set_succ(clone);
2316       // Update predecessor information
2317       head->predecessors()->remove(tail);
2318       clone->predecessors()->append(tail);
2319     }
2320   }
2321   flow_block(tail, temp_vector, temp_set);
2322   if (head == tail) {
2323     // For self-loops, clone->head becomes clone->clone
2324     flow_block(clone, temp_vector, temp_set);
2325     for (SuccIter iter(clone); !iter.done(); iter.next()) {
2326       if (iter.succ() == head) {
2327         iter.set_succ(clone);
2328         // Update predecessor information
2329         head->predecessors()->remove(clone);
2330         clone->predecessors()->append(clone);
2331         break;
2332       }
2333     }
2334   }
2335   flow_block(clone, temp_vector, temp_set);
2336 
2337   return clone;
2338 }
2339 
2340 // ------------------------------------------------------------------
2341 // ciTypeFlow::flow_block
2342 //
2343 // Interpret the effects of the bytecodes on the incoming state
2344 // vector of a basic block.  Push the changed state to succeeding
2345 // basic blocks.
2346 void ciTypeFlow::flow_block(ciTypeFlow::Block* block,
2347                             ciTypeFlow::StateVector* state,
2348                             ciTypeFlow::JsrSet* jsrs) {
2349   if (CITraceTypeFlow) {
2350     tty->print("\n>> ANALYZING BLOCK : ");
2351     tty->cr();
2352     block->print_on(tty);
2353   }
2354   assert(block->has_pre_order(), "pre-order is assigned before 1st flow");
2355 
2356   int start = block->start();
2357   int limit = block->limit();
2358   int control = block->control();
2359   if (control != ciBlock::fall_through_bci) {
2360     limit = control;
2361   }
2362 
2363   // Grab the state from the current block.
2364   block->copy_state_into(state);
2365   state->def_locals()->clear();
2366 
2367   GrowableArray<Block*>*           exceptions = block->exceptions();
2368   GrowableArray<ciInstanceKlass*>* exc_klasses = block->exc_klasses();
2369   bool has_exceptions = exceptions->length() > 0;
2370 
2371   bool exceptions_used = false;
2372 
2373   ciBytecodeStream str(method());
2374   str.reset_to_bci(start);
2375   Bytecodes::Code code;
2376   while ((code = str.next()) != ciBytecodeStream::EOBC() &&
2377          str.cur_bci() < limit) {
2378     // Check for exceptional control flow from this point.
2379     if (has_exceptions && can_trap(str)) {
2380       flow_exceptions(exceptions, exc_klasses, state);
2381       exceptions_used = true;
2382     }
2383     // Apply the effects of the current bytecode to our state.
2384     bool res = state->apply_one_bytecode(&str);
2385 
2386     // Watch for bailouts.
2387     if (failing())  return;
2388 
2389     if (str.cur_bc() == Bytecodes::_monitorenter) {
2390       block->set_has_monitorenter();
2391     }
2392 
2393     if (res) {
2394 
2395       // We have encountered a trap.  Record it in this block.
2396       block->set_trap(state->trap_bci(), state->trap_index());
2397 
2398       if (CITraceTypeFlow) {
2399         tty->print_cr(">> Found trap");
2400         block->print_on(tty);
2401       }
2402 
2403       // Save set of locals defined in this block
2404       block->def_locals()->add(state->def_locals());
2405 
2406       // Record (no) successors.
2407       block->successors(&str, state, jsrs);
2408 
2409       assert(!has_exceptions || exceptions_used, "Not removing exceptions");
2410 
2411       // Discontinue interpretation of this Block.
2412       return;
2413     }
2414   }
2415 
2416   GrowableArray<Block*>* successors = NULL;
2417   if (control != ciBlock::fall_through_bci) {
2418     // Check for exceptional control flow from this point.
2419     if (has_exceptions && can_trap(str)) {
2420       flow_exceptions(exceptions, exc_klasses, state);
2421       exceptions_used = true;
2422     }
2423 
2424     // Fix the JsrSet to reflect effect of the bytecode.
2425     block->copy_jsrs_into(jsrs);
2426     jsrs->apply_control(this, &str, state);
2427 
2428     // Find successor edges based on old state and new JsrSet.
2429     successors = block->successors(&str, state, jsrs);
2430 
2431     // Apply the control changes to the state.
2432     state->apply_one_bytecode(&str);
2433   } else {
2434     // Fall through control
2435     successors = block->successors(&str, NULL, NULL);
2436   }
2437 
2438   // Save set of locals defined in this block
2439   block->def_locals()->add(state->def_locals());
2440 
2441   // Remove untaken exception paths
2442   if (!exceptions_used)
2443     exceptions->clear();
2444 
2445   // Pass our state to successors.
2446   flow_successors(successors, state);
2447 }
2448 
2449 // ------------------------------------------------------------------
2450 // ciTypeFlow::PostOrderLoops::next
2451 //
2452 // Advance to next loop tree using a postorder, left-to-right traversal.
2453 void ciTypeFlow::PostorderLoops::next() {
2454   assert(!done(), "must not be done.");
2455   if (_current->sibling() != NULL) {
2456     _current = _current->sibling();
2457     while (_current->child() != NULL) {
2458       _current = _current->child();
2459     }
2460   } else {
2461     _current = _current->parent();
2462   }
2463 }
2464 
2465 // ------------------------------------------------------------------
2466 // ciTypeFlow::PreOrderLoops::next
2467 //
2468 // Advance to next loop tree using a preorder, left-to-right traversal.
2469 void ciTypeFlow::PreorderLoops::next() {
2470   assert(!done(), "must not be done.");
2471   if (_current->child() != NULL) {
2472     _current = _current->child();
2473   } else if (_current->sibling() != NULL) {
2474     _current = _current->sibling();
2475   } else {
2476     while (_current != _root && _current->sibling() == NULL) {
2477       _current = _current->parent();
2478     }
2479     if (_current == _root) {
2480       _current = NULL;
2481       assert(done(), "must be done.");
2482     } else {
2483       assert(_current->sibling() != NULL, "must be more to do");
2484       _current = _current->sibling();
2485     }
2486   }
2487 }
2488 
2489 // ------------------------------------------------------------------
2490 // ciTypeFlow::Loop::sorted_merge
2491 //
2492 // Merge the branch lp into this branch, sorting on the loop head
2493 // pre_orders. Returns the leaf of the merged branch.
2494 // Child and sibling pointers will be setup later.
2495 // Sort is (looking from leaf towards the root)
2496 //  descending on primary key: loop head's pre_order, and
2497 //  ascending  on secondary key: loop tail's pre_order.
2498 ciTypeFlow::Loop* ciTypeFlow::Loop::sorted_merge(Loop* lp) {
2499   Loop* leaf = this;
2500   Loop* prev = NULL;
2501   Loop* current = leaf;
2502   while (lp != NULL) {
2503     int lp_pre_order = lp->head()->pre_order();
2504     // Find insertion point for "lp"
2505     while (current != NULL) {
2506       if (current == lp)
2507         return leaf; // Already in list
2508       if (current->head()->pre_order() < lp_pre_order)
2509         break;
2510       if (current->head()->pre_order() == lp_pre_order &&
2511           current->tail()->pre_order() > lp->tail()->pre_order()) {
2512         break;
2513       }
2514       prev = current;
2515       current = current->parent();
2516     }
2517     Loop* next_lp = lp->parent(); // Save future list of items to insert
2518     // Insert lp before current
2519     lp->set_parent(current);
2520     if (prev != NULL) {
2521       prev->set_parent(lp);
2522     } else {
2523       leaf = lp;
2524     }
2525     prev = lp;     // Inserted item is new prev[ious]
2526     lp = next_lp;  // Next item to insert
2527   }
2528   return leaf;
2529 }
2530 
2531 // ------------------------------------------------------------------
2532 // ciTypeFlow::build_loop_tree
2533 //
2534 // Incrementally build loop tree.
2535 void ciTypeFlow::build_loop_tree(Block* blk) {
2536   assert(!blk->is_post_visited(), "precondition");
2537   Loop* innermost = NULL; // merge of loop tree branches over all successors
2538 
2539   for (SuccIter iter(blk); !iter.done(); iter.next()) {
2540     Loop*  lp   = NULL;
2541     Block* succ = iter.succ();
2542     if (!succ->is_post_visited()) {
2543       // Found backedge since predecessor post visited, but successor is not
2544       assert(succ->pre_order() <= blk->pre_order(), "should be backedge");
2545 
2546       // Create a LoopNode to mark this loop.
2547       lp = new (arena()) Loop(succ, blk);
2548       if (succ->loop() == NULL)
2549         succ->set_loop(lp);
2550       // succ->loop will be updated to innermost loop on a later call, when blk==succ
2551 
2552     } else {  // Nested loop
2553       lp = succ->loop();
2554 
2555       // If succ is loop head, find outer loop.
2556       while (lp != NULL && lp->head() == succ) {
2557         lp = lp->parent();
2558       }
2559       if (lp == NULL) {
2560         // Infinite loop, it's parent is the root
2561         lp = loop_tree_root();
2562       }
2563     }
2564 
2565     // Check for irreducible loop.
2566     // Successor has already been visited. If the successor's loop head
2567     // has already been post-visited, then this is another entry into the loop.
2568     while (lp->head()->is_post_visited() && lp != loop_tree_root()) {
2569       _has_irreducible_entry = true;
2570       lp->set_irreducible(succ);
2571       if (!succ->is_on_work_list()) {
2572         // Assume irreducible entries need more data flow
2573         add_to_work_list(succ);
2574       }
2575       Loop* plp = lp->parent();
2576       if (plp == NULL) {
2577         // This only happens for some irreducible cases.  The parent
2578         // will be updated during a later pass.
2579         break;
2580       }
2581       lp = plp;
2582     }
2583 
2584     // Merge loop tree branch for all successors.
2585     innermost = innermost == NULL ? lp : innermost->sorted_merge(lp);
2586 
2587   } // end loop
2588 
2589   if (innermost == NULL) {
2590     assert(blk->successors()->length() == 0, "CFG exit");
2591     blk->set_loop(loop_tree_root());
2592   } else if (innermost->head() == blk) {
2593     // If loop header, complete the tree pointers
2594     if (blk->loop() != innermost) {
2595 #ifdef ASSERT
2596       assert(blk->loop()->head() == innermost->head(), "same head");
2597       Loop* dl;
2598       for (dl = innermost; dl != NULL && dl != blk->loop(); dl = dl->parent());
2599       assert(dl == blk->loop(), "blk->loop() already in innermost list");
2600 #endif
2601       blk->set_loop(innermost);
2602     }
2603     innermost->def_locals()->add(blk->def_locals());
2604     Loop* l = innermost;
2605     Loop* p = l->parent();
2606     while (p && l->head() == blk) {
2607       l->set_sibling(p->child());  // Put self on parents 'next child'
2608       p->set_child(l);             // Make self the first child of parent
2609       p->def_locals()->add(l->def_locals());
2610       l = p;                       // Walk up the parent chain
2611       p = l->parent();
2612     }
2613   } else {
2614     blk->set_loop(innermost);
2615     innermost->def_locals()->add(blk->def_locals());
2616   }
2617 }
2618 
2619 // ------------------------------------------------------------------
2620 // ciTypeFlow::Loop::contains
2621 //
2622 // Returns true if lp is nested loop.
2623 bool ciTypeFlow::Loop::contains(ciTypeFlow::Loop* lp) const {
2624   assert(lp != NULL, "");
2625   if (this == lp || head() == lp->head()) return true;
2626   int depth1 = depth();
2627   int depth2 = lp->depth();
2628   if (depth1 > depth2)
2629     return false;
2630   while (depth1 < depth2) {
2631     depth2--;
2632     lp = lp->parent();
2633   }
2634   return this == lp;
2635 }
2636 
2637 // ------------------------------------------------------------------
2638 // ciTypeFlow::Loop::depth
2639 //
2640 // Loop depth
2641 int ciTypeFlow::Loop::depth() const {
2642   int dp = 0;
2643   for (Loop* lp = this->parent(); lp != NULL; lp = lp->parent())
2644     dp++;
2645   return dp;
2646 }
2647 
2648 #ifndef PRODUCT
2649 // ------------------------------------------------------------------
2650 // ciTypeFlow::Loop::print
2651 void ciTypeFlow::Loop::print(outputStream* st, int indent) const {
2652   for (int i = 0; i < indent; i++) st->print(" ");
2653   st->print("%d<-%d %s",
2654             is_root() ? 0 : this->head()->pre_order(),
2655             is_root() ? 0 : this->tail()->pre_order(),
2656             is_irreducible()?" irr":"");
2657   st->print(" defs: ");
2658   def_locals()->print_on(st, _head->outer()->method()->max_locals());
2659   st->cr();
2660   for (Loop* ch = child(); ch != NULL; ch = ch->sibling())
2661     ch->print(st, indent+2);
2662 }
2663 #endif
2664 
2665 // ------------------------------------------------------------------
2666 // ciTypeFlow::df_flow_types
2667 //
2668 // Perform the depth first type flow analysis. Helper for flow_types.
2669 void ciTypeFlow::df_flow_types(Block* start,
2670                                bool do_flow,
2671                                StateVector* temp_vector,
2672                                JsrSet* temp_set) {
2673   int dft_len = 100;
2674   GrowableArray<Block*> stk(dft_len);
2675 
2676   ciBlock* dummy = _methodBlocks->make_dummy_block();
2677   JsrSet* root_set = new JsrSet(NULL, 0);
2678   Block* root_head = new (arena()) Block(this, dummy, root_set);
2679   Block* root_tail = new (arena()) Block(this, dummy, root_set);
2680   root_head->set_pre_order(0);
2681   root_head->set_post_order(0);
2682   root_tail->set_pre_order(max_jint);
2683   root_tail->set_post_order(max_jint);
2684   set_loop_tree_root(new (arena()) Loop(root_head, root_tail));
2685 
2686   stk.push(start);
2687 
2688   _next_pre_order = 0;  // initialize pre_order counter
2689   _rpo_list = NULL;
2690   int next_po = 0;      // initialize post_order counter
2691 
2692   // Compute RPO and the control flow graph
2693   int size;
2694   while ((size = stk.length()) > 0) {
2695     Block* blk = stk.top(); // Leave node on stack
2696     if (!blk->is_visited()) {
2697       // forward arc in graph
2698       assert (!blk->has_pre_order(), "");
2699       blk->set_next_pre_order();
2700 
2701       if (_next_pre_order >= (int)Compile::current()->max_node_limit() / 2) {
2702         // Too many basic blocks.  Bail out.
2703         // This can happen when try/finally constructs are nested to depth N,
2704         // and there is O(2**N) cloning of jsr bodies.  See bug 4697245!
2705         // "MaxNodeLimit / 2" is used because probably the parser will
2706         // generate at least twice that many nodes and bail out.
2707         record_failure("too many basic blocks");
2708         return;
2709       }
2710       if (do_flow) {
2711         flow_block(blk, temp_vector, temp_set);
2712         if (failing()) return; // Watch for bailouts.
2713       }
2714     } else if (!blk->is_post_visited()) {
2715       // cross or back arc
2716       for (SuccIter iter(blk); !iter.done(); iter.next()) {
2717         Block* succ = iter.succ();
2718         if (!succ->is_visited()) {
2719           stk.push(succ);
2720         }
2721       }
2722       if (stk.length() == size) {
2723         // There were no additional children, post visit node now
2724         stk.pop(); // Remove node from stack
2725 
2726         build_loop_tree(blk);
2727         blk->set_post_order(next_po++);   // Assign post order
2728         prepend_to_rpo_list(blk);
2729         assert(blk->is_post_visited(), "");
2730 
2731         if (blk->is_loop_head() && !blk->is_on_work_list()) {
2732           // Assume loop heads need more data flow
2733           add_to_work_list(blk);
2734         }
2735       }
2736     } else {
2737       stk.pop(); // Remove post-visited node from stack
2738     }
2739   }
2740 }
2741 
2742 // ------------------------------------------------------------------
2743 // ciTypeFlow::flow_types
2744 //
2745 // Perform the type flow analysis, creating and cloning Blocks as
2746 // necessary.
2747 void ciTypeFlow::flow_types() {
2748   ResourceMark rm;
2749   StateVector* temp_vector = new StateVector(this);
2750   JsrSet* temp_set = new JsrSet(NULL, 16);
2751 
2752   // Create the method entry block.
2753   Block* start = block_at(start_bci(), temp_set);
2754 
2755   // Load the initial state into it.
2756   const StateVector* start_state = get_start_state();
2757   if (failing())  return;
2758   start->meet(start_state);
2759 
2760   // Depth first visit
2761   df_flow_types(start, true /*do flow*/, temp_vector, temp_set);
2762 
2763   if (failing())  return;
2764   assert(_rpo_list == start, "must be start");
2765 
2766   // Any loops found?
2767   if (loop_tree_root()->child() != NULL &&
2768       env()->comp_level() >= CompLevel_full_optimization) {
2769       // Loop optimizations are not performed on Tier1 compiles.
2770 
2771     bool changed = clone_loop_heads(loop_tree_root(), temp_vector, temp_set);
2772 
2773     // If some loop heads were cloned, recompute postorder and loop tree
2774     if (changed) {
2775       loop_tree_root()->set_child(NULL);
2776       for (Block* blk = _rpo_list; blk != NULL;) {
2777         Block* next = blk->rpo_next();
2778         blk->df_init();
2779         blk = next;
2780       }
2781       df_flow_types(start, false /*no flow*/, temp_vector, temp_set);
2782     }
2783   }
2784 
2785   if (CITraceTypeFlow) {
2786     tty->print_cr("\nLoop tree");
2787     loop_tree_root()->print();
2788   }
2789 
2790   // Continue flow analysis until fixed point reached
2791 
2792   debug_only(int max_block = _next_pre_order;)
2793 
2794   while (!work_list_empty()) {
2795     Block* blk = work_list_next();
2796     assert (blk->has_post_order(), "post order assigned above");
2797 
2798     flow_block(blk, temp_vector, temp_set);
2799 
2800     assert (max_block == _next_pre_order, "no new blocks");
2801     assert (!failing(), "no more bailouts");
2802   }
2803 }
2804 
2805 // ------------------------------------------------------------------
2806 // ciTypeFlow::map_blocks
2807 //
2808 // Create the block map, which indexes blocks in reverse post-order.
2809 void ciTypeFlow::map_blocks() {
2810   assert(_block_map == NULL, "single initialization");
2811   int block_ct = _next_pre_order;
2812   _block_map = NEW_ARENA_ARRAY(arena(), Block*, block_ct);
2813   assert(block_ct == block_count(), "");
2814 
2815   Block* blk = _rpo_list;
2816   for (int m = 0; m < block_ct; m++) {
2817     int rpo = blk->rpo();
2818     assert(rpo == m, "should be sequential");
2819     _block_map[rpo] = blk;
2820     blk = blk->rpo_next();
2821   }
2822   assert(blk == NULL, "should be done");
2823 
2824   for (int j = 0; j < block_ct; j++) {
2825     assert(_block_map[j] != NULL, "must not drop any blocks");
2826     Block* block = _block_map[j];
2827     // Remove dead blocks from successor lists:
2828     for (int e = 0; e <= 1; e++) {
2829       GrowableArray<Block*>* l = e? block->exceptions(): block->successors();
2830       for (int k = 0; k < l->length(); k++) {
2831         Block* s = l->at(k);
2832         if (!s->has_post_order()) {
2833           if (CITraceTypeFlow) {
2834             tty->print("Removing dead %s successor of #%d: ", (e? "exceptional":  "normal"), block->pre_order());
2835             s->print_value_on(tty);
2836             tty->cr();
2837           }
2838           l->remove(s);
2839           --k;
2840         }
2841       }
2842     }
2843   }
2844 }
2845 
2846 // ------------------------------------------------------------------
2847 // ciTypeFlow::get_block_for
2848 //
2849 // Find a block with this ciBlock which has a compatible JsrSet.
2850 // If no such block exists, create it, unless the option is no_create.
2851 // If the option is create_backedge_copy, always create a fresh backedge copy.
2852 ciTypeFlow::Block* ciTypeFlow::get_block_for(int ciBlockIndex, ciTypeFlow::JsrSet* jsrs, CreateOption option) {
2853   Arena* a = arena();
2854   GrowableArray<Block*>* blocks = _idx_to_blocklist[ciBlockIndex];
2855   if (blocks == NULL) {
2856     // Query only?
2857     if (option == no_create)  return NULL;
2858 
2859     // Allocate the growable array.
2860     blocks = new (a) GrowableArray<Block*>(a, 4, 0, NULL);
2861     _idx_to_blocklist[ciBlockIndex] = blocks;
2862   }
2863 
2864   if (option != create_backedge_copy) {
2865     int len = blocks->length();
2866     for (int i = 0; i < len; i++) {
2867       Block* block = blocks->at(i);
2868       if (!block->is_backedge_copy() && block->is_compatible_with(jsrs)) {
2869         return block;
2870       }
2871     }
2872   }
2873 
2874   // Query only?
2875   if (option == no_create)  return NULL;
2876 
2877   // We did not find a compatible block.  Create one.
2878   Block* new_block = new (a) Block(this, _methodBlocks->block(ciBlockIndex), jsrs);
2879   if (option == create_backedge_copy)  new_block->set_backedge_copy(true);
2880   blocks->append(new_block);
2881   return new_block;
2882 }
2883 
2884 // ------------------------------------------------------------------
2885 // ciTypeFlow::backedge_copy_count
2886 //
2887 int ciTypeFlow::backedge_copy_count(int ciBlockIndex, ciTypeFlow::JsrSet* jsrs) const {
2888   GrowableArray<Block*>* blocks = _idx_to_blocklist[ciBlockIndex];
2889 
2890   if (blocks == NULL) {
2891     return 0;
2892   }
2893 
2894   int count = 0;
2895   int len = blocks->length();
2896   for (int i = 0; i < len; i++) {
2897     Block* block = blocks->at(i);
2898     if (block->is_backedge_copy() && block->is_compatible_with(jsrs)) {
2899       count++;
2900     }
2901   }
2902 
2903   return count;
2904 }
2905 
2906 // ------------------------------------------------------------------
2907 // ciTypeFlow::do_flow
2908 //
2909 // Perform type inference flow analysis.
2910 void ciTypeFlow::do_flow() {
2911   if (CITraceTypeFlow) {
2912     tty->print_cr("\nPerforming flow analysis on method");
2913     method()->print();
2914     if (is_osr_flow())  tty->print(" at OSR bci %d", start_bci());
2915     tty->cr();
2916     method()->print_codes();
2917   }
2918   if (CITraceTypeFlow) {
2919     tty->print_cr("Initial CI Blocks");
2920     print_on(tty);
2921   }
2922   flow_types();
2923   // Watch for bailouts.
2924   if (failing()) {
2925     return;
2926   }
2927 
2928   map_blocks();
2929 
2930   if (CIPrintTypeFlow || CITraceTypeFlow) {
2931     rpo_print_on(tty);
2932   }
2933 }
2934 
2935 // ------------------------------------------------------------------
2936 // ciTypeFlow::is_dominated_by
2937 //
2938 // Determine if the instruction at bci is dominated by the instruction at dom_bci.
2939 bool ciTypeFlow::is_dominated_by(int bci, int dom_bci) {
2940   assert(!method()->has_jsrs(), "jsrs are not supported");
2941 
2942   ResourceMark rm;
2943   JsrSet* jsrs = new ciTypeFlow::JsrSet(NULL);
2944   int        index = _methodBlocks->block_containing(bci)->index();
2945   int    dom_index = _methodBlocks->block_containing(dom_bci)->index();
2946   Block*     block = get_block_for(index, jsrs, ciTypeFlow::no_create);
2947   Block* dom_block = get_block_for(dom_index, jsrs, ciTypeFlow::no_create);
2948 
2949   // Start block dominates all other blocks
2950   if (start_block()->rpo() == dom_block->rpo()) {
2951     return true;
2952   }
2953 
2954   // Dominated[i] is true if block i is dominated by dom_block
2955   int num_blocks = block_count();
2956   bool* dominated = NEW_RESOURCE_ARRAY(bool, num_blocks);
2957   for (int i = 0; i < num_blocks; ++i) {
2958     dominated[i] = true;
2959   }
2960   dominated[start_block()->rpo()] = false;
2961 
2962   // Iterative dominator algorithm
2963   bool changed = true;
2964   while (changed) {
2965     changed = false;
2966     // Use reverse postorder iteration
2967     for (Block* blk = _rpo_list; blk != NULL; blk = blk->rpo_next()) {
2968       if (blk->is_start()) {
2969         // Ignore start block
2970         continue;
2971       }
2972       // The block is dominated if it is the dominating block
2973       // itself or if all predecessors are dominated.
2974       int index = blk->rpo();
2975       bool dom = (index == dom_block->rpo());
2976       if (!dom) {
2977         // Check if all predecessors are dominated
2978         dom = true;
2979         for (int i = 0; i < blk->predecessors()->length(); ++i) {
2980           Block* pred = blk->predecessors()->at(i);
2981           if (!dominated[pred->rpo()]) {
2982             dom = false;
2983             break;
2984           }
2985         }
2986       }
2987       // Update dominator information
2988       if (dominated[index] != dom) {
2989         changed = true;
2990         dominated[index] = dom;
2991       }
2992     }
2993   }
2994   // block dominated by dom_block?
2995   return dominated[block->rpo()];
2996 }
2997 
2998 // ------------------------------------------------------------------
2999 // ciTypeFlow::record_failure()
3000 // The ciTypeFlow object keeps track of failure reasons separately from the ciEnv.
3001 // This is required because there is not a 1-1 relation between the ciEnv and
3002 // the TypeFlow passes within a compilation task.  For example, if the compiler
3003 // is considering inlining a method, it will request a TypeFlow.  If that fails,
3004 // the compilation as a whole may continue without the inlining.  Some TypeFlow
3005 // requests are not optional; if they fail the requestor is responsible for
3006 // copying the failure reason up to the ciEnv.  (See Parse::Parse.)
3007 void ciTypeFlow::record_failure(const char* reason) {
3008   if (env()->log() != NULL) {
3009     env()->log()->elem("failure reason='%s' phase='typeflow'", reason);
3010   }
3011   if (_failure_reason == NULL) {
3012     // Record the first failure reason.
3013     _failure_reason = reason;
3014   }
3015 }
3016 
3017 #ifndef PRODUCT
3018 // ------------------------------------------------------------------
3019 // ciTypeFlow::print_on
3020 void ciTypeFlow::print_on(outputStream* st) const {
3021   // Walk through CI blocks
3022   st->print_cr("********************************************************");
3023   st->print   ("TypeFlow for ");
3024   method()->name()->print_symbol_on(st);
3025   int limit_bci = code_size();
3026   st->print_cr("  %d bytes", limit_bci);
3027   ciMethodBlocks  *mblks = _methodBlocks;
3028   ciBlock* current = NULL;
3029   for (int bci = 0; bci < limit_bci; bci++) {
3030     ciBlock* blk = mblks->block_containing(bci);
3031     if (blk != NULL && blk != current) {
3032       current = blk;
3033       current->print_on(st);
3034 
3035       GrowableArray<Block*>* blocks = _idx_to_blocklist[blk->index()];
3036       int num_blocks = (blocks == NULL) ? 0 : blocks->length();
3037 
3038       if (num_blocks == 0) {
3039         st->print_cr("  No Blocks");
3040       } else {
3041         for (int i = 0; i < num_blocks; i++) {
3042           Block* block = blocks->at(i);
3043           block->print_on(st);
3044         }
3045       }
3046       st->print_cr("--------------------------------------------------------");
3047       st->cr();
3048     }
3049   }
3050   st->print_cr("********************************************************");
3051   st->cr();
3052 }
3053 
3054 void ciTypeFlow::rpo_print_on(outputStream* st) const {
3055   st->print_cr("********************************************************");
3056   st->print   ("TypeFlow for ");
3057   method()->name()->print_symbol_on(st);
3058   int limit_bci = code_size();
3059   st->print_cr("  %d bytes", limit_bci);
3060   for (Block* blk = _rpo_list; blk != NULL; blk = blk->rpo_next()) {
3061     blk->print_on(st);
3062     st->print_cr("--------------------------------------------------------");
3063     st->cr();
3064   }
3065   st->print_cr("********************************************************");
3066   st->cr();
3067 }
3068 #endif