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_newarray
 774 void ciTypeFlow::StateVector::do_newarray(ciBytecodeStream* str) {
 775   pop_int();
 776   ciKlass* klass = ciTypeArrayKlass::make((BasicType)str->get_index());
 777   push_object(klass);
 778 }
 779 
 780 // ------------------------------------------------------------------
 781 // ciTypeFlow::StateVector::do_putfield
 782 void ciTypeFlow::StateVector::do_putfield(ciBytecodeStream* str) {
 783   do_putstatic(str);
 784   if (_trap_bci != -1)  return;  // unloaded field holder, etc.
 785   // could add assert here for type of object.
 786   pop_object();
 787 }
 788 
 789 // ------------------------------------------------------------------
 790 // ciTypeFlow::StateVector::do_putstatic
 791 void ciTypeFlow::StateVector::do_putstatic(ciBytecodeStream* str) {
 792   bool will_link;
 793   ciField* field = str->get_field(will_link);
 794   if (!will_link) {
 795     trap(str, field->holder(), str->get_field_holder_index());
 796   } else {
 797     ciType* field_type = field->type();
 798     ciType* type = pop_value();
 799     // Do I want to check this type?
 800     //      assert(type->is_subtype_of(field_type), "bad type for field value");
 801     if (field_type->is_two_word()) {
 802       ciType* type2 = pop_value();
 803       assert(type2->is_two_word(), "must be 2nd half");
 804       assert(type == half_type(type2), "must be 2nd half");
 805     }
 806   }
 807 }
 808 
 809 // ------------------------------------------------------------------
 810 // ciTypeFlow::StateVector::do_ret
 811 void ciTypeFlow::StateVector::do_ret(ciBytecodeStream* str) {
 812   Cell index = local(str->get_index());
 813 
 814   ciType* address = type_at(index);
 815   assert(address->is_return_address(), "bad return address");
 816   set_type_at(index, bottom_type());
 817 }
 818 
 819 // ------------------------------------------------------------------
 820 // ciTypeFlow::StateVector::trap
 821 //
 822 // Stop interpretation of this path with a trap.
 823 void ciTypeFlow::StateVector::trap(ciBytecodeStream* str, ciKlass* klass, int index) {
 824   _trap_bci = str->cur_bci();
 825   _trap_index = index;
 826 
 827   // Log information about this trap:
 828   CompileLog* log = outer()->env()->log();
 829   if (log != NULL) {
 830     int mid = log->identify(outer()->method());
 831     int kid = (klass == NULL)? -1: log->identify(klass);
 832     log->begin_elem("uncommon_trap method='%d' bci='%d'", mid, str->cur_bci());
 833     char buf[100];
 834     log->print(" %s", Deoptimization::format_trap_request(buf, sizeof(buf),
 835                                                           index));
 836     if (kid >= 0)
 837       log->print(" klass='%d'", kid);
 838     log->end_elem();
 839   }
 840 }
 841 
 842 // ------------------------------------------------------------------
 843 // ciTypeFlow::StateVector::do_null_assert
 844 // Corresponds to graphKit::do_null_assert.
 845 void ciTypeFlow::StateVector::do_null_assert(ciKlass* unloaded_klass) {
 846   if (unloaded_klass->is_loaded()) {
 847     // We failed to link, but we can still compute with this class,
 848     // since it is loaded somewhere.  The compiler will uncommon_trap
 849     // if the object is not null, but the typeflow pass can not assume
 850     // that the object will be null, otherwise it may incorrectly tell
 851     // the parser that an object is known to be null. 4761344, 4807707
 852     push_object(unloaded_klass);
 853   } else {
 854     // The class is not loaded anywhere.  It is safe to model the
 855     // null in the typestates, because we can compile in a null check
 856     // which will deoptimize us if someone manages to load the
 857     // class later.
 858     push_null();
 859   }
 860 }
 861 
 862 
 863 // ------------------------------------------------------------------
 864 // ciTypeFlow::StateVector::apply_one_bytecode
 865 //
 866 // Apply the effect of one bytecode to this StateVector
 867 bool ciTypeFlow::StateVector::apply_one_bytecode(ciBytecodeStream* str) {
 868   _trap_bci = -1;
 869   _trap_index = 0;
 870 
 871   if (CITraceTypeFlow) {
 872     tty->print_cr(">> Interpreting bytecode %d:%s", str->cur_bci(),
 873                   Bytecodes::name(str->cur_bc()));
 874   }
 875 
 876   switch(str->cur_bc()) {
 877   case Bytecodes::_aaload: do_aaload(str);                       break;
 878 
 879   case Bytecodes::_aastore:
 880     {
 881       pop_object();
 882       pop_int();
 883       pop_objArray();
 884       break;
 885     }
 886   case Bytecodes::_aconst_null:
 887     {
 888       push_null();
 889       break;
 890     }
 891   case Bytecodes::_aload:   load_local_object(str->get_index());    break;
 892   case Bytecodes::_aload_0: load_local_object(0);                   break;
 893   case Bytecodes::_aload_1: load_local_object(1);                   break;
 894   case Bytecodes::_aload_2: load_local_object(2);                   break;
 895   case Bytecodes::_aload_3: load_local_object(3);                   break;
 896 
 897   case Bytecodes::_anewarray:
 898     {
 899       pop_int();
 900       bool will_link;
 901       ciKlass* element_klass = str->get_klass(will_link);
 902       if (!will_link) {
 903         trap(str, element_klass, str->get_klass_index());
 904       } else {
 905         push_object(ciObjArrayKlass::make(element_klass));
 906       }
 907       break;
 908     }
 909   case Bytecodes::_areturn:
 910   case Bytecodes::_ifnonnull:
 911   case Bytecodes::_ifnull:
 912     {
 913       pop_object();
 914       break;
 915     }
 916   case Bytecodes::_monitorenter:
 917     {
 918       pop_object();
 919       set_monitor_count(monitor_count() + 1);
 920       break;
 921     }
 922   case Bytecodes::_monitorexit:
 923     {
 924       pop_object();
 925       assert(monitor_count() > 0, "must be a monitor to exit from");
 926       set_monitor_count(monitor_count() - 1);
 927       break;
 928     }
 929   case Bytecodes::_arraylength:
 930     {
 931       pop_array();
 932       push_int();
 933       break;
 934     }
 935   case Bytecodes::_astore:   store_local_object(str->get_index());  break;
 936   case Bytecodes::_astore_0: store_local_object(0);                 break;
 937   case Bytecodes::_astore_1: store_local_object(1);                 break;
 938   case Bytecodes::_astore_2: store_local_object(2);                 break;
 939   case Bytecodes::_astore_3: store_local_object(3);                 break;
 940 
 941   case Bytecodes::_athrow:
 942     {
 943       NEEDS_CLEANUP;
 944       pop_object();
 945       break;
 946     }
 947   case Bytecodes::_baload:
 948   case Bytecodes::_caload:
 949   case Bytecodes::_iaload:
 950   case Bytecodes::_saload:
 951     {
 952       pop_int();
 953       ciTypeArrayKlass* array_klass = pop_typeArray();
 954       // Put assert here for right type?
 955       push_int();
 956       break;
 957     }
 958   case Bytecodes::_bastore:
 959   case Bytecodes::_castore:
 960   case Bytecodes::_iastore:
 961   case Bytecodes::_sastore:
 962     {
 963       pop_int();
 964       pop_int();
 965       pop_typeArray();
 966       // assert here?
 967       break;
 968     }
 969   case Bytecodes::_bipush:
 970   case Bytecodes::_iconst_m1:
 971   case Bytecodes::_iconst_0:
 972   case Bytecodes::_iconst_1:
 973   case Bytecodes::_iconst_2:
 974   case Bytecodes::_iconst_3:
 975   case Bytecodes::_iconst_4:
 976   case Bytecodes::_iconst_5:
 977   case Bytecodes::_sipush:
 978     {
 979       push_int();
 980       break;
 981     }
 982   case Bytecodes::_checkcast: do_checkcast(str);                  break;
 983 
 984   case Bytecodes::_d2f:
 985     {
 986       pop_double();
 987       push_float();
 988       break;
 989     }
 990   case Bytecodes::_d2i:
 991     {
 992       pop_double();
 993       push_int();
 994       break;
 995     }
 996   case Bytecodes::_d2l:
 997     {
 998       pop_double();
 999       push_long();
1000       break;
1001     }
1002   case Bytecodes::_dadd:
1003   case Bytecodes::_ddiv:
1004   case Bytecodes::_dmul:
1005   case Bytecodes::_drem:
1006   case Bytecodes::_dsub:
1007     {
1008       pop_double();
1009       pop_double();
1010       push_double();
1011       break;
1012     }
1013   case Bytecodes::_daload:
1014     {
1015       pop_int();
1016       ciTypeArrayKlass* array_klass = pop_typeArray();
1017       // Put assert here for right type?
1018       push_double();
1019       break;
1020     }
1021   case Bytecodes::_dastore:
1022     {
1023       pop_double();
1024       pop_int();
1025       pop_typeArray();
1026       // assert here?
1027       break;
1028     }
1029   case Bytecodes::_dcmpg:
1030   case Bytecodes::_dcmpl:
1031     {
1032       pop_double();
1033       pop_double();
1034       push_int();
1035       break;
1036     }
1037   case Bytecodes::_dconst_0:
1038   case Bytecodes::_dconst_1:
1039     {
1040       push_double();
1041       break;
1042     }
1043   case Bytecodes::_dload:   load_local_double(str->get_index());    break;
1044   case Bytecodes::_dload_0: load_local_double(0);                   break;
1045   case Bytecodes::_dload_1: load_local_double(1);                   break;
1046   case Bytecodes::_dload_2: load_local_double(2);                   break;
1047   case Bytecodes::_dload_3: load_local_double(3);                   break;
1048 
1049   case Bytecodes::_dneg:
1050     {
1051       pop_double();
1052       push_double();
1053       break;
1054     }
1055   case Bytecodes::_dreturn:
1056     {
1057       pop_double();
1058       break;
1059     }
1060   case Bytecodes::_dstore:   store_local_double(str->get_index());  break;
1061   case Bytecodes::_dstore_0: store_local_double(0);                 break;
1062   case Bytecodes::_dstore_1: store_local_double(1);                 break;
1063   case Bytecodes::_dstore_2: store_local_double(2);                 break;
1064   case Bytecodes::_dstore_3: store_local_double(3);                 break;
1065 
1066   case Bytecodes::_dup:
1067     {
1068       push(type_at_tos());
1069       break;
1070     }
1071   case Bytecodes::_dup_x1:
1072     {
1073       ciType* value1 = pop_value();
1074       ciType* value2 = pop_value();
1075       push(value1);
1076       push(value2);
1077       push(value1);
1078       break;
1079     }
1080   case Bytecodes::_dup_x2:
1081     {
1082       ciType* value1 = pop_value();
1083       ciType* value2 = pop_value();
1084       ciType* value3 = pop_value();
1085       push(value1);
1086       push(value3);
1087       push(value2);
1088       push(value1);
1089       break;
1090     }
1091   case Bytecodes::_dup2:
1092     {
1093       ciType* value1 = pop_value();
1094       ciType* value2 = pop_value();
1095       push(value2);
1096       push(value1);
1097       push(value2);
1098       push(value1);
1099       break;
1100     }
1101   case Bytecodes::_dup2_x1:
1102     {
1103       ciType* value1 = pop_value();
1104       ciType* value2 = pop_value();
1105       ciType* value3 = pop_value();
1106       push(value2);
1107       push(value1);
1108       push(value3);
1109       push(value2);
1110       push(value1);
1111       break;
1112     }
1113   case Bytecodes::_dup2_x2:
1114     {
1115       ciType* value1 = pop_value();
1116       ciType* value2 = pop_value();
1117       ciType* value3 = pop_value();
1118       ciType* value4 = pop_value();
1119       push(value2);
1120       push(value1);
1121       push(value4);
1122       push(value3);
1123       push(value2);
1124       push(value1);
1125       break;
1126     }
1127   case Bytecodes::_f2d:
1128     {
1129       pop_float();
1130       push_double();
1131       break;
1132     }
1133   case Bytecodes::_f2i:
1134     {
1135       pop_float();
1136       push_int();
1137       break;
1138     }
1139   case Bytecodes::_f2l:
1140     {
1141       pop_float();
1142       push_long();
1143       break;
1144     }
1145   case Bytecodes::_fadd:
1146   case Bytecodes::_fdiv:
1147   case Bytecodes::_fmul:
1148   case Bytecodes::_frem:
1149   case Bytecodes::_fsub:
1150     {
1151       pop_float();
1152       pop_float();
1153       push_float();
1154       break;
1155     }
1156   case Bytecodes::_faload:
1157     {
1158       pop_int();
1159       ciTypeArrayKlass* array_klass = pop_typeArray();
1160       // Put assert here.
1161       push_float();
1162       break;
1163     }
1164   case Bytecodes::_fastore:
1165     {
1166       pop_float();
1167       pop_int();
1168       ciTypeArrayKlass* array_klass = pop_typeArray();
1169       // Put assert here.
1170       break;
1171     }
1172   case Bytecodes::_fcmpg:
1173   case Bytecodes::_fcmpl:
1174     {
1175       pop_float();
1176       pop_float();
1177       push_int();
1178       break;
1179     }
1180   case Bytecodes::_fconst_0:
1181   case Bytecodes::_fconst_1:
1182   case Bytecodes::_fconst_2:
1183     {
1184       push_float();
1185       break;
1186     }
1187   case Bytecodes::_fload:   load_local_float(str->get_index());     break;
1188   case Bytecodes::_fload_0: load_local_float(0);                    break;
1189   case Bytecodes::_fload_1: load_local_float(1);                    break;
1190   case Bytecodes::_fload_2: load_local_float(2);                    break;
1191   case Bytecodes::_fload_3: load_local_float(3);                    break;
1192 
1193   case Bytecodes::_fneg:
1194     {
1195       pop_float();
1196       push_float();
1197       break;
1198     }
1199   case Bytecodes::_freturn:
1200     {
1201       pop_float();
1202       break;
1203     }
1204   case Bytecodes::_fstore:    store_local_float(str->get_index());   break;
1205   case Bytecodes::_fstore_0:  store_local_float(0);                  break;
1206   case Bytecodes::_fstore_1:  store_local_float(1);                  break;
1207   case Bytecodes::_fstore_2:  store_local_float(2);                  break;
1208   case Bytecodes::_fstore_3:  store_local_float(3);                  break;
1209 
1210   case Bytecodes::_getfield:  do_getfield(str);                      break;
1211   case Bytecodes::_getstatic: do_getstatic(str);                     break;
1212 
1213   case Bytecodes::_goto:
1214   case Bytecodes::_goto_w:
1215   case Bytecodes::_nop:
1216   case Bytecodes::_return:
1217     {
1218       // do nothing.
1219       break;
1220     }
1221   case Bytecodes::_i2b:
1222   case Bytecodes::_i2c:
1223   case Bytecodes::_i2s:
1224   case Bytecodes::_ineg:
1225     {
1226       pop_int();
1227       push_int();
1228       break;
1229     }
1230   case Bytecodes::_i2d:
1231     {
1232       pop_int();
1233       push_double();
1234       break;
1235     }
1236   case Bytecodes::_i2f:
1237     {
1238       pop_int();
1239       push_float();
1240       break;
1241     }
1242   case Bytecodes::_i2l:
1243     {
1244       pop_int();
1245       push_long();
1246       break;
1247     }
1248   case Bytecodes::_iadd:
1249   case Bytecodes::_iand:
1250   case Bytecodes::_idiv:
1251   case Bytecodes::_imul:
1252   case Bytecodes::_ior:
1253   case Bytecodes::_irem:
1254   case Bytecodes::_ishl:
1255   case Bytecodes::_ishr:
1256   case Bytecodes::_isub:
1257   case Bytecodes::_iushr:
1258   case Bytecodes::_ixor:
1259     {
1260       pop_int();
1261       pop_int();
1262       push_int();
1263       break;
1264     }
1265   case Bytecodes::_if_acmpeq:
1266   case Bytecodes::_if_acmpne:
1267     {
1268       pop_object();
1269       pop_object();
1270       break;
1271     }
1272   case Bytecodes::_if_icmpeq:
1273   case Bytecodes::_if_icmpge:
1274   case Bytecodes::_if_icmpgt:
1275   case Bytecodes::_if_icmple:
1276   case Bytecodes::_if_icmplt:
1277   case Bytecodes::_if_icmpne:
1278     {
1279       pop_int();
1280       pop_int();
1281       break;
1282     }
1283   case Bytecodes::_ifeq:
1284   case Bytecodes::_ifle:
1285   case Bytecodes::_iflt:
1286   case Bytecodes::_ifge:
1287   case Bytecodes::_ifgt:
1288   case Bytecodes::_ifne:
1289   case Bytecodes::_ireturn:
1290   case Bytecodes::_lookupswitch:
1291   case Bytecodes::_tableswitch:
1292     {
1293       pop_int();
1294       break;
1295     }
1296   case Bytecodes::_iinc:
1297     {
1298       int lnum = str->get_index();
1299       check_int(local(lnum));
1300       store_to_local(lnum);
1301       break;
1302     }
1303   case Bytecodes::_iload:   load_local_int(str->get_index()); break;
1304   case Bytecodes::_iload_0: load_local_int(0);                      break;
1305   case Bytecodes::_iload_1: load_local_int(1);                      break;
1306   case Bytecodes::_iload_2: load_local_int(2);                      break;
1307   case Bytecodes::_iload_3: load_local_int(3);                      break;
1308 
1309   case Bytecodes::_instanceof:
1310     {
1311       // Check for uncommon trap:
1312       do_checkcast(str);
1313       pop_object();
1314       push_int();
1315       break;
1316     }
1317   case Bytecodes::_invokeinterface: do_invoke(str, true);           break;
1318   case Bytecodes::_invokespecial:   do_invoke(str, true);           break;
1319   case Bytecodes::_invokestatic:    do_invoke(str, false);          break;
1320   case Bytecodes::_invokevirtual:   do_invoke(str, true);           break;
1321   case Bytecodes::_invokedynamic:   do_invoke(str, false);          break;
1322 
1323   case Bytecodes::_istore:   store_local_int(str->get_index());     break;
1324   case Bytecodes::_istore_0: store_local_int(0);                    break;
1325   case Bytecodes::_istore_1: store_local_int(1);                    break;
1326   case Bytecodes::_istore_2: store_local_int(2);                    break;
1327   case Bytecodes::_istore_3: store_local_int(3);                    break;
1328 
1329   case Bytecodes::_jsr:
1330   case Bytecodes::_jsr_w: do_jsr(str);                              break;
1331 
1332   case Bytecodes::_l2d:
1333     {
1334       pop_long();
1335       push_double();
1336       break;
1337     }
1338   case Bytecodes::_l2f:
1339     {
1340       pop_long();
1341       push_float();
1342       break;
1343     }
1344   case Bytecodes::_l2i:
1345     {
1346       pop_long();
1347       push_int();
1348       break;
1349     }
1350   case Bytecodes::_ladd:
1351   case Bytecodes::_land:
1352   case Bytecodes::_ldiv:
1353   case Bytecodes::_lmul:
1354   case Bytecodes::_lor:
1355   case Bytecodes::_lrem:
1356   case Bytecodes::_lsub:
1357   case Bytecodes::_lxor:
1358     {
1359       pop_long();
1360       pop_long();
1361       push_long();
1362       break;
1363     }
1364   case Bytecodes::_laload:
1365     {
1366       pop_int();
1367       ciTypeArrayKlass* array_klass = pop_typeArray();
1368       // Put assert here for right type?
1369       push_long();
1370       break;
1371     }
1372   case Bytecodes::_lastore:
1373     {
1374       pop_long();
1375       pop_int();
1376       pop_typeArray();
1377       // assert here?
1378       break;
1379     }
1380   case Bytecodes::_lcmp:
1381     {
1382       pop_long();
1383       pop_long();
1384       push_int();
1385       break;
1386     }
1387   case Bytecodes::_lconst_0:
1388   case Bytecodes::_lconst_1:
1389     {
1390       push_long();
1391       break;
1392     }
1393   case Bytecodes::_ldc:
1394   case Bytecodes::_ldc_w:
1395   case Bytecodes::_ldc2_w:
1396     {
1397       do_ldc(str);
1398       break;
1399     }
1400 
1401   case Bytecodes::_lload:   load_local_long(str->get_index());      break;
1402   case Bytecodes::_lload_0: load_local_long(0);                     break;
1403   case Bytecodes::_lload_1: load_local_long(1);                     break;
1404   case Bytecodes::_lload_2: load_local_long(2);                     break;
1405   case Bytecodes::_lload_3: load_local_long(3);                     break;
1406 
1407   case Bytecodes::_lneg:
1408     {
1409       pop_long();
1410       push_long();
1411       break;
1412     }
1413   case Bytecodes::_lreturn:
1414     {
1415       pop_long();
1416       break;
1417     }
1418   case Bytecodes::_lshl:
1419   case Bytecodes::_lshr:
1420   case Bytecodes::_lushr:
1421     {
1422       pop_int();
1423       pop_long();
1424       push_long();
1425       break;
1426     }
1427   case Bytecodes::_lstore:   store_local_long(str->get_index());    break;
1428   case Bytecodes::_lstore_0: store_local_long(0);                   break;
1429   case Bytecodes::_lstore_1: store_local_long(1);                   break;
1430   case Bytecodes::_lstore_2: store_local_long(2);                   break;
1431   case Bytecodes::_lstore_3: store_local_long(3);                   break;
1432 
1433   case Bytecodes::_multianewarray: do_multianewarray(str);          break;
1434 
1435   case Bytecodes::_new:      do_new(str);                           break;
1436 
1437   case Bytecodes::_newarray: do_newarray(str);                      break;
1438 
1439   case Bytecodes::_pop:
1440     {
1441       pop();
1442       break;
1443     }
1444   case Bytecodes::_pop2:
1445     {
1446       pop();
1447       pop();
1448       break;
1449     }
1450 
1451   case Bytecodes::_putfield:       do_putfield(str);                 break;
1452   case Bytecodes::_putstatic:      do_putstatic(str);                break;
1453 
1454   case Bytecodes::_ret: do_ret(str);                                 break;
1455 
1456   case Bytecodes::_swap:
1457     {
1458       ciType* value1 = pop_value();
1459       ciType* value2 = pop_value();
1460       push(value1);
1461       push(value2);
1462       break;
1463     }
1464   case Bytecodes::_wide:
1465   default:
1466     {
1467       // The iterator should skip this.
1468       ShouldNotReachHere();
1469       break;
1470     }
1471   }
1472 
1473   if (CITraceTypeFlow) {
1474     print_on(tty);
1475   }
1476 
1477   return (_trap_bci != -1);
1478 }
1479 
1480 #ifndef PRODUCT
1481 // ------------------------------------------------------------------
1482 // ciTypeFlow::StateVector::print_cell_on
1483 void ciTypeFlow::StateVector::print_cell_on(outputStream* st, Cell c) const {
1484   ciType* type = type_at(c);
1485   if (type == top_type()) {
1486     st->print("top");
1487   } else if (type == bottom_type()) {
1488     st->print("bottom");
1489   } else if (type == null_type()) {
1490     st->print("null");
1491   } else if (type == long2_type()) {
1492     st->print("long2");
1493   } else if (type == double2_type()) {
1494     st->print("double2");
1495   } else if (is_int(type)) {
1496     st->print("int");
1497   } else if (is_long(type)) {
1498     st->print("long");
1499   } else if (is_float(type)) {
1500     st->print("float");
1501   } else if (is_double(type)) {
1502     st->print("double");
1503   } else if (type->is_return_address()) {
1504     st->print("address(%d)", type->as_return_address()->bci());
1505   } else {
1506     if (type->is_klass()) {
1507       type->as_klass()->name()->print_symbol_on(st);
1508     } else {
1509       st->print("UNEXPECTED TYPE");
1510       type->print();
1511     }
1512   }
1513 }
1514 
1515 // ------------------------------------------------------------------
1516 // ciTypeFlow::StateVector::print_on
1517 void ciTypeFlow::StateVector::print_on(outputStream* st) const {
1518   int num_locals   = _outer->max_locals();
1519   int num_stack    = stack_size();
1520   int num_monitors = monitor_count();
1521   st->print_cr("  State : locals %d, stack %d, monitors %d", num_locals, num_stack, num_monitors);
1522   if (num_stack >= 0) {
1523     int i;
1524     for (i = 0; i < num_locals; i++) {
1525       st->print("    local %2d : ", i);
1526       print_cell_on(st, local(i));
1527       st->cr();
1528     }
1529     for (i = 0; i < num_stack; i++) {
1530       st->print("    stack %2d : ", i);
1531       print_cell_on(st, stack(i));
1532       st->cr();
1533     }
1534   }
1535 }
1536 #endif
1537 
1538 
1539 // ------------------------------------------------------------------
1540 // ciTypeFlow::SuccIter::next
1541 //
1542 void ciTypeFlow::SuccIter::next() {
1543   int succ_ct = _pred->successors()->length();
1544   int next = _index + 1;
1545   if (next < succ_ct) {
1546     _index = next;
1547     _succ = _pred->successors()->at(next);
1548     return;
1549   }
1550   for (int i = next - succ_ct; i < _pred->exceptions()->length(); i++) {
1551     // Do not compile any code for unloaded exception types.
1552     // Following compiler passes are responsible for doing this also.
1553     ciInstanceKlass* exception_klass = _pred->exc_klasses()->at(i);
1554     if (exception_klass->is_loaded()) {
1555       _index = next;
1556       _succ = _pred->exceptions()->at(i);
1557       return;
1558     }
1559     next++;
1560   }
1561   _index = -1;
1562   _succ = NULL;
1563 }
1564 
1565 // ------------------------------------------------------------------
1566 // ciTypeFlow::SuccIter::set_succ
1567 //
1568 void ciTypeFlow::SuccIter::set_succ(Block* succ) {
1569   int succ_ct = _pred->successors()->length();
1570   if (_index < succ_ct) {
1571     _pred->successors()->at_put(_index, succ);
1572   } else {
1573     int idx = _index - succ_ct;
1574     _pred->exceptions()->at_put(idx, succ);
1575   }
1576 }
1577 
1578 // ciTypeFlow::Block
1579 //
1580 // A basic block.
1581 
1582 // ------------------------------------------------------------------
1583 // ciTypeFlow::Block::Block
1584 ciTypeFlow::Block::Block(ciTypeFlow* outer,
1585                          ciBlock *ciblk,
1586                          ciTypeFlow::JsrSet* jsrs) {
1587   _ciblock = ciblk;
1588   _exceptions = NULL;
1589   _exc_klasses = NULL;
1590   _successors = NULL;
1591   _state = new (outer->arena()) StateVector(outer);
1592   JsrSet* new_jsrs =
1593     new (outer->arena()) JsrSet(outer->arena(), jsrs->size());
1594   jsrs->copy_into(new_jsrs);
1595   _jsrs = new_jsrs;
1596   _next = NULL;
1597   _on_work_list = false;
1598   _backedge_copy = false;
1599   _has_monitorenter = false;
1600   _trap_bci = -1;
1601   _trap_index = 0;
1602   df_init();
1603 
1604   if (CITraceTypeFlow) {
1605     tty->print_cr(">> Created new block");
1606     print_on(tty);
1607   }
1608 
1609   assert(this->outer() == outer, "outer link set up");
1610   assert(!outer->have_block_count(), "must not have mapped blocks yet");
1611 }
1612 
1613 // ------------------------------------------------------------------
1614 // ciTypeFlow::Block::df_init
1615 void ciTypeFlow::Block::df_init() {
1616   _pre_order = -1; assert(!has_pre_order(), "");
1617   _post_order = -1; assert(!has_post_order(), "");
1618   _loop = NULL;
1619   _irreducible_entry = false;
1620   _rpo_next = NULL;
1621 }
1622 
1623 // ------------------------------------------------------------------
1624 // ciTypeFlow::Block::successors
1625 //
1626 // Get the successors for this Block.
1627 GrowableArray<ciTypeFlow::Block*>*
1628 ciTypeFlow::Block::successors(ciBytecodeStream* str,
1629                               ciTypeFlow::StateVector* state,
1630                               ciTypeFlow::JsrSet* jsrs) {
1631   if (_successors == NULL) {
1632     if (CITraceTypeFlow) {
1633       tty->print(">> Computing successors for block ");
1634       print_value_on(tty);
1635       tty->cr();
1636     }
1637 
1638     ciTypeFlow* analyzer = outer();
1639     Arena* arena = analyzer->arena();
1640     Block* block = NULL;
1641     bool has_successor = !has_trap() &&
1642                          (control() != ciBlock::fall_through_bci || limit() < analyzer->code_size());
1643     if (!has_successor) {
1644       _successors =
1645         new (arena) GrowableArray<Block*>(arena, 1, 0, NULL);
1646       // No successors
1647     } else if (control() == ciBlock::fall_through_bci) {
1648       assert(str->cur_bci() == limit(), "bad block end");
1649       // This block simply falls through to the next.
1650       _successors =
1651         new (arena) GrowableArray<Block*>(arena, 1, 0, NULL);
1652 
1653       Block* block = analyzer->block_at(limit(), _jsrs);
1654       assert(_successors->length() == FALL_THROUGH, "");
1655       _successors->append(block);
1656     } else {
1657       int current_bci = str->cur_bci();
1658       int next_bci = str->next_bci();
1659       int branch_bci = -1;
1660       Block* target = NULL;
1661       assert(str->next_bci() == limit(), "bad block end");
1662       // This block is not a simple fall-though.  Interpret
1663       // the current bytecode to find our successors.
1664       switch (str->cur_bc()) {
1665       case Bytecodes::_ifeq:         case Bytecodes::_ifne:
1666       case Bytecodes::_iflt:         case Bytecodes::_ifge:
1667       case Bytecodes::_ifgt:         case Bytecodes::_ifle:
1668       case Bytecodes::_if_icmpeq:    case Bytecodes::_if_icmpne:
1669       case Bytecodes::_if_icmplt:    case Bytecodes::_if_icmpge:
1670       case Bytecodes::_if_icmpgt:    case Bytecodes::_if_icmple:
1671       case Bytecodes::_if_acmpeq:    case Bytecodes::_if_acmpne:
1672       case Bytecodes::_ifnull:       case Bytecodes::_ifnonnull:
1673         // Our successors are the branch target and the next bci.
1674         branch_bci = str->get_dest();
1675         _successors =
1676           new (arena) GrowableArray<Block*>(arena, 2, 0, NULL);
1677         assert(_successors->length() == IF_NOT_TAKEN, "");
1678         _successors->append(analyzer->block_at(next_bci, jsrs));
1679         assert(_successors->length() == IF_TAKEN, "");
1680         _successors->append(analyzer->block_at(branch_bci, jsrs));
1681         break;
1682 
1683       case Bytecodes::_goto:
1684         branch_bci = str->get_dest();
1685         _successors =
1686           new (arena) GrowableArray<Block*>(arena, 1, 0, NULL);
1687         assert(_successors->length() == GOTO_TARGET, "");
1688         _successors->append(analyzer->block_at(branch_bci, jsrs));
1689         break;
1690 
1691       case Bytecodes::_jsr:
1692         branch_bci = str->get_dest();
1693         _successors =
1694           new (arena) GrowableArray<Block*>(arena, 1, 0, NULL);
1695         assert(_successors->length() == GOTO_TARGET, "");
1696         _successors->append(analyzer->block_at(branch_bci, jsrs));
1697         break;
1698 
1699       case Bytecodes::_goto_w:
1700       case Bytecodes::_jsr_w:
1701         _successors =
1702           new (arena) GrowableArray<Block*>(arena, 1, 0, NULL);
1703         assert(_successors->length() == GOTO_TARGET, "");
1704         _successors->append(analyzer->block_at(str->get_far_dest(), jsrs));
1705         break;
1706 
1707       case Bytecodes::_tableswitch:  {
1708         Bytecode_tableswitch tableswitch(str);
1709 
1710         int len = tableswitch.length();
1711         _successors =
1712           new (arena) GrowableArray<Block*>(arena, len+1, 0, NULL);
1713         int bci = current_bci + tableswitch.default_offset();
1714         Block* block = analyzer->block_at(bci, jsrs);
1715         assert(_successors->length() == SWITCH_DEFAULT, "");
1716         _successors->append(block);
1717         while (--len >= 0) {
1718           int bci = current_bci + tableswitch.dest_offset_at(len);
1719           block = analyzer->block_at(bci, jsrs);
1720           assert(_successors->length() >= SWITCH_CASES, "");
1721           _successors->append_if_missing(block);
1722         }
1723         break;
1724       }
1725 
1726       case Bytecodes::_lookupswitch: {
1727         Bytecode_lookupswitch lookupswitch(str);
1728 
1729         int npairs = lookupswitch.number_of_pairs();
1730         _successors =
1731           new (arena) GrowableArray<Block*>(arena, npairs+1, 0, NULL);
1732         int bci = current_bci + lookupswitch.default_offset();
1733         Block* block = analyzer->block_at(bci, jsrs);
1734         assert(_successors->length() == SWITCH_DEFAULT, "");
1735         _successors->append(block);
1736         while(--npairs >= 0) {
1737           LookupswitchPair pair = lookupswitch.pair_at(npairs);
1738           int bci = current_bci + pair.offset();
1739           Block* block = analyzer->block_at(bci, jsrs);
1740           assert(_successors->length() >= SWITCH_CASES, "");
1741           _successors->append_if_missing(block);
1742         }
1743         break;
1744       }
1745 
1746       case Bytecodes::_athrow:     case Bytecodes::_ireturn:
1747       case Bytecodes::_lreturn:    case Bytecodes::_freturn:
1748       case Bytecodes::_dreturn:    case Bytecodes::_areturn:
1749       case Bytecodes::_return:
1750         _successors =
1751           new (arena) GrowableArray<Block*>(arena, 1, 0, NULL);
1752         // No successors
1753         break;
1754 
1755       case Bytecodes::_ret: {
1756         _successors =
1757           new (arena) GrowableArray<Block*>(arena, 1, 0, NULL);
1758 
1759         Cell local = state->local(str->get_index());
1760         ciType* return_address = state->type_at(local);
1761         assert(return_address->is_return_address(), "verify: wrong type");
1762         int bci = return_address->as_return_address()->bci();
1763         assert(_successors->length() == GOTO_TARGET, "");
1764         _successors->append(analyzer->block_at(bci, jsrs));
1765         break;
1766       }
1767 
1768       case Bytecodes::_wide:
1769       default:
1770         ShouldNotReachHere();
1771         break;
1772       }
1773     }
1774   }
1775   return _successors;
1776 }
1777 
1778 // ------------------------------------------------------------------
1779 // ciTypeFlow::Block:compute_exceptions
1780 //
1781 // Compute the exceptional successors and types for this Block.
1782 void ciTypeFlow::Block::compute_exceptions() {
1783   assert(_exceptions == NULL && _exc_klasses == NULL, "repeat");
1784 
1785   if (CITraceTypeFlow) {
1786     tty->print(">> Computing exceptions for block ");
1787     print_value_on(tty);
1788     tty->cr();
1789   }
1790 
1791   ciTypeFlow* analyzer = outer();
1792   Arena* arena = analyzer->arena();
1793 
1794   // Any bci in the block will do.
1795   ciExceptionHandlerStream str(analyzer->method(), start());
1796 
1797   // Allocate our growable arrays.
1798   int exc_count = str.count();
1799   _exceptions = new (arena) GrowableArray<Block*>(arena, exc_count, 0, NULL);
1800   _exc_klasses = new (arena) GrowableArray<ciInstanceKlass*>(arena, exc_count,
1801                                                              0, NULL);
1802 
1803   for ( ; !str.is_done(); str.next()) {
1804     ciExceptionHandler* handler = str.handler();
1805     int bci = handler->handler_bci();
1806     ciInstanceKlass* klass = NULL;
1807     if (bci == -1) {
1808       // There is no catch all.  It is possible to exit the method.
1809       break;
1810     }
1811     if (handler->is_catch_all()) {
1812       klass = analyzer->env()->Throwable_klass();
1813     } else {
1814       klass = handler->catch_klass();
1815     }
1816     _exceptions->append(analyzer->block_at(bci, _jsrs));
1817     _exc_klasses->append(klass);
1818   }
1819 }
1820 
1821 // ------------------------------------------------------------------
1822 // ciTypeFlow::Block::set_backedge_copy
1823 // Use this only to make a pre-existing public block into a backedge copy.
1824 void ciTypeFlow::Block::set_backedge_copy(bool z) {
1825   assert(z || (z == is_backedge_copy()), "cannot make a backedge copy public");
1826   _backedge_copy = z;
1827 }
1828 
1829 // ------------------------------------------------------------------
1830 // ciTypeFlow::Block::is_clonable_exit
1831 //
1832 // At most 2 normal successors, one of which continues looping,
1833 // and all exceptional successors must exit.
1834 bool ciTypeFlow::Block::is_clonable_exit(ciTypeFlow::Loop* lp) {
1835   int normal_cnt  = 0;
1836   int in_loop_cnt = 0;
1837   for (SuccIter iter(this); !iter.done(); iter.next()) {
1838     Block* succ = iter.succ();
1839     if (iter.is_normal_ctrl()) {
1840       if (++normal_cnt > 2) return false;
1841       if (lp->contains(succ->loop())) {
1842         if (++in_loop_cnt > 1) return false;
1843       }
1844     } else {
1845       if (lp->contains(succ->loop())) return false;
1846     }
1847   }
1848   return in_loop_cnt == 1;
1849 }
1850 
1851 // ------------------------------------------------------------------
1852 // ciTypeFlow::Block::looping_succ
1853 //
1854 ciTypeFlow::Block* ciTypeFlow::Block::looping_succ(ciTypeFlow::Loop* lp) {
1855   assert(successors()->length() <= 2, "at most 2 normal successors");
1856   for (SuccIter iter(this); !iter.done(); iter.next()) {
1857     Block* succ = iter.succ();
1858     if (lp->contains(succ->loop())) {
1859       return succ;
1860     }
1861   }
1862   return NULL;
1863 }
1864 
1865 #ifndef PRODUCT
1866 // ------------------------------------------------------------------
1867 // ciTypeFlow::Block::print_value_on
1868 void ciTypeFlow::Block::print_value_on(outputStream* st) const {
1869   if (has_pre_order()) st->print("#%-2d ", pre_order());
1870   if (has_rpo())       st->print("rpo#%-2d ", rpo());
1871   st->print("[%d - %d)", start(), limit());
1872   if (is_loop_head()) st->print(" lphd");
1873   if (is_irreducible_entry()) st->print(" irred");
1874   if (_jsrs->size() > 0) { st->print("/");  _jsrs->print_on(st); }
1875   if (is_backedge_copy())  st->print("/backedge_copy");
1876 }
1877 
1878 // ------------------------------------------------------------------
1879 // ciTypeFlow::Block::print_on
1880 void ciTypeFlow::Block::print_on(outputStream* st) const {
1881   if ((Verbose || WizardMode) && (limit() >= 0)) {
1882     // Don't print 'dummy' blocks (i.e. blocks with limit() '-1')
1883     outer()->method()->print_codes_on(start(), limit(), st);
1884   }
1885   st->print_cr("  ====================================================  ");
1886   st->print ("  ");
1887   print_value_on(st);
1888   st->print(" Stored locals: "); def_locals()->print_on(st, outer()->method()->max_locals()); tty->cr();
1889   if (loop() && loop()->parent() != NULL) {
1890     st->print(" loops:");
1891     Loop* lp = loop();
1892     do {
1893       st->print(" %d<-%d", lp->head()->pre_order(),lp->tail()->pre_order());
1894       if (lp->is_irreducible()) st->print("(ir)");
1895       lp = lp->parent();
1896     } while (lp->parent() != NULL);
1897   }
1898   st->cr();
1899   _state->print_on(st);
1900   if (_successors == NULL) {
1901     st->print_cr("  No successor information");
1902   } else {
1903     int num_successors = _successors->length();
1904     st->print_cr("  Successors : %d", num_successors);
1905     for (int i = 0; i < num_successors; i++) {
1906       Block* successor = _successors->at(i);
1907       st->print("    ");
1908       successor->print_value_on(st);
1909       st->cr();
1910     }
1911   }
1912   if (_exceptions == NULL) {
1913     st->print_cr("  No exception information");
1914   } else {
1915     int num_exceptions = _exceptions->length();
1916     st->print_cr("  Exceptions : %d", num_exceptions);
1917     for (int i = 0; i < num_exceptions; i++) {
1918       Block* exc_succ = _exceptions->at(i);
1919       ciInstanceKlass* exc_klass = _exc_klasses->at(i);
1920       st->print("    ");
1921       exc_succ->print_value_on(st);
1922       st->print(" -- ");
1923       exc_klass->name()->print_symbol_on(st);
1924       st->cr();
1925     }
1926   }
1927   if (has_trap()) {
1928     st->print_cr("  Traps on %d with trap index %d", trap_bci(), trap_index());
1929   }
1930   st->print_cr("  ====================================================  ");
1931 }
1932 #endif
1933 
1934 #ifndef PRODUCT
1935 // ------------------------------------------------------------------
1936 // ciTypeFlow::LocalSet::print_on
1937 void ciTypeFlow::LocalSet::print_on(outputStream* st, int limit) const {
1938   st->print("{");
1939   for (int i = 0; i < max; i++) {
1940     if (test(i)) st->print(" %d", i);
1941   }
1942   if (limit > max) {
1943     st->print(" %d..%d ", max, limit);
1944   }
1945   st->print(" }");
1946 }
1947 #endif
1948 
1949 // ciTypeFlow
1950 //
1951 // This is a pass over the bytecodes which computes the following:
1952 //   basic block structure
1953 //   interpreter type-states (a la the verifier)
1954 
1955 // ------------------------------------------------------------------
1956 // ciTypeFlow::ciTypeFlow
1957 ciTypeFlow::ciTypeFlow(ciEnv* env, ciMethod* method, int osr_bci) {
1958   _env = env;
1959   _method = method;
1960   _methodBlocks = method->get_method_blocks();
1961   _max_locals = method->max_locals();
1962   _max_stack = method->max_stack();
1963   _code_size = method->code_size();
1964   _has_irreducible_entry = false;
1965   _osr_bci = osr_bci;
1966   _failure_reason = NULL;
1967   assert(0 <= start_bci() && start_bci() < code_size() , err_msg("correct osr_bci argument: 0 <= %d < %d", start_bci(), code_size()));
1968   _work_list = NULL;
1969 
1970   _ciblock_count = _methodBlocks->num_blocks();
1971   _idx_to_blocklist = NEW_ARENA_ARRAY(arena(), GrowableArray<Block*>*, _ciblock_count);
1972   for (int i = 0; i < _ciblock_count; i++) {
1973     _idx_to_blocklist[i] = NULL;
1974   }
1975   _block_map = NULL;  // until all blocks are seen
1976   _jsr_count = 0;
1977   _jsr_records = NULL;
1978 }
1979 
1980 // ------------------------------------------------------------------
1981 // ciTypeFlow::work_list_next
1982 //
1983 // Get the next basic block from our work list.
1984 ciTypeFlow::Block* ciTypeFlow::work_list_next() {
1985   assert(!work_list_empty(), "work list must not be empty");
1986   Block* next_block = _work_list;
1987   _work_list = next_block->next();
1988   next_block->set_next(NULL);
1989   next_block->set_on_work_list(false);
1990   return next_block;
1991 }
1992 
1993 // ------------------------------------------------------------------
1994 // ciTypeFlow::add_to_work_list
1995 //
1996 // Add a basic block to our work list.
1997 // List is sorted by decreasing postorder sort (same as increasing RPO)
1998 void ciTypeFlow::add_to_work_list(ciTypeFlow::Block* block) {
1999   assert(!block->is_on_work_list(), "must not already be on work list");
2000 
2001   if (CITraceTypeFlow) {
2002     tty->print(">> Adding block ");
2003     block->print_value_on(tty);
2004     tty->print_cr(" to the work list : ");
2005   }
2006 
2007   block->set_on_work_list(true);
2008 
2009   // decreasing post order sort
2010 
2011   Block* prev = NULL;
2012   Block* current = _work_list;
2013   int po = block->post_order();
2014   while (current != NULL) {
2015     if (!current->has_post_order() || po > current->post_order())
2016       break;
2017     prev = current;
2018     current = current->next();
2019   }
2020   if (prev == NULL) {
2021     block->set_next(_work_list);
2022     _work_list = block;
2023   } else {
2024     block->set_next(current);
2025     prev->set_next(block);
2026   }
2027 
2028   if (CITraceTypeFlow) {
2029     tty->cr();
2030   }
2031 }
2032 
2033 // ------------------------------------------------------------------
2034 // ciTypeFlow::block_at
2035 //
2036 // Return the block beginning at bci which has a JsrSet compatible
2037 // with jsrs.
2038 ciTypeFlow::Block* ciTypeFlow::block_at(int bci, ciTypeFlow::JsrSet* jsrs, CreateOption option) {
2039   // First find the right ciBlock.
2040   if (CITraceTypeFlow) {
2041     tty->print(">> Requesting block for %d/", bci);
2042     jsrs->print_on(tty);
2043     tty->cr();
2044   }
2045 
2046   ciBlock* ciblk = _methodBlocks->block_containing(bci);
2047   assert(ciblk->start_bci() == bci, "bad ciBlock boundaries");
2048   Block* block = get_block_for(ciblk->index(), jsrs, option);
2049 
2050   assert(block == NULL? (option == no_create): block->is_backedge_copy() == (option == create_backedge_copy), "create option consistent with result");
2051 
2052   if (CITraceTypeFlow) {
2053     if (block != NULL) {
2054       tty->print(">> Found block ");
2055       block->print_value_on(tty);
2056       tty->cr();
2057     } else {
2058       tty->print_cr(">> No such block.");
2059     }
2060   }
2061 
2062   return block;
2063 }
2064 
2065 // ------------------------------------------------------------------
2066 // ciTypeFlow::make_jsr_record
2067 //
2068 // Make a JsrRecord for a given (entry, return) pair, if such a record
2069 // does not already exist.
2070 ciTypeFlow::JsrRecord* ciTypeFlow::make_jsr_record(int entry_address,
2071                                                    int return_address) {
2072   if (_jsr_records == NULL) {
2073     _jsr_records = new (arena()) GrowableArray<JsrRecord*>(arena(),
2074                                                            _jsr_count,
2075                                                            0,
2076                                                            NULL);
2077   }
2078   JsrRecord* record = NULL;
2079   int len = _jsr_records->length();
2080   for (int i = 0; i < len; i++) {
2081     JsrRecord* record = _jsr_records->at(i);
2082     if (record->entry_address() == entry_address &&
2083         record->return_address() == return_address) {
2084       return record;
2085     }
2086   }
2087 
2088   record = new (arena()) JsrRecord(entry_address, return_address);
2089   _jsr_records->append(record);
2090   return record;
2091 }
2092 
2093 // ------------------------------------------------------------------
2094 // ciTypeFlow::flow_exceptions
2095 //
2096 // Merge the current state into all exceptional successors at the
2097 // current point in the code.
2098 void ciTypeFlow::flow_exceptions(GrowableArray<ciTypeFlow::Block*>* exceptions,
2099                                  GrowableArray<ciInstanceKlass*>* exc_klasses,
2100                                  ciTypeFlow::StateVector* state) {
2101   int len = exceptions->length();
2102   assert(exc_klasses->length() == len, "must have same length");
2103   for (int i = 0; i < len; i++) {
2104     Block* block = exceptions->at(i);
2105     ciInstanceKlass* exception_klass = exc_klasses->at(i);
2106 
2107     if (!exception_klass->is_loaded()) {
2108       // Do not compile any code for unloaded exception types.
2109       // Following compiler passes are responsible for doing this also.
2110       continue;
2111     }
2112 
2113     if (block->meet_exception(exception_klass, state)) {
2114       // Block was modified and has PO.  Add it to the work list.
2115       if (block->has_post_order() &&
2116           !block->is_on_work_list()) {
2117         add_to_work_list(block);
2118       }
2119     }
2120   }
2121 }
2122 
2123 // ------------------------------------------------------------------
2124 // ciTypeFlow::flow_successors
2125 //
2126 // Merge the current state into all successors at the current point
2127 // in the code.
2128 void ciTypeFlow::flow_successors(GrowableArray<ciTypeFlow::Block*>* successors,
2129                                  ciTypeFlow::StateVector* state) {
2130   int len = successors->length();
2131   for (int i = 0; i < len; i++) {
2132     Block* block = successors->at(i);
2133     if (block->meet(state)) {
2134       // Block was modified and has PO.  Add it to the work list.
2135       if (block->has_post_order() &&
2136           !block->is_on_work_list()) {
2137         add_to_work_list(block);
2138       }
2139     }
2140   }
2141 }
2142 
2143 // ------------------------------------------------------------------
2144 // ciTypeFlow::can_trap
2145 //
2146 // Tells if a given instruction is able to generate an exception edge.
2147 bool ciTypeFlow::can_trap(ciBytecodeStream& str) {
2148   // Cf. GenerateOopMap::do_exception_edge.
2149   if (!Bytecodes::can_trap(str.cur_bc()))  return false;
2150 
2151   switch (str.cur_bc()) {
2152     // %%% FIXME: ldc of Class can generate an exception
2153     case Bytecodes::_ldc:
2154     case Bytecodes::_ldc_w:
2155     case Bytecodes::_ldc2_w:
2156     case Bytecodes::_aload_0:
2157       // These bytecodes can trap for rewriting.  We need to assume that
2158       // they do not throw exceptions to make the monitor analysis work.
2159       return false;
2160 
2161     case Bytecodes::_ireturn:
2162     case Bytecodes::_lreturn:
2163     case Bytecodes::_freturn:
2164     case Bytecodes::_dreturn:
2165     case Bytecodes::_areturn:
2166     case Bytecodes::_return:
2167       // We can assume the monitor stack is empty in this analysis.
2168       return false;
2169 
2170     case Bytecodes::_monitorexit:
2171       // We can assume monitors are matched in this analysis.
2172       return false;
2173   }
2174 
2175   return true;
2176 }
2177 
2178 // ------------------------------------------------------------------
2179 // ciTypeFlow::clone_loop_heads
2180 //
2181 // Clone the loop heads
2182 bool ciTypeFlow::clone_loop_heads(Loop* lp, StateVector* temp_vector, JsrSet* temp_set) {
2183   bool rslt = false;
2184   for (PreorderLoops iter(loop_tree_root()); !iter.done(); iter.next()) {
2185     lp = iter.current();
2186     Block* head = lp->head();
2187     if (lp == loop_tree_root() ||
2188         lp->is_irreducible() ||
2189         !head->is_clonable_exit(lp))
2190       continue;
2191 
2192     // Avoid BoxLock merge.
2193     if (EliminateNestedLocks && head->has_monitorenter())
2194       continue;
2195 
2196     // check not already cloned
2197     if (head->backedge_copy_count() != 0)
2198       continue;
2199 
2200     // Don't clone head of OSR loop to get correct types in start block.
2201     if (is_osr_flow() && head->start() == start_bci())
2202       continue;
2203 
2204     // check _no_ shared head below us
2205     Loop* ch;
2206     for (ch = lp->child(); ch != NULL && ch->head() != head; ch = ch->sibling());
2207     if (ch != NULL)
2208       continue;
2209 
2210     // Clone head
2211     Block* new_head = head->looping_succ(lp);
2212     Block* clone = clone_loop_head(lp, temp_vector, temp_set);
2213     // Update lp's info
2214     clone->set_loop(lp);
2215     lp->set_head(new_head);
2216     lp->set_tail(clone);
2217     // And move original head into outer loop
2218     head->set_loop(lp->parent());
2219 
2220     rslt = true;
2221   }
2222   return rslt;
2223 }
2224 
2225 // ------------------------------------------------------------------
2226 // ciTypeFlow::clone_loop_head
2227 //
2228 // Clone lp's head and replace tail's successors with clone.
2229 //
2230 //  |
2231 //  v
2232 // head <-> body
2233 //  |
2234 //  v
2235 // exit
2236 //
2237 // new_head
2238 //
2239 //  |
2240 //  v
2241 // head ----------\
2242 //  |             |
2243 //  |             v
2244 //  |  clone <-> body
2245 //  |    |
2246 //  | /--/
2247 //  | |
2248 //  v v
2249 // exit
2250 //
2251 ciTypeFlow::Block* ciTypeFlow::clone_loop_head(Loop* lp, StateVector* temp_vector, JsrSet* temp_set) {
2252   Block* head = lp->head();
2253   Block* tail = lp->tail();
2254   if (CITraceTypeFlow) {
2255     tty->print(">> Requesting clone of loop head "); head->print_value_on(tty);
2256     tty->print("  for predecessor ");                tail->print_value_on(tty);
2257     tty->cr();
2258   }
2259   Block* clone = block_at(head->start(), head->jsrs(), create_backedge_copy);
2260   assert(clone->backedge_copy_count() == 1, "one backedge copy for all back edges");
2261 
2262   assert(!clone->has_pre_order(), "just created");
2263   clone->set_next_pre_order();
2264 
2265   // Insert clone after (orig) tail in reverse post order
2266   clone->set_rpo_next(tail->rpo_next());
2267   tail->set_rpo_next(clone);
2268 
2269   // tail->head becomes tail->clone
2270   for (SuccIter iter(tail); !iter.done(); iter.next()) {
2271     if (iter.succ() == head) {
2272       iter.set_succ(clone);
2273     }
2274   }
2275   flow_block(tail, temp_vector, temp_set);
2276   if (head == tail) {
2277     // For self-loops, clone->head becomes clone->clone
2278     flow_block(clone, temp_vector, temp_set);
2279     for (SuccIter iter(clone); !iter.done(); iter.next()) {
2280       if (iter.succ() == head) {
2281         iter.set_succ(clone);
2282         break;
2283       }
2284     }
2285   }
2286   flow_block(clone, temp_vector, temp_set);
2287 
2288   return clone;
2289 }
2290 
2291 // ------------------------------------------------------------------
2292 // ciTypeFlow::flow_block
2293 //
2294 // Interpret the effects of the bytecodes on the incoming state
2295 // vector of a basic block.  Push the changed state to succeeding
2296 // basic blocks.
2297 void ciTypeFlow::flow_block(ciTypeFlow::Block* block,
2298                             ciTypeFlow::StateVector* state,
2299                             ciTypeFlow::JsrSet* jsrs) {
2300   if (CITraceTypeFlow) {
2301     tty->print("\n>> ANALYZING BLOCK : ");
2302     tty->cr();
2303     block->print_on(tty);
2304   }
2305   assert(block->has_pre_order(), "pre-order is assigned before 1st flow");
2306 
2307   int start = block->start();
2308   int limit = block->limit();
2309   int control = block->control();
2310   if (control != ciBlock::fall_through_bci) {
2311     limit = control;
2312   }
2313 
2314   // Grab the state from the current block.
2315   block->copy_state_into(state);
2316   state->def_locals()->clear();
2317 
2318   GrowableArray<Block*>*           exceptions = block->exceptions();
2319   GrowableArray<ciInstanceKlass*>* exc_klasses = block->exc_klasses();
2320   bool has_exceptions = exceptions->length() > 0;
2321 
2322   bool exceptions_used = false;
2323 
2324   ciBytecodeStream str(method());
2325   str.reset_to_bci(start);
2326   Bytecodes::Code code;
2327   while ((code = str.next()) != ciBytecodeStream::EOBC() &&
2328          str.cur_bci() < limit) {
2329     // Check for exceptional control flow from this point.
2330     if (has_exceptions && can_trap(str)) {
2331       flow_exceptions(exceptions, exc_klasses, state);
2332       exceptions_used = true;
2333     }
2334     // Apply the effects of the current bytecode to our state.
2335     bool res = state->apply_one_bytecode(&str);
2336 
2337     // Watch for bailouts.
2338     if (failing())  return;
2339 
2340     if (str.cur_bc() == Bytecodes::_monitorenter) {
2341       block->set_has_monitorenter();
2342     }
2343 
2344     if (res) {
2345 
2346       // We have encountered a trap.  Record it in this block.
2347       block->set_trap(state->trap_bci(), state->trap_index());
2348 
2349       if (CITraceTypeFlow) {
2350         tty->print_cr(">> Found trap");
2351         block->print_on(tty);
2352       }
2353 
2354       // Save set of locals defined in this block
2355       block->def_locals()->add(state->def_locals());
2356 
2357       // Record (no) successors.
2358       block->successors(&str, state, jsrs);
2359 
2360       assert(!has_exceptions || exceptions_used, "Not removing exceptions");
2361 
2362       // Discontinue interpretation of this Block.
2363       return;
2364     }
2365   }
2366 
2367   GrowableArray<Block*>* successors = NULL;
2368   if (control != ciBlock::fall_through_bci) {
2369     // Check for exceptional control flow from this point.
2370     if (has_exceptions && can_trap(str)) {
2371       flow_exceptions(exceptions, exc_klasses, state);
2372       exceptions_used = true;
2373     }
2374 
2375     // Fix the JsrSet to reflect effect of the bytecode.
2376     block->copy_jsrs_into(jsrs);
2377     jsrs->apply_control(this, &str, state);
2378 
2379     // Find successor edges based on old state and new JsrSet.
2380     successors = block->successors(&str, state, jsrs);
2381 
2382     // Apply the control changes to the state.
2383     state->apply_one_bytecode(&str);
2384   } else {
2385     // Fall through control
2386     successors = block->successors(&str, NULL, NULL);
2387   }
2388 
2389   // Save set of locals defined in this block
2390   block->def_locals()->add(state->def_locals());
2391 
2392   // Remove untaken exception paths
2393   if (!exceptions_used)
2394     exceptions->clear();
2395 
2396   // Pass our state to successors.
2397   flow_successors(successors, state);
2398 }
2399 
2400 // ------------------------------------------------------------------
2401 // ciTypeFlow::PostOrderLoops::next
2402 //
2403 // Advance to next loop tree using a postorder, left-to-right traversal.
2404 void ciTypeFlow::PostorderLoops::next() {
2405   assert(!done(), "must not be done.");
2406   if (_current->sibling() != NULL) {
2407     _current = _current->sibling();
2408     while (_current->child() != NULL) {
2409       _current = _current->child();
2410     }
2411   } else {
2412     _current = _current->parent();
2413   }
2414 }
2415 
2416 // ------------------------------------------------------------------
2417 // ciTypeFlow::PreOrderLoops::next
2418 //
2419 // Advance to next loop tree using a preorder, left-to-right traversal.
2420 void ciTypeFlow::PreorderLoops::next() {
2421   assert(!done(), "must not be done.");
2422   if (_current->child() != NULL) {
2423     _current = _current->child();
2424   } else if (_current->sibling() != NULL) {
2425     _current = _current->sibling();
2426   } else {
2427     while (_current != _root && _current->sibling() == NULL) {
2428       _current = _current->parent();
2429     }
2430     if (_current == _root) {
2431       _current = NULL;
2432       assert(done(), "must be done.");
2433     } else {
2434       assert(_current->sibling() != NULL, "must be more to do");
2435       _current = _current->sibling();
2436     }
2437   }
2438 }
2439 
2440 // ------------------------------------------------------------------
2441 // ciTypeFlow::Loop::sorted_merge
2442 //
2443 // Merge the branch lp into this branch, sorting on the loop head
2444 // pre_orders. Returns the leaf of the merged branch.
2445 // Child and sibling pointers will be setup later.
2446 // Sort is (looking from leaf towards the root)
2447 //  descending on primary key: loop head's pre_order, and
2448 //  ascending  on secondary key: loop tail's pre_order.
2449 ciTypeFlow::Loop* ciTypeFlow::Loop::sorted_merge(Loop* lp) {
2450   Loop* leaf = this;
2451   Loop* prev = NULL;
2452   Loop* current = leaf;
2453   while (lp != NULL) {
2454     int lp_pre_order = lp->head()->pre_order();
2455     // Find insertion point for "lp"
2456     while (current != NULL) {
2457       if (current == lp)
2458         return leaf; // Already in list
2459       if (current->head()->pre_order() < lp_pre_order)
2460         break;
2461       if (current->head()->pre_order() == lp_pre_order &&
2462           current->tail()->pre_order() > lp->tail()->pre_order()) {
2463         break;
2464       }
2465       prev = current;
2466       current = current->parent();
2467     }
2468     Loop* next_lp = lp->parent(); // Save future list of items to insert
2469     // Insert lp before current
2470     lp->set_parent(current);
2471     if (prev != NULL) {
2472       prev->set_parent(lp);
2473     } else {
2474       leaf = lp;
2475     }
2476     prev = lp;     // Inserted item is new prev[ious]
2477     lp = next_lp;  // Next item to insert
2478   }
2479   return leaf;
2480 }
2481 
2482 // ------------------------------------------------------------------
2483 // ciTypeFlow::build_loop_tree
2484 //
2485 // Incrementally build loop tree.
2486 void ciTypeFlow::build_loop_tree(Block* blk) {
2487   assert(!blk->is_post_visited(), "precondition");
2488   Loop* innermost = NULL; // merge of loop tree branches over all successors
2489 
2490   for (SuccIter iter(blk); !iter.done(); iter.next()) {
2491     Loop*  lp   = NULL;
2492     Block* succ = iter.succ();
2493     if (!succ->is_post_visited()) {
2494       // Found backedge since predecessor post visited, but successor is not
2495       assert(succ->pre_order() <= blk->pre_order(), "should be backedge");
2496 
2497       // Create a LoopNode to mark this loop.
2498       lp = new (arena()) Loop(succ, blk);
2499       if (succ->loop() == NULL)
2500         succ->set_loop(lp);
2501       // succ->loop will be updated to innermost loop on a later call, when blk==succ
2502 
2503     } else {  // Nested loop
2504       lp = succ->loop();
2505 
2506       // If succ is loop head, find outer loop.
2507       while (lp != NULL && lp->head() == succ) {
2508         lp = lp->parent();
2509       }
2510       if (lp == NULL) {
2511         // Infinite loop, it's parent is the root
2512         lp = loop_tree_root();
2513       }
2514     }
2515 
2516     // Check for irreducible loop.
2517     // Successor has already been visited. If the successor's loop head
2518     // has already been post-visited, then this is another entry into the loop.
2519     while (lp->head()->is_post_visited() && lp != loop_tree_root()) {
2520       _has_irreducible_entry = true;
2521       lp->set_irreducible(succ);
2522       if (!succ->is_on_work_list()) {
2523         // Assume irreducible entries need more data flow
2524         add_to_work_list(succ);
2525       }
2526       Loop* plp = lp->parent();
2527       if (plp == NULL) {
2528         // This only happens for some irreducible cases.  The parent
2529         // will be updated during a later pass.
2530         break;
2531       }
2532       lp = plp;
2533     }
2534 
2535     // Merge loop tree branch for all successors.
2536     innermost = innermost == NULL ? lp : innermost->sorted_merge(lp);
2537 
2538   } // end loop
2539 
2540   if (innermost == NULL) {
2541     assert(blk->successors()->length() == 0, "CFG exit");
2542     blk->set_loop(loop_tree_root());
2543   } else if (innermost->head() == blk) {
2544     // If loop header, complete the tree pointers
2545     if (blk->loop() != innermost) {
2546 #ifdef ASSERT
2547       assert(blk->loop()->head() == innermost->head(), "same head");
2548       Loop* dl;
2549       for (dl = innermost; dl != NULL && dl != blk->loop(); dl = dl->parent());
2550       assert(dl == blk->loop(), "blk->loop() already in innermost list");
2551 #endif
2552       blk->set_loop(innermost);
2553     }
2554     innermost->def_locals()->add(blk->def_locals());
2555     Loop* l = innermost;
2556     Loop* p = l->parent();
2557     while (p && l->head() == blk) {
2558       l->set_sibling(p->child());  // Put self on parents 'next child'
2559       p->set_child(l);             // Make self the first child of parent
2560       p->def_locals()->add(l->def_locals());
2561       l = p;                       // Walk up the parent chain
2562       p = l->parent();
2563     }
2564   } else {
2565     blk->set_loop(innermost);
2566     innermost->def_locals()->add(blk->def_locals());
2567   }
2568 }
2569 
2570 // ------------------------------------------------------------------
2571 // ciTypeFlow::Loop::contains
2572 //
2573 // Returns true if lp is nested loop.
2574 bool ciTypeFlow::Loop::contains(ciTypeFlow::Loop* lp) const {
2575   assert(lp != NULL, "");
2576   if (this == lp || head() == lp->head()) return true;
2577   int depth1 = depth();
2578   int depth2 = lp->depth();
2579   if (depth1 > depth2)
2580     return false;
2581   while (depth1 < depth2) {
2582     depth2--;
2583     lp = lp->parent();
2584   }
2585   return this == lp;
2586 }
2587 
2588 // ------------------------------------------------------------------
2589 // ciTypeFlow::Loop::depth
2590 //
2591 // Loop depth
2592 int ciTypeFlow::Loop::depth() const {
2593   int dp = 0;
2594   for (Loop* lp = this->parent(); lp != NULL; lp = lp->parent())
2595     dp++;
2596   return dp;
2597 }
2598 
2599 #ifndef PRODUCT
2600 // ------------------------------------------------------------------
2601 // ciTypeFlow::Loop::print
2602 void ciTypeFlow::Loop::print(outputStream* st, int indent) const {
2603   for (int i = 0; i < indent; i++) st->print(" ");
2604   st->print("%d<-%d %s",
2605             is_root() ? 0 : this->head()->pre_order(),
2606             is_root() ? 0 : this->tail()->pre_order(),
2607             is_irreducible()?" irr":"");
2608   st->print(" defs: ");
2609   def_locals()->print_on(st, _head->outer()->method()->max_locals());
2610   st->cr();
2611   for (Loop* ch = child(); ch != NULL; ch = ch->sibling())
2612     ch->print(st, indent+2);
2613 }
2614 #endif
2615 
2616 // ------------------------------------------------------------------
2617 // ciTypeFlow::df_flow_types
2618 //
2619 // Perform the depth first type flow analysis. Helper for flow_types.
2620 void ciTypeFlow::df_flow_types(Block* start,
2621                                bool do_flow,
2622                                StateVector* temp_vector,
2623                                JsrSet* temp_set) {
2624   int dft_len = 100;
2625   GrowableArray<Block*> stk(dft_len);
2626 
2627   ciBlock* dummy = _methodBlocks->make_dummy_block();
2628   JsrSet* root_set = new JsrSet(NULL, 0);
2629   Block* root_head = new (arena()) Block(this, dummy, root_set);
2630   Block* root_tail = new (arena()) Block(this, dummy, root_set);
2631   root_head->set_pre_order(0);
2632   root_head->set_post_order(0);
2633   root_tail->set_pre_order(max_jint);
2634   root_tail->set_post_order(max_jint);
2635   set_loop_tree_root(new (arena()) Loop(root_head, root_tail));
2636 
2637   stk.push(start);
2638 
2639   _next_pre_order = 0;  // initialize pre_order counter
2640   _rpo_list = NULL;
2641   int next_po = 0;      // initialize post_order counter
2642 
2643   // Compute RPO and the control flow graph
2644   int size;
2645   while ((size = stk.length()) > 0) {
2646     Block* blk = stk.top(); // Leave node on stack
2647     if (!blk->is_visited()) {
2648       // forward arc in graph
2649       assert (!blk->has_pre_order(), "");
2650       blk->set_next_pre_order();
2651 
2652       if (_next_pre_order >= (int)Compile::current()->max_node_limit() / 2) {
2653         // Too many basic blocks.  Bail out.
2654         // This can happen when try/finally constructs are nested to depth N,
2655         // and there is O(2**N) cloning of jsr bodies.  See bug 4697245!
2656         // "MaxNodeLimit / 2" is used because probably the parser will
2657         // generate at least twice that many nodes and bail out.
2658         record_failure("too many basic blocks");
2659         return;
2660       }
2661       if (do_flow) {
2662         flow_block(blk, temp_vector, temp_set);
2663         if (failing()) return; // Watch for bailouts.
2664       }
2665     } else if (!blk->is_post_visited()) {
2666       // cross or back arc
2667       for (SuccIter iter(blk); !iter.done(); iter.next()) {
2668         Block* succ = iter.succ();
2669         if (!succ->is_visited()) {
2670           stk.push(succ);
2671         }
2672       }
2673       if (stk.length() == size) {
2674         // There were no additional children, post visit node now
2675         stk.pop(); // Remove node from stack
2676 
2677         build_loop_tree(blk);
2678         blk->set_post_order(next_po++);   // Assign post order
2679         prepend_to_rpo_list(blk);
2680         assert(blk->is_post_visited(), "");
2681 
2682         if (blk->is_loop_head() && !blk->is_on_work_list()) {
2683           // Assume loop heads need more data flow
2684           add_to_work_list(blk);
2685         }
2686       }
2687     } else {
2688       stk.pop(); // Remove post-visited node from stack
2689     }
2690   }
2691 }
2692 
2693 // ------------------------------------------------------------------
2694 // ciTypeFlow::flow_types
2695 //
2696 // Perform the type flow analysis, creating and cloning Blocks as
2697 // necessary.
2698 void ciTypeFlow::flow_types() {
2699   ResourceMark rm;
2700   StateVector* temp_vector = new StateVector(this);
2701   JsrSet* temp_set = new JsrSet(NULL, 16);
2702 
2703   // Create the method entry block.
2704   Block* start = block_at(start_bci(), temp_set);
2705 
2706   // Load the initial state into it.
2707   const StateVector* start_state = get_start_state();
2708   if (failing())  return;
2709   start->meet(start_state);
2710 
2711   // Depth first visit
2712   df_flow_types(start, true /*do flow*/, temp_vector, temp_set);
2713 
2714   if (failing())  return;
2715   assert(_rpo_list == start, "must be start");
2716 
2717   // Any loops found?
2718   if (loop_tree_root()->child() != NULL &&
2719       env()->comp_level() >= CompLevel_full_optimization) {
2720       // Loop optimizations are not performed on Tier1 compiles.
2721 
2722     bool changed = clone_loop_heads(loop_tree_root(), temp_vector, temp_set);
2723 
2724     // If some loop heads were cloned, recompute postorder and loop tree
2725     if (changed) {
2726       loop_tree_root()->set_child(NULL);
2727       for (Block* blk = _rpo_list; blk != NULL;) {
2728         Block* next = blk->rpo_next();
2729         blk->df_init();
2730         blk = next;
2731       }
2732       df_flow_types(start, false /*no flow*/, temp_vector, temp_set);
2733     }
2734   }
2735 
2736   if (CITraceTypeFlow) {
2737     tty->print_cr("\nLoop tree");
2738     loop_tree_root()->print();
2739   }
2740 
2741   // Continue flow analysis until fixed point reached
2742 
2743   debug_only(int max_block = _next_pre_order;)
2744 
2745   while (!work_list_empty()) {
2746     Block* blk = work_list_next();
2747     assert (blk->has_post_order(), "post order assigned above");
2748 
2749     flow_block(blk, temp_vector, temp_set);
2750 
2751     assert (max_block == _next_pre_order, "no new blocks");
2752     assert (!failing(), "no more bailouts");
2753   }
2754 }
2755 
2756 // ------------------------------------------------------------------
2757 // ciTypeFlow::map_blocks
2758 //
2759 // Create the block map, which indexes blocks in reverse post-order.
2760 void ciTypeFlow::map_blocks() {
2761   assert(_block_map == NULL, "single initialization");
2762   int block_ct = _next_pre_order;
2763   _block_map = NEW_ARENA_ARRAY(arena(), Block*, block_ct);
2764   assert(block_ct == block_count(), "");
2765 
2766   Block* blk = _rpo_list;
2767   for (int m = 0; m < block_ct; m++) {
2768     int rpo = blk->rpo();
2769     assert(rpo == m, "should be sequential");
2770     _block_map[rpo] = blk;
2771     blk = blk->rpo_next();
2772   }
2773   assert(blk == NULL, "should be done");
2774 
2775   for (int j = 0; j < block_ct; j++) {
2776     assert(_block_map[j] != NULL, "must not drop any blocks");
2777     Block* block = _block_map[j];
2778     // Remove dead blocks from successor lists:
2779     for (int e = 0; e <= 1; e++) {
2780       GrowableArray<Block*>* l = e? block->exceptions(): block->successors();
2781       for (int k = 0; k < l->length(); k++) {
2782         Block* s = l->at(k);
2783         if (!s->has_post_order()) {
2784           if (CITraceTypeFlow) {
2785             tty->print("Removing dead %s successor of #%d: ", (e? "exceptional":  "normal"), block->pre_order());
2786             s->print_value_on(tty);
2787             tty->cr();
2788           }
2789           l->remove(s);
2790           --k;
2791         }
2792       }
2793     }
2794   }
2795 }
2796 
2797 // ------------------------------------------------------------------
2798 // ciTypeFlow::get_block_for
2799 //
2800 // Find a block with this ciBlock which has a compatible JsrSet.
2801 // If no such block exists, create it, unless the option is no_create.
2802 // If the option is create_backedge_copy, always create a fresh backedge copy.
2803 ciTypeFlow::Block* ciTypeFlow::get_block_for(int ciBlockIndex, ciTypeFlow::JsrSet* jsrs, CreateOption option) {
2804   Arena* a = arena();
2805   GrowableArray<Block*>* blocks = _idx_to_blocklist[ciBlockIndex];
2806   if (blocks == NULL) {
2807     // Query only?
2808     if (option == no_create)  return NULL;
2809 
2810     // Allocate the growable array.
2811     blocks = new (a) GrowableArray<Block*>(a, 4, 0, NULL);
2812     _idx_to_blocklist[ciBlockIndex] = blocks;
2813   }
2814 
2815   if (option != create_backedge_copy) {
2816     int len = blocks->length();
2817     for (int i = 0; i < len; i++) {
2818       Block* block = blocks->at(i);
2819       if (!block->is_backedge_copy() && block->is_compatible_with(jsrs)) {
2820         return block;
2821       }
2822     }
2823   }
2824 
2825   // Query only?
2826   if (option == no_create)  return NULL;
2827 
2828   // We did not find a compatible block.  Create one.
2829   Block* new_block = new (a) Block(this, _methodBlocks->block(ciBlockIndex), jsrs);
2830   if (option == create_backedge_copy)  new_block->set_backedge_copy(true);
2831   blocks->append(new_block);
2832   return new_block;
2833 }
2834 
2835 // ------------------------------------------------------------------
2836 // ciTypeFlow::backedge_copy_count
2837 //
2838 int ciTypeFlow::backedge_copy_count(int ciBlockIndex, ciTypeFlow::JsrSet* jsrs) const {
2839   GrowableArray<Block*>* blocks = _idx_to_blocklist[ciBlockIndex];
2840 
2841   if (blocks == NULL) {
2842     return 0;
2843   }
2844 
2845   int count = 0;
2846   int len = blocks->length();
2847   for (int i = 0; i < len; i++) {
2848     Block* block = blocks->at(i);
2849     if (block->is_backedge_copy() && block->is_compatible_with(jsrs)) {
2850       count++;
2851     }
2852   }
2853 
2854   return count;
2855 }
2856 
2857 // ------------------------------------------------------------------
2858 // ciTypeFlow::do_flow
2859 //
2860 // Perform type inference flow analysis.
2861 void ciTypeFlow::do_flow() {
2862   if (CITraceTypeFlow) {
2863     tty->print_cr("\nPerforming flow analysis on method");
2864     method()->print();
2865     if (is_osr_flow())  tty->print(" at OSR bci %d", start_bci());
2866     tty->cr();
2867     method()->print_codes();
2868   }
2869   if (CITraceTypeFlow) {
2870     tty->print_cr("Initial CI Blocks");
2871     print_on(tty);
2872   }
2873   flow_types();
2874   // Watch for bailouts.
2875   if (failing()) {
2876     return;
2877   }
2878 
2879   map_blocks();
2880 
2881   if (CIPrintTypeFlow || CITraceTypeFlow) {
2882     rpo_print_on(tty);
2883   }
2884 }
2885 
2886 // ------------------------------------------------------------------
2887 // ciTypeFlow::record_failure()
2888 // The ciTypeFlow object keeps track of failure reasons separately from the ciEnv.
2889 // This is required because there is not a 1-1 relation between the ciEnv and
2890 // the TypeFlow passes within a compilation task.  For example, if the compiler
2891 // is considering inlining a method, it will request a TypeFlow.  If that fails,
2892 // the compilation as a whole may continue without the inlining.  Some TypeFlow
2893 // requests are not optional; if they fail the requestor is responsible for
2894 // copying the failure reason up to the ciEnv.  (See Parse::Parse.)
2895 void ciTypeFlow::record_failure(const char* reason) {
2896   if (env()->log() != NULL) {
2897     env()->log()->elem("failure reason='%s' phase='typeflow'", reason);
2898   }
2899   if (_failure_reason == NULL) {
2900     // Record the first failure reason.
2901     _failure_reason = reason;
2902   }
2903 }
2904 
2905 #ifndef PRODUCT
2906 // ------------------------------------------------------------------
2907 // ciTypeFlow::print_on
2908 void ciTypeFlow::print_on(outputStream* st) const {
2909   // Walk through CI blocks
2910   st->print_cr("********************************************************");
2911   st->print   ("TypeFlow for ");
2912   method()->name()->print_symbol_on(st);
2913   int limit_bci = code_size();
2914   st->print_cr("  %d bytes", limit_bci);
2915   ciMethodBlocks  *mblks = _methodBlocks;
2916   ciBlock* current = NULL;
2917   for (int bci = 0; bci < limit_bci; bci++) {
2918     ciBlock* blk = mblks->block_containing(bci);
2919     if (blk != NULL && blk != current) {
2920       current = blk;
2921       current->print_on(st);
2922 
2923       GrowableArray<Block*>* blocks = _idx_to_blocklist[blk->index()];
2924       int num_blocks = (blocks == NULL) ? 0 : blocks->length();
2925 
2926       if (num_blocks == 0) {
2927         st->print_cr("  No Blocks");
2928       } else {
2929         for (int i = 0; i < num_blocks; i++) {
2930           Block* block = blocks->at(i);
2931           block->print_on(st);
2932         }
2933       }
2934       st->print_cr("--------------------------------------------------------");
2935       st->cr();
2936     }
2937   }
2938   st->print_cr("********************************************************");
2939   st->cr();
2940 }
2941 
2942 void ciTypeFlow::rpo_print_on(outputStream* st) const {
2943   st->print_cr("********************************************************");
2944   st->print   ("TypeFlow for ");
2945   method()->name()->print_symbol_on(st);
2946   int limit_bci = code_size();
2947   st->print_cr("  %d bytes", limit_bci);
2948   for (Block* blk = _rpo_list; blk != NULL; blk = blk->rpo_next()) {
2949     blk->print_on(st);
2950     st->print_cr("--------------------------------------------------------");
2951     st->cr();
2952   }
2953   st->print_cr("********************************************************");
2954   st->cr();
2955 }
2956 #endif