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