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