1 /*
   2  * Copyright (c) 1998, 2019, 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/ciMethodData.hpp"
  27 #include "classfile/systemDictionary.hpp"
  28 #include "classfile/vmSymbols.hpp"
  29 #include "compiler/compileLog.hpp"
  30 #include "interpreter/linkResolver.hpp"
  31 #include "memory/resourceArea.hpp"
  32 #include "memory/universe.hpp"
  33 #include "oops/oop.inline.hpp"
  34 #include "opto/addnode.hpp"
  35 #include "opto/castnode.hpp"
  36 #include "opto/convertnode.hpp"
  37 #include "opto/divnode.hpp"
  38 #include "opto/idealGraphPrinter.hpp"
  39 #include "opto/idealKit.hpp"
  40 #include "opto/matcher.hpp"
  41 #include "opto/memnode.hpp"
  42 #include "opto/mulnode.hpp"
  43 #include "opto/opaquenode.hpp"
  44 #include "opto/parse.hpp"
  45 #include "opto/runtime.hpp"
  46 #include "opto/valuetypenode.hpp"
  47 #include "runtime/deoptimization.hpp"
  48 #include "runtime/sharedRuntime.hpp"
  49 
  50 #ifndef PRODUCT
  51 extern int explicit_null_checks_inserted,
  52            explicit_null_checks_elided;
  53 #endif
  54 
  55 //---------------------------------array_load----------------------------------
  56 void Parse::array_load(BasicType bt) {
  57   const Type* elemtype = Type::TOP;
  58   Node* adr = array_addressing(bt, 0, &elemtype);
  59   if (stopped())  return;     // guaranteed null or range check
  60 
  61   Node* idx = pop();
  62   Node* ary = pop();
  63 
  64   // Handle value type arrays
  65   const TypeOopPtr* elemptr = elemtype->make_oopptr();
  66   const TypeAryPtr* ary_t = _gvn.type(ary)->is_aryptr();
  67   if (elemtype->isa_valuetype() != NULL) {
  68     // Load from flattened value type array
  69     Node* vt = ValueTypeNode::make_from_flattened(this, elemtype->value_klass(), ary, adr);
  70     push(vt);
  71     return;
  72   } else if (elemptr != NULL && elemptr->is_valuetypeptr() && !elemptr->maybe_null()) {
  73     // Load from non-flattened but flattenable value type array (elements can never be null)
  74     bt = T_VALUETYPE;
  75   } else if (ValueArrayFlatten && elemptr != NULL && elemptr->can_be_value_type() &&
  76              ((!elemptr->is_valuetypeptr() && !ary_t->klass_is_exact()) || (elemptr->is_valuetypeptr() && elemptr->value_klass()->flatten_array()))) {
  77     // Cannot statically determine if array is flattened, emit runtime check
  78     IdealKit ideal(this);
  79     IdealVariable res(ideal);
  80     ideal.declarations_done();
  81     Node* kls = load_object_klass(ary);
  82     Node* tag = load_lh_array_tag(kls);
  83     ideal.if_then(tag, BoolTest::ne, intcon(Klass::_lh_array_tag_vt_value)); {
  84       // non-flattened
  85       sync_kit(ideal);
  86       const TypeAryPtr* adr_type = TypeAryPtr::get_array_body_type(bt);
  87       Node* ld = access_load_at(ary, adr, adr_type, elemptr, bt,
  88                                 IN_HEAP | IS_ARRAY | C2_CONTROL_DEPENDENT_LOAD);
  89       ideal.sync_kit(this);
  90       ideal.set(res, ld);
  91     } ideal.else_(); {
  92       // flattened
  93       sync_kit(ideal);
  94       if (elemptr->is_valuetypeptr()) {
  95         // Element type is known, cast and load from flattened representation
  96         assert(elemptr->maybe_null(), "must be nullable");
  97         ciValueKlass* vk = elemptr->value_klass();
  98         assert(vk->flatten_array(), "must be flattenable");
  99         ciArrayKlass* array_klass = ciArrayKlass::make(vk, /* never_null */ true);
 100         const TypeAryPtr* arytype = TypeOopPtr::make_from_klass(array_klass)->isa_aryptr();
 101         Node* cast = _gvn.transform(new CheckCastPPNode(control(), ary, arytype));
 102         adr = array_element_address(cast, idx, T_VALUETYPE, ary_t->size(), control());
 103         Node* vt = ValueTypeNode::make_from_flattened(this, vk, cast, adr)->allocate(this, false, false)->get_oop();
 104         ideal.set(res, vt);
 105       } else {
 106         // Element type is unknown, emit runtime call
 107         assert(!ary_t->klass_is_exact(), "should not have exact type here");
 108         Node* k_adr = basic_plus_adr(kls, in_bytes(ArrayKlass::element_klass_offset()));
 109         Node* elem_klass = _gvn.transform(LoadKlassNode::make(_gvn, NULL, immutable_memory(), k_adr, TypeInstPtr::KLASS));
 110         Node* obj_size  = NULL;
 111         kill_dead_locals();
 112         inc_sp(2);
 113         Node* alloc_obj = new_instance(elem_klass, NULL, &obj_size, /*deoptimize_on_exception=*/true);
 114         dec_sp(2);
 115 
 116         AllocateNode* alloc = AllocateNode::Ideal_allocation(alloc_obj, &_gvn);
 117         assert(alloc->maybe_set_complete(&_gvn), "");
 118         alloc->initialization()->set_complete_with_arraycopy();
 119         BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
 120         // Unknown value type might contain reference fields
 121         if (!bs->array_copy_requires_gc_barriers(false, T_OBJECT, false, BarrierSetC2::Parsing)) {
 122           int base_off = sizeof(instanceOopDesc);
 123           Node* dst_base = basic_plus_adr(alloc_obj, base_off);
 124           Node* countx = obj_size;
 125           countx = _gvn.transform(new SubXNode(countx, MakeConX(base_off)));
 126           countx = _gvn.transform(new URShiftXNode(countx, intcon(LogBytesPerLong)));
 127 
 128           assert(Klass::_lh_log2_element_size_shift == 0, "use shift in place");
 129           Node* lhp = basic_plus_adr(kls, in_bytes(Klass::layout_helper_offset()));
 130           Node* elem_shift = make_load(NULL, lhp, TypeInt::INT, T_INT, MemNode::unordered);
 131           uint header = arrayOopDesc::base_offset_in_bytes(T_VALUETYPE);
 132           Node* base  = basic_plus_adr(ary, header);
 133           idx = Compile::conv_I2X_index(&_gvn, idx, TypeInt::POS, control());
 134           Node* scale = _gvn.transform(new LShiftXNode(idx, elem_shift));
 135           Node* adr = basic_plus_adr(ary, base, scale);
 136 
 137           access_clone(adr, dst_base, countx, false);
 138         } else {
 139           ideal.sync_kit(this);
 140           ideal.make_leaf_call(OptoRuntime::load_unknown_value_Type(),
 141                                CAST_FROM_FN_PTR(address, OptoRuntime::load_unknown_value),
 142                                "load_unknown_value",
 143                                ary, idx, alloc_obj);
 144           sync_kit(ideal);
 145         }
 146 
 147         insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out_or_null(AllocateNode::RawAddress));
 148 
 149         ideal.set(res, alloc_obj);
 150       }
 151       ideal.sync_kit(this);
 152     } ideal.end_if();
 153     sync_kit(ideal);
 154     push_node(bt, _gvn.transform(ideal.value(res)));
 155     return;
 156   }
 157 
 158   if (elemtype == TypeInt::BOOL) {
 159     bt = T_BOOLEAN;
 160   } else if (bt == T_OBJECT) {
 161     elemtype = ary_t->elem()->make_oopptr();
 162   }
 163 
 164   const TypeAryPtr* adr_type = TypeAryPtr::get_array_body_type(bt);
 165   Node* ld = access_load_at(ary, adr, adr_type, elemtype, bt,
 166                             IN_HEAP | IS_ARRAY | C2_CONTROL_DEPENDENT_LOAD);
 167   if (bt == T_VALUETYPE) {
 168     // Loading a non-flattened (but flattenable) value type from an array
 169     assert(!gvn().type(ld)->maybe_null(), "value type array elements should never be null");
 170     if (elemptr->value_klass()->is_scalarizable()) {
 171       ld = ValueTypeNode::make_from_oop(this, ld, elemptr->value_klass());
 172     }
 173   }
 174 
 175   push_node(bt, ld);
 176 }
 177 
 178 
 179 //--------------------------------array_store----------------------------------
 180 void Parse::array_store(BasicType bt) {
 181   const Type* elemtype = Type::TOP;
 182   Node* adr = array_addressing(bt, type2size[bt], &elemtype);
 183   if (stopped())  return;     // guaranteed null or range check
 184   Node* cast_val = NULL;
 185   if (bt == T_OBJECT) {
 186     cast_val = array_store_check();
 187     if (stopped()) return;
 188   }
 189   Node* val = pop_node(bt); // Value to store
 190   Node* idx = pop();        // Index in the array
 191   Node* ary = pop();        // The array itself
 192 
 193   const TypeAryPtr* ary_t = _gvn.type(ary)->is_aryptr();
 194   if (bt == T_OBJECT) {
 195     const TypeOopPtr* elemptr = elemtype->make_oopptr();
 196     const Type* val_t = _gvn.type(val);
 197     if (elemtype->isa_valuetype() != NULL) {
 198       // Store to flattened value type array
 199       if (!cast_val->is_ValueType()) {
 200         inc_sp(3);
 201         cast_val = null_check(cast_val);
 202         if (stopped()) return;
 203         dec_sp(3);
 204         cast_val = ValueTypeNode::make_from_oop(this, cast_val, elemtype->value_klass());
 205       }
 206       cast_val->as_ValueType()->store_flattened(this, ary, adr);
 207       return;
 208     } else if (elemptr->is_valuetypeptr() && !elemptr->maybe_null()) {
 209       // Store to non-flattened but flattenable value type array (elements can never be null)
 210       if (!cast_val->is_ValueType()) {
 211         inc_sp(3);
 212         cast_val = null_check(cast_val);
 213         if (stopped()) return;
 214         dec_sp(3);
 215       }
 216     } else if (elemptr->can_be_value_type() && (!ary_t->klass_is_exact() || elemptr->is_valuetypeptr()) &&
 217                (val->is_ValueType() || val_t == TypePtr::NULL_PTR || val_t->is_oopptr()->can_be_value_type())) {
 218       // Cannot statically determine if array is flattened, emit runtime check
 219       ciValueKlass* vk = NULL;
 220       // Try to determine the value klass
 221       if (val->is_ValueType()) {
 222         vk = val_t->value_klass();
 223       } else if (elemptr->is_valuetypeptr()) {
 224         vk = elemptr->value_klass();
 225       }
 226       if (ValueArrayFlatten && (vk == NULL || vk->flatten_array())) {
 227         IdealKit ideal(this);
 228         Node* kls = load_object_klass(ary);
 229         Node* layout_val = load_lh_array_tag(kls);
 230         ideal.if_then(layout_val, BoolTest::ne, intcon(Klass::_lh_array_tag_vt_value)); {
 231           // non-flattened
 232           sync_kit(ideal);
 233           gen_value_array_null_guard(ary, val, 3);
 234           const TypeAryPtr* adr_type = TypeAryPtr::get_array_body_type(bt);
 235           elemtype = ary_t->elem()->make_oopptr();
 236           access_store_at(ary, adr, adr_type, val, elemtype, bt, MO_UNORDERED | IN_HEAP | IS_ARRAY, false, false);
 237           ideal.sync_kit(this);
 238         } ideal.else_(); {
 239           // flattened
 240           if (!val->is_ValueType() && TypePtr::NULL_PTR->higher_equal(val_t)) {
 241             // Add null check
 242             sync_kit(ideal);
 243             Node* null_ctl = top();
 244             val = null_check_oop(val, &null_ctl);
 245             if (null_ctl != top()) {
 246               PreserveJVMState pjvms(this);
 247               inc_sp(3);
 248               set_control(null_ctl);
 249               uncommon_trap(Deoptimization::Reason_null_check, Deoptimization::Action_none);
 250               dec_sp(3);
 251             }
 252             ideal.sync_kit(this);
 253           }
 254           if (vk != NULL && !stopped()) {
 255             // Element type is known, cast and store to flattened representation
 256             sync_kit(ideal);
 257             assert(vk->flatten_array(), "must be flattenable");
 258             assert(elemptr->maybe_null(), "must be nullable");
 259             ciArrayKlass* array_klass = ciArrayKlass::make(vk, /* never_null */ true);
 260             const TypeAryPtr* arytype = TypeOopPtr::make_from_klass(array_klass)->isa_aryptr();
 261             ary = _gvn.transform(new CheckCastPPNode(control(), ary, arytype));
 262             adr = array_element_address(ary, idx, T_OBJECT, arytype->size(), control());
 263             if (!val->is_ValueType()) {
 264               assert(!gvn().type(val)->maybe_null(), "value type array elements should never be null");
 265               val = ValueTypeNode::make_from_oop(this, val, vk);
 266             }
 267             val->as_ValueType()->store_flattened(this, ary, adr);
 268             ideal.sync_kit(this);
 269           } else if (!ideal.ctrl()->is_top()) {
 270             // Element type is unknown, emit runtime call
 271             assert(!ary_t->klass_is_exact(), "should not have exact type here");
 272             ideal.make_leaf_call(OptoRuntime::store_unknown_value_Type(),
 273                                  CAST_FROM_FN_PTR(address, OptoRuntime::store_unknown_value),
 274                                  "store_unknown_value",
 275                                  val, ary, idx);
 276           }
 277         } ideal.end_if();
 278         sync_kit(ideal);
 279         return;
 280       } else {
 281         gen_value_array_null_guard(ary, val, 3);
 282       }
 283     }
 284   }
 285 
 286   if (elemtype == TypeInt::BOOL) {
 287     bt = T_BOOLEAN;
 288   } else if (bt == T_OBJECT) {
 289     elemtype = ary_t->elem()->make_oopptr();
 290   }
 291 
 292   const TypeAryPtr* adr_type = TypeAryPtr::get_array_body_type(bt);
 293 
 294   access_store_at(ary, adr, adr_type, val, elemtype, bt, MO_UNORDERED | IN_HEAP | IS_ARRAY);
 295 }
 296 
 297 
 298 //------------------------------array_addressing-------------------------------
 299 // Pull array and index from the stack.  Compute pointer-to-element.
 300 Node* Parse::array_addressing(BasicType type, int vals, const Type* *result2) {
 301   Node *idx   = peek(0+vals);   // Get from stack without popping
 302   Node *ary   = peek(1+vals);   // in case of exception
 303 
 304   // Null check the array base, with correct stack contents
 305   ary = null_check(ary, T_ARRAY);
 306   // Compile-time detect of null-exception?
 307   if (stopped())  return top();
 308 
 309   const TypeAryPtr* arytype  = _gvn.type(ary)->is_aryptr();
 310   const TypeInt*    sizetype = arytype->size();
 311   const Type*       elemtype = arytype->elem();
 312 
 313   if (UseUniqueSubclasses && result2 != NULL) {
 314     const Type* el = elemtype->make_ptr();
 315     if (el && el->isa_instptr()) {
 316       const TypeInstPtr* toop = el->is_instptr();
 317       if (toop->klass()->as_instance_klass()->unique_concrete_subklass()) {
 318         // If we load from "AbstractClass[]" we must see "ConcreteSubClass".
 319         const Type* subklass = Type::get_const_type(toop->klass());
 320         elemtype = subklass->join_speculative(el);
 321       }
 322     }
 323   }
 324 
 325   // Check for big class initializers with all constant offsets
 326   // feeding into a known-size array.
 327   const TypeInt* idxtype = _gvn.type(idx)->is_int();
 328   // See if the highest idx value is less than the lowest array bound,
 329   // and if the idx value cannot be negative:
 330   bool need_range_check = true;
 331   if (idxtype->_hi < sizetype->_lo && idxtype->_lo >= 0) {
 332     need_range_check = false;
 333     if (C->log() != NULL)   C->log()->elem("observe that='!need_range_check'");
 334   }
 335 
 336   ciKlass * arytype_klass = arytype->klass();
 337   if ((arytype_klass != NULL) && (!arytype_klass->is_loaded())) {
 338     // Only fails for some -Xcomp runs
 339     // The class is unloaded.  We have to run this bytecode in the interpreter.
 340     uncommon_trap(Deoptimization::Reason_unloaded,
 341                   Deoptimization::Action_reinterpret,
 342                   arytype->klass(), "!loaded array");
 343     return top();
 344   }
 345 
 346   // Do the range check
 347   if (GenerateRangeChecks && need_range_check) {
 348     Node* tst;
 349     if (sizetype->_hi <= 0) {
 350       // The greatest array bound is negative, so we can conclude that we're
 351       // compiling unreachable code, but the unsigned compare trick used below
 352       // only works with non-negative lengths.  Instead, hack "tst" to be zero so
 353       // the uncommon_trap path will always be taken.
 354       tst = _gvn.intcon(0);
 355     } else {
 356       // Range is constant in array-oop, so we can use the original state of mem
 357       Node* len = load_array_length(ary);
 358 
 359       // Test length vs index (standard trick using unsigned compare)
 360       Node* chk = _gvn.transform( new CmpUNode(idx, len) );
 361       BoolTest::mask btest = BoolTest::lt;
 362       tst = _gvn.transform( new BoolNode(chk, btest) );
 363     }
 364     RangeCheckNode* rc = new RangeCheckNode(control(), tst, PROB_MAX, COUNT_UNKNOWN);
 365     _gvn.set_type(rc, rc->Value(&_gvn));
 366     if (!tst->is_Con()) {
 367       record_for_igvn(rc);
 368     }
 369     set_control(_gvn.transform(new IfTrueNode(rc)));
 370     // Branch to failure if out of bounds
 371     {
 372       PreserveJVMState pjvms(this);
 373       set_control(_gvn.transform(new IfFalseNode(rc)));
 374       if (C->allow_range_check_smearing()) {
 375         // Do not use builtin_throw, since range checks are sometimes
 376         // made more stringent by an optimistic transformation.
 377         // This creates "tentative" range checks at this point,
 378         // which are not guaranteed to throw exceptions.
 379         // See IfNode::Ideal, is_range_check, adjust_check.
 380         uncommon_trap(Deoptimization::Reason_range_check,
 381                       Deoptimization::Action_make_not_entrant,
 382                       NULL, "range_check");
 383       } else {
 384         // If we have already recompiled with the range-check-widening
 385         // heroic optimization turned off, then we must really be throwing
 386         // range check exceptions.
 387         builtin_throw(Deoptimization::Reason_range_check, idx);
 388       }
 389     }
 390   }
 391   // Check for always knowing you are throwing a range-check exception
 392   if (stopped())  return top();
 393 
 394   // Make array address computation control dependent to prevent it
 395   // from floating above the range check during loop optimizations.
 396   Node* ptr = array_element_address(ary, idx, type, sizetype, control());
 397 
 398   if (result2 != NULL)  *result2 = elemtype;
 399 
 400   assert(ptr != top(), "top should go hand-in-hand with stopped");
 401 
 402   return ptr;
 403 }
 404 
 405 
 406 // returns IfNode
 407 IfNode* Parse::jump_if_fork_int(Node* a, Node* b, BoolTest::mask mask, float prob, float cnt) {
 408   Node   *cmp = _gvn.transform(new CmpINode(a, b)); // two cases: shiftcount > 32 and shiftcount <= 32
 409   Node   *tst = _gvn.transform(new BoolNode(cmp, mask));
 410   IfNode *iff = create_and_map_if(control(), tst, prob, cnt);
 411   return iff;
 412 }
 413 
 414 // return Region node
 415 Node* Parse::jump_if_join(Node* iffalse, Node* iftrue) {
 416   Node *region  = new RegionNode(3); // 2 results
 417   record_for_igvn(region);
 418   region->init_req(1, iffalse);
 419   region->init_req(2, iftrue );
 420   _gvn.set_type(region, Type::CONTROL);
 421   region = _gvn.transform(region);
 422   set_control (region);
 423   return region;
 424 }
 425 
 426 // sentinel value for the target bci to mark never taken branches
 427 // (according to profiling)
 428 static const int never_reached = INT_MAX;
 429 
 430 //------------------------------helper for tableswitch-------------------------
 431 void Parse::jump_if_true_fork(IfNode *iff, int dest_bci_if_true, int prof_table_index, bool unc) {
 432   // True branch, use existing map info
 433   { PreserveJVMState pjvms(this);
 434     Node *iftrue  = _gvn.transform( new IfTrueNode (iff) );
 435     set_control( iftrue );
 436     if (unc) {
 437       repush_if_args();
 438       uncommon_trap(Deoptimization::Reason_unstable_if,
 439                     Deoptimization::Action_reinterpret,
 440                     NULL,
 441                     "taken always");
 442     } else {
 443       assert(dest_bci_if_true != never_reached, "inconsistent dest");
 444       profile_switch_case(prof_table_index);
 445       merge_new_path(dest_bci_if_true);
 446     }
 447   }
 448 
 449   // False branch
 450   Node *iffalse = _gvn.transform( new IfFalseNode(iff) );
 451   set_control( iffalse );
 452 }
 453 
 454 void Parse::jump_if_false_fork(IfNode *iff, int dest_bci_if_true, int prof_table_index, bool unc) {
 455   // True branch, use existing map info
 456   { PreserveJVMState pjvms(this);
 457     Node *iffalse  = _gvn.transform( new IfFalseNode (iff) );
 458     set_control( iffalse );
 459     if (unc) {
 460       repush_if_args();
 461       uncommon_trap(Deoptimization::Reason_unstable_if,
 462                     Deoptimization::Action_reinterpret,
 463                     NULL,
 464                     "taken never");
 465     } else {
 466       assert(dest_bci_if_true != never_reached, "inconsistent dest");
 467       profile_switch_case(prof_table_index);
 468       merge_new_path(dest_bci_if_true);
 469     }
 470   }
 471 
 472   // False branch
 473   Node *iftrue = _gvn.transform( new IfTrueNode(iff) );
 474   set_control( iftrue );
 475 }
 476 
 477 void Parse::jump_if_always_fork(int dest_bci, int prof_table_index, bool unc) {
 478   // False branch, use existing map and control()
 479   if (unc) {
 480     repush_if_args();
 481     uncommon_trap(Deoptimization::Reason_unstable_if,
 482                   Deoptimization::Action_reinterpret,
 483                   NULL,
 484                   "taken never");
 485   } else {
 486     assert(dest_bci != never_reached, "inconsistent dest");
 487     profile_switch_case(prof_table_index);
 488     merge_new_path(dest_bci);
 489   }
 490 }
 491 
 492 
 493 extern "C" {
 494   static int jint_cmp(const void *i, const void *j) {
 495     int a = *(jint *)i;
 496     int b = *(jint *)j;
 497     return a > b ? 1 : a < b ? -1 : 0;
 498   }
 499 }
 500 
 501 
 502 // Default value for methodData switch indexing. Must be a negative value to avoid
 503 // conflict with any legal switch index.
 504 #define NullTableIndex -1
 505 
 506 class SwitchRange : public StackObj {
 507   // a range of integers coupled with a bci destination
 508   jint _lo;                     // inclusive lower limit
 509   jint _hi;                     // inclusive upper limit
 510   int _dest;
 511   int _table_index;             // index into method data table
 512   float _cnt;                   // how many times this range was hit according to profiling
 513 
 514 public:
 515   jint lo() const              { return _lo;   }
 516   jint hi() const              { return _hi;   }
 517   int  dest() const            { return _dest; }
 518   int  table_index() const     { return _table_index; }
 519   bool is_singleton() const    { return _lo == _hi; }
 520   float cnt() const            { return _cnt; }
 521 
 522   void setRange(jint lo, jint hi, int dest, int table_index, float cnt) {
 523     assert(lo <= hi, "must be a non-empty range");
 524     _lo = lo, _hi = hi; _dest = dest; _table_index = table_index; _cnt = cnt;
 525     assert(_cnt >= 0, "");
 526   }
 527   bool adjoinRange(jint lo, jint hi, int dest, int table_index, float cnt, bool trim_ranges) {
 528     assert(lo <= hi, "must be a non-empty range");
 529     if (lo == _hi+1 && table_index == _table_index) {
 530       // see merge_ranges() comment below
 531       if (trim_ranges) {
 532         if (cnt == 0) {
 533           if (_cnt != 0) {
 534             return false;
 535           }
 536           if (dest != _dest) {
 537             _dest = never_reached;
 538           }
 539         } else {
 540           if (_cnt == 0) {
 541             return false;
 542           }
 543           if (dest != _dest) {
 544             return false;
 545           }
 546         }
 547       } else {
 548         if (dest != _dest) {
 549           return false;
 550         }
 551       }
 552       _hi = hi;
 553       _cnt += cnt;
 554       return true;
 555     }
 556     return false;
 557   }
 558 
 559   void set (jint value, int dest, int table_index, float cnt) {
 560     setRange(value, value, dest, table_index, cnt);
 561   }
 562   bool adjoin(jint value, int dest, int table_index, float cnt, bool trim_ranges) {
 563     return adjoinRange(value, value, dest, table_index, cnt, trim_ranges);
 564   }
 565   bool adjoin(SwitchRange& other) {
 566     return adjoinRange(other._lo, other._hi, other._dest, other._table_index, other._cnt, false);
 567   }
 568 
 569   void print() {
 570     if (is_singleton())
 571       tty->print(" {%d}=>%d (cnt=%f)", lo(), dest(), cnt());
 572     else if (lo() == min_jint)
 573       tty->print(" {..%d}=>%d (cnt=%f)", hi(), dest(), cnt());
 574     else if (hi() == max_jint)
 575       tty->print(" {%d..}=>%d (cnt=%f)", lo(), dest(), cnt());
 576     else
 577       tty->print(" {%d..%d}=>%d (cnt=%f)", lo(), hi(), dest(), cnt());
 578   }
 579 };
 580 
 581 // We try to minimize the number of ranges and the size of the taken
 582 // ones using profiling data. When ranges are created,
 583 // SwitchRange::adjoinRange() only allows 2 adjoining ranges to merge
 584 // if both were never hit or both were hit to build longer unreached
 585 // ranges. Here, we now merge adjoining ranges with the same
 586 // destination and finally set destination of unreached ranges to the
 587 // special value never_reached because it can help minimize the number
 588 // of tests that are necessary.
 589 //
 590 // For instance:
 591 // [0, 1] to target1 sometimes taken
 592 // [1, 2] to target1 never taken
 593 // [2, 3] to target2 never taken
 594 // would lead to:
 595 // [0, 1] to target1 sometimes taken
 596 // [1, 3] never taken
 597 //
 598 // (first 2 ranges to target1 are not merged)
 599 static void merge_ranges(SwitchRange* ranges, int& rp) {
 600   if (rp == 0) {
 601     return;
 602   }
 603   int shift = 0;
 604   for (int j = 0; j < rp; j++) {
 605     SwitchRange& r1 = ranges[j-shift];
 606     SwitchRange& r2 = ranges[j+1];
 607     if (r1.adjoin(r2)) {
 608       shift++;
 609     } else if (shift > 0) {
 610       ranges[j+1-shift] = r2;
 611     }
 612   }
 613   rp -= shift;
 614   for (int j = 0; j <= rp; j++) {
 615     SwitchRange& r = ranges[j];
 616     if (r.cnt() == 0 && r.dest() != never_reached) {
 617       r.setRange(r.lo(), r.hi(), never_reached, r.table_index(), r.cnt());
 618     }
 619   }
 620 }
 621 
 622 //-------------------------------do_tableswitch--------------------------------
 623 void Parse::do_tableswitch() {
 624   Node* lookup = pop();
 625   // Get information about tableswitch
 626   int default_dest = iter().get_dest_table(0);
 627   int lo_index     = iter().get_int_table(1);
 628   int hi_index     = iter().get_int_table(2);
 629   int len          = hi_index - lo_index + 1;
 630 
 631   if (len < 1) {
 632     // If this is a backward branch, add safepoint
 633     maybe_add_safepoint(default_dest);
 634     merge(default_dest);
 635     return;
 636   }
 637 
 638   ciMethodData* methodData = method()->method_data();
 639   ciMultiBranchData* profile = NULL;
 640   if (methodData->is_mature() && UseSwitchProfiling) {
 641     ciProfileData* data = methodData->bci_to_data(bci());
 642     if (data != NULL && data->is_MultiBranchData()) {
 643       profile = (ciMultiBranchData*)data;
 644     }
 645   }
 646   bool trim_ranges = !method_data_update() && !C->too_many_traps(method(), bci(), Deoptimization::Reason_unstable_if);
 647 
 648   // generate decision tree, using trichotomy when possible
 649   int rnum = len+2;
 650   bool makes_backward_branch = false;
 651   SwitchRange* ranges = NEW_RESOURCE_ARRAY(SwitchRange, rnum);
 652   int rp = -1;
 653   if (lo_index != min_jint) {
 654     uint cnt = 1;
 655     if (profile != NULL) {
 656       cnt = profile->default_count() / (hi_index != max_jint ? 2 : 1);
 657     }
 658     ranges[++rp].setRange(min_jint, lo_index-1, default_dest, NullTableIndex, cnt);
 659   }
 660   for (int j = 0; j < len; j++) {
 661     jint match_int = lo_index+j;
 662     int  dest      = iter().get_dest_table(j+3);
 663     makes_backward_branch |= (dest <= bci());
 664     int  table_index = method_data_update() ? j : NullTableIndex;
 665     uint cnt = 1;
 666     if (profile != NULL) {
 667       cnt = profile->count_at(j);
 668     }
 669     if (rp < 0 || !ranges[rp].adjoin(match_int, dest, table_index, cnt, trim_ranges)) {
 670       ranges[++rp].set(match_int, dest, table_index, cnt);
 671     }
 672   }
 673   jint highest = lo_index+(len-1);
 674   assert(ranges[rp].hi() == highest, "");
 675   if (highest != max_jint) {
 676     uint cnt = 1;
 677     if (profile != NULL) {
 678       cnt = profile->default_count() / (lo_index != min_jint ? 2 : 1);
 679     }
 680     if (!ranges[rp].adjoinRange(highest+1, max_jint, default_dest, NullTableIndex, cnt, trim_ranges)) {
 681       ranges[++rp].setRange(highest+1, max_jint, default_dest, NullTableIndex, cnt);
 682     }
 683   }
 684   assert(rp < len+2, "not too many ranges");
 685 
 686   if (trim_ranges) {
 687     merge_ranges(ranges, rp);
 688   }
 689 
 690   // Safepoint in case if backward branch observed
 691   if( makes_backward_branch && UseLoopSafepoints )
 692     add_safepoint();
 693 
 694   jump_switch_ranges(lookup, &ranges[0], &ranges[rp]);
 695 }
 696 
 697 
 698 //------------------------------do_lookupswitch--------------------------------
 699 void Parse::do_lookupswitch() {
 700   Node *lookup = pop();         // lookup value
 701   // Get information about lookupswitch
 702   int default_dest = iter().get_dest_table(0);
 703   int len          = iter().get_int_table(1);
 704 
 705   if (len < 1) {    // If this is a backward branch, add safepoint
 706     maybe_add_safepoint(default_dest);
 707     merge(default_dest);
 708     return;
 709   }
 710 
 711   ciMethodData* methodData = method()->method_data();
 712   ciMultiBranchData* profile = NULL;
 713   if (methodData->is_mature() && UseSwitchProfiling) {
 714     ciProfileData* data = methodData->bci_to_data(bci());
 715     if (data != NULL && data->is_MultiBranchData()) {
 716       profile = (ciMultiBranchData*)data;
 717     }
 718   }
 719   bool trim_ranges = !method_data_update() && !C->too_many_traps(method(), bci(), Deoptimization::Reason_unstable_if);
 720 
 721   // generate decision tree, using trichotomy when possible
 722   jint* table = NEW_RESOURCE_ARRAY(jint, len*3);
 723   {
 724     for (int j = 0; j < len; j++) {
 725       table[3*j+0] = iter().get_int_table(2+2*j);
 726       table[3*j+1] = iter().get_dest_table(2+2*j+1);
 727       table[3*j+2] = profile == NULL ? 1 : profile->count_at(j);
 728     }
 729     qsort(table, len, 3*sizeof(table[0]), jint_cmp);
 730   }
 731 
 732   float defaults = 0;
 733   jint prev = min_jint;
 734   for (int j = 0; j < len; j++) {
 735     jint match_int = table[3*j+0];
 736     if (match_int != prev) {
 737       defaults += (float)match_int - prev;
 738     }
 739     prev = match_int+1;
 740   }
 741   if (prev-1 != max_jint) {
 742     defaults += (float)max_jint - prev + 1;
 743   }
 744   float default_cnt = 1;
 745   if (profile != NULL) {
 746     default_cnt = profile->default_count()/defaults;
 747   }
 748 
 749   int rnum = len*2+1;
 750   bool makes_backward_branch = false;
 751   SwitchRange* ranges = NEW_RESOURCE_ARRAY(SwitchRange, rnum);
 752   int rp = -1;
 753   for (int j = 0; j < len; j++) {
 754     jint match_int   = table[3*j+0];
 755     int  dest        = table[3*j+1];
 756     int  cnt         = table[3*j+2];
 757     int  next_lo     = rp < 0 ? min_jint : ranges[rp].hi()+1;
 758     int  table_index = method_data_update() ? j : NullTableIndex;
 759     makes_backward_branch |= (dest <= bci());
 760     float c = default_cnt * ((float)match_int - next_lo);
 761     if (match_int != next_lo && (rp < 0 || !ranges[rp].adjoinRange(next_lo, match_int-1, default_dest, NullTableIndex, c, trim_ranges))) {
 762       assert(default_dest != never_reached, "sentinel value for dead destinations");
 763       ranges[++rp].setRange(next_lo, match_int-1, default_dest, NullTableIndex, c);
 764     }
 765     if (rp < 0 || !ranges[rp].adjoin(match_int, dest, table_index, cnt, trim_ranges)) {
 766       assert(dest != never_reached, "sentinel value for dead destinations");
 767       ranges[++rp].set(match_int, dest, table_index, cnt);
 768     }
 769   }
 770   jint highest = table[3*(len-1)];
 771   assert(ranges[rp].hi() == highest, "");
 772   if (highest != max_jint &&
 773       !ranges[rp].adjoinRange(highest+1, max_jint, default_dest, NullTableIndex, default_cnt * ((float)max_jint - highest), trim_ranges)) {
 774     ranges[++rp].setRange(highest+1, max_jint, default_dest, NullTableIndex, default_cnt * ((float)max_jint - highest));
 775   }
 776   assert(rp < rnum, "not too many ranges");
 777 
 778   if (trim_ranges) {
 779     merge_ranges(ranges, rp);
 780   }
 781 
 782   // Safepoint in case backward branch observed
 783   if (makes_backward_branch && UseLoopSafepoints)
 784     add_safepoint();
 785 
 786   jump_switch_ranges(lookup, &ranges[0], &ranges[rp]);
 787 }
 788 
 789 static float if_prob(float taken_cnt, float total_cnt) {
 790   assert(taken_cnt <= total_cnt, "");
 791   if (total_cnt == 0) {
 792     return PROB_FAIR;
 793   }
 794   float p = taken_cnt / total_cnt;
 795   return MIN2(MAX2(p, PROB_MIN), PROB_MAX);
 796 }
 797 
 798 static float if_cnt(float cnt) {
 799   if (cnt == 0) {
 800     return COUNT_UNKNOWN;
 801   }
 802   return cnt;
 803 }
 804 
 805 static float sum_of_cnts(SwitchRange *lo, SwitchRange *hi) {
 806   float total_cnt = 0;
 807   for (SwitchRange* sr = lo; sr <= hi; sr++) {
 808     total_cnt += sr->cnt();
 809   }
 810   return total_cnt;
 811 }
 812 
 813 class SwitchRanges : public ResourceObj {
 814 public:
 815   SwitchRange* _lo;
 816   SwitchRange* _hi;
 817   SwitchRange* _mid;
 818   float _cost;
 819 
 820   enum {
 821     Start,
 822     LeftDone,
 823     RightDone,
 824     Done
 825   } _state;
 826 
 827   SwitchRanges(SwitchRange *lo, SwitchRange *hi)
 828     : _lo(lo), _hi(hi), _mid(NULL),
 829       _cost(0), _state(Start) {
 830   }
 831 
 832   SwitchRanges()
 833     : _lo(NULL), _hi(NULL), _mid(NULL),
 834       _cost(0), _state(Start) {}
 835 };
 836 
 837 // Estimate cost of performing a binary search on lo..hi
 838 static float compute_tree_cost(SwitchRange *lo, SwitchRange *hi, float total_cnt) {
 839   GrowableArray<SwitchRanges> tree;
 840   SwitchRanges root(lo, hi);
 841   tree.push(root);
 842 
 843   float cost = 0;
 844   do {
 845     SwitchRanges& r = *tree.adr_at(tree.length()-1);
 846     if (r._hi != r._lo) {
 847       if (r._mid == NULL) {
 848         float r_cnt = sum_of_cnts(r._lo, r._hi);
 849 
 850         if (r_cnt == 0) {
 851           tree.pop();
 852           cost = 0;
 853           continue;
 854         }
 855 
 856         SwitchRange* mid = NULL;
 857         mid = r._lo;
 858         for (float cnt = 0; ; ) {
 859           assert(mid <= r._hi, "out of bounds");
 860           cnt += mid->cnt();
 861           if (cnt > r_cnt / 2) {
 862             break;
 863           }
 864           mid++;
 865         }
 866         assert(mid <= r._hi, "out of bounds");
 867         r._mid = mid;
 868         r._cost = r_cnt / total_cnt;
 869       }
 870       r._cost += cost;
 871       if (r._state < SwitchRanges::LeftDone && r._mid > r._lo) {
 872         cost = 0;
 873         r._state = SwitchRanges::LeftDone;
 874         tree.push(SwitchRanges(r._lo, r._mid-1));
 875       } else if (r._state < SwitchRanges::RightDone) {
 876         cost = 0;
 877         r._state = SwitchRanges::RightDone;
 878         tree.push(SwitchRanges(r._mid == r._lo ? r._mid+1 : r._mid, r._hi));
 879       } else {
 880         tree.pop();
 881         cost = r._cost;
 882       }
 883     } else {
 884       tree.pop();
 885       cost = r._cost;
 886     }
 887   } while (tree.length() > 0);
 888 
 889 
 890   return cost;
 891 }
 892 
 893 // It sometimes pays off to test most common ranges before the binary search
 894 void Parse::linear_search_switch_ranges(Node* key_val, SwitchRange*& lo, SwitchRange*& hi) {
 895   uint nr = hi - lo + 1;
 896   float total_cnt = sum_of_cnts(lo, hi);
 897 
 898   float min = compute_tree_cost(lo, hi, total_cnt);
 899   float extra = 1;
 900   float sub = 0;
 901 
 902   SwitchRange* array1 = lo;
 903   SwitchRange* array2 = NEW_RESOURCE_ARRAY(SwitchRange, nr);
 904 
 905   SwitchRange* ranges = NULL;
 906 
 907   while (nr >= 2) {
 908     assert(lo == array1 || lo == array2, "one the 2 already allocated arrays");
 909     ranges = (lo == array1) ? array2 : array1;
 910 
 911     // Find highest frequency range
 912     SwitchRange* candidate = lo;
 913     for (SwitchRange* sr = lo+1; sr <= hi; sr++) {
 914       if (sr->cnt() > candidate->cnt()) {
 915         candidate = sr;
 916       }
 917     }
 918     SwitchRange most_freq = *candidate;
 919     if (most_freq.cnt() == 0) {
 920       break;
 921     }
 922 
 923     // Copy remaining ranges into another array
 924     int shift = 0;
 925     for (uint i = 0; i < nr; i++) {
 926       SwitchRange* sr = &lo[i];
 927       if (sr != candidate) {
 928         ranges[i-shift] = *sr;
 929       } else {
 930         shift++;
 931         if (i > 0 && i < nr-1) {
 932           SwitchRange prev = lo[i-1];
 933           prev.setRange(prev.lo(), sr->hi(), prev.dest(), prev.table_index(), prev.cnt());
 934           if (prev.adjoin(lo[i+1])) {
 935             shift++;
 936             i++;
 937           }
 938           ranges[i-shift] = prev;
 939         }
 940       }
 941     }
 942     nr -= shift;
 943 
 944     // Evaluate cost of testing the most common range and performing a
 945     // binary search on the other ranges
 946     float cost = extra + compute_tree_cost(&ranges[0], &ranges[nr-1], total_cnt);
 947     if (cost >= min) {
 948       break;
 949     }
 950     // swap arrays
 951     lo = &ranges[0];
 952     hi = &ranges[nr-1];
 953 
 954     // It pays off: emit the test for the most common range
 955     assert(most_freq.cnt() > 0, "must be taken");
 956     Node* val = _gvn.transform(new SubINode(key_val, _gvn.intcon(most_freq.lo())));
 957     Node* cmp = _gvn.transform(new CmpUNode(val, _gvn.intcon(most_freq.hi() - most_freq.lo())));
 958     Node* tst = _gvn.transform(new BoolNode(cmp, BoolTest::le));
 959     IfNode* iff = create_and_map_if(control(), tst, if_prob(most_freq.cnt(), total_cnt), if_cnt(most_freq.cnt()));
 960     jump_if_true_fork(iff, most_freq.dest(), most_freq.table_index(), false);
 961 
 962     sub += most_freq.cnt() / total_cnt;
 963     extra += 1 - sub;
 964     min = cost;
 965   }
 966 }
 967 
 968 //----------------------------create_jump_tables-------------------------------
 969 bool Parse::create_jump_tables(Node* key_val, SwitchRange* lo, SwitchRange* hi) {
 970   // Are jumptables enabled
 971   if (!UseJumpTables)  return false;
 972 
 973   // Are jumptables supported
 974   if (!Matcher::has_match_rule(Op_Jump))  return false;
 975 
 976   // Don't make jump table if profiling
 977   if (method_data_update())  return false;
 978 
 979   bool trim_ranges = !C->too_many_traps(method(), bci(), Deoptimization::Reason_unstable_if);
 980 
 981   // Decide if a guard is needed to lop off big ranges at either (or
 982   // both) end(s) of the input set. We'll call this the default target
 983   // even though we can't be sure that it is the true "default".
 984 
 985   bool needs_guard = false;
 986   int default_dest;
 987   int64_t total_outlier_size = 0;
 988   int64_t hi_size = ((int64_t)hi->hi()) - ((int64_t)hi->lo()) + 1;
 989   int64_t lo_size = ((int64_t)lo->hi()) - ((int64_t)lo->lo()) + 1;
 990 
 991   if (lo->dest() == hi->dest()) {
 992     total_outlier_size = hi_size + lo_size;
 993     default_dest = lo->dest();
 994   } else if (lo_size > hi_size) {
 995     total_outlier_size = lo_size;
 996     default_dest = lo->dest();
 997   } else {
 998     total_outlier_size = hi_size;
 999     default_dest = hi->dest();
1000   }
1001 
1002   float total = sum_of_cnts(lo, hi);
1003   float cost = compute_tree_cost(lo, hi, total);
1004 
1005   // If a guard test will eliminate very sparse end ranges, then
1006   // it is worth the cost of an extra jump.
1007   float trimmed_cnt = 0;
1008   if (total_outlier_size > (MaxJumpTableSparseness * 4)) {
1009     needs_guard = true;
1010     if (default_dest == lo->dest()) {
1011       trimmed_cnt += lo->cnt();
1012       lo++;
1013     }
1014     if (default_dest == hi->dest()) {
1015       trimmed_cnt += hi->cnt();
1016       hi--;
1017     }
1018   }
1019 
1020   // Find the total number of cases and ranges
1021   int64_t num_cases = ((int64_t)hi->hi()) - ((int64_t)lo->lo()) + 1;
1022   int num_range = hi - lo + 1;
1023 
1024   // Don't create table if: too large, too small, or too sparse.
1025   if (num_cases > MaxJumpTableSize)
1026     return false;
1027   if (UseSwitchProfiling) {
1028     // MinJumpTableSize is set so with a well balanced binary tree,
1029     // when the number of ranges is MinJumpTableSize, it's cheaper to
1030     // go through a JumpNode that a tree of IfNodes. Average cost of a
1031     // tree of IfNodes with MinJumpTableSize is
1032     // log2f(MinJumpTableSize) comparisons. So if the cost computed
1033     // from profile data is less than log2f(MinJumpTableSize) then
1034     // going with the binary search is cheaper.
1035     if (cost < log2f(MinJumpTableSize)) {
1036       return false;
1037     }
1038   } else {
1039     if (num_cases < MinJumpTableSize)
1040       return false;
1041   }
1042   if (num_cases > (MaxJumpTableSparseness * num_range))
1043     return false;
1044 
1045   // Normalize table lookups to zero
1046   int lowval = lo->lo();
1047   key_val = _gvn.transform( new SubINode(key_val, _gvn.intcon(lowval)) );
1048 
1049   // Generate a guard to protect against input keyvals that aren't
1050   // in the switch domain.
1051   if (needs_guard) {
1052     Node*   size = _gvn.intcon(num_cases);
1053     Node*   cmp = _gvn.transform(new CmpUNode(key_val, size));
1054     Node*   tst = _gvn.transform(new BoolNode(cmp, BoolTest::ge));
1055     IfNode* iff = create_and_map_if(control(), tst, if_prob(trimmed_cnt, total), if_cnt(trimmed_cnt));
1056     jump_if_true_fork(iff, default_dest, NullTableIndex, trim_ranges && trimmed_cnt == 0);
1057 
1058     total -= trimmed_cnt;
1059   }
1060 
1061   // Create an ideal node JumpTable that has projections
1062   // of all possible ranges for a switch statement
1063   // The key_val input must be converted to a pointer offset and scaled.
1064   // Compare Parse::array_addressing above.
1065 
1066   // Clean the 32-bit int into a real 64-bit offset.
1067   // Otherwise, the jint value 0 might turn into an offset of 0x0800000000.
1068   const TypeInt* ikeytype = TypeInt::make(0, num_cases, Type::WidenMin);
1069   // Make I2L conversion control dependent to prevent it from
1070   // floating above the range check during loop optimizations.
1071   key_val = C->conv_I2X_index(&_gvn, key_val, ikeytype, control());
1072 
1073   // Shift the value by wordsize so we have an index into the table, rather
1074   // than a switch value
1075   Node *shiftWord = _gvn.MakeConX(wordSize);
1076   key_val = _gvn.transform( new MulXNode( key_val, shiftWord));
1077 
1078   // Create the JumpNode
1079   Arena* arena = C->comp_arena();
1080   float* probs = (float*)arena->Amalloc(sizeof(float)*num_cases);
1081   int i = 0;
1082   if (total == 0) {
1083     for (SwitchRange* r = lo; r <= hi; r++) {
1084       for (int64_t j = r->lo(); j <= r->hi(); j++, i++) {
1085         probs[i] = 1.0F / num_cases;
1086       }
1087     }
1088   } else {
1089     for (SwitchRange* r = lo; r <= hi; r++) {
1090       float prob = r->cnt()/total;
1091       for (int64_t j = r->lo(); j <= r->hi(); j++, i++) {
1092         probs[i] = prob / (r->hi() - r->lo() + 1);
1093       }
1094     }
1095   }
1096 
1097   ciMethodData* methodData = method()->method_data();
1098   ciMultiBranchData* profile = NULL;
1099   if (methodData->is_mature()) {
1100     ciProfileData* data = methodData->bci_to_data(bci());
1101     if (data != NULL && data->is_MultiBranchData()) {
1102       profile = (ciMultiBranchData*)data;
1103     }
1104   }
1105 
1106   Node* jtn = _gvn.transform(new JumpNode(control(), key_val, num_cases, probs, profile == NULL ? COUNT_UNKNOWN : total));
1107 
1108   // These are the switch destinations hanging off the jumpnode
1109   i = 0;
1110   for (SwitchRange* r = lo; r <= hi; r++) {
1111     for (int64_t j = r->lo(); j <= r->hi(); j++, i++) {
1112       Node* input = _gvn.transform(new JumpProjNode(jtn, i, r->dest(), (int)(j - lowval)));
1113       {
1114         PreserveJVMState pjvms(this);
1115         set_control(input);
1116         jump_if_always_fork(r->dest(), r->table_index(), trim_ranges && r->cnt() == 0);
1117       }
1118     }
1119   }
1120   assert(i == num_cases, "miscount of cases");
1121   stop_and_kill_map();  // no more uses for this JVMS
1122   return true;
1123 }
1124 
1125 //----------------------------jump_switch_ranges-------------------------------
1126 void Parse::jump_switch_ranges(Node* key_val, SwitchRange *lo, SwitchRange *hi, int switch_depth) {
1127   Block* switch_block = block();
1128   bool trim_ranges = !method_data_update() && !C->too_many_traps(method(), bci(), Deoptimization::Reason_unstable_if);
1129 
1130   if (switch_depth == 0) {
1131     // Do special processing for the top-level call.
1132     assert(lo->lo() == min_jint, "initial range must exhaust Type::INT");
1133     assert(hi->hi() == max_jint, "initial range must exhaust Type::INT");
1134 
1135     // Decrement pred-numbers for the unique set of nodes.
1136 #ifdef ASSERT
1137     if (!trim_ranges) {
1138       // Ensure that the block's successors are a (duplicate-free) set.
1139       int successors_counted = 0;  // block occurrences in [hi..lo]
1140       int unique_successors = switch_block->num_successors();
1141       for (int i = 0; i < unique_successors; i++) {
1142         Block* target = switch_block->successor_at(i);
1143 
1144         // Check that the set of successors is the same in both places.
1145         int successors_found = 0;
1146         for (SwitchRange* p = lo; p <= hi; p++) {
1147           if (p->dest() == target->start())  successors_found++;
1148         }
1149         assert(successors_found > 0, "successor must be known");
1150         successors_counted += successors_found;
1151       }
1152       assert(successors_counted == (hi-lo)+1, "no unexpected successors");
1153     }
1154 #endif
1155 
1156     // Maybe prune the inputs, based on the type of key_val.
1157     jint min_val = min_jint;
1158     jint max_val = max_jint;
1159     const TypeInt* ti = key_val->bottom_type()->isa_int();
1160     if (ti != NULL) {
1161       min_val = ti->_lo;
1162       max_val = ti->_hi;
1163       assert(min_val <= max_val, "invalid int type");
1164     }
1165     while (lo->hi() < min_val) {
1166       lo++;
1167     }
1168     if (lo->lo() < min_val)  {
1169       lo->setRange(min_val, lo->hi(), lo->dest(), lo->table_index(), lo->cnt());
1170     }
1171     while (hi->lo() > max_val) {
1172       hi--;
1173     }
1174     if (hi->hi() > max_val) {
1175       hi->setRange(hi->lo(), max_val, hi->dest(), hi->table_index(), hi->cnt());
1176     }
1177 
1178     linear_search_switch_ranges(key_val, lo, hi);
1179   }
1180 
1181 #ifndef PRODUCT
1182   if (switch_depth == 0) {
1183     _max_switch_depth = 0;
1184     _est_switch_depth = log2_intptr((hi-lo+1)-1)+1;
1185   }
1186 #endif
1187 
1188   assert(lo <= hi, "must be a non-empty set of ranges");
1189   if (lo == hi) {
1190     jump_if_always_fork(lo->dest(), lo->table_index(), trim_ranges && lo->cnt() == 0);
1191   } else {
1192     assert(lo->hi() == (lo+1)->lo()-1, "contiguous ranges");
1193     assert(hi->lo() == (hi-1)->hi()+1, "contiguous ranges");
1194 
1195     if (create_jump_tables(key_val, lo, hi)) return;
1196 
1197     SwitchRange* mid = NULL;
1198     float total_cnt = sum_of_cnts(lo, hi);
1199 
1200     int nr = hi - lo + 1;
1201     if (UseSwitchProfiling) {
1202       // Don't keep the binary search tree balanced: pick up mid point
1203       // that split frequencies in half.
1204       float cnt = 0;
1205       for (SwitchRange* sr = lo; sr <= hi; sr++) {
1206         cnt += sr->cnt();
1207         if (cnt >= total_cnt / 2) {
1208           mid = sr;
1209           break;
1210         }
1211       }
1212     } else {
1213       mid = lo + nr/2;
1214 
1215       // if there is an easy choice, pivot at a singleton:
1216       if (nr > 3 && !mid->is_singleton() && (mid-1)->is_singleton())  mid--;
1217 
1218       assert(lo < mid && mid <= hi, "good pivot choice");
1219       assert(nr != 2 || mid == hi,   "should pick higher of 2");
1220       assert(nr != 3 || mid == hi-1, "should pick middle of 3");
1221     }
1222 
1223 
1224     Node *test_val = _gvn.intcon(mid == lo ? mid->hi() : mid->lo());
1225 
1226     if (mid->is_singleton()) {
1227       IfNode *iff_ne = jump_if_fork_int(key_val, test_val, BoolTest::ne, 1-if_prob(mid->cnt(), total_cnt), if_cnt(mid->cnt()));
1228       jump_if_false_fork(iff_ne, mid->dest(), mid->table_index(), trim_ranges && mid->cnt() == 0);
1229 
1230       // Special Case:  If there are exactly three ranges, and the high
1231       // and low range each go to the same place, omit the "gt" test,
1232       // since it will not discriminate anything.
1233       bool eq_test_only = (hi == lo+2 && hi->dest() == lo->dest() && mid == hi-1) || mid == lo;
1234 
1235       // if there is a higher range, test for it and process it:
1236       if (mid < hi && !eq_test_only) {
1237         // two comparisons of same values--should enable 1 test for 2 branches
1238         // Use BoolTest::le instead of BoolTest::gt
1239         float cnt = sum_of_cnts(lo, mid-1);
1240         IfNode *iff_le  = jump_if_fork_int(key_val, test_val, BoolTest::le, if_prob(cnt, total_cnt), if_cnt(cnt));
1241         Node   *iftrue  = _gvn.transform( new IfTrueNode(iff_le) );
1242         Node   *iffalse = _gvn.transform( new IfFalseNode(iff_le) );
1243         { PreserveJVMState pjvms(this);
1244           set_control(iffalse);
1245           jump_switch_ranges(key_val, mid+1, hi, switch_depth+1);
1246         }
1247         set_control(iftrue);
1248       }
1249 
1250     } else {
1251       // mid is a range, not a singleton, so treat mid..hi as a unit
1252       float cnt = sum_of_cnts(mid == lo ? mid+1 : mid, hi);
1253       IfNode *iff_ge = jump_if_fork_int(key_val, test_val, mid == lo ? BoolTest::gt : BoolTest::ge, if_prob(cnt, total_cnt), if_cnt(cnt));
1254 
1255       // if there is a higher range, test for it and process it:
1256       if (mid == hi) {
1257         jump_if_true_fork(iff_ge, mid->dest(), mid->table_index(), trim_ranges && cnt == 0);
1258       } else {
1259         Node *iftrue  = _gvn.transform( new IfTrueNode(iff_ge) );
1260         Node *iffalse = _gvn.transform( new IfFalseNode(iff_ge) );
1261         { PreserveJVMState pjvms(this);
1262           set_control(iftrue);
1263           jump_switch_ranges(key_val, mid == lo ? mid+1 : mid, hi, switch_depth+1);
1264         }
1265         set_control(iffalse);
1266       }
1267     }
1268 
1269     // in any case, process the lower range
1270     if (mid == lo) {
1271       if (mid->is_singleton()) {
1272         jump_switch_ranges(key_val, lo+1, hi, switch_depth+1);
1273       } else {
1274         jump_if_always_fork(lo->dest(), lo->table_index(), trim_ranges && lo->cnt() == 0);
1275       }
1276     } else {
1277       jump_switch_ranges(key_val, lo, mid-1, switch_depth+1);
1278     }
1279   }
1280 
1281   // Decrease pred_count for each successor after all is done.
1282   if (switch_depth == 0) {
1283     int unique_successors = switch_block->num_successors();
1284     for (int i = 0; i < unique_successors; i++) {
1285       Block* target = switch_block->successor_at(i);
1286       // Throw away the pre-allocated path for each unique successor.
1287       target->next_path_num();
1288     }
1289   }
1290 
1291 #ifndef PRODUCT
1292   _max_switch_depth = MAX2(switch_depth, _max_switch_depth);
1293   if (TraceOptoParse && Verbose && WizardMode && switch_depth == 0) {
1294     SwitchRange* r;
1295     int nsing = 0;
1296     for( r = lo; r <= hi; r++ ) {
1297       if( r->is_singleton() )  nsing++;
1298     }
1299     tty->print(">>> ");
1300     _method->print_short_name();
1301     tty->print_cr(" switch decision tree");
1302     tty->print_cr("    %d ranges (%d singletons), max_depth=%d, est_depth=%d",
1303                   (int) (hi-lo+1), nsing, _max_switch_depth, _est_switch_depth);
1304     if (_max_switch_depth > _est_switch_depth) {
1305       tty->print_cr("******** BAD SWITCH DEPTH ********");
1306     }
1307     tty->print("   ");
1308     for( r = lo; r <= hi; r++ ) {
1309       r->print();
1310     }
1311     tty->cr();
1312   }
1313 #endif
1314 }
1315 
1316 void Parse::modf() {
1317   Node *f2 = pop();
1318   Node *f1 = pop();
1319   Node* c = make_runtime_call(RC_LEAF, OptoRuntime::modf_Type(),
1320                               CAST_FROM_FN_PTR(address, SharedRuntime::frem),
1321                               "frem", NULL, //no memory effects
1322                               f1, f2);
1323   Node* res = _gvn.transform(new ProjNode(c, TypeFunc::Parms + 0));
1324 
1325   push(res);
1326 }
1327 
1328 void Parse::modd() {
1329   Node *d2 = pop_pair();
1330   Node *d1 = pop_pair();
1331   Node* c = make_runtime_call(RC_LEAF, OptoRuntime::Math_DD_D_Type(),
1332                               CAST_FROM_FN_PTR(address, SharedRuntime::drem),
1333                               "drem", NULL, //no memory effects
1334                               d1, top(), d2, top());
1335   Node* res_d   = _gvn.transform(new ProjNode(c, TypeFunc::Parms + 0));
1336 
1337 #ifdef ASSERT
1338   Node* res_top = _gvn.transform(new ProjNode(c, TypeFunc::Parms + 1));
1339   assert(res_top == top(), "second value must be top");
1340 #endif
1341 
1342   push_pair(res_d);
1343 }
1344 
1345 void Parse::l2f() {
1346   Node* f2 = pop();
1347   Node* f1 = pop();
1348   Node* c = make_runtime_call(RC_LEAF, OptoRuntime::l2f_Type(),
1349                               CAST_FROM_FN_PTR(address, SharedRuntime::l2f),
1350                               "l2f", NULL, //no memory effects
1351                               f1, f2);
1352   Node* res = _gvn.transform(new ProjNode(c, TypeFunc::Parms + 0));
1353 
1354   push(res);
1355 }
1356 
1357 void Parse::do_irem() {
1358   // Must keep both values on the expression-stack during null-check
1359   zero_check_int(peek());
1360   // Compile-time detect of null-exception?
1361   if (stopped())  return;
1362 
1363   Node* b = pop();
1364   Node* a = pop();
1365 
1366   const Type *t = _gvn.type(b);
1367   if (t != Type::TOP) {
1368     const TypeInt *ti = t->is_int();
1369     if (ti->is_con()) {
1370       int divisor = ti->get_con();
1371       // check for positive power of 2
1372       if (divisor > 0 &&
1373           (divisor & ~(divisor-1)) == divisor) {
1374         // yes !
1375         Node *mask = _gvn.intcon((divisor - 1));
1376         // Sigh, must handle negative dividends
1377         Node *zero = _gvn.intcon(0);
1378         IfNode *ifff = jump_if_fork_int(a, zero, BoolTest::lt, PROB_FAIR, COUNT_UNKNOWN);
1379         Node *iff = _gvn.transform( new IfFalseNode(ifff) );
1380         Node *ift = _gvn.transform( new IfTrueNode (ifff) );
1381         Node *reg = jump_if_join(ift, iff);
1382         Node *phi = PhiNode::make(reg, NULL, TypeInt::INT);
1383         // Negative path; negate/and/negate
1384         Node *neg = _gvn.transform( new SubINode(zero, a) );
1385         Node *andn= _gvn.transform( new AndINode(neg, mask) );
1386         Node *negn= _gvn.transform( new SubINode(zero, andn) );
1387         phi->init_req(1, negn);
1388         // Fast positive case
1389         Node *andx = _gvn.transform( new AndINode(a, mask) );
1390         phi->init_req(2, andx);
1391         // Push the merge
1392         push( _gvn.transform(phi) );
1393         return;
1394       }
1395     }
1396   }
1397   // Default case
1398   push( _gvn.transform( new ModINode(control(),a,b) ) );
1399 }
1400 
1401 // Handle jsr and jsr_w bytecode
1402 void Parse::do_jsr() {
1403   assert(bc() == Bytecodes::_jsr || bc() == Bytecodes::_jsr_w, "wrong bytecode");
1404 
1405   // Store information about current state, tagged with new _jsr_bci
1406   int return_bci = iter().next_bci();
1407   int jsr_bci    = (bc() == Bytecodes::_jsr) ? iter().get_dest() : iter().get_far_dest();
1408 
1409   // Update method data
1410   profile_taken_branch(jsr_bci);
1411 
1412   // The way we do things now, there is only one successor block
1413   // for the jsr, because the target code is cloned by ciTypeFlow.
1414   Block* target = successor_for_bci(jsr_bci);
1415 
1416   // What got pushed?
1417   const Type* ret_addr = target->peek();
1418   assert(ret_addr->singleton(), "must be a constant (cloned jsr body)");
1419 
1420   // Effect on jsr on stack
1421   push(_gvn.makecon(ret_addr));
1422 
1423   // Flow to the jsr.
1424   merge(jsr_bci);
1425 }
1426 
1427 // Handle ret bytecode
1428 void Parse::do_ret() {
1429   // Find to whom we return.
1430   assert(block()->num_successors() == 1, "a ret can only go one place now");
1431   Block* target = block()->successor_at(0);
1432   assert(!target->is_ready(), "our arrival must be expected");
1433   profile_ret(target->flow()->start());
1434   int pnum = target->next_path_num();
1435   merge_common(target, pnum);
1436 }
1437 
1438 static bool has_injected_profile(BoolTest::mask btest, Node* test, int& taken, int& not_taken) {
1439   if (btest != BoolTest::eq && btest != BoolTest::ne) {
1440     // Only ::eq and ::ne are supported for profile injection.
1441     return false;
1442   }
1443   if (test->is_Cmp() &&
1444       test->in(1)->Opcode() == Op_ProfileBoolean) {
1445     ProfileBooleanNode* profile = (ProfileBooleanNode*)test->in(1);
1446     int false_cnt = profile->false_count();
1447     int  true_cnt = profile->true_count();
1448 
1449     // Counts matching depends on the actual test operation (::eq or ::ne).
1450     // No need to scale the counts because profile injection was designed
1451     // to feed exact counts into VM.
1452     taken     = (btest == BoolTest::eq) ? false_cnt :  true_cnt;
1453     not_taken = (btest == BoolTest::eq) ?  true_cnt : false_cnt;
1454 
1455     profile->consume();
1456     return true;
1457   }
1458   return false;
1459 }
1460 //--------------------------dynamic_branch_prediction--------------------------
1461 // Try to gather dynamic branch prediction behavior.  Return a probability
1462 // of the branch being taken and set the "cnt" field.  Returns a -1.0
1463 // if we need to use static prediction for some reason.
1464 float Parse::dynamic_branch_prediction(float &cnt, BoolTest::mask btest, Node* test) {
1465   ResourceMark rm;
1466 
1467   cnt  = COUNT_UNKNOWN;
1468 
1469   int     taken = 0;
1470   int not_taken = 0;
1471 
1472   bool use_mdo = !has_injected_profile(btest, test, taken, not_taken);
1473 
1474   if (use_mdo) {
1475     // Use MethodData information if it is available
1476     // FIXME: free the ProfileData structure
1477     ciMethodData* methodData = method()->method_data();
1478     if (!methodData->is_mature())  return PROB_UNKNOWN;
1479     ciProfileData* data = methodData->bci_to_data(bci());
1480     if (data == NULL) {
1481       return PROB_UNKNOWN;
1482     }
1483     if (!data->is_JumpData())  return PROB_UNKNOWN;
1484 
1485     // get taken and not taken values
1486     taken = data->as_JumpData()->taken();
1487     not_taken = 0;
1488     if (data->is_BranchData()) {
1489       not_taken = data->as_BranchData()->not_taken();
1490     }
1491 
1492     // scale the counts to be commensurate with invocation counts:
1493     taken = method()->scale_count(taken);
1494     not_taken = method()->scale_count(not_taken);
1495   }
1496 
1497   // Give up if too few (or too many, in which case the sum will overflow) counts to be meaningful.
1498   // We also check that individual counters are positive first, otherwise the sum can become positive.
1499   if (taken < 0 || not_taken < 0 || taken + not_taken < 40) {
1500     if (C->log() != NULL) {
1501       C->log()->elem("branch target_bci='%d' taken='%d' not_taken='%d'", iter().get_dest(), taken, not_taken);
1502     }
1503     return PROB_UNKNOWN;
1504   }
1505 
1506   // Compute frequency that we arrive here
1507   float sum = taken + not_taken;
1508   // Adjust, if this block is a cloned private block but the
1509   // Jump counts are shared.  Taken the private counts for
1510   // just this path instead of the shared counts.
1511   if( block()->count() > 0 )
1512     sum = block()->count();
1513   cnt = sum / FreqCountInvocations;
1514 
1515   // Pin probability to sane limits
1516   float prob;
1517   if( !taken )
1518     prob = (0+PROB_MIN) / 2;
1519   else if( !not_taken )
1520     prob = (1+PROB_MAX) / 2;
1521   else {                         // Compute probability of true path
1522     prob = (float)taken / (float)(taken + not_taken);
1523     if (prob > PROB_MAX)  prob = PROB_MAX;
1524     if (prob < PROB_MIN)   prob = PROB_MIN;
1525   }
1526 
1527   assert((cnt > 0.0f) && (prob > 0.0f),
1528          "Bad frequency assignment in if");
1529 
1530   if (C->log() != NULL) {
1531     const char* prob_str = NULL;
1532     if (prob >= PROB_MAX)  prob_str = (prob == PROB_MAX) ? "max" : "always";
1533     if (prob <= PROB_MIN)  prob_str = (prob == PROB_MIN) ? "min" : "never";
1534     char prob_str_buf[30];
1535     if (prob_str == NULL) {
1536       jio_snprintf(prob_str_buf, sizeof(prob_str_buf), "%20.2f", prob);
1537       prob_str = prob_str_buf;
1538     }
1539     C->log()->elem("branch target_bci='%d' taken='%d' not_taken='%d' cnt='%f' prob='%s'",
1540                    iter().get_dest(), taken, not_taken, cnt, prob_str);
1541   }
1542   return prob;
1543 }
1544 
1545 //-----------------------------branch_prediction-------------------------------
1546 float Parse::branch_prediction(float& cnt,
1547                                BoolTest::mask btest,
1548                                int target_bci,
1549                                Node* test) {
1550   float prob = dynamic_branch_prediction(cnt, btest, test);
1551   // If prob is unknown, switch to static prediction
1552   if (prob != PROB_UNKNOWN)  return prob;
1553 
1554   prob = PROB_FAIR;                   // Set default value
1555   if (btest == BoolTest::eq)          // Exactly equal test?
1556     prob = PROB_STATIC_INFREQUENT;    // Assume its relatively infrequent
1557   else if (btest == BoolTest::ne)
1558     prob = PROB_STATIC_FREQUENT;      // Assume its relatively frequent
1559 
1560   // If this is a conditional test guarding a backwards branch,
1561   // assume its a loop-back edge.  Make it a likely taken branch.
1562   if (target_bci < bci()) {
1563     if (is_osr_parse()) {    // Could be a hot OSR'd loop; force deopt
1564       // Since it's an OSR, we probably have profile data, but since
1565       // branch_prediction returned PROB_UNKNOWN, the counts are too small.
1566       // Let's make a special check here for completely zero counts.
1567       ciMethodData* methodData = method()->method_data();
1568       if (!methodData->is_empty()) {
1569         ciProfileData* data = methodData->bci_to_data(bci());
1570         // Only stop for truly zero counts, which mean an unknown part
1571         // of the OSR-ed method, and we want to deopt to gather more stats.
1572         // If you have ANY counts, then this loop is simply 'cold' relative
1573         // to the OSR loop.
1574         if (data == NULL ||
1575             (data->as_BranchData()->taken() +  data->as_BranchData()->not_taken() == 0)) {
1576           // This is the only way to return PROB_UNKNOWN:
1577           return PROB_UNKNOWN;
1578         }
1579       }
1580     }
1581     prob = PROB_STATIC_FREQUENT;     // Likely to take backwards branch
1582   }
1583 
1584   assert(prob != PROB_UNKNOWN, "must have some guess at this point");
1585   return prob;
1586 }
1587 
1588 // The magic constants are chosen so as to match the output of
1589 // branch_prediction() when the profile reports a zero taken count.
1590 // It is important to distinguish zero counts unambiguously, because
1591 // some branches (e.g., _213_javac.Assembler.eliminate) validly produce
1592 // very small but nonzero probabilities, which if confused with zero
1593 // counts would keep the program recompiling indefinitely.
1594 bool Parse::seems_never_taken(float prob) const {
1595   return prob < PROB_MIN;
1596 }
1597 
1598 // True if the comparison seems to be the kind that will not change its
1599 // statistics from true to false.  See comments in adjust_map_after_if.
1600 // This question is only asked along paths which are already
1601 // classifed as untaken (by seems_never_taken), so really,
1602 // if a path is never taken, its controlling comparison is
1603 // already acting in a stable fashion.  If the comparison
1604 // seems stable, we will put an expensive uncommon trap
1605 // on the untaken path.
1606 bool Parse::seems_stable_comparison() const {
1607   if (C->too_many_traps(method(), bci(), Deoptimization::Reason_unstable_if)) {
1608     return false;
1609   }
1610   return true;
1611 }
1612 
1613 //-------------------------------repush_if_args--------------------------------
1614 // Push arguments of an "if" bytecode back onto the stack by adjusting _sp.
1615 inline int Parse::repush_if_args() {
1616   if (PrintOpto && WizardMode) {
1617     tty->print("defending against excessive implicit null exceptions on %s @%d in ",
1618                Bytecodes::name(iter().cur_bc()), iter().cur_bci());
1619     method()->print_name(); tty->cr();
1620   }
1621   int bc_depth = - Bytecodes::depth(iter().cur_bc());
1622   assert(bc_depth == 1 || bc_depth == 2, "only two kinds of branches");
1623   DEBUG_ONLY(sync_jvms());   // argument(n) requires a synced jvms
1624   assert(argument(0) != NULL, "must exist");
1625   assert(bc_depth == 1 || argument(1) != NULL, "two must exist");
1626   inc_sp(bc_depth);
1627   return bc_depth;
1628 }
1629 
1630 //----------------------------------do_ifnull----------------------------------
1631 void Parse::do_ifnull(BoolTest::mask btest, Node *c) {
1632   int target_bci = iter().get_dest();
1633 
1634   Block* branch_block = successor_for_bci(target_bci);
1635   Block* next_block   = successor_for_bci(iter().next_bci());
1636 
1637   float cnt;
1638   float prob = branch_prediction(cnt, btest, target_bci, c);
1639   if (prob == PROB_UNKNOWN) {
1640     // (An earlier version of do_ifnull omitted this trap for OSR methods.)
1641     if (PrintOpto && Verbose) {
1642       tty->print_cr("Never-taken edge stops compilation at bci %d", bci());
1643     }
1644     repush_if_args(); // to gather stats on loop
1645     // We need to mark this branch as taken so that if we recompile we will
1646     // see that it is possible. In the tiered system the interpreter doesn't
1647     // do profiling and by the time we get to the lower tier from the interpreter
1648     // the path may be cold again. Make sure it doesn't look untaken
1649     profile_taken_branch(target_bci, !ProfileInterpreter);
1650     uncommon_trap(Deoptimization::Reason_unreached,
1651                   Deoptimization::Action_reinterpret,
1652                   NULL, "cold");
1653     if (C->eliminate_boxing()) {
1654       // Mark the successor blocks as parsed
1655       branch_block->next_path_num();
1656       next_block->next_path_num();
1657     }
1658     return;
1659   }
1660 
1661   NOT_PRODUCT(explicit_null_checks_inserted++);
1662 
1663   // Generate real control flow
1664   Node   *tst = _gvn.transform( new BoolNode( c, btest ) );
1665 
1666   // Sanity check the probability value
1667   assert(prob > 0.0f,"Bad probability in Parser");
1668  // Need xform to put node in hash table
1669   IfNode *iff = create_and_xform_if( control(), tst, prob, cnt );
1670   assert(iff->_prob > 0.0f,"Optimizer made bad probability in parser");
1671   // True branch
1672   { PreserveJVMState pjvms(this);
1673     Node* iftrue  = _gvn.transform( new IfTrueNode (iff) );
1674     set_control(iftrue);
1675 
1676     if (stopped()) {            // Path is dead?
1677       NOT_PRODUCT(explicit_null_checks_elided++);
1678       if (C->eliminate_boxing()) {
1679         // Mark the successor block as parsed
1680         branch_block->next_path_num();
1681       }
1682     } else {                    // Path is live.
1683       // Update method data
1684       profile_taken_branch(target_bci);
1685       adjust_map_after_if(btest, c, prob, branch_block);
1686       if (!stopped()) {
1687         merge(target_bci);
1688       }
1689     }
1690   }
1691 
1692   // False branch
1693   Node* iffalse = _gvn.transform( new IfFalseNode(iff) );
1694   set_control(iffalse);
1695 
1696   if (stopped()) {              // Path is dead?
1697     NOT_PRODUCT(explicit_null_checks_elided++);
1698     if (C->eliminate_boxing()) {
1699       // Mark the successor block as parsed
1700       next_block->next_path_num();
1701     }
1702   } else  {                     // Path is live.
1703     // Update method data
1704     profile_not_taken_branch();
1705     adjust_map_after_if(BoolTest(btest).negate(), c, 1.0-prob, next_block);
1706   }
1707 }
1708 
1709 //------------------------------------do_if------------------------------------
1710 void Parse::do_if(BoolTest::mask btest, Node* c, bool new_path, Node** ctrl_taken) {
1711   int target_bci = iter().get_dest();
1712 
1713   Block* branch_block = successor_for_bci(target_bci);
1714   Block* next_block   = successor_for_bci(iter().next_bci());
1715 
1716   float cnt;
1717   float prob = branch_prediction(cnt, btest, target_bci, c);
1718   float untaken_prob = 1.0 - prob;
1719 
1720   if (prob == PROB_UNKNOWN) {
1721     if (PrintOpto && Verbose) {
1722       tty->print_cr("Never-taken edge stops compilation at bci %d", bci());
1723     }
1724     repush_if_args(); // to gather stats on loop
1725     // We need to mark this branch as taken so that if we recompile we will
1726     // see that it is possible. In the tiered system the interpreter doesn't
1727     // do profiling and by the time we get to the lower tier from the interpreter
1728     // the path may be cold again. Make sure it doesn't look untaken
1729     profile_taken_branch(target_bci, !ProfileInterpreter);
1730     uncommon_trap(Deoptimization::Reason_unreached,
1731                   Deoptimization::Action_reinterpret,
1732                   NULL, "cold");
1733     if (C->eliminate_boxing()) {
1734       // Mark the successor blocks as parsed
1735       branch_block->next_path_num();
1736       next_block->next_path_num();
1737     }
1738     return;
1739   }
1740 
1741   // Sanity check the probability value
1742   assert(0.0f < prob && prob < 1.0f,"Bad probability in Parser");
1743 
1744   bool taken_if_true = true;
1745   // Convert BoolTest to canonical form:
1746   if (!BoolTest(btest).is_canonical()) {
1747     btest         = BoolTest(btest).negate();
1748     taken_if_true = false;
1749     // prob is NOT updated here; it remains the probability of the taken
1750     // path (as opposed to the prob of the path guarded by an 'IfTrueNode').
1751   }
1752   assert(btest != BoolTest::eq, "!= is the only canonical exact test");
1753 
1754   Node* tst0 = new BoolNode(c, btest);
1755   Node* tst = _gvn.transform(tst0);
1756   BoolTest::mask taken_btest   = BoolTest::illegal;
1757   BoolTest::mask untaken_btest = BoolTest::illegal;
1758 
1759   if (tst->is_Bool()) {
1760     // Refresh c from the transformed bool node, since it may be
1761     // simpler than the original c.  Also re-canonicalize btest.
1762     // This wins when (Bool ne (Conv2B p) 0) => (Bool ne (CmpP p NULL)).
1763     // That can arise from statements like: if (x instanceof C) ...
1764     if (tst != tst0) {
1765       // Canonicalize one more time since transform can change it.
1766       btest = tst->as_Bool()->_test._test;
1767       if (!BoolTest(btest).is_canonical()) {
1768         // Reverse edges one more time...
1769         tst   = _gvn.transform( tst->as_Bool()->negate(&_gvn) );
1770         btest = tst->as_Bool()->_test._test;
1771         assert(BoolTest(btest).is_canonical(), "sanity");
1772         taken_if_true = !taken_if_true;
1773       }
1774       c = tst->in(1);
1775     }
1776     BoolTest::mask neg_btest = BoolTest(btest).negate();
1777     taken_btest   = taken_if_true ?     btest : neg_btest;
1778     untaken_btest = taken_if_true ? neg_btest :     btest;
1779   }
1780 
1781   // Generate real control flow
1782   float true_prob = (taken_if_true ? prob : untaken_prob);
1783   IfNode* iff = create_and_map_if(control(), tst, true_prob, cnt);
1784   assert(iff->_prob > 0.0f,"Optimizer made bad probability in parser");
1785   Node* taken_branch   = new IfTrueNode(iff);
1786   Node* untaken_branch = new IfFalseNode(iff);
1787   if (!taken_if_true) {  // Finish conversion to canonical form
1788     Node* tmp      = taken_branch;
1789     taken_branch   = untaken_branch;
1790     untaken_branch = tmp;
1791   }
1792 
1793   // Branch is taken:
1794   { PreserveJVMState pjvms(this);
1795     taken_branch = _gvn.transform(taken_branch);
1796     set_control(taken_branch);
1797 
1798     if (stopped()) {
1799       if (C->eliminate_boxing() && !new_path) {
1800         // Mark the successor block as parsed (if we haven't created a new path)
1801         branch_block->next_path_num();
1802       }
1803     } else {
1804       // Update method data
1805       profile_taken_branch(target_bci);
1806       adjust_map_after_if(taken_btest, c, prob, branch_block);
1807       if (!stopped()) {
1808         if (new_path) {
1809           // Merge by using a new path
1810           merge_new_path(target_bci);
1811         } else if (ctrl_taken != NULL) {
1812           // Don't merge but save taken branch to be wired by caller
1813           *ctrl_taken = control();
1814         } else {
1815           merge(target_bci);
1816         }
1817       }
1818     }
1819   }
1820 
1821   untaken_branch = _gvn.transform(untaken_branch);
1822   set_control(untaken_branch);
1823 
1824   // Branch not taken.
1825   if (stopped() && ctrl_taken == NULL) {
1826     if (C->eliminate_boxing()) {
1827       // Mark the successor block as parsed (if caller does not re-wire control flow)
1828       next_block->next_path_num();
1829     }
1830   } else {
1831     // Update method data
1832     profile_not_taken_branch();
1833     adjust_map_after_if(untaken_btest, c, untaken_prob, next_block);
1834   }
1835 }
1836 
1837 void Parse::do_acmp(BoolTest::mask btest, Node* a, Node* b) {
1838   ciMethod* subst_method = ciEnv::current()->ValueBootstrapMethods_klass()->find_method(ciSymbol::isSubstitutable_name(), ciSymbol::object_object_boolean_signature());
1839   // If current method is ValueBootstrapMethods::isSubstitutable(),
1840   // compile the acmp as a regular pointer comparison otherwise we
1841   // could call ValueBootstrapMethods::isSubstitutable() back
1842   if (ACmpOnValues == 0 || method() == subst_method) {
1843     Node* cmp = CmpP(a, b);
1844     cmp = optimize_cmp_with_klass(cmp);
1845     do_if(btest, cmp);
1846     return;
1847   }
1848 
1849   if (ACmpOnValues == 3) {
1850     // Substitutability test
1851     if (a->is_ValueType()) {
1852       inc_sp(2);
1853       a = a->as_ValueType()->allocate(this, true)->get_oop();
1854       dec_sp(2);
1855     }
1856     if (b->is_ValueType()) {
1857       inc_sp(2);
1858       b = b->as_ValueType()->allocate(this, true)->get_oop();
1859       dec_sp(2);
1860     }
1861 
1862     const TypeOopPtr* ta = _gvn.type(a)->isa_oopptr();
1863     const TypeOopPtr* tb = _gvn.type(b)->isa_oopptr();
1864 
1865     if (ta == NULL || !ta->can_be_value_type_raw() ||
1866         tb == NULL || !tb->can_be_value_type_raw()) {
1867       Node* cmp = CmpP(a, b);
1868       cmp = optimize_cmp_with_klass(cmp);
1869       do_if(btest, cmp);
1870       return;
1871     }
1872 
1873     Node* cmp = CmpP(a, b);
1874     cmp = optimize_cmp_with_klass(cmp);
1875     Node* eq_region = NULL;
1876     if (btest == BoolTest::eq) {
1877       do_if(btest, cmp, true);
1878       if (stopped()) {
1879         return;
1880       }
1881     } else {
1882       assert(btest == BoolTest::ne, "only eq or ne");
1883       Node* is_not_equal = NULL;
1884       eq_region = new RegionNode(3);
1885       {
1886         PreserveJVMState pjvms(this);
1887         do_if(btest, cmp, false, &is_not_equal);
1888         if (!stopped()) {
1889           eq_region->init_req(1, control());
1890         }
1891       }
1892       if (is_not_equal == NULL || is_not_equal->is_top()) {
1893         record_for_igvn(eq_region);
1894         set_control(_gvn.transform(eq_region));
1895         return;
1896       }
1897       set_control(is_not_equal);
1898     }
1899     // Pointers not equal, check for values
1900     Node* ne_region = new RegionNode(6);
1901     inc_sp(2);
1902     Node* null_ctl = top();
1903     Node* not_null_a = null_check_oop(a, &null_ctl, !too_many_traps(Deoptimization::Reason_null_check), false, false);
1904     dec_sp(2);
1905     ne_region->init_req(1, null_ctl);
1906     if (stopped()) {
1907       record_for_igvn(ne_region);
1908       set_control(_gvn.transform(ne_region));
1909       if (btest == BoolTest::ne) {
1910         {
1911           PreserveJVMState pjvms(this);
1912           int target_bci = iter().get_dest();
1913           merge(target_bci);
1914         }
1915         record_for_igvn(eq_region);
1916         set_control(_gvn.transform(eq_region));
1917       }
1918       return;
1919     }
1920 
1921     Node* is_value = is_always_locked(not_null_a);
1922     Node* value_mask = _gvn.MakeConX(markOopDesc::always_locked_pattern);
1923     Node* is_value_cmp = _gvn.transform(new CmpXNode(is_value, value_mask));
1924     Node* is_value_bol = _gvn.transform(new BoolNode(is_value_cmp, BoolTest::ne));
1925     IfNode* is_value_iff = create_and_map_if(control(), is_value_bol, PROB_FAIR, COUNT_UNKNOWN);
1926     Node* not_value = _gvn.transform(new IfTrueNode(is_value_iff));
1927     set_control(_gvn.transform(new IfFalseNode(is_value_iff)));
1928     ne_region->init_req(2, not_value);
1929 
1930     // One of the 2 pointers refers to a value, check if both are of
1931     // the same class
1932     inc_sp(2);
1933     null_ctl = top();
1934     Node* not_null_b = null_check_oop(b, &null_ctl, !too_many_traps(Deoptimization::Reason_null_check), false, false);
1935     dec_sp(2);
1936     ne_region->init_req(3, null_ctl);
1937     if (stopped()) {
1938       record_for_igvn(ne_region);
1939       set_control(_gvn.transform(ne_region));
1940       if (btest == BoolTest::ne) {
1941         {
1942           PreserveJVMState pjvms(this);
1943           int target_bci = iter().get_dest();
1944           merge(target_bci);
1945         }
1946         record_for_igvn(eq_region);
1947         set_control(_gvn.transform(eq_region));
1948       }
1949       return;
1950     }
1951     Node* kls_a = load_object_klass(not_null_a);
1952     Node* kls_b = load_object_klass(not_null_b);
1953     Node* kls_cmp = CmpP(kls_a, kls_b);
1954     Node* kls_bol = _gvn.transform(new BoolNode(kls_cmp, BoolTest::ne));
1955     IfNode* kls_iff = create_and_map_if(control(), kls_bol, PROB_FAIR, COUNT_UNKNOWN);
1956     Node* kls_ne = _gvn.transform(new IfTrueNode(kls_iff));
1957     set_control(_gvn.transform(new IfFalseNode(kls_iff)));
1958     ne_region->init_req(4, kls_ne);
1959 
1960     if (stopped()) {
1961       record_for_igvn(ne_region);
1962       set_control(_gvn.transform(ne_region));
1963       if (btest == BoolTest::ne) {
1964         {
1965           PreserveJVMState pjvms(this);
1966           int target_bci = iter().get_dest();
1967           merge(target_bci);
1968         }
1969         record_for_igvn(eq_region);
1970         set_control(_gvn.transform(eq_region));
1971       }
1972       return;
1973     }
1974     // Both are values of the same class, we need to perform a
1975     // substitutability test. Delegate to
1976     // ValueBootstrapMethods::isSubstitutable().
1977 
1978     Node* ne_io_phi = PhiNode::make(ne_region, i_o());
1979     Node* mem = reset_memory();
1980     Node* ne_mem_phi = PhiNode::make(ne_region, mem);
1981 
1982     Node* eq_io_phi = NULL;
1983     Node* eq_mem_phi = NULL;
1984     if (eq_region != NULL) {
1985       eq_io_phi = PhiNode::make(eq_region, i_o());
1986       eq_mem_phi = PhiNode::make(eq_region, mem);
1987     }
1988 
1989     set_all_memory(mem);
1990 
1991     kill_dead_locals();
1992     CallStaticJavaNode *call = new CallStaticJavaNode(C, TypeFunc::make(subst_method), SharedRuntime::get_resolve_static_call_stub(), subst_method, bci());
1993     call->set_override_symbolic_info(true);
1994     call->init_req(TypeFunc::Parms, not_null_a);
1995     call->init_req(TypeFunc::Parms+1, not_null_b);
1996     inc_sp(2);
1997     set_edges_for_java_call(call, false, false);
1998     Node* ret = set_results_for_java_call(call, false, true);
1999     dec_sp(2);
2000 
2001     // Test the return value of ValueBootstrapMethods::isSubstitutable()
2002     Node* subst_cmp = _gvn.transform(new CmpINode(ret, intcon(1)));
2003     if (btest == BoolTest::eq) {
2004       do_if(btest, subst_cmp);
2005     } else {
2006       assert(btest == BoolTest::ne, "only eq or ne");
2007       Node* is_not_equal = NULL;
2008       {
2009         PreserveJVMState pjvms(this);
2010         do_if(btest, subst_cmp, false, &is_not_equal);
2011         if (!stopped()) {
2012           eq_region->init_req(2, control());
2013           eq_io_phi->init_req(2, i_o());
2014           eq_mem_phi->init_req(2, reset_memory());
2015         }
2016       }
2017       set_control(is_not_equal);
2018     }
2019     ne_region->init_req(5, control());
2020     ne_io_phi->init_req(5, i_o());
2021     ne_mem_phi->init_req(5, reset_memory());
2022 
2023     record_for_igvn(ne_region);
2024     set_control(_gvn.transform(ne_region));
2025     set_i_o(_gvn.transform(ne_io_phi));
2026     set_all_memory(_gvn.transform(ne_mem_phi));
2027 
2028     if (btest == BoolTest::ne) {
2029       {
2030         PreserveJVMState pjvms(this);
2031         int target_bci = iter().get_dest();
2032         merge(target_bci);
2033       }
2034 
2035       record_for_igvn(eq_region);
2036       set_control(_gvn.transform(eq_region));
2037       set_i_o(_gvn.transform(eq_io_phi));
2038       set_all_memory(_gvn.transform(eq_mem_phi));
2039     }
2040 
2041     return;
2042   }
2043   // In the case were both operands might be value types, we need to
2044   // use the new acmp implementation. Otherwise, i.e. if one operand
2045   // is not a value type, we can use the old acmp implementation.
2046   Node* cmp = C->optimize_acmp(&_gvn, a, b);
2047   if (cmp != NULL) {
2048     // Use optimized/old acmp
2049     cmp = optimize_cmp_with_klass(_gvn.transform(cmp));
2050     do_if(btest, cmp);
2051     return;
2052   }
2053 
2054   Node* ctrl = NULL;
2055   bool safe_for_replace = true;
2056   if (ACmpOnValues != 1) {
2057     // Emit old acmp before new acmp for quick a != b check
2058     cmp = CmpP(a, b);
2059     cmp = optimize_cmp_with_klass(_gvn.transform(cmp));
2060     if (btest == BoolTest::ne) {
2061       do_if(btest, cmp, true);
2062       if (stopped()) {
2063         return; // Never equal
2064       }
2065     } else if (btest == BoolTest::eq) {
2066       Node* is_equal = NULL;
2067       {
2068         PreserveJVMState pjvms(this);
2069         do_if(btest, cmp, false, &is_equal);
2070         if (!stopped()) {
2071           // Not equal, skip valuetype check
2072           ctrl = new RegionNode(3);
2073           ctrl->init_req(1, control());
2074           _gvn.set_type(ctrl, Type::CONTROL);
2075           record_for_igvn(ctrl);
2076           safe_for_replace = false;
2077         }
2078       }
2079       if (is_equal == NULL) {
2080         assert(ctrl != NULL, "no control left");
2081         set_control(_gvn.transform(ctrl));
2082         return; // Never equal
2083       }
2084       set_control(is_equal);
2085     }
2086   }
2087 
2088   // Null check operand before loading the is_value bit
2089   bool speculate = false;
2090   if (!TypePtr::NULL_PTR->higher_equal(_gvn.type(b))) {
2091     // Operand 'b' is never null, swap operands to avoid null check
2092     swap(a, b);
2093   } else if (!too_many_traps(Deoptimization::Reason_speculate_null_check)) {
2094     // Speculate on non-nullness of one operand
2095     if (!_gvn.type(a)->speculative_maybe_null()) {
2096       speculate = true;
2097     } else if (!_gvn.type(b)->speculative_maybe_null()) {
2098       speculate = true;
2099       swap(a, b);
2100     }
2101   }
2102   inc_sp(2);
2103   Node* null_ctl = top();
2104   Node* not_null_a = null_check_oop(a, &null_ctl, speculate, safe_for_replace, speculate);
2105   assert(!stopped(), "operand is always null");
2106   dec_sp(2);
2107   Node* region = new RegionNode(2);
2108   Node* is_value = new PhiNode(region, TypeX_X);
2109   if (null_ctl != top()) {
2110     assert(!speculate, "should never be null");
2111     region->add_req(null_ctl);
2112     is_value->add_req(_gvn.MakeConX(0));
2113   }
2114 
2115   Node* value_mask = _gvn.MakeConX(markOopDesc::always_locked_pattern);
2116   if (ACmpOnValues == 1) {
2117     Node* mark_addr = basic_plus_adr(not_null_a, oopDesc::mark_offset_in_bytes());
2118     Node* mark = make_load(NULL, mark_addr, TypeX_X, TypeX_X->basic_type(), MemNode::unordered);
2119     Node* not_mark = _gvn.transform(new XorXNode(mark, _gvn.MakeConX(-1)));
2120     Node* andn = _gvn.transform(new AndXNode(not_mark, value_mask));
2121     Node* neg_if_value = _gvn.transform(new SubXNode(andn, _gvn.MakeConX(1)));
2122     is_value->init_req(1, _gvn.transform(new RShiftXNode(neg_if_value, _gvn.intcon(63))));
2123   } else {
2124     is_value->init_req(1, is_always_locked(not_null_a));
2125   }
2126   region->init_req(1, control());
2127 
2128   set_control(_gvn.transform(region));
2129   is_value = _gvn.transform(is_value);
2130 
2131   if (ACmpOnValues == 1) {
2132     // Perturbe oop if operand is a value type to make comparison fail
2133     Node* pert = _gvn.transform(new AddPNode(a, a, is_value));
2134     cmp = _gvn.transform(new CmpPNode(pert, b));
2135   } else {
2136     // Check for a value type because we already know that operands are equal
2137     cmp = _gvn.transform(new CmpXNode(is_value, value_mask));
2138     btest = (btest == BoolTest::eq) ? BoolTest::ne : BoolTest::eq;
2139   }
2140   cmp = optimize_cmp_with_klass(cmp);
2141   do_if(btest, cmp);
2142 
2143   if (ctrl != NULL) {
2144     ctrl->init_req(2, control());
2145     set_control(_gvn.transform(ctrl));
2146   }
2147 }
2148 
2149 bool Parse::path_is_suitable_for_uncommon_trap(float prob) const {
2150   // Don't want to speculate on uncommon traps when running with -Xcomp
2151   if (!UseInterpreter) {
2152     return false;
2153   }
2154   return (seems_never_taken(prob) && seems_stable_comparison());
2155 }
2156 
2157 void Parse::maybe_add_predicate_after_if(Block* path) {
2158   if (path->is_SEL_head() && path->preds_parsed() == 0) {
2159     // Add predicates at bci of if dominating the loop so traps can be
2160     // recorded on the if's profile data
2161     int bc_depth = repush_if_args();
2162     add_predicate();
2163     dec_sp(bc_depth);
2164     path->set_has_predicates();
2165   }
2166 }
2167 
2168 
2169 //----------------------------adjust_map_after_if------------------------------
2170 // Adjust the JVM state to reflect the result of taking this path.
2171 // Basically, it means inspecting the CmpNode controlling this
2172 // branch, seeing how it constrains a tested value, and then
2173 // deciding if it's worth our while to encode this constraint
2174 // as graph nodes in the current abstract interpretation map.
2175 void Parse::adjust_map_after_if(BoolTest::mask btest, Node* c, float prob, Block* path) {
2176   if (!c->is_Cmp()) {
2177     maybe_add_predicate_after_if(path);
2178     return;
2179   }
2180 
2181   if (stopped() || btest == BoolTest::illegal) {
2182     return;                             // nothing to do
2183   }
2184 
2185   bool is_fallthrough = (path == successor_for_bci(iter().next_bci()));
2186 
2187   if (path_is_suitable_for_uncommon_trap(prob)) {
2188     repush_if_args();
2189     uncommon_trap(Deoptimization::Reason_unstable_if,
2190                   Deoptimization::Action_reinterpret,
2191                   NULL,
2192                   (is_fallthrough ? "taken always" : "taken never"));
2193     return;
2194   }
2195 
2196   Node* val = c->in(1);
2197   Node* con = c->in(2);
2198   const Type* tcon = _gvn.type(con);
2199   const Type* tval = _gvn.type(val);
2200   bool have_con = tcon->singleton();
2201   if (tval->singleton()) {
2202     if (!have_con) {
2203       // Swap, so constant is in con.
2204       con  = val;
2205       tcon = tval;
2206       val  = c->in(2);
2207       tval = _gvn.type(val);
2208       btest = BoolTest(btest).commute();
2209       have_con = true;
2210     } else {
2211       // Do we have two constants?  Then leave well enough alone.
2212       have_con = false;
2213     }
2214   }
2215   if (!have_con) {                        // remaining adjustments need a con
2216     maybe_add_predicate_after_if(path);
2217     return;
2218   }
2219 
2220   sharpen_type_after_if(btest, con, tcon, val, tval);
2221   maybe_add_predicate_after_if(path);
2222 }
2223 
2224 
2225 static Node* extract_obj_from_klass_load(PhaseGVN* gvn, Node* n) {
2226   Node* ldk;
2227   if (n->is_DecodeNKlass()) {
2228     if (n->in(1)->Opcode() != Op_LoadNKlass) {
2229       return NULL;
2230     } else {
2231       ldk = n->in(1);
2232     }
2233   } else if (n->Opcode() != Op_LoadKlass) {
2234     return NULL;
2235   } else {
2236     ldk = n;
2237   }
2238   assert(ldk != NULL && ldk->is_Load(), "should have found a LoadKlass or LoadNKlass node");
2239 
2240   Node* adr = ldk->in(MemNode::Address);
2241   intptr_t off = 0;
2242   Node* obj = AddPNode::Ideal_base_and_offset(adr, gvn, off);
2243   if (obj == NULL || off != oopDesc::klass_offset_in_bytes()) // loading oopDesc::_klass?
2244     return NULL;
2245   const TypePtr* tp = gvn->type(obj)->is_ptr();
2246   if (tp == NULL || !(tp->isa_instptr() || tp->isa_aryptr())) // is obj a Java object ptr?
2247     return NULL;
2248 
2249   return obj;
2250 }
2251 
2252 void Parse::sharpen_type_after_if(BoolTest::mask btest,
2253                                   Node* con, const Type* tcon,
2254                                   Node* val, const Type* tval) {
2255   // Look for opportunities to sharpen the type of a node
2256   // whose klass is compared with a constant klass.
2257   if (btest == BoolTest::eq && tcon->isa_klassptr()) {
2258     Node* obj = extract_obj_from_klass_load(&_gvn, val);
2259     const TypeOopPtr* con_type = tcon->isa_klassptr()->as_instance_type();
2260     if (obj != NULL && (con_type->isa_instptr() || con_type->isa_aryptr())) {
2261        // Found:
2262        //   Bool(CmpP(LoadKlass(obj._klass), ConP(Foo.klass)), [eq])
2263        // or the narrowOop equivalent.
2264        const Type* obj_type = _gvn.type(obj);
2265        const TypeOopPtr* tboth = obj_type->join_speculative(con_type)->isa_oopptr();
2266        if (tboth != NULL && tboth->klass_is_exact() && tboth != obj_type &&
2267            tboth->higher_equal(obj_type)) {
2268           // obj has to be of the exact type Foo if the CmpP succeeds.
2269           int obj_in_map = map()->find_edge(obj);
2270           JVMState* jvms = this->jvms();
2271           if (obj_in_map >= 0 &&
2272               (jvms->is_loc(obj_in_map) || jvms->is_stk(obj_in_map))) {
2273             TypeNode* ccast = new CheckCastPPNode(control(), obj, tboth);
2274             const Type* tcc = ccast->as_Type()->type();
2275             assert(tcc != obj_type && tcc->higher_equal(obj_type), "must improve");
2276             // Delay transform() call to allow recovery of pre-cast value
2277             // at the control merge.
2278             _gvn.set_type_bottom(ccast);
2279             record_for_igvn(ccast);
2280             // Here's the payoff.
2281             replace_in_map(obj, ccast);
2282           }
2283        }
2284     }
2285   }
2286 
2287   int val_in_map = map()->find_edge(val);
2288   if (val_in_map < 0)  return;          // replace_in_map would be useless
2289   {
2290     JVMState* jvms = this->jvms();
2291     if (!(jvms->is_loc(val_in_map) ||
2292           jvms->is_stk(val_in_map)))
2293       return;                           // again, it would be useless
2294   }
2295 
2296   // Check for a comparison to a constant, and "know" that the compared
2297   // value is constrained on this path.
2298   assert(tcon->singleton(), "");
2299   ConstraintCastNode* ccast = NULL;
2300   Node* cast = NULL;
2301 
2302   switch (btest) {
2303   case BoolTest::eq:                    // Constant test?
2304     {
2305       const Type* tboth = tcon->join_speculative(tval);
2306       if (tboth == tval)  break;        // Nothing to gain.
2307       if (tcon->isa_int()) {
2308         ccast = new CastIINode(val, tboth);
2309       } else if (tcon == TypePtr::NULL_PTR) {
2310         // Cast to null, but keep the pointer identity temporarily live.
2311         ccast = new CastPPNode(val, tboth);
2312       } else {
2313         const TypeF* tf = tcon->isa_float_constant();
2314         const TypeD* td = tcon->isa_double_constant();
2315         // Exclude tests vs float/double 0 as these could be
2316         // either +0 or -0.  Just because you are equal to +0
2317         // doesn't mean you ARE +0!
2318         // Note, following code also replaces Long and Oop values.
2319         if ((!tf || tf->_f != 0.0) &&
2320             (!td || td->_d != 0.0))
2321           cast = con;                   // Replace non-constant val by con.
2322       }
2323     }
2324     break;
2325 
2326   case BoolTest::ne:
2327     if (tcon == TypePtr::NULL_PTR) {
2328       cast = cast_not_null(val, false);
2329     }
2330     break;
2331 
2332   default:
2333     // (At this point we could record int range types with CastII.)
2334     break;
2335   }
2336 
2337   if (ccast != NULL) {
2338     const Type* tcc = ccast->as_Type()->type();
2339     assert(tcc != tval && tcc->higher_equal(tval), "must improve");
2340     // Delay transform() call to allow recovery of pre-cast value
2341     // at the control merge.
2342     ccast->set_req(0, control());
2343     _gvn.set_type_bottom(ccast);
2344     record_for_igvn(ccast);
2345     cast = ccast;
2346   }
2347 
2348   if (cast != NULL) {                   // Here's the payoff.
2349     replace_in_map(val, cast);
2350   }
2351 }
2352 
2353 /**
2354  * Use speculative type to optimize CmpP node: if comparison is
2355  * against the low level class, cast the object to the speculative
2356  * type if any. CmpP should then go away.
2357  *
2358  * @param c  expected CmpP node
2359  * @return   result of CmpP on object casted to speculative type
2360  *
2361  */
2362 Node* Parse::optimize_cmp_with_klass(Node* c) {
2363   // If this is transformed by the _gvn to a comparison with the low
2364   // level klass then we may be able to use speculation
2365   if (c->Opcode() == Op_CmpP &&
2366       (c->in(1)->Opcode() == Op_LoadKlass || c->in(1)->Opcode() == Op_DecodeNKlass) &&
2367       c->in(2)->is_Con()) {
2368     Node* load_klass = NULL;
2369     Node* decode = NULL;
2370     if (c->in(1)->Opcode() == Op_DecodeNKlass) {
2371       decode = c->in(1);
2372       load_klass = c->in(1)->in(1);
2373     } else {
2374       load_klass = c->in(1);
2375     }
2376     if (load_klass->in(2)->is_AddP()) {
2377       Node* addp = load_klass->in(2);
2378       Node* obj = addp->in(AddPNode::Address);
2379       const TypeOopPtr* obj_type = _gvn.type(obj)->is_oopptr();
2380       if (obj_type->speculative_type_not_null() != NULL) {
2381         ciKlass* k = obj_type->speculative_type();
2382         inc_sp(2);
2383         obj = maybe_cast_profiled_obj(obj, k);
2384         dec_sp(2);
2385         if (obj->is_ValueType()) {
2386           assert(obj->as_ValueType()->is_allocated(&_gvn), "must be allocated");
2387           obj = obj->as_ValueType()->get_oop();
2388         }
2389         // Make the CmpP use the casted obj
2390         addp = basic_plus_adr(obj, addp->in(AddPNode::Offset));
2391         load_klass = load_klass->clone();
2392         load_klass->set_req(2, addp);
2393         load_klass = _gvn.transform(load_klass);
2394         if (decode != NULL) {
2395           decode = decode->clone();
2396           decode->set_req(1, load_klass);
2397           load_klass = _gvn.transform(decode);
2398         }
2399         c = c->clone();
2400         c->set_req(1, load_klass);
2401         c = _gvn.transform(c);
2402       }
2403     }
2404   }
2405   return c;
2406 }
2407 
2408 //------------------------------do_one_bytecode--------------------------------
2409 // Parse this bytecode, and alter the Parsers JVM->Node mapping
2410 void Parse::do_one_bytecode() {
2411   Node *a, *b, *c, *d;          // Handy temps
2412   BoolTest::mask btest;
2413   int i;
2414 
2415   assert(!has_exceptions(), "bytecode entry state must be clear of throws");
2416 
2417   if (C->check_node_count(NodeLimitFudgeFactor * 5,
2418                           "out of nodes parsing method")) {
2419     return;
2420   }
2421 
2422 #ifdef ASSERT
2423   // for setting breakpoints
2424   if (TraceOptoParse) {
2425     tty->print(" @");
2426     dump_bci(bci());
2427     tty->cr();
2428   }
2429 #endif
2430 
2431   switch (bc()) {
2432   case Bytecodes::_nop:
2433     // do nothing
2434     break;
2435   case Bytecodes::_lconst_0:
2436     push_pair(longcon(0));
2437     break;
2438 
2439   case Bytecodes::_lconst_1:
2440     push_pair(longcon(1));
2441     break;
2442 
2443   case Bytecodes::_fconst_0:
2444     push(zerocon(T_FLOAT));
2445     break;
2446 
2447   case Bytecodes::_fconst_1:
2448     push(makecon(TypeF::ONE));
2449     break;
2450 
2451   case Bytecodes::_fconst_2:
2452     push(makecon(TypeF::make(2.0f)));
2453     break;
2454 
2455   case Bytecodes::_dconst_0:
2456     push_pair(zerocon(T_DOUBLE));
2457     break;
2458 
2459   case Bytecodes::_dconst_1:
2460     push_pair(makecon(TypeD::ONE));
2461     break;
2462 
2463   case Bytecodes::_iconst_m1:push(intcon(-1)); break;
2464   case Bytecodes::_iconst_0: push(intcon( 0)); break;
2465   case Bytecodes::_iconst_1: push(intcon( 1)); break;
2466   case Bytecodes::_iconst_2: push(intcon( 2)); break;
2467   case Bytecodes::_iconst_3: push(intcon( 3)); break;
2468   case Bytecodes::_iconst_4: push(intcon( 4)); break;
2469   case Bytecodes::_iconst_5: push(intcon( 5)); break;
2470   case Bytecodes::_bipush:   push(intcon(iter().get_constant_u1())); break;
2471   case Bytecodes::_sipush:   push(intcon(iter().get_constant_u2())); break;
2472   case Bytecodes::_aconst_null: push(null());  break;
2473   case Bytecodes::_ldc:
2474   case Bytecodes::_ldc_w:
2475   case Bytecodes::_ldc2_w:
2476     // If the constant is unresolved, run this BC once in the interpreter.
2477     {
2478       ciConstant constant = iter().get_constant();
2479       if (!constant.is_valid() ||
2480           (constant.basic_type() == T_OBJECT &&
2481            !constant.as_object()->is_loaded())) {
2482         int index = iter().get_constant_pool_index();
2483         constantTag tag = iter().get_constant_pool_tag(index);
2484         uncommon_trap(Deoptimization::make_trap_request
2485                       (Deoptimization::Reason_unloaded,
2486                        Deoptimization::Action_reinterpret,
2487                        index),
2488                       NULL, tag.internal_name());
2489         break;
2490       }
2491       assert(constant.basic_type() != T_OBJECT || constant.as_object()->is_instance(),
2492              "must be java_mirror of klass");
2493       const Type* con_type = Type::make_from_constant(constant);
2494       if (con_type != NULL) {
2495         push_node(con_type->basic_type(), makecon(con_type));
2496       }
2497     }
2498 
2499     break;
2500 
2501   case Bytecodes::_aload_0:
2502     push( local(0) );
2503     break;
2504   case Bytecodes::_aload_1:
2505     push( local(1) );
2506     break;
2507   case Bytecodes::_aload_2:
2508     push( local(2) );
2509     break;
2510   case Bytecodes::_aload_3:
2511     push( local(3) );
2512     break;
2513   case Bytecodes::_aload:
2514     push( local(iter().get_index()) );
2515     break;
2516 
2517   case Bytecodes::_fload_0:
2518   case Bytecodes::_iload_0:
2519     push( local(0) );
2520     break;
2521   case Bytecodes::_fload_1:
2522   case Bytecodes::_iload_1:
2523     push( local(1) );
2524     break;
2525   case Bytecodes::_fload_2:
2526   case Bytecodes::_iload_2:
2527     push( local(2) );
2528     break;
2529   case Bytecodes::_fload_3:
2530   case Bytecodes::_iload_3:
2531     push( local(3) );
2532     break;
2533   case Bytecodes::_fload:
2534   case Bytecodes::_iload:
2535     push( local(iter().get_index()) );
2536     break;
2537   case Bytecodes::_lload_0:
2538     push_pair_local( 0 );
2539     break;
2540   case Bytecodes::_lload_1:
2541     push_pair_local( 1 );
2542     break;
2543   case Bytecodes::_lload_2:
2544     push_pair_local( 2 );
2545     break;
2546   case Bytecodes::_lload_3:
2547     push_pair_local( 3 );
2548     break;
2549   case Bytecodes::_lload:
2550     push_pair_local( iter().get_index() );
2551     break;
2552 
2553   case Bytecodes::_dload_0:
2554     push_pair_local(0);
2555     break;
2556   case Bytecodes::_dload_1:
2557     push_pair_local(1);
2558     break;
2559   case Bytecodes::_dload_2:
2560     push_pair_local(2);
2561     break;
2562   case Bytecodes::_dload_3:
2563     push_pair_local(3);
2564     break;
2565   case Bytecodes::_dload:
2566     push_pair_local(iter().get_index());
2567     break;
2568   case Bytecodes::_fstore_0:
2569   case Bytecodes::_istore_0:
2570   case Bytecodes::_astore_0:
2571     set_local( 0, pop() );
2572     break;
2573   case Bytecodes::_fstore_1:
2574   case Bytecodes::_istore_1:
2575   case Bytecodes::_astore_1:
2576     set_local( 1, pop() );
2577     break;
2578   case Bytecodes::_fstore_2:
2579   case Bytecodes::_istore_2:
2580   case Bytecodes::_astore_2:
2581     set_local( 2, pop() );
2582     break;
2583   case Bytecodes::_fstore_3:
2584   case Bytecodes::_istore_3:
2585   case Bytecodes::_astore_3:
2586     set_local( 3, pop() );
2587     break;
2588   case Bytecodes::_fstore:
2589   case Bytecodes::_istore:
2590   case Bytecodes::_astore:
2591     set_local( iter().get_index(), pop() );
2592     break;
2593   // long stores
2594   case Bytecodes::_lstore_0:
2595     set_pair_local( 0, pop_pair() );
2596     break;
2597   case Bytecodes::_lstore_1:
2598     set_pair_local( 1, pop_pair() );
2599     break;
2600   case Bytecodes::_lstore_2:
2601     set_pair_local( 2, pop_pair() );
2602     break;
2603   case Bytecodes::_lstore_3:
2604     set_pair_local( 3, pop_pair() );
2605     break;
2606   case Bytecodes::_lstore:
2607     set_pair_local( iter().get_index(), pop_pair() );
2608     break;
2609 
2610   // double stores
2611   case Bytecodes::_dstore_0:
2612     set_pair_local( 0, dstore_rounding(pop_pair()) );
2613     break;
2614   case Bytecodes::_dstore_1:
2615     set_pair_local( 1, dstore_rounding(pop_pair()) );
2616     break;
2617   case Bytecodes::_dstore_2:
2618     set_pair_local( 2, dstore_rounding(pop_pair()) );
2619     break;
2620   case Bytecodes::_dstore_3:
2621     set_pair_local( 3, dstore_rounding(pop_pair()) );
2622     break;
2623   case Bytecodes::_dstore:
2624     set_pair_local( iter().get_index(), dstore_rounding(pop_pair()) );
2625     break;
2626 
2627   case Bytecodes::_pop:  dec_sp(1);   break;
2628   case Bytecodes::_pop2: dec_sp(2);   break;
2629   case Bytecodes::_swap:
2630     a = pop();
2631     b = pop();
2632     push(a);
2633     push(b);
2634     break;
2635   case Bytecodes::_dup:
2636     a = pop();
2637     push(a);
2638     push(a);
2639     break;
2640   case Bytecodes::_dup_x1:
2641     a = pop();
2642     b = pop();
2643     push( a );
2644     push( b );
2645     push( a );
2646     break;
2647   case Bytecodes::_dup_x2:
2648     a = pop();
2649     b = pop();
2650     c = pop();
2651     push( a );
2652     push( c );
2653     push( b );
2654     push( a );
2655     break;
2656   case Bytecodes::_dup2:
2657     a = pop();
2658     b = pop();
2659     push( b );
2660     push( a );
2661     push( b );
2662     push( a );
2663     break;
2664 
2665   case Bytecodes::_dup2_x1:
2666     // before: .. c, b, a
2667     // after:  .. b, a, c, b, a
2668     // not tested
2669     a = pop();
2670     b = pop();
2671     c = pop();
2672     push( b );
2673     push( a );
2674     push( c );
2675     push( b );
2676     push( a );
2677     break;
2678   case Bytecodes::_dup2_x2:
2679     // before: .. d, c, b, a
2680     // after:  .. b, a, d, c, b, a
2681     // not tested
2682     a = pop();
2683     b = pop();
2684     c = pop();
2685     d = pop();
2686     push( b );
2687     push( a );
2688     push( d );
2689     push( c );
2690     push( b );
2691     push( a );
2692     break;
2693 
2694   case Bytecodes::_arraylength: {
2695     // Must do null-check with value on expression stack
2696     Node *ary = null_check(peek(), T_ARRAY);
2697     // Compile-time detect of null-exception?
2698     if (stopped())  return;
2699     a = pop();
2700     push(load_array_length(a));
2701     break;
2702   }
2703 
2704   case Bytecodes::_baload:  array_load(T_BYTE);    break;
2705   case Bytecodes::_caload:  array_load(T_CHAR);    break;
2706   case Bytecodes::_iaload:  array_load(T_INT);     break;
2707   case Bytecodes::_saload:  array_load(T_SHORT);   break;
2708   case Bytecodes::_faload:  array_load(T_FLOAT);   break;
2709   case Bytecodes::_aaload:  array_load(T_OBJECT);  break;
2710   case Bytecodes::_laload:  array_load(T_LONG);    break;
2711   case Bytecodes::_daload:  array_load(T_DOUBLE);  break;
2712   case Bytecodes::_bastore: array_store(T_BYTE);   break;
2713   case Bytecodes::_castore: array_store(T_CHAR);   break;
2714   case Bytecodes::_iastore: array_store(T_INT);    break;
2715   case Bytecodes::_sastore: array_store(T_SHORT);  break;
2716   case Bytecodes::_fastore: array_store(T_FLOAT);  break;
2717   case Bytecodes::_aastore: array_store(T_OBJECT); break;
2718   case Bytecodes::_lastore: array_store(T_LONG);   break;
2719   case Bytecodes::_dastore: array_store(T_DOUBLE); break;
2720 
2721   case Bytecodes::_getfield:
2722     do_getfield();
2723     break;
2724 
2725   case Bytecodes::_getstatic:
2726     do_getstatic();
2727     break;
2728 
2729   case Bytecodes::_putfield:
2730     do_putfield();
2731     break;
2732 
2733   case Bytecodes::_putstatic:
2734     do_putstatic();
2735     break;
2736 
2737   case Bytecodes::_irem:
2738     do_irem();
2739     break;
2740   case Bytecodes::_idiv:
2741     // Must keep both values on the expression-stack during null-check
2742     zero_check_int(peek());
2743     // Compile-time detect of null-exception?
2744     if (stopped())  return;
2745     b = pop();
2746     a = pop();
2747     push( _gvn.transform( new DivINode(control(),a,b) ) );
2748     break;
2749   case Bytecodes::_imul:
2750     b = pop(); a = pop();
2751     push( _gvn.transform( new MulINode(a,b) ) );
2752     break;
2753   case Bytecodes::_iadd:
2754     b = pop(); a = pop();
2755     push( _gvn.transform( new AddINode(a,b) ) );
2756     break;
2757   case Bytecodes::_ineg:
2758     a = pop();
2759     push( _gvn.transform( new SubINode(_gvn.intcon(0),a)) );
2760     break;
2761   case Bytecodes::_isub:
2762     b = pop(); a = pop();
2763     push( _gvn.transform( new SubINode(a,b) ) );
2764     break;
2765   case Bytecodes::_iand:
2766     b = pop(); a = pop();
2767     push( _gvn.transform( new AndINode(a,b) ) );
2768     break;
2769   case Bytecodes::_ior:
2770     b = pop(); a = pop();
2771     push( _gvn.transform( new OrINode(a,b) ) );
2772     break;
2773   case Bytecodes::_ixor:
2774     b = pop(); a = pop();
2775     push( _gvn.transform( new XorINode(a,b) ) );
2776     break;
2777   case Bytecodes::_ishl:
2778     b = pop(); a = pop();
2779     push( _gvn.transform( new LShiftINode(a,b) ) );
2780     break;
2781   case Bytecodes::_ishr:
2782     b = pop(); a = pop();
2783     push( _gvn.transform( new RShiftINode(a,b) ) );
2784     break;
2785   case Bytecodes::_iushr:
2786     b = pop(); a = pop();
2787     push( _gvn.transform( new URShiftINode(a,b) ) );
2788     break;
2789 
2790   case Bytecodes::_fneg:
2791     a = pop();
2792     b = _gvn.transform(new NegFNode (a));
2793     push(b);
2794     break;
2795 
2796   case Bytecodes::_fsub:
2797     b = pop();
2798     a = pop();
2799     c = _gvn.transform( new SubFNode(a,b) );
2800     d = precision_rounding(c);
2801     push( d );
2802     break;
2803 
2804   case Bytecodes::_fadd:
2805     b = pop();
2806     a = pop();
2807     c = _gvn.transform( new AddFNode(a,b) );
2808     d = precision_rounding(c);
2809     push( d );
2810     break;
2811 
2812   case Bytecodes::_fmul:
2813     b = pop();
2814     a = pop();
2815     c = _gvn.transform( new MulFNode(a,b) );
2816     d = precision_rounding(c);
2817     push( d );
2818     break;
2819 
2820   case Bytecodes::_fdiv:
2821     b = pop();
2822     a = pop();
2823     c = _gvn.transform( new DivFNode(0,a,b) );
2824     d = precision_rounding(c);
2825     push( d );
2826     break;
2827 
2828   case Bytecodes::_frem:
2829     if (Matcher::has_match_rule(Op_ModF)) {
2830       // Generate a ModF node.
2831       b = pop();
2832       a = pop();
2833       c = _gvn.transform( new ModFNode(0,a,b) );
2834       d = precision_rounding(c);
2835       push( d );
2836     }
2837     else {
2838       // Generate a call.
2839       modf();
2840     }
2841     break;
2842 
2843   case Bytecodes::_fcmpl:
2844     b = pop();
2845     a = pop();
2846     c = _gvn.transform( new CmpF3Node( a, b));
2847     push(c);
2848     break;
2849   case Bytecodes::_fcmpg:
2850     b = pop();
2851     a = pop();
2852 
2853     // Same as fcmpl but need to flip the unordered case.  Swap the inputs,
2854     // which negates the result sign except for unordered.  Flip the unordered
2855     // as well by using CmpF3 which implements unordered-lesser instead of
2856     // unordered-greater semantics.  Finally, commute the result bits.  Result
2857     // is same as using a CmpF3Greater except we did it with CmpF3 alone.
2858     c = _gvn.transform( new CmpF3Node( b, a));
2859     c = _gvn.transform( new SubINode(_gvn.intcon(0),c) );
2860     push(c);
2861     break;
2862 
2863   case Bytecodes::_f2i:
2864     a = pop();
2865     push(_gvn.transform(new ConvF2INode(a)));
2866     break;
2867 
2868   case Bytecodes::_d2i:
2869     a = pop_pair();
2870     b = _gvn.transform(new ConvD2INode(a));
2871     push( b );
2872     break;
2873 
2874   case Bytecodes::_f2d:
2875     a = pop();
2876     b = _gvn.transform( new ConvF2DNode(a));
2877     push_pair( b );
2878     break;
2879 
2880   case Bytecodes::_d2f:
2881     a = pop_pair();
2882     b = _gvn.transform( new ConvD2FNode(a));
2883     // This breaks _227_mtrt (speed & correctness) and _222_mpegaudio (speed)
2884     //b = _gvn.transform(new RoundFloatNode(0, b) );
2885     push( b );
2886     break;
2887 
2888   case Bytecodes::_l2f:
2889     if (Matcher::convL2FSupported()) {
2890       a = pop_pair();
2891       b = _gvn.transform( new ConvL2FNode(a));
2892       // For i486.ad, FILD doesn't restrict precision to 24 or 53 bits.
2893       // Rather than storing the result into an FP register then pushing
2894       // out to memory to round, the machine instruction that implements
2895       // ConvL2D is responsible for rounding.
2896       // c = precision_rounding(b);
2897       c = _gvn.transform(b);
2898       push(c);
2899     } else {
2900       l2f();
2901     }
2902     break;
2903 
2904   case Bytecodes::_l2d:
2905     a = pop_pair();
2906     b = _gvn.transform( new ConvL2DNode(a));
2907     // For i486.ad, rounding is always necessary (see _l2f above).
2908     // c = dprecision_rounding(b);
2909     c = _gvn.transform(b);
2910     push_pair(c);
2911     break;
2912 
2913   case Bytecodes::_f2l:
2914     a = pop();
2915     b = _gvn.transform( new ConvF2LNode(a));
2916     push_pair(b);
2917     break;
2918 
2919   case Bytecodes::_d2l:
2920     a = pop_pair();
2921     b = _gvn.transform( new ConvD2LNode(a));
2922     push_pair(b);
2923     break;
2924 
2925   case Bytecodes::_dsub:
2926     b = pop_pair();
2927     a = pop_pair();
2928     c = _gvn.transform( new SubDNode(a,b) );
2929     d = dprecision_rounding(c);
2930     push_pair( d );
2931     break;
2932 
2933   case Bytecodes::_dadd:
2934     b = pop_pair();
2935     a = pop_pair();
2936     c = _gvn.transform( new AddDNode(a,b) );
2937     d = dprecision_rounding(c);
2938     push_pair( d );
2939     break;
2940 
2941   case Bytecodes::_dmul:
2942     b = pop_pair();
2943     a = pop_pair();
2944     c = _gvn.transform( new MulDNode(a,b) );
2945     d = dprecision_rounding(c);
2946     push_pair( d );
2947     break;
2948 
2949   case Bytecodes::_ddiv:
2950     b = pop_pair();
2951     a = pop_pair();
2952     c = _gvn.transform( new DivDNode(0,a,b) );
2953     d = dprecision_rounding(c);
2954     push_pair( d );
2955     break;
2956 
2957   case Bytecodes::_dneg:
2958     a = pop_pair();
2959     b = _gvn.transform(new NegDNode (a));
2960     push_pair(b);
2961     break;
2962 
2963   case Bytecodes::_drem:
2964     if (Matcher::has_match_rule(Op_ModD)) {
2965       // Generate a ModD node.
2966       b = pop_pair();
2967       a = pop_pair();
2968       // a % b
2969 
2970       c = _gvn.transform( new ModDNode(0,a,b) );
2971       d = dprecision_rounding(c);
2972       push_pair( d );
2973     }
2974     else {
2975       // Generate a call.
2976       modd();
2977     }
2978     break;
2979 
2980   case Bytecodes::_dcmpl:
2981     b = pop_pair();
2982     a = pop_pair();
2983     c = _gvn.transform( new CmpD3Node( a, b));
2984     push(c);
2985     break;
2986 
2987   case Bytecodes::_dcmpg:
2988     b = pop_pair();
2989     a = pop_pair();
2990     // Same as dcmpl but need to flip the unordered case.
2991     // Commute the inputs, which negates the result sign except for unordered.
2992     // Flip the unordered as well by using CmpD3 which implements
2993     // unordered-lesser instead of unordered-greater semantics.
2994     // Finally, negate the result bits.  Result is same as using a
2995     // CmpD3Greater except we did it with CmpD3 alone.
2996     c = _gvn.transform( new CmpD3Node( b, a));
2997     c = _gvn.transform( new SubINode(_gvn.intcon(0),c) );
2998     push(c);
2999     break;
3000 
3001 
3002     // Note for longs -> lo word is on TOS, hi word is on TOS - 1
3003   case Bytecodes::_land:
3004     b = pop_pair();
3005     a = pop_pair();
3006     c = _gvn.transform( new AndLNode(a,b) );
3007     push_pair(c);
3008     break;
3009   case Bytecodes::_lor:
3010     b = pop_pair();
3011     a = pop_pair();
3012     c = _gvn.transform( new OrLNode(a,b) );
3013     push_pair(c);
3014     break;
3015   case Bytecodes::_lxor:
3016     b = pop_pair();
3017     a = pop_pair();
3018     c = _gvn.transform( new XorLNode(a,b) );
3019     push_pair(c);
3020     break;
3021 
3022   case Bytecodes::_lshl:
3023     b = pop();                  // the shift count
3024     a = pop_pair();             // value to be shifted
3025     c = _gvn.transform( new LShiftLNode(a,b) );
3026     push_pair(c);
3027     break;
3028   case Bytecodes::_lshr:
3029     b = pop();                  // the shift count
3030     a = pop_pair();             // value to be shifted
3031     c = _gvn.transform( new RShiftLNode(a,b) );
3032     push_pair(c);
3033     break;
3034   case Bytecodes::_lushr:
3035     b = pop();                  // the shift count
3036     a = pop_pair();             // value to be shifted
3037     c = _gvn.transform( new URShiftLNode(a,b) );
3038     push_pair(c);
3039     break;
3040   case Bytecodes::_lmul:
3041     b = pop_pair();
3042     a = pop_pair();
3043     c = _gvn.transform( new MulLNode(a,b) );
3044     push_pair(c);
3045     break;
3046 
3047   case Bytecodes::_lrem:
3048     // Must keep both values on the expression-stack during null-check
3049     assert(peek(0) == top(), "long word order");
3050     zero_check_long(peek(1));
3051     // Compile-time detect of null-exception?
3052     if (stopped())  return;
3053     b = pop_pair();
3054     a = pop_pair();
3055     c = _gvn.transform( new ModLNode(control(),a,b) );
3056     push_pair(c);
3057     break;
3058 
3059   case Bytecodes::_ldiv:
3060     // Must keep both values on the expression-stack during null-check
3061     assert(peek(0) == top(), "long word order");
3062     zero_check_long(peek(1));
3063     // Compile-time detect of null-exception?
3064     if (stopped())  return;
3065     b = pop_pair();
3066     a = pop_pair();
3067     c = _gvn.transform( new DivLNode(control(),a,b) );
3068     push_pair(c);
3069     break;
3070 
3071   case Bytecodes::_ladd:
3072     b = pop_pair();
3073     a = pop_pair();
3074     c = _gvn.transform( new AddLNode(a,b) );
3075     push_pair(c);
3076     break;
3077   case Bytecodes::_lsub:
3078     b = pop_pair();
3079     a = pop_pair();
3080     c = _gvn.transform( new SubLNode(a,b) );
3081     push_pair(c);
3082     break;
3083   case Bytecodes::_lcmp:
3084     // Safepoints are now inserted _before_ branches.  The long-compare
3085     // bytecode painfully produces a 3-way value (-1,0,+1) which requires a
3086     // slew of control flow.  These are usually followed by a CmpI vs zero and
3087     // a branch; this pattern then optimizes to the obvious long-compare and
3088     // branch.  However, if the branch is backwards there's a Safepoint
3089     // inserted.  The inserted Safepoint captures the JVM state at the
3090     // pre-branch point, i.e. it captures the 3-way value.  Thus if a
3091     // long-compare is used to control a loop the debug info will force
3092     // computation of the 3-way value, even though the generated code uses a
3093     // long-compare and branch.  We try to rectify the situation by inserting
3094     // a SafePoint here and have it dominate and kill the safepoint added at a
3095     // following backwards branch.  At this point the JVM state merely holds 2
3096     // longs but not the 3-way value.
3097     if( UseLoopSafepoints ) {
3098       switch( iter().next_bc() ) {
3099       case Bytecodes::_ifgt:
3100       case Bytecodes::_iflt:
3101       case Bytecodes::_ifge:
3102       case Bytecodes::_ifle:
3103       case Bytecodes::_ifne:
3104       case Bytecodes::_ifeq:
3105         // If this is a backwards branch in the bytecodes, add Safepoint
3106         maybe_add_safepoint(iter().next_get_dest());
3107       default:
3108         break;
3109       }
3110     }
3111     b = pop_pair();
3112     a = pop_pair();
3113     c = _gvn.transform( new CmpL3Node( a, b ));
3114     push(c);
3115     break;
3116 
3117   case Bytecodes::_lneg:
3118     a = pop_pair();
3119     b = _gvn.transform( new SubLNode(longcon(0),a));
3120     push_pair(b);
3121     break;
3122   case Bytecodes::_l2i:
3123     a = pop_pair();
3124     push( _gvn.transform( new ConvL2INode(a)));
3125     break;
3126   case Bytecodes::_i2l:
3127     a = pop();
3128     b = _gvn.transform( new ConvI2LNode(a));
3129     push_pair(b);
3130     break;
3131   case Bytecodes::_i2b:
3132     // Sign extend
3133     a = pop();
3134     a = _gvn.transform( new LShiftINode(a,_gvn.intcon(24)) );
3135     a = _gvn.transform( new RShiftINode(a,_gvn.intcon(24)) );
3136     push( a );
3137     break;
3138   case Bytecodes::_i2s:
3139     a = pop();
3140     a = _gvn.transform( new LShiftINode(a,_gvn.intcon(16)) );
3141     a = _gvn.transform( new RShiftINode(a,_gvn.intcon(16)) );
3142     push( a );
3143     break;
3144   case Bytecodes::_i2c:
3145     a = pop();
3146     push( _gvn.transform( new AndINode(a,_gvn.intcon(0xFFFF)) ) );
3147     break;
3148 
3149   case Bytecodes::_i2f:
3150     a = pop();
3151     b = _gvn.transform( new ConvI2FNode(a) ) ;
3152     c = precision_rounding(b);
3153     push (b);
3154     break;
3155 
3156   case Bytecodes::_i2d:
3157     a = pop();
3158     b = _gvn.transform( new ConvI2DNode(a));
3159     push_pair(b);
3160     break;
3161 
3162   case Bytecodes::_iinc:        // Increment local
3163     i = iter().get_index();     // Get local index
3164     set_local( i, _gvn.transform( new AddINode( _gvn.intcon(iter().get_iinc_con()), local(i) ) ) );
3165     break;
3166 
3167   // Exit points of synchronized methods must have an unlock node
3168   case Bytecodes::_return:
3169     return_current(NULL);
3170     break;
3171 
3172   case Bytecodes::_ireturn:
3173   case Bytecodes::_areturn:
3174   case Bytecodes::_freturn:
3175     return_current(pop());
3176     break;
3177   case Bytecodes::_lreturn:
3178     return_current(pop_pair());
3179     break;
3180   case Bytecodes::_dreturn:
3181     return_current(pop_pair());
3182     break;
3183 
3184   case Bytecodes::_athrow:
3185     // null exception oop throws NULL pointer exception
3186     null_check(peek());
3187     if (stopped())  return;
3188     // Hook the thrown exception directly to subsequent handlers.
3189     if (BailoutToInterpreterForThrows) {
3190       // Keep method interpreted from now on.
3191       uncommon_trap(Deoptimization::Reason_unhandled,
3192                     Deoptimization::Action_make_not_compilable);
3193       return;
3194     }
3195     if (env()->jvmti_can_post_on_exceptions()) {
3196       // check if we must post exception events, take uncommon trap if so (with must_throw = false)
3197       uncommon_trap_if_should_post_on_exceptions(Deoptimization::Reason_unhandled, false);
3198     }
3199     // Here if either can_post_on_exceptions or should_post_on_exceptions is false
3200     add_exception_state(make_exception_state(peek()));
3201     break;
3202 
3203   case Bytecodes::_goto:   // fall through
3204   case Bytecodes::_goto_w: {
3205     int target_bci = (bc() == Bytecodes::_goto) ? iter().get_dest() : iter().get_far_dest();
3206 
3207     // If this is a backwards branch in the bytecodes, add Safepoint
3208     maybe_add_safepoint(target_bci);
3209 
3210     // Update method data
3211     profile_taken_branch(target_bci);
3212 
3213     // Merge the current control into the target basic block
3214     merge(target_bci);
3215 
3216     // See if we can get some profile data and hand it off to the next block
3217     Block *target_block = block()->successor_for_bci(target_bci);
3218     if (target_block->pred_count() != 1)  break;
3219     ciMethodData* methodData = method()->method_data();
3220     if (!methodData->is_mature())  break;
3221     ciProfileData* data = methodData->bci_to_data(bci());
3222     assert(data != NULL && data->is_JumpData(), "need JumpData for taken branch");
3223     int taken = ((ciJumpData*)data)->taken();
3224     taken = method()->scale_count(taken);
3225     target_block->set_count(taken);
3226     break;
3227   }
3228 
3229   case Bytecodes::_ifnull:    btest = BoolTest::eq; goto handle_if_null;
3230   case Bytecodes::_ifnonnull: btest = BoolTest::ne; goto handle_if_null;
3231   handle_if_null:
3232     // If this is a backwards branch in the bytecodes, add Safepoint
3233     maybe_add_safepoint(iter().get_dest());
3234     a = null();
3235     b = pop();
3236     if (b->is_ValueType()) {
3237       // Return constant false because 'b' is always non-null
3238       c = _gvn.makecon(TypeInt::CC_GT);
3239     } else {
3240       if (!_gvn.type(b)->speculative_maybe_null() &&
3241           !too_many_traps(Deoptimization::Reason_speculate_null_check)) {
3242         inc_sp(1);
3243         Node* null_ctl = top();
3244         b = null_check_oop(b, &null_ctl, true, true, true);
3245         assert(null_ctl->is_top(), "no null control here");
3246         dec_sp(1);
3247       } else if (_gvn.type(b)->speculative_always_null() &&
3248                  !too_many_traps(Deoptimization::Reason_speculate_null_assert)) {
3249         inc_sp(1);
3250         b = null_assert(b);
3251         dec_sp(1);
3252       }
3253       c = _gvn.transform( new CmpPNode(b, a) );
3254     }
3255     do_ifnull(btest, c);
3256     break;
3257 
3258   case Bytecodes::_if_acmpeq: btest = BoolTest::eq; goto handle_if_acmp;
3259   case Bytecodes::_if_acmpne: btest = BoolTest::ne; goto handle_if_acmp;
3260   handle_if_acmp:
3261     // If this is a backwards branch in the bytecodes, add Safepoint
3262     maybe_add_safepoint(iter().get_dest());
3263     a = access_resolve(pop(), 0);
3264     b = access_resolve(pop(), 0);
3265     do_acmp(btest, a, b);
3266     break;
3267 
3268   case Bytecodes::_ifeq: btest = BoolTest::eq; goto handle_ifxx;
3269   case Bytecodes::_ifne: btest = BoolTest::ne; goto handle_ifxx;
3270   case Bytecodes::_iflt: btest = BoolTest::lt; goto handle_ifxx;
3271   case Bytecodes::_ifle: btest = BoolTest::le; goto handle_ifxx;
3272   case Bytecodes::_ifgt: btest = BoolTest::gt; goto handle_ifxx;
3273   case Bytecodes::_ifge: btest = BoolTest::ge; goto handle_ifxx;
3274   handle_ifxx:
3275     // If this is a backwards branch in the bytecodes, add Safepoint
3276     maybe_add_safepoint(iter().get_dest());
3277     a = _gvn.intcon(0);
3278     b = pop();
3279     c = _gvn.transform( new CmpINode(b, a) );
3280     do_if(btest, c);
3281     break;
3282 
3283   case Bytecodes::_if_icmpeq: btest = BoolTest::eq; goto handle_if_icmp;
3284   case Bytecodes::_if_icmpne: btest = BoolTest::ne; goto handle_if_icmp;
3285   case Bytecodes::_if_icmplt: btest = BoolTest::lt; goto handle_if_icmp;
3286   case Bytecodes::_if_icmple: btest = BoolTest::le; goto handle_if_icmp;
3287   case Bytecodes::_if_icmpgt: btest = BoolTest::gt; goto handle_if_icmp;
3288   case Bytecodes::_if_icmpge: btest = BoolTest::ge; goto handle_if_icmp;
3289   handle_if_icmp:
3290     // If this is a backwards branch in the bytecodes, add Safepoint
3291     maybe_add_safepoint(iter().get_dest());
3292     a = pop();
3293     b = pop();
3294     c = _gvn.transform( new CmpINode( b, a ) );
3295     do_if(btest, c);
3296     break;
3297 
3298   case Bytecodes::_tableswitch:
3299     do_tableswitch();
3300     break;
3301 
3302   case Bytecodes::_lookupswitch:
3303     do_lookupswitch();
3304     break;
3305 
3306   case Bytecodes::_invokestatic:
3307   case Bytecodes::_invokedynamic:
3308   case Bytecodes::_invokespecial:
3309   case Bytecodes::_invokevirtual:
3310   case Bytecodes::_invokeinterface:
3311     do_call();
3312     break;
3313   case Bytecodes::_checkcast:
3314     do_checkcast();
3315     break;
3316   case Bytecodes::_instanceof:
3317     do_instanceof();
3318     break;
3319   case Bytecodes::_anewarray:
3320     do_newarray();
3321     break;
3322   case Bytecodes::_newarray:
3323     do_newarray((BasicType)iter().get_index());
3324     break;
3325   case Bytecodes::_multianewarray:
3326     do_multianewarray();
3327     break;
3328   case Bytecodes::_new:
3329     do_new();
3330     break;
3331   case Bytecodes::_defaultvalue:
3332     do_defaultvalue();
3333     break;
3334   case Bytecodes::_withfield:
3335     do_withfield();
3336     break;
3337 
3338   case Bytecodes::_jsr:
3339   case Bytecodes::_jsr_w:
3340     do_jsr();
3341     break;
3342 
3343   case Bytecodes::_ret:
3344     do_ret();
3345     break;
3346 
3347 
3348   case Bytecodes::_monitorenter:
3349     do_monitor_enter();
3350     break;
3351 
3352   case Bytecodes::_monitorexit:
3353     do_monitor_exit();
3354     break;
3355 
3356   case Bytecodes::_breakpoint:
3357     // Breakpoint set concurrently to compile
3358     // %%% use an uncommon trap?
3359     C->record_failure("breakpoint in method");
3360     return;
3361 
3362   default:
3363 #ifndef PRODUCT
3364     map()->dump(99);
3365 #endif
3366     tty->print("\nUnhandled bytecode %s\n", Bytecodes::name(bc()) );
3367     ShouldNotReachHere();
3368   }
3369 
3370 #ifndef PRODUCT
3371   IdealGraphPrinter *printer = C->printer();
3372   if (printer && printer->should_print(1)) {
3373     char buffer[256];
3374     jio_snprintf(buffer, sizeof(buffer), "Bytecode %d: %s", bci(), Bytecodes::name(bc()));
3375     bool old = printer->traverse_outs();
3376     printer->set_traverse_outs(true);
3377     printer->print_method(buffer, 4);
3378     printer->set_traverse_outs(old);
3379   }
3380 #endif
3381 }