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