1 /*
   2  * Copyright (c) 2005, 2024, 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 "c1/c1_Compilation.hpp"
  27 #include "c1/c1_Defs.hpp"
  28 #include "c1/c1_FrameMap.hpp"
  29 #include "c1/c1_Instruction.hpp"
  30 #include "c1/c1_LIRAssembler.hpp"
  31 #include "c1/c1_LIRGenerator.hpp"
  32 #include "c1/c1_ValueStack.hpp"
  33 #include "ci/ciArrayKlass.hpp"
  34 #include "ci/ciFlatArrayKlass.hpp"
  35 #include "ci/ciInlineKlass.hpp"
  36 #include "ci/ciInstance.hpp"
  37 #include "ci/ciObjArray.hpp"
  38 #include "ci/ciUtilities.hpp"
  39 #include "compiler/compilerDefinitions.inline.hpp"
  40 #include "compiler/compilerOracle.hpp"
  41 #include "gc/shared/barrierSet.hpp"
  42 #include "gc/shared/c1/barrierSetC1.hpp"
  43 #include "oops/klass.inline.hpp"
  44 #include "oops/methodCounters.hpp"
  45 #include "runtime/sharedRuntime.hpp"
  46 #include "runtime/stubRoutines.hpp"
  47 #include "runtime/vm_version.hpp"
  48 #include "utilities/bitMap.inline.hpp"
  49 #include "utilities/macros.hpp"
  50 #include "utilities/powerOfTwo.hpp"
  51 
  52 #ifdef ASSERT
  53 #define __ gen()->lir(__FILE__, __LINE__)->
  54 #else
  55 #define __ gen()->lir()->
  56 #endif
  57 
  58 #ifndef PATCHED_ADDR
  59 #define PATCHED_ADDR  (max_jint)
  60 #endif
  61 
  62 void PhiResolverState::reset() {
  63   _virtual_operands.clear();
  64   _other_operands.clear();
  65   _vreg_table.clear();
  66 }
  67 
  68 
  69 //--------------------------------------------------------------
  70 // PhiResolver
  71 
  72 // Resolves cycles:
  73 //
  74 //  r1 := r2  becomes  temp := r1
  75 //  r2 := r1           r1 := r2
  76 //                     r2 := temp
  77 // and orders moves:
  78 //
  79 //  r2 := r3  becomes  r1 := r2
  80 //  r1 := r2           r2 := r3
  81 
  82 PhiResolver::PhiResolver(LIRGenerator* gen)
  83  : _gen(gen)
  84  , _state(gen->resolver_state())
  85  , _loop(nullptr)
  86  , _temp(LIR_OprFact::illegalOpr)
  87 {
  88   // reinitialize the shared state arrays
  89   _state.reset();
  90 }
  91 
  92 
  93 void PhiResolver::emit_move(LIR_Opr src, LIR_Opr dest) {
  94   assert(src->is_valid(), "");
  95   assert(dest->is_valid(), "");
  96   __ move(src, dest);
  97 }
  98 
  99 
 100 void PhiResolver::move_temp_to(LIR_Opr dest) {
 101   assert(_temp->is_valid(), "");
 102   emit_move(_temp, dest);
 103   NOT_PRODUCT(_temp = LIR_OprFact::illegalOpr);
 104 }
 105 
 106 
 107 void PhiResolver::move_to_temp(LIR_Opr src) {
 108   assert(_temp->is_illegal(), "");
 109   _temp = _gen->new_register(src->type());
 110   emit_move(src, _temp);
 111 }
 112 
 113 
 114 // Traverse assignment graph in depth first order and generate moves in post order
 115 // ie. two assignments: b := c, a := b start with node c:
 116 // Call graph: move(null, c) -> move(c, b) -> move(b, a)
 117 // Generates moves in this order: move b to a and move c to b
 118 // ie. cycle a := b, b := a start with node a
 119 // Call graph: move(null, a) -> move(a, b) -> move(b, a)
 120 // Generates moves in this order: move b to temp, move a to b, move temp to a
 121 void PhiResolver::move(ResolveNode* src, ResolveNode* dest) {
 122   if (!dest->visited()) {
 123     dest->set_visited();
 124     for (int i = dest->no_of_destinations()-1; i >= 0; i --) {
 125       move(dest, dest->destination_at(i));
 126     }
 127   } else if (!dest->start_node()) {
 128     // cylce in graph detected
 129     assert(_loop == nullptr, "only one loop valid!");
 130     _loop = dest;
 131     move_to_temp(src->operand());
 132     return;
 133   } // else dest is a start node
 134 
 135   if (!dest->assigned()) {
 136     if (_loop == dest) {
 137       move_temp_to(dest->operand());
 138       dest->set_assigned();
 139     } else if (src != nullptr) {
 140       emit_move(src->operand(), dest->operand());
 141       dest->set_assigned();
 142     }
 143   }
 144 }
 145 
 146 
 147 PhiResolver::~PhiResolver() {
 148   int i;
 149   // resolve any cycles in moves from and to virtual registers
 150   for (i = virtual_operands().length() - 1; i >= 0; i --) {
 151     ResolveNode* node = virtual_operands().at(i);
 152     if (!node->visited()) {
 153       _loop = nullptr;
 154       move(nullptr, node);
 155       node->set_start_node();
 156       assert(_temp->is_illegal(), "move_temp_to() call missing");
 157     }
 158   }
 159 
 160   // generate move for move from non virtual register to abitrary destination
 161   for (i = other_operands().length() - 1; i >= 0; i --) {
 162     ResolveNode* node = other_operands().at(i);
 163     for (int j = node->no_of_destinations() - 1; j >= 0; j --) {
 164       emit_move(node->operand(), node->destination_at(j)->operand());
 165     }
 166   }
 167 }
 168 
 169 
 170 ResolveNode* PhiResolver::create_node(LIR_Opr opr, bool source) {
 171   ResolveNode* node;
 172   if (opr->is_virtual()) {
 173     int vreg_num = opr->vreg_number();
 174     node = vreg_table().at_grow(vreg_num, nullptr);
 175     assert(node == nullptr || node->operand() == opr, "");
 176     if (node == nullptr) {
 177       node = new ResolveNode(opr);
 178       vreg_table().at_put(vreg_num, node);
 179     }
 180     // Make sure that all virtual operands show up in the list when
 181     // they are used as the source of a move.
 182     if (source && !virtual_operands().contains(node)) {
 183       virtual_operands().append(node);
 184     }
 185   } else {
 186     assert(source, "");
 187     node = new ResolveNode(opr);
 188     other_operands().append(node);
 189   }
 190   return node;
 191 }
 192 
 193 
 194 void PhiResolver::move(LIR_Opr src, LIR_Opr dest) {
 195   assert(dest->is_virtual(), "");
 196   // tty->print("move "); src->print(); tty->print(" to "); dest->print(); tty->cr();
 197   assert(src->is_valid(), "");
 198   assert(dest->is_valid(), "");
 199   ResolveNode* source = source_node(src);
 200   source->append(destination_node(dest));
 201 }
 202 
 203 
 204 //--------------------------------------------------------------
 205 // LIRItem
 206 
 207 void LIRItem::set_result(LIR_Opr opr) {
 208   assert(value()->operand()->is_illegal() || value()->operand()->is_constant(), "operand should never change");
 209   value()->set_operand(opr);
 210 
 211 #ifdef ASSERT
 212   if (opr->is_virtual()) {
 213     _gen->_instruction_for_operand.at_put_grow(opr->vreg_number(), value(), nullptr);
 214   }
 215 #endif
 216 
 217   _result = opr;
 218 }
 219 
 220 void LIRItem::load_item() {
 221   assert(!_gen->in_conditional_code(), "LIRItem cannot be loaded in conditional code");
 222 
 223   if (result()->is_illegal()) {
 224     // update the items result
 225     _result = value()->operand();
 226   }
 227   if (!result()->is_register()) {
 228     LIR_Opr reg = _gen->new_register(value()->type());
 229     __ move(result(), reg);
 230     if (result()->is_constant()) {
 231       _result = reg;
 232     } else {
 233       set_result(reg);
 234     }
 235   }
 236 }
 237 
 238 
 239 void LIRItem::load_for_store(BasicType type) {
 240   if (_gen->can_store_as_constant(value(), type)) {
 241     _result = value()->operand();
 242     if (!_result->is_constant()) {
 243       _result = LIR_OprFact::value_type(value()->type());
 244     }
 245   } else if (type == T_BYTE || type == T_BOOLEAN) {
 246     load_byte_item();
 247   } else {
 248     load_item();
 249   }
 250 }
 251 
 252 void LIRItem::load_item_force(LIR_Opr reg) {
 253   LIR_Opr r = result();
 254   if (r != reg) {
 255 #if !defined(ARM) && !defined(E500V2)
 256     if (r->type() != reg->type()) {
 257       // moves between different types need an intervening spill slot
 258       r = _gen->force_to_spill(r, reg->type());
 259     }
 260 #endif
 261     __ move(r, reg);
 262     _result = reg;
 263   }
 264 }
 265 
 266 ciObject* LIRItem::get_jobject_constant() const {
 267   ObjectType* oc = type()->as_ObjectType();
 268   if (oc) {
 269     return oc->constant_value();
 270   }
 271   return nullptr;
 272 }
 273 
 274 
 275 jint LIRItem::get_jint_constant() const {
 276   assert(is_constant() && value() != nullptr, "");
 277   assert(type()->as_IntConstant() != nullptr, "type check");
 278   return type()->as_IntConstant()->value();
 279 }
 280 
 281 
 282 jint LIRItem::get_address_constant() const {
 283   assert(is_constant() && value() != nullptr, "");
 284   assert(type()->as_AddressConstant() != nullptr, "type check");
 285   return type()->as_AddressConstant()->value();
 286 }
 287 
 288 
 289 jfloat LIRItem::get_jfloat_constant() const {
 290   assert(is_constant() && value() != nullptr, "");
 291   assert(type()->as_FloatConstant() != nullptr, "type check");
 292   return type()->as_FloatConstant()->value();
 293 }
 294 
 295 
 296 jdouble LIRItem::get_jdouble_constant() const {
 297   assert(is_constant() && value() != nullptr, "");
 298   assert(type()->as_DoubleConstant() != nullptr, "type check");
 299   return type()->as_DoubleConstant()->value();
 300 }
 301 
 302 
 303 jlong LIRItem::get_jlong_constant() const {
 304   assert(is_constant() && value() != nullptr, "");
 305   assert(type()->as_LongConstant() != nullptr, "type check");
 306   return type()->as_LongConstant()->value();
 307 }
 308 
 309 
 310 
 311 //--------------------------------------------------------------
 312 
 313 
 314 void LIRGenerator::block_do_prolog(BlockBegin* block) {
 315 #ifndef PRODUCT
 316   if (PrintIRWithLIR) {
 317     block->print();
 318   }
 319 #endif
 320 
 321   // set up the list of LIR instructions
 322   assert(block->lir() == nullptr, "LIR list already computed for this block");
 323   _lir = new LIR_List(compilation(), block);
 324   block->set_lir(_lir);
 325 
 326   __ branch_destination(block->label());
 327 
 328   if (LIRTraceExecution &&
 329       Compilation::current()->hir()->start()->block_id() != block->block_id() &&
 330       !block->is_set(BlockBegin::exception_entry_flag)) {
 331     assert(block->lir()->instructions_list()->length() == 1, "should come right after br_dst");
 332     trace_block_entry(block);
 333   }
 334 }
 335 
 336 
 337 void LIRGenerator::block_do_epilog(BlockBegin* block) {
 338 #ifndef PRODUCT
 339   if (PrintIRWithLIR) {
 340     tty->cr();
 341   }
 342 #endif
 343 
 344   // LIR_Opr for unpinned constants shouldn't be referenced by other
 345   // blocks so clear them out after processing the block.
 346   for (int i = 0; i < _unpinned_constants.length(); i++) {
 347     _unpinned_constants.at(i)->clear_operand();
 348   }
 349   _unpinned_constants.trunc_to(0);
 350 
 351   // clear our any registers for other local constants
 352   _constants.trunc_to(0);
 353   _reg_for_constants.trunc_to(0);
 354 }
 355 
 356 
 357 void LIRGenerator::block_do(BlockBegin* block) {
 358   CHECK_BAILOUT();
 359 
 360   block_do_prolog(block);
 361   set_block(block);
 362 
 363   for (Instruction* instr = block; instr != nullptr; instr = instr->next()) {
 364     if (instr->is_pinned()) do_root(instr);
 365   }
 366 
 367   set_block(nullptr);
 368   block_do_epilog(block);
 369 }
 370 
 371 
 372 //-------------------------LIRGenerator-----------------------------
 373 
 374 // This is where the tree-walk starts; instr must be root;
 375 void LIRGenerator::do_root(Value instr) {
 376   CHECK_BAILOUT();
 377 
 378   InstructionMark im(compilation(), instr);
 379 
 380   assert(instr->is_pinned(), "use only with roots");
 381   assert(instr->subst() == instr, "shouldn't have missed substitution");
 382 
 383   instr->visit(this);
 384 
 385   assert(!instr->has_uses() || instr->operand()->is_valid() ||
 386          instr->as_Constant() != nullptr || bailed_out(), "invalid item set");
 387 }
 388 
 389 
 390 // This is called for each node in tree; the walk stops if a root is reached
 391 void LIRGenerator::walk(Value instr) {
 392   InstructionMark im(compilation(), instr);
 393   //stop walk when encounter a root
 394   if ((instr->is_pinned() && instr->as_Phi() == nullptr) || instr->operand()->is_valid()) {
 395     assert(instr->operand() != LIR_OprFact::illegalOpr || instr->as_Constant() != nullptr, "this root has not yet been visited");
 396   } else {
 397     assert(instr->subst() == instr, "shouldn't have missed substitution");
 398     instr->visit(this);
 399     // assert(instr->use_count() > 0 || instr->as_Phi() != nullptr, "leaf instruction must have a use");
 400   }
 401 }
 402 
 403 
 404 CodeEmitInfo* LIRGenerator::state_for(Instruction* x, ValueStack* state, bool ignore_xhandler) {
 405   assert(state != nullptr, "state must be defined");
 406 
 407 #ifndef PRODUCT
 408   state->verify();
 409 #endif
 410 
 411   ValueStack* s = state;
 412   for_each_state(s) {
 413     if (s->kind() == ValueStack::EmptyExceptionState ||
 414         s->kind() == ValueStack::CallerEmptyExceptionState)
 415     {
 416 #ifdef ASSERT
 417       int index;
 418       Value value;
 419       for_each_stack_value(s, index, value) {
 420         fatal("state must be empty");
 421       }
 422       for_each_local_value(s, index, value) {
 423         fatal("state must be empty");
 424       }
 425 #endif
 426       assert(s->locks_size() == 0 || s->locks_size() == 1, "state must be empty");
 427       continue;
 428     }
 429 
 430     int index;
 431     Value value;
 432     for_each_stack_value(s, index, value) {
 433       assert(value->subst() == value, "missed substitution");
 434       if (!value->is_pinned() && value->as_Constant() == nullptr && value->as_Local() == nullptr) {
 435         walk(value);
 436         assert(value->operand()->is_valid(), "must be evaluated now");
 437       }
 438     }
 439 
 440     int bci = s->bci();
 441     IRScope* scope = s->scope();
 442     ciMethod* method = scope->method();
 443 
 444     MethodLivenessResult liveness = method->liveness_at_bci(bci);
 445     if (bci == SynchronizationEntryBCI) {
 446       if (x->as_ExceptionObject() || x->as_Throw()) {
 447         // all locals are dead on exit from the synthetic unlocker
 448         liveness.clear();
 449       } else {
 450         assert(x->as_MonitorEnter() || x->as_ProfileInvoke(), "only other cases are MonitorEnter and ProfileInvoke");
 451       }
 452     }
 453     if (!liveness.is_valid()) {
 454       // Degenerate or breakpointed method.
 455       bailout("Degenerate or breakpointed method");
 456     } else {
 457       assert((int)liveness.size() == s->locals_size(), "error in use of liveness");
 458       for_each_local_value(s, index, value) {
 459         assert(value->subst() == value, "missed substitution");
 460         if (liveness.at(index) && !value->type()->is_illegal()) {
 461           if (!value->is_pinned() && value->as_Constant() == nullptr && value->as_Local() == nullptr) {
 462             walk(value);
 463             assert(value->operand()->is_valid(), "must be evaluated now");
 464           }
 465         } else {
 466           // null out this local so that linear scan can assume that all non-null values are live.
 467           s->invalidate_local(index);
 468         }
 469       }
 470     }
 471   }
 472 
 473   return new CodeEmitInfo(state, ignore_xhandler ? nullptr : x->exception_handlers(), x->check_flag(Instruction::DeoptimizeOnException));
 474 }
 475 
 476 
 477 CodeEmitInfo* LIRGenerator::state_for(Instruction* x) {
 478   return state_for(x, x->exception_state());
 479 }
 480 
 481 
 482 void LIRGenerator::klass2reg_with_patching(LIR_Opr r, ciMetadata* obj, CodeEmitInfo* info, bool need_resolve) {
 483   /* C2 relies on constant pool entries being resolved (ciTypeFlow), so if tiered compilation
 484    * is active and the class hasn't yet been resolved we need to emit a patch that resolves
 485    * the class. */
 486   if ((!CompilerConfig::is_c1_only_no_jvmci() && need_resolve) || !obj->is_loaded() || PatchALot) {
 487     assert(info != nullptr, "info must be set if class is not loaded");
 488     __ klass2reg_patch(nullptr, r, info);
 489   } else {
 490     // no patching needed
 491     __ metadata2reg(obj->constant_encoding(), r);
 492   }
 493 }
 494 
 495 
 496 void LIRGenerator::array_range_check(LIR_Opr array, LIR_Opr index,
 497                                     CodeEmitInfo* null_check_info, CodeEmitInfo* range_check_info) {
 498   CodeStub* stub = new RangeCheckStub(range_check_info, index, array);
 499   if (index->is_constant()) {
 500     cmp_mem_int(lir_cond_belowEqual, array, arrayOopDesc::length_offset_in_bytes(),
 501                 index->as_jint(), null_check_info);
 502     __ branch(lir_cond_belowEqual, stub); // forward branch
 503   } else {
 504     cmp_reg_mem(lir_cond_aboveEqual, index, array,
 505                 arrayOopDesc::length_offset_in_bytes(), T_INT, null_check_info);
 506     __ branch(lir_cond_aboveEqual, stub); // forward branch
 507   }
 508 }
 509 
 510 void LIRGenerator::arithmetic_op(Bytecodes::Code code, LIR_Opr result, LIR_Opr left, LIR_Opr right, LIR_Opr tmp_op, CodeEmitInfo* info) {
 511   LIR_Opr result_op = result;
 512   LIR_Opr left_op   = left;
 513   LIR_Opr right_op  = right;
 514 
 515   if (two_operand_lir_form && left_op != result_op) {
 516     assert(right_op != result_op, "malformed");
 517     __ move(left_op, result_op);
 518     left_op = result_op;
 519   }
 520 
 521   switch(code) {
 522     case Bytecodes::_dadd:
 523     case Bytecodes::_fadd:
 524     case Bytecodes::_ladd:
 525     case Bytecodes::_iadd:  __ add(left_op, right_op, result_op); break;
 526     case Bytecodes::_fmul:
 527     case Bytecodes::_lmul:  __ mul(left_op, right_op, result_op); break;
 528 
 529     case Bytecodes::_dmul:  __ mul(left_op, right_op, result_op, tmp_op); break;
 530 
 531     case Bytecodes::_imul:
 532       {
 533         bool did_strength_reduce = false;
 534 
 535         if (right->is_constant()) {
 536           jint c = right->as_jint();
 537           if (c > 0 && is_power_of_2(c)) {
 538             // do not need tmp here
 539             __ shift_left(left_op, exact_log2(c), result_op);
 540             did_strength_reduce = true;
 541           } else {
 542             did_strength_reduce = strength_reduce_multiply(left_op, c, result_op, tmp_op);
 543           }
 544         }
 545         // we couldn't strength reduce so just emit the multiply
 546         if (!did_strength_reduce) {
 547           __ mul(left_op, right_op, result_op);
 548         }
 549       }
 550       break;
 551 
 552     case Bytecodes::_dsub:
 553     case Bytecodes::_fsub:
 554     case Bytecodes::_lsub:
 555     case Bytecodes::_isub: __ sub(left_op, right_op, result_op); break;
 556 
 557     case Bytecodes::_fdiv: __ div (left_op, right_op, result_op); break;
 558     // ldiv and lrem are implemented with a direct runtime call
 559 
 560     case Bytecodes::_ddiv: __ div(left_op, right_op, result_op, tmp_op); break;
 561 
 562     case Bytecodes::_drem:
 563     case Bytecodes::_frem: __ rem (left_op, right_op, result_op); break;
 564 
 565     default: ShouldNotReachHere();
 566   }
 567 }
 568 
 569 
 570 void LIRGenerator::arithmetic_op_int(Bytecodes::Code code, LIR_Opr result, LIR_Opr left, LIR_Opr right, LIR_Opr tmp) {
 571   arithmetic_op(code, result, left, right, tmp);
 572 }
 573 
 574 
 575 void LIRGenerator::arithmetic_op_long(Bytecodes::Code code, LIR_Opr result, LIR_Opr left, LIR_Opr right, CodeEmitInfo* info) {
 576   arithmetic_op(code, result, left, right, LIR_OprFact::illegalOpr, info);
 577 }
 578 
 579 
 580 void LIRGenerator::arithmetic_op_fpu(Bytecodes::Code code, LIR_Opr result, LIR_Opr left, LIR_Opr right, LIR_Opr tmp) {
 581   arithmetic_op(code, result, left, right, tmp);
 582 }
 583 
 584 
 585 void LIRGenerator::shift_op(Bytecodes::Code code, LIR_Opr result_op, LIR_Opr value, LIR_Opr count, LIR_Opr tmp) {
 586 
 587   if (two_operand_lir_form && value != result_op
 588       // Only 32bit right shifts require two operand form on S390.
 589       S390_ONLY(&& (code == Bytecodes::_ishr || code == Bytecodes::_iushr))) {
 590     assert(count != result_op, "malformed");
 591     __ move(value, result_op);
 592     value = result_op;
 593   }
 594 
 595   assert(count->is_constant() || count->is_register(), "must be");
 596   switch(code) {
 597   case Bytecodes::_ishl:
 598   case Bytecodes::_lshl: __ shift_left(value, count, result_op, tmp); break;
 599   case Bytecodes::_ishr:
 600   case Bytecodes::_lshr: __ shift_right(value, count, result_op, tmp); break;
 601   case Bytecodes::_iushr:
 602   case Bytecodes::_lushr: __ unsigned_shift_right(value, count, result_op, tmp); break;
 603   default: ShouldNotReachHere();
 604   }
 605 }
 606 
 607 
 608 void LIRGenerator::logic_op (Bytecodes::Code code, LIR_Opr result_op, LIR_Opr left_op, LIR_Opr right_op) {
 609   if (two_operand_lir_form && left_op != result_op) {
 610     assert(right_op != result_op, "malformed");
 611     __ move(left_op, result_op);
 612     left_op = result_op;
 613   }
 614 
 615   switch(code) {
 616     case Bytecodes::_iand:
 617     case Bytecodes::_land:  __ logical_and(left_op, right_op, result_op); break;
 618 
 619     case Bytecodes::_ior:
 620     case Bytecodes::_lor:   __ logical_or(left_op, right_op, result_op);  break;
 621 
 622     case Bytecodes::_ixor:
 623     case Bytecodes::_lxor:  __ logical_xor(left_op, right_op, result_op); break;
 624 
 625     default: ShouldNotReachHere();
 626   }
 627 }
 628 
 629 
 630 void LIRGenerator::monitor_enter(LIR_Opr object, LIR_Opr lock, LIR_Opr hdr, LIR_Opr scratch, int monitor_no,
 631                                  CodeEmitInfo* info_for_exception, CodeEmitInfo* info, CodeStub* throw_ie_stub) {
 632   if (!GenerateSynchronizationCode) return;
 633   // for slow path, use debug info for state after successful locking
 634   CodeStub* slow_path = new MonitorEnterStub(object, lock, info, throw_ie_stub, scratch);
 635   __ load_stack_address_monitor(monitor_no, lock);
 636   // for handling NullPointerException, use debug info representing just the lock stack before this monitorenter
 637   __ lock_object(hdr, object, lock, scratch, slow_path, info_for_exception, throw_ie_stub);
 638 }
 639 
 640 
 641 void LIRGenerator::monitor_exit(LIR_Opr object, LIR_Opr lock, LIR_Opr new_hdr, LIR_Opr scratch, int monitor_no) {
 642   if (!GenerateSynchronizationCode) return;
 643   // setup registers
 644   LIR_Opr hdr = lock;
 645   lock = new_hdr;
 646   CodeStub* slow_path = new MonitorExitStub(lock, LockingMode != LM_MONITOR, monitor_no);
 647   __ load_stack_address_monitor(monitor_no, lock);
 648   __ unlock_object(hdr, object, lock, scratch, slow_path);
 649 }
 650 
 651 #ifndef PRODUCT
 652 void LIRGenerator::print_if_not_loaded(const NewInstance* new_instance) {
 653   if (PrintNotLoaded && !new_instance->klass()->is_loaded()) {
 654     tty->print_cr("   ###class not loaded at new bci %d", new_instance->printable_bci());
 655   } else if (PrintNotLoaded && (!CompilerConfig::is_c1_only_no_jvmci() && new_instance->is_unresolved())) {
 656     tty->print_cr("   ###class not resolved at new bci %d", new_instance->printable_bci());
 657   }
 658 }
 659 #endif
 660 
 661 void LIRGenerator::new_instance(LIR_Opr dst, ciInstanceKlass* klass, bool is_unresolved, bool allow_inline, LIR_Opr scratch1, LIR_Opr scratch2, LIR_Opr scratch3, LIR_Opr scratch4, LIR_Opr klass_reg, CodeEmitInfo* info) {
 662   if (allow_inline) {
 663     assert(!is_unresolved && klass->is_loaded(), "inline type klass should be resolved");
 664     __ metadata2reg(klass->constant_encoding(), klass_reg);
 665   } else {
 666     klass2reg_with_patching(klass_reg, klass, info, is_unresolved);
 667   }
 668   // If klass is not loaded we do not know if the klass has finalizers or is an unexpected inline klass
 669   if (UseFastNewInstance && klass->is_loaded() && (allow_inline || !klass->is_inlinetype())
 670       && !Klass::layout_helper_needs_slow_path(klass->layout_helper())) {
 671 
 672     Runtime1::StubID stub_id = klass->is_initialized() ? Runtime1::fast_new_instance_id : Runtime1::fast_new_instance_init_check_id;
 673 
 674     CodeStub* slow_path = new NewInstanceStub(klass_reg, dst, klass, info, stub_id);
 675 
 676     assert(klass->is_loaded(), "must be loaded");
 677     // allocate space for instance
 678     assert(klass->size_helper() > 0, "illegal instance size");
 679     const int instance_size = align_object_size(klass->size_helper());
 680     __ allocate_object(dst, scratch1, scratch2, scratch3, scratch4,
 681                        oopDesc::header_size(), instance_size, klass_reg, !klass->is_initialized(), slow_path);
 682   } else {
 683     CodeStub* slow_path = new NewInstanceStub(klass_reg, dst, klass, info, Runtime1::new_instance_id);
 684     __ jump(slow_path);
 685     __ branch_destination(slow_path->continuation());
 686   }
 687 }
 688 
 689 
 690 static bool is_constant_zero(Instruction* inst) {
 691   IntConstant* c = inst->type()->as_IntConstant();
 692   if (c) {
 693     return (c->value() == 0);
 694   }
 695   return false;
 696 }
 697 
 698 
 699 static bool positive_constant(Instruction* inst) {
 700   IntConstant* c = inst->type()->as_IntConstant();
 701   if (c) {
 702     return (c->value() >= 0);
 703   }
 704   return false;
 705 }
 706 
 707 
 708 static ciArrayKlass* as_array_klass(ciType* type) {
 709   if (type != nullptr && type->is_array_klass() && type->is_loaded()) {
 710     return (ciArrayKlass*)type;
 711   } else {
 712     return nullptr;
 713   }
 714 }
 715 
 716 static ciType* phi_declared_type(Phi* phi) {
 717   ciType* t = phi->operand_at(0)->declared_type();
 718   if (t == nullptr) {
 719     return nullptr;
 720   }
 721   for(int i = 1; i < phi->operand_count(); i++) {
 722     if (t != phi->operand_at(i)->declared_type()) {
 723       return nullptr;
 724     }
 725   }
 726   return t;
 727 }
 728 
 729 void LIRGenerator::arraycopy_helper(Intrinsic* x, int* flagsp, ciArrayKlass** expected_typep) {
 730   Instruction* src     = x->argument_at(0);
 731   Instruction* src_pos = x->argument_at(1);
 732   Instruction* dst     = x->argument_at(2);
 733   Instruction* dst_pos = x->argument_at(3);
 734   Instruction* length  = x->argument_at(4);
 735 
 736   // first try to identify the likely type of the arrays involved
 737   ciArrayKlass* expected_type = nullptr;
 738   bool is_exact = false, src_objarray = false, dst_objarray = false;
 739   {
 740     ciArrayKlass* src_exact_type    = as_array_klass(src->exact_type());
 741     ciArrayKlass* src_declared_type = as_array_klass(src->declared_type());
 742     Phi* phi;
 743     if (src_declared_type == nullptr && (phi = src->as_Phi()) != nullptr) {
 744       src_declared_type = as_array_klass(phi_declared_type(phi));
 745     }
 746     ciArrayKlass* dst_exact_type    = as_array_klass(dst->exact_type());
 747     ciArrayKlass* dst_declared_type = as_array_klass(dst->declared_type());
 748     if (dst_declared_type == nullptr && (phi = dst->as_Phi()) != nullptr) {
 749       dst_declared_type = as_array_klass(phi_declared_type(phi));
 750     }
 751 
 752     if (src_exact_type != nullptr && src_exact_type == dst_exact_type) {
 753       // the types exactly match so the type is fully known
 754       is_exact = true;
 755       expected_type = src_exact_type;
 756     } else if (dst_exact_type != nullptr && dst_exact_type->is_obj_array_klass()) {
 757       ciArrayKlass* dst_type = (ciArrayKlass*) dst_exact_type;
 758       ciArrayKlass* src_type = nullptr;
 759       if (src_exact_type != nullptr && src_exact_type->is_obj_array_klass()) {
 760         src_type = (ciArrayKlass*) src_exact_type;
 761       } else if (src_declared_type != nullptr && src_declared_type->is_obj_array_klass()) {
 762         src_type = (ciArrayKlass*) src_declared_type;
 763       }
 764       if (src_type != nullptr) {
 765         if (src_type->element_type()->is_subtype_of(dst_type->element_type())) {
 766           is_exact = true;
 767           expected_type = dst_type;
 768         }
 769       }
 770     }
 771     // at least pass along a good guess
 772     if (expected_type == nullptr) expected_type = dst_exact_type;
 773     if (expected_type == nullptr) expected_type = src_declared_type;
 774     if (expected_type == nullptr) expected_type = dst_declared_type;
 775 
 776     src_objarray = (src_exact_type && src_exact_type->is_obj_array_klass()) || (src_declared_type && src_declared_type->is_obj_array_klass());
 777     dst_objarray = (dst_exact_type && dst_exact_type->is_obj_array_klass()) || (dst_declared_type && dst_declared_type->is_obj_array_klass());
 778   }
 779 
 780   // if a probable array type has been identified, figure out if any
 781   // of the required checks for a fast case can be elided.
 782   int flags = LIR_OpArrayCopy::all_flags;
 783 
 784   if (!src->is_loaded_flat_array() && !dst->is_loaded_flat_array()) {
 785     flags &= ~LIR_OpArrayCopy::always_slow_path;
 786   }
 787   if (!src->maybe_flat_array()) {
 788     flags &= ~LIR_OpArrayCopy::src_inlinetype_check;
 789   }
 790   if (!dst->maybe_flat_array() && !dst->maybe_null_free_array()) {
 791     flags &= ~LIR_OpArrayCopy::dst_inlinetype_check;
 792   }
 793 
 794   if (!src_objarray)
 795     flags &= ~LIR_OpArrayCopy::src_objarray;
 796   if (!dst_objarray)
 797     flags &= ~LIR_OpArrayCopy::dst_objarray;
 798 
 799   if (!x->arg_needs_null_check(0))
 800     flags &= ~LIR_OpArrayCopy::src_null_check;
 801   if (!x->arg_needs_null_check(2))
 802     flags &= ~LIR_OpArrayCopy::dst_null_check;
 803 
 804 
 805   if (expected_type != nullptr) {
 806     Value length_limit = nullptr;
 807 
 808     IfOp* ifop = length->as_IfOp();
 809     if (ifop != nullptr) {
 810       // look for expressions like min(v, a.length) which ends up as
 811       //   x > y ? y : x  or  x >= y ? y : x
 812       if ((ifop->cond() == If::gtr || ifop->cond() == If::geq) &&
 813           ifop->x() == ifop->fval() &&
 814           ifop->y() == ifop->tval()) {
 815         length_limit = ifop->y();
 816       }
 817     }
 818 
 819     // try to skip null checks and range checks
 820     NewArray* src_array = src->as_NewArray();
 821     if (src_array != nullptr) {
 822       flags &= ~LIR_OpArrayCopy::src_null_check;
 823       if (length_limit != nullptr &&
 824           src_array->length() == length_limit &&
 825           is_constant_zero(src_pos)) {
 826         flags &= ~LIR_OpArrayCopy::src_range_check;
 827       }
 828     }
 829 
 830     NewArray* dst_array = dst->as_NewArray();
 831     if (dst_array != nullptr) {
 832       flags &= ~LIR_OpArrayCopy::dst_null_check;
 833       if (length_limit != nullptr &&
 834           dst_array->length() == length_limit &&
 835           is_constant_zero(dst_pos)) {
 836         flags &= ~LIR_OpArrayCopy::dst_range_check;
 837       }
 838     }
 839 
 840     // check from incoming constant values
 841     if (positive_constant(src_pos))
 842       flags &= ~LIR_OpArrayCopy::src_pos_positive_check;
 843     if (positive_constant(dst_pos))
 844       flags &= ~LIR_OpArrayCopy::dst_pos_positive_check;
 845     if (positive_constant(length))
 846       flags &= ~LIR_OpArrayCopy::length_positive_check;
 847 
 848     // see if the range check can be elided, which might also imply
 849     // that src or dst is non-null.
 850     ArrayLength* al = length->as_ArrayLength();
 851     if (al != nullptr) {
 852       if (al->array() == src) {
 853         // it's the length of the source array
 854         flags &= ~LIR_OpArrayCopy::length_positive_check;
 855         flags &= ~LIR_OpArrayCopy::src_null_check;
 856         if (is_constant_zero(src_pos))
 857           flags &= ~LIR_OpArrayCopy::src_range_check;
 858       }
 859       if (al->array() == dst) {
 860         // it's the length of the destination array
 861         flags &= ~LIR_OpArrayCopy::length_positive_check;
 862         flags &= ~LIR_OpArrayCopy::dst_null_check;
 863         if (is_constant_zero(dst_pos))
 864           flags &= ~LIR_OpArrayCopy::dst_range_check;
 865       }
 866     }
 867     if (is_exact) {
 868       flags &= ~LIR_OpArrayCopy::type_check;
 869     }
 870   }
 871 
 872   IntConstant* src_int = src_pos->type()->as_IntConstant();
 873   IntConstant* dst_int = dst_pos->type()->as_IntConstant();
 874   if (src_int && dst_int) {
 875     int s_offs = src_int->value();
 876     int d_offs = dst_int->value();
 877     if (src_int->value() >= dst_int->value()) {
 878       flags &= ~LIR_OpArrayCopy::overlapping;
 879     }
 880     if (expected_type != nullptr) {
 881       BasicType t = expected_type->element_type()->basic_type();
 882       int element_size = type2aelembytes(t);
 883       if (((arrayOopDesc::base_offset_in_bytes(t) + (uint)s_offs * element_size) % HeapWordSize == 0) &&
 884           ((arrayOopDesc::base_offset_in_bytes(t) + (uint)d_offs * element_size) % HeapWordSize == 0)) {
 885         flags &= ~LIR_OpArrayCopy::unaligned;
 886       }
 887     }
 888   } else if (src_pos == dst_pos || is_constant_zero(dst_pos)) {
 889     // src and dest positions are the same, or dst is zero so assume
 890     // nonoverlapping copy.
 891     flags &= ~LIR_OpArrayCopy::overlapping;
 892   }
 893 
 894   if (src == dst) {
 895     // moving within a single array so no type checks are needed
 896     if (flags & LIR_OpArrayCopy::type_check) {
 897       flags &= ~LIR_OpArrayCopy::type_check;
 898     }
 899   }
 900   *flagsp = flags;
 901   *expected_typep = (ciArrayKlass*)expected_type;
 902 }
 903 
 904 
 905 LIR_Opr LIRGenerator::round_item(LIR_Opr opr) {
 906   assert(opr->is_register(), "why spill if item is not register?");
 907 
 908   if (strict_fp_requires_explicit_rounding) {
 909 #ifdef IA32
 910     if (UseSSE < 1 && opr->is_single_fpu()) {
 911       LIR_Opr result = new_register(T_FLOAT);
 912       set_vreg_flag(result, must_start_in_memory);
 913       assert(opr->is_register(), "only a register can be spilled");
 914       assert(opr->value_type()->is_float(), "rounding only for floats available");
 915       __ roundfp(opr, LIR_OprFact::illegalOpr, result);
 916       return result;
 917     }
 918 #else
 919     Unimplemented();
 920 #endif // IA32
 921   }
 922   return opr;
 923 }
 924 
 925 
 926 LIR_Opr LIRGenerator::force_to_spill(LIR_Opr value, BasicType t) {
 927   assert(type2size[t] == type2size[value->type()],
 928          "size mismatch: t=%s, value->type()=%s", type2name(t), type2name(value->type()));
 929   if (!value->is_register()) {
 930     // force into a register
 931     LIR_Opr r = new_register(value->type());
 932     __ move(value, r);
 933     value = r;
 934   }
 935 
 936   // create a spill location
 937   LIR_Opr tmp = new_register(t);
 938   set_vreg_flag(tmp, LIRGenerator::must_start_in_memory);
 939 
 940   // move from register to spill
 941   __ move(value, tmp);
 942   return tmp;
 943 }
 944 
 945 void LIRGenerator::profile_branch(If* if_instr, If::Condition cond) {
 946   if (if_instr->should_profile()) {
 947     ciMethod* method = if_instr->profiled_method();
 948     assert(method != nullptr, "method should be set if branch is profiled");
 949     ciMethodData* md = method->method_data_or_null();
 950     assert(md != nullptr, "Sanity");
 951     ciProfileData* data = md->bci_to_data(if_instr->profiled_bci());
 952     assert(data != nullptr, "must have profiling data");
 953     assert(data->is_BranchData(), "need BranchData for two-way branches");
 954     int taken_count_offset     = md->byte_offset_of_slot(data, BranchData::taken_offset());
 955     int not_taken_count_offset = md->byte_offset_of_slot(data, BranchData::not_taken_offset());
 956     if (if_instr->is_swapped()) {
 957       int t = taken_count_offset;
 958       taken_count_offset = not_taken_count_offset;
 959       not_taken_count_offset = t;
 960     }
 961 
 962     LIR_Opr md_reg = new_register(T_METADATA);
 963     __ metadata2reg(md->constant_encoding(), md_reg);
 964 
 965     LIR_Opr data_offset_reg = new_pointer_register();
 966     __ cmove(lir_cond(cond),
 967              LIR_OprFact::intptrConst(taken_count_offset),
 968              LIR_OprFact::intptrConst(not_taken_count_offset),
 969              data_offset_reg, as_BasicType(if_instr->x()->type()));
 970 
 971     // MDO cells are intptr_t, so the data_reg width is arch-dependent.
 972     LIR_Opr data_reg = new_pointer_register();
 973     LIR_Address* data_addr = new LIR_Address(md_reg, data_offset_reg, data_reg->type());
 974     __ move(data_addr, data_reg);
 975     // Use leal instead of add to avoid destroying condition codes on x86
 976     LIR_Address* fake_incr_value = new LIR_Address(data_reg, DataLayout::counter_increment, T_INT);
 977     __ leal(LIR_OprFact::address(fake_incr_value), data_reg);
 978     __ move(data_reg, data_addr);
 979   }
 980 }
 981 
 982 // Phi technique:
 983 // This is about passing live values from one basic block to the other.
 984 // In code generated with Java it is rather rare that more than one
 985 // value is on the stack from one basic block to the other.
 986 // We optimize our technique for efficient passing of one value
 987 // (of type long, int, double..) but it can be extended.
 988 // When entering or leaving a basic block, all registers and all spill
 989 // slots are release and empty. We use the released registers
 990 // and spill slots to pass the live values from one block
 991 // to the other. The topmost value, i.e., the value on TOS of expression
 992 // stack is passed in registers. All other values are stored in spilling
 993 // area. Every Phi has an index which designates its spill slot
 994 // At exit of a basic block, we fill the register(s) and spill slots.
 995 // At entry of a basic block, the block_prolog sets up the content of phi nodes
 996 // and locks necessary registers and spilling slots.
 997 
 998 
 999 // move current value to referenced phi function
1000 void LIRGenerator::move_to_phi(PhiResolver* resolver, Value cur_val, Value sux_val) {
1001   Phi* phi = sux_val->as_Phi();
1002   // cur_val can be null without phi being null in conjunction with inlining
1003   if (phi != nullptr && cur_val != nullptr && cur_val != phi && !phi->is_illegal()) {
1004     if (phi->is_local()) {
1005       for (int i = 0; i < phi->operand_count(); i++) {
1006         Value op = phi->operand_at(i);
1007         if (op != nullptr && op->type()->is_illegal()) {
1008           bailout("illegal phi operand");
1009         }
1010       }
1011     }
1012     Phi* cur_phi = cur_val->as_Phi();
1013     if (cur_phi != nullptr && cur_phi->is_illegal()) {
1014       // Phi and local would need to get invalidated
1015       // (which is unexpected for Linear Scan).
1016       // But this case is very rare so we simply bail out.
1017       bailout("propagation of illegal phi");
1018       return;
1019     }
1020     LIR_Opr operand = cur_val->operand();
1021     if (operand->is_illegal()) {
1022       assert(cur_val->as_Constant() != nullptr || cur_val->as_Local() != nullptr,
1023              "these can be produced lazily");
1024       operand = operand_for_instruction(cur_val);
1025     }
1026     resolver->move(operand, operand_for_instruction(phi));
1027   }
1028 }
1029 
1030 
1031 // Moves all stack values into their PHI position
1032 void LIRGenerator::move_to_phi(ValueStack* cur_state) {
1033   BlockBegin* bb = block();
1034   if (bb->number_of_sux() == 1) {
1035     BlockBegin* sux = bb->sux_at(0);
1036     assert(sux->number_of_preds() > 0, "invalid CFG");
1037 
1038     // a block with only one predecessor never has phi functions
1039     if (sux->number_of_preds() > 1) {
1040       PhiResolver resolver(this);
1041 
1042       ValueStack* sux_state = sux->state();
1043       Value sux_value;
1044       int index;
1045 
1046       assert(cur_state->scope() == sux_state->scope(), "not matching");
1047       assert(cur_state->locals_size() == sux_state->locals_size(), "not matching");
1048       assert(cur_state->stack_size() == sux_state->stack_size(), "not matching");
1049 
1050       for_each_stack_value(sux_state, index, sux_value) {
1051         move_to_phi(&resolver, cur_state->stack_at(index), sux_value);
1052       }
1053 
1054       for_each_local_value(sux_state, index, sux_value) {
1055         move_to_phi(&resolver, cur_state->local_at(index), sux_value);
1056       }
1057 
1058       assert(cur_state->caller_state() == sux_state->caller_state(), "caller states must be equal");
1059     }
1060   }
1061 }
1062 
1063 
1064 LIR_Opr LIRGenerator::new_register(BasicType type) {
1065   int vreg_num = _virtual_register_number;
1066   // Add a little fudge factor for the bailout since the bailout is only checked periodically. This allows us to hand out
1067   // a few extra registers before we really run out which helps to avoid to trip over assertions.
1068   if (vreg_num + 20 >= LIR_Opr::vreg_max) {
1069     bailout("out of virtual registers in LIR generator");
1070     if (vreg_num + 2 >= LIR_Opr::vreg_max) {
1071       // Wrap it around and continue until bailout really happens to avoid hitting assertions.
1072       _virtual_register_number = LIR_Opr::vreg_base;
1073       vreg_num = LIR_Opr::vreg_base;
1074     }
1075   }
1076   _virtual_register_number += 1;
1077   LIR_Opr vreg = LIR_OprFact::virtual_register(vreg_num, type);
1078   assert(vreg != LIR_OprFact::illegal(), "ran out of virtual registers");
1079   return vreg;
1080 }
1081 
1082 
1083 // Try to lock using register in hint
1084 LIR_Opr LIRGenerator::rlock(Value instr) {
1085   return new_register(instr->type());
1086 }
1087 
1088 
1089 // does an rlock and sets result
1090 LIR_Opr LIRGenerator::rlock_result(Value x) {
1091   LIR_Opr reg = rlock(x);
1092   set_result(x, reg);
1093   return reg;
1094 }
1095 
1096 
1097 // does an rlock and sets result
1098 LIR_Opr LIRGenerator::rlock_result(Value x, BasicType type) {
1099   LIR_Opr reg;
1100   switch (type) {
1101   case T_BYTE:
1102   case T_BOOLEAN:
1103     reg = rlock_byte(type);
1104     break;
1105   default:
1106     reg = rlock(x);
1107     break;
1108   }
1109 
1110   set_result(x, reg);
1111   return reg;
1112 }
1113 
1114 
1115 //---------------------------------------------------------------------
1116 ciObject* LIRGenerator::get_jobject_constant(Value value) {
1117   ObjectType* oc = value->type()->as_ObjectType();
1118   if (oc) {
1119     return oc->constant_value();
1120   }
1121   return nullptr;
1122 }
1123 
1124 
1125 void LIRGenerator::do_ExceptionObject(ExceptionObject* x) {
1126   assert(block()->is_set(BlockBegin::exception_entry_flag), "ExceptionObject only allowed in exception handler block");
1127   assert(block()->next() == x, "ExceptionObject must be first instruction of block");
1128 
1129   // no moves are created for phi functions at the begin of exception
1130   // handlers, so assign operands manually here
1131   for_each_phi_fun(block(), phi,
1132                    if (!phi->is_illegal()) { operand_for_instruction(phi); });
1133 
1134   LIR_Opr thread_reg = getThreadPointer();
1135   __ move_wide(new LIR_Address(thread_reg, in_bytes(JavaThread::exception_oop_offset()), T_OBJECT),
1136                exceptionOopOpr());
1137   __ move_wide(LIR_OprFact::oopConst(nullptr),
1138                new LIR_Address(thread_reg, in_bytes(JavaThread::exception_oop_offset()), T_OBJECT));
1139   __ move_wide(LIR_OprFact::oopConst(nullptr),
1140                new LIR_Address(thread_reg, in_bytes(JavaThread::exception_pc_offset()), T_OBJECT));
1141 
1142   LIR_Opr result = new_register(T_OBJECT);
1143   __ move(exceptionOopOpr(), result);
1144   set_result(x, result);
1145 }
1146 
1147 
1148 //----------------------------------------------------------------------
1149 //----------------------------------------------------------------------
1150 //----------------------------------------------------------------------
1151 //----------------------------------------------------------------------
1152 //                        visitor functions
1153 //----------------------------------------------------------------------
1154 //----------------------------------------------------------------------
1155 //----------------------------------------------------------------------
1156 //----------------------------------------------------------------------
1157 
1158 void LIRGenerator::do_Phi(Phi* x) {
1159   // phi functions are never visited directly
1160   ShouldNotReachHere();
1161 }
1162 
1163 
1164 // Code for a constant is generated lazily unless the constant is frequently used and can't be inlined.
1165 void LIRGenerator::do_Constant(Constant* x) {
1166   if (x->state_before() != nullptr) {
1167     // Any constant with a ValueStack requires patching so emit the patch here
1168     LIR_Opr reg = rlock_result(x);
1169     CodeEmitInfo* info = state_for(x, x->state_before());
1170     __ oop2reg_patch(nullptr, reg, info);
1171   } else if (x->use_count() > 1 && !can_inline_as_constant(x)) {
1172     if (!x->is_pinned()) {
1173       // unpinned constants are handled specially so that they can be
1174       // put into registers when they are used multiple times within a
1175       // block.  After the block completes their operand will be
1176       // cleared so that other blocks can't refer to that register.
1177       set_result(x, load_constant(x));
1178     } else {
1179       LIR_Opr res = x->operand();
1180       if (!res->is_valid()) {
1181         res = LIR_OprFact::value_type(x->type());
1182       }
1183       if (res->is_constant()) {
1184         LIR_Opr reg = rlock_result(x);
1185         __ move(res, reg);
1186       } else {
1187         set_result(x, res);
1188       }
1189     }
1190   } else {
1191     set_result(x, LIR_OprFact::value_type(x->type()));
1192   }
1193 }
1194 
1195 
1196 void LIRGenerator::do_Local(Local* x) {
1197   // operand_for_instruction has the side effect of setting the result
1198   // so there's no need to do it here.
1199   operand_for_instruction(x);
1200 }
1201 
1202 
1203 void LIRGenerator::do_Return(Return* x) {
1204   if (compilation()->env()->dtrace_method_probes()) {
1205     BasicTypeList signature;
1206     signature.append(LP64_ONLY(T_LONG) NOT_LP64(T_INT));    // thread
1207     signature.append(T_METADATA); // Method*
1208     LIR_OprList* args = new LIR_OprList();
1209     args->append(getThreadPointer());
1210     LIR_Opr meth = new_register(T_METADATA);
1211     __ metadata2reg(method()->constant_encoding(), meth);
1212     args->append(meth);
1213     call_runtime(&signature, args, CAST_FROM_FN_PTR(address, SharedRuntime::dtrace_method_exit), voidType, nullptr);
1214   }
1215 
1216   if (x->type()->is_void()) {
1217     __ return_op(LIR_OprFact::illegalOpr);
1218   } else {
1219     LIR_Opr reg = result_register_for(x->type(), /*callee=*/true);
1220     LIRItem result(x->result(), this);
1221 
1222     result.load_item_force(reg);
1223     __ return_op(result.result());
1224   }
1225   set_no_result(x);
1226 }
1227 
1228 // Example: ref.get()
1229 // Combination of LoadField and g1 pre-write barrier
1230 void LIRGenerator::do_Reference_get(Intrinsic* x) {
1231 
1232   const int referent_offset = java_lang_ref_Reference::referent_offset();
1233 
1234   assert(x->number_of_arguments() == 1, "wrong type");
1235 
1236   LIRItem reference(x->argument_at(0), this);
1237   reference.load_item();
1238 
1239   // need to perform the null check on the reference object
1240   CodeEmitInfo* info = nullptr;
1241   if (x->needs_null_check()) {
1242     info = state_for(x);
1243   }
1244 
1245   LIR_Opr result = rlock_result(x, T_OBJECT);
1246   access_load_at(IN_HEAP | ON_WEAK_OOP_REF, T_OBJECT,
1247                  reference, LIR_OprFact::intConst(referent_offset), result,
1248                  nullptr, info);
1249 }
1250 
1251 // Example: clazz.isInstance(object)
1252 void LIRGenerator::do_isInstance(Intrinsic* x) {
1253   assert(x->number_of_arguments() == 2, "wrong type");
1254 
1255   // TODO could try to substitute this node with an equivalent InstanceOf
1256   // if clazz is known to be a constant Class. This will pick up newly found
1257   // constants after HIR construction. I'll leave this to a future change.
1258 
1259   // as a first cut, make a simple leaf call to runtime to stay platform independent.
1260   // could follow the aastore example in a future change.
1261 
1262   LIRItem clazz(x->argument_at(0), this);
1263   LIRItem object(x->argument_at(1), this);
1264   clazz.load_item();
1265   object.load_item();
1266   LIR_Opr result = rlock_result(x);
1267 
1268   // need to perform null check on clazz
1269   if (x->needs_null_check()) {
1270     CodeEmitInfo* info = state_for(x);
1271     __ null_check(clazz.result(), info);
1272   }
1273 
1274   LIR_Opr call_result = call_runtime(clazz.value(), object.value(),
1275                                      CAST_FROM_FN_PTR(address, Runtime1::is_instance_of),
1276                                      x->type(),
1277                                      nullptr); // null CodeEmitInfo results in a leaf call
1278   __ move(call_result, result);
1279 }
1280 
1281 void LIRGenerator::load_klass(LIR_Opr obj, LIR_Opr klass, CodeEmitInfo* null_check_info) {
1282   __ load_klass(obj, klass, null_check_info);
1283 }
1284 
1285 // Example: object.getClass ()
1286 void LIRGenerator::do_getClass(Intrinsic* x) {
1287   assert(x->number_of_arguments() == 1, "wrong type");
1288 
1289   LIRItem rcvr(x->argument_at(0), this);
1290   rcvr.load_item();
1291   LIR_Opr temp = new_register(T_ADDRESS);
1292   LIR_Opr result = rlock_result(x);
1293 
1294   // need to perform the null check on the rcvr
1295   CodeEmitInfo* info = nullptr;
1296   if (x->needs_null_check()) {
1297     info = state_for(x);
1298   }
1299 
1300   LIR_Opr klass = new_register(T_METADATA);
1301   load_klass(rcvr.result(), klass, info);
1302   __ move_wide(new LIR_Address(klass, in_bytes(Klass::java_mirror_offset()), T_ADDRESS), temp);
1303   // mirror = ((OopHandle)mirror)->resolve();
1304   access_load(IN_NATIVE, T_OBJECT,
1305               LIR_OprFact::address(new LIR_Address(temp, T_OBJECT)), result);
1306 }
1307 
1308 // java.lang.Class::isPrimitive()
1309 void LIRGenerator::do_isPrimitive(Intrinsic* x) {
1310   assert(x->number_of_arguments() == 1, "wrong type");
1311 
1312   LIRItem rcvr(x->argument_at(0), this);
1313   rcvr.load_item();
1314   LIR_Opr temp = new_register(T_METADATA);
1315   LIR_Opr result = rlock_result(x);
1316 
1317   CodeEmitInfo* info = nullptr;
1318   if (x->needs_null_check()) {
1319     info = state_for(x);
1320   }
1321 
1322   __ move(new LIR_Address(rcvr.result(), java_lang_Class::klass_offset(), T_ADDRESS), temp, info);
1323   __ cmp(lir_cond_notEqual, temp, LIR_OprFact::metadataConst(nullptr));
1324   __ cmove(lir_cond_notEqual, LIR_OprFact::intConst(0), LIR_OprFact::intConst(1), result, T_BOOLEAN);
1325 }
1326 
1327 // Example: Foo.class.getModifiers()
1328 void LIRGenerator::do_getModifiers(Intrinsic* x) {
1329   assert(x->number_of_arguments() == 1, "wrong type");
1330 
1331   LIRItem receiver(x->argument_at(0), this);
1332   receiver.load_item();
1333   LIR_Opr result = rlock_result(x);
1334 
1335   CodeEmitInfo* info = nullptr;
1336   if (x->needs_null_check()) {
1337     info = state_for(x);
1338   }
1339 
1340   // While reading off the universal constant mirror is less efficient than doing
1341   // another branch and returning the constant answer, this branchless code runs into
1342   // much less risk of confusion for C1 register allocator. The choice of the universe
1343   // object here is correct as long as it returns the same modifiers we would expect
1344   // from the primitive class itself. See spec for Class.getModifiers that provides
1345   // the typed array klasses with similar modifiers as their component types.
1346 
1347   // Valhalla update: the code is now a bit convuloted because arrays and primitive
1348   // classes don't have the same modifiers set anymore, but we cannot introduce
1349   // branches in LIR generation (JDK-8211231). So, the first part of the code remains
1350   // identical, using the byteArrayKlass object to avoid a NPE when accessing the
1351   // modifiers. But then the code also prepares the correct modifiers set for
1352   // primitive classes, and there's a second conditional move to put the right
1353   // value into result.
1354 
1355 
1356   Klass* univ_klass = Universe::byteArrayKlass();
1357   assert(univ_klass->modifier_flags() == (JVM_ACC_ABSTRACT | JVM_ACC_FINAL | JVM_ACC_PUBLIC
1358                                           | (Arguments::enable_preview() ? JVM_ACC_IDENTITY : 0)), "Sanity");
1359   LIR_Opr prim_klass = LIR_OprFact::metadataConst(univ_klass);
1360 
1361   LIR_Opr recv_klass = new_register(T_METADATA);
1362   __ move(new LIR_Address(receiver.result(), java_lang_Class::klass_offset(), T_ADDRESS), recv_klass, info);
1363 
1364   // Check if this is a Java mirror of primitive type, and select the appropriate klass.
1365   LIR_Opr klass = new_register(T_METADATA);
1366   __ cmp(lir_cond_equal, recv_klass, LIR_OprFact::metadataConst(nullptr));
1367   __ cmove(lir_cond_equal, prim_klass, recv_klass, klass, T_ADDRESS);
1368   LIR_Opr klass_modifiers = new_register(T_INT);
1369   __ move(new LIR_Address(klass, in_bytes(Klass::modifier_flags_offset()), T_INT), klass_modifiers);
1370 
1371   LIR_Opr prim_modifiers = load_immediate(JVM_ACC_ABSTRACT | JVM_ACC_FINAL | JVM_ACC_PUBLIC, T_INT);
1372 
1373   __ cmp(lir_cond_equal, recv_klass, LIR_OprFact::metadataConst(0));
1374   __ cmove(lir_cond_equal, prim_modifiers, klass_modifiers, result, T_INT);
1375 
1376 }
1377 
1378 void LIRGenerator::do_getObjectSize(Intrinsic* x) {
1379   assert(x->number_of_arguments() == 3, "wrong type");
1380   LIR_Opr result_reg = rlock_result(x);
1381 
1382   LIRItem value(x->argument_at(2), this);
1383   value.load_item();
1384 
1385   LIR_Opr klass = new_register(T_METADATA);
1386   load_klass(value.result(), klass, nullptr);
1387   LIR_Opr layout = new_register(T_INT);
1388   __ move(new LIR_Address(klass, in_bytes(Klass::layout_helper_offset()), T_INT), layout);
1389 
1390   LabelObj* L_done = new LabelObj();
1391   LabelObj* L_array = new LabelObj();
1392 
1393   __ cmp(lir_cond_lessEqual, layout, 0);
1394   __ branch(lir_cond_lessEqual, L_array->label());
1395 
1396   // Instance case: the layout helper gives us instance size almost directly,
1397   // but we need to mask out the _lh_instance_slow_path_bit.
1398 
1399   assert((int) Klass::_lh_instance_slow_path_bit < BytesPerLong, "clear bit");
1400 
1401   LIR_Opr mask = load_immediate(~(jint) right_n_bits(LogBytesPerLong), T_INT);
1402   __ logical_and(layout, mask, layout);
1403   __ convert(Bytecodes::_i2l, layout, result_reg);
1404 
1405   __ branch(lir_cond_always, L_done->label());
1406 
1407   // Array case: size is round(header + element_size*arraylength).
1408   // Since arraylength is different for every array instance, we have to
1409   // compute the whole thing at runtime.
1410 
1411   __ branch_destination(L_array->label());
1412 
1413   int round_mask = MinObjAlignmentInBytes - 1;
1414 
1415   // Figure out header sizes first.
1416   LIR_Opr hss = load_immediate(Klass::_lh_header_size_shift, T_INT);
1417   LIR_Opr hsm = load_immediate(Klass::_lh_header_size_mask, T_INT);
1418 
1419   LIR_Opr header_size = new_register(T_INT);
1420   __ move(layout, header_size);
1421   LIR_Opr tmp = new_register(T_INT);
1422   __ unsigned_shift_right(header_size, hss, header_size, tmp);
1423   __ logical_and(header_size, hsm, header_size);
1424   __ add(header_size, LIR_OprFact::intConst(round_mask), header_size);
1425 
1426   // Figure out the array length in bytes
1427   assert(Klass::_lh_log2_element_size_shift == 0, "use shift in place");
1428   LIR_Opr l2esm = load_immediate(Klass::_lh_log2_element_size_mask, T_INT);
1429   __ logical_and(layout, l2esm, layout);
1430 
1431   LIR_Opr length_int = new_register(T_INT);
1432   __ move(new LIR_Address(value.result(), arrayOopDesc::length_offset_in_bytes(), T_INT), length_int);
1433 
1434 #ifdef _LP64
1435   LIR_Opr length = new_register(T_LONG);
1436   __ convert(Bytecodes::_i2l, length_int, length);
1437 #endif
1438 
1439   // Shift-left awkwardness. Normally it is just:
1440   //   __ shift_left(length, layout, length);
1441   // But C1 cannot perform shift_left with non-constant count, so we end up
1442   // doing the per-bit loop dance here. x86_32 also does not know how to shift
1443   // longs, so we have to act on ints.
1444   LabelObj* L_shift_loop = new LabelObj();
1445   LabelObj* L_shift_exit = new LabelObj();
1446 
1447   __ branch_destination(L_shift_loop->label());
1448   __ cmp(lir_cond_equal, layout, 0);
1449   __ branch(lir_cond_equal, L_shift_exit->label());
1450 
1451 #ifdef _LP64
1452   __ shift_left(length, 1, length);
1453 #else
1454   __ shift_left(length_int, 1, length_int);
1455 #endif
1456 
1457   __ sub(layout, LIR_OprFact::intConst(1), layout);
1458 
1459   __ branch(lir_cond_always, L_shift_loop->label());
1460   __ branch_destination(L_shift_exit->label());
1461 
1462   // Mix all up, round, and push to the result.
1463 #ifdef _LP64
1464   LIR_Opr header_size_long = new_register(T_LONG);
1465   __ convert(Bytecodes::_i2l, header_size, header_size_long);
1466   __ add(length, header_size_long, length);
1467   if (round_mask != 0) {
1468     LIR_Opr round_mask_opr = load_immediate(~(jlong)round_mask, T_LONG);
1469     __ logical_and(length, round_mask_opr, length);
1470   }
1471   __ move(length, result_reg);
1472 #else
1473   __ add(length_int, header_size, length_int);
1474   if (round_mask != 0) {
1475     LIR_Opr round_mask_opr = load_immediate(~round_mask, T_INT);
1476     __ logical_and(length_int, round_mask_opr, length_int);
1477   }
1478   __ convert(Bytecodes::_i2l, length_int, result_reg);
1479 #endif
1480 
1481   __ branch_destination(L_done->label());
1482 }
1483 
1484 void LIRGenerator::do_scopedValueCache(Intrinsic* x) {
1485   do_JavaThreadField(x, JavaThread::scopedValueCache_offset());
1486 }
1487 
1488 // Example: Thread.currentCarrierThread()
1489 void LIRGenerator::do_currentCarrierThread(Intrinsic* x) {
1490   do_JavaThreadField(x, JavaThread::threadObj_offset());
1491 }
1492 
1493 void LIRGenerator::do_vthread(Intrinsic* x) {
1494   do_JavaThreadField(x, JavaThread::vthread_offset());
1495 }
1496 
1497 void LIRGenerator::do_JavaThreadField(Intrinsic* x, ByteSize offset) {
1498   assert(x->number_of_arguments() == 0, "wrong type");
1499   LIR_Opr temp = new_register(T_ADDRESS);
1500   LIR_Opr reg = rlock_result(x);
1501   __ move(new LIR_Address(getThreadPointer(), in_bytes(offset), T_ADDRESS), temp);
1502   access_load(IN_NATIVE, T_OBJECT,
1503               LIR_OprFact::address(new LIR_Address(temp, T_OBJECT)), reg);
1504 }
1505 
1506 void LIRGenerator::do_RegisterFinalizer(Intrinsic* x) {
1507   assert(x->number_of_arguments() == 1, "wrong type");
1508   LIRItem receiver(x->argument_at(0), this);
1509 
1510   receiver.load_item();
1511   BasicTypeList signature;
1512   signature.append(T_OBJECT); // receiver
1513   LIR_OprList* args = new LIR_OprList();
1514   args->append(receiver.result());
1515   CodeEmitInfo* info = state_for(x, x->state());
1516   call_runtime(&signature, args,
1517                CAST_FROM_FN_PTR(address, Runtime1::entry_for(Runtime1::register_finalizer_id)),
1518                voidType, info);
1519 
1520   set_no_result(x);
1521 }
1522 
1523 
1524 //------------------------local access--------------------------------------
1525 
1526 LIR_Opr LIRGenerator::operand_for_instruction(Instruction* x) {
1527   if (x->operand()->is_illegal()) {
1528     Constant* c = x->as_Constant();
1529     if (c != nullptr) {
1530       x->set_operand(LIR_OprFact::value_type(c->type()));
1531     } else {
1532       assert(x->as_Phi() || x->as_Local() != nullptr, "only for Phi and Local");
1533       // allocate a virtual register for this local or phi
1534       x->set_operand(rlock(x));
1535 #ifdef ASSERT
1536       _instruction_for_operand.at_put_grow(x->operand()->vreg_number(), x, nullptr);
1537 #endif
1538     }
1539   }
1540   return x->operand();
1541 }
1542 
1543 #ifdef ASSERT
1544 Instruction* LIRGenerator::instruction_for_vreg(int reg_num) {
1545   if (reg_num < _instruction_for_operand.length()) {
1546     return _instruction_for_operand.at(reg_num);
1547   }
1548   return nullptr;
1549 }
1550 #endif
1551 
1552 void LIRGenerator::set_vreg_flag(int vreg_num, VregFlag f) {
1553   if (_vreg_flags.size_in_bits() == 0) {
1554     BitMap2D temp(100, num_vreg_flags);
1555     _vreg_flags = temp;
1556   }
1557   _vreg_flags.at_put_grow(vreg_num, f, true);
1558 }
1559 
1560 bool LIRGenerator::is_vreg_flag_set(int vreg_num, VregFlag f) {
1561   if (!_vreg_flags.is_valid_index(vreg_num, f)) {
1562     return false;
1563   }
1564   return _vreg_flags.at(vreg_num, f);
1565 }
1566 
1567 
1568 // Block local constant handling.  This code is useful for keeping
1569 // unpinned constants and constants which aren't exposed in the IR in
1570 // registers.  Unpinned Constant instructions have their operands
1571 // cleared when the block is finished so that other blocks can't end
1572 // up referring to their registers.
1573 
1574 LIR_Opr LIRGenerator::load_constant(Constant* x) {
1575   assert(!x->is_pinned(), "only for unpinned constants");
1576   _unpinned_constants.append(x);
1577   return load_constant(LIR_OprFact::value_type(x->type())->as_constant_ptr());
1578 }
1579 
1580 
1581 LIR_Opr LIRGenerator::load_constant(LIR_Const* c) {
1582   BasicType t = c->type();
1583   for (int i = 0; i < _constants.length(); i++) {
1584     LIR_Const* other = _constants.at(i);
1585     if (t == other->type()) {
1586       switch (t) {
1587       case T_INT:
1588       case T_FLOAT:
1589         if (c->as_jint_bits() != other->as_jint_bits()) continue;
1590         break;
1591       case T_LONG:
1592       case T_DOUBLE:
1593         if (c->as_jint_hi_bits() != other->as_jint_hi_bits()) continue;
1594         if (c->as_jint_lo_bits() != other->as_jint_lo_bits()) continue;
1595         break;
1596       case T_OBJECT:
1597         if (c->as_jobject() != other->as_jobject()) continue;
1598         break;
1599       default:
1600         break;
1601       }
1602       return _reg_for_constants.at(i);
1603     }
1604   }
1605 
1606   LIR_Opr result = new_register(t);
1607   __ move((LIR_Opr)c, result);
1608   if (!in_conditional_code()) {
1609     _constants.append(c);
1610     _reg_for_constants.append(result);
1611   }
1612   return result;
1613 }
1614 
1615 void LIRGenerator::set_in_conditional_code(bool v) {
1616   assert(v != _in_conditional_code, "must change state");
1617   _in_conditional_code = v;
1618 }
1619 
1620 
1621 //------------------------field access--------------------------------------
1622 
1623 void LIRGenerator::do_CompareAndSwap(Intrinsic* x, ValueType* type) {
1624   assert(x->number_of_arguments() == 4, "wrong type");
1625   LIRItem obj   (x->argument_at(0), this);  // object
1626   LIRItem offset(x->argument_at(1), this);  // offset of field
1627   LIRItem cmp   (x->argument_at(2), this);  // value to compare with field
1628   LIRItem val   (x->argument_at(3), this);  // replace field with val if matches cmp
1629   assert(obj.type()->tag() == objectTag, "invalid type");
1630   assert(cmp.type()->tag() == type->tag(), "invalid type");
1631   assert(val.type()->tag() == type->tag(), "invalid type");
1632 
1633   LIR_Opr result = access_atomic_cmpxchg_at(IN_HEAP, as_BasicType(type),
1634                                             obj, offset, cmp, val);
1635   set_result(x, result);
1636 }
1637 
1638 // Comment copied form templateTable_i486.cpp
1639 // ----------------------------------------------------------------------------
1640 // Volatile variables demand their effects be made known to all CPU's in
1641 // order.  Store buffers on most chips allow reads & writes to reorder; the
1642 // JMM's ReadAfterWrite.java test fails in -Xint mode without some kind of
1643 // memory barrier (i.e., it's not sufficient that the interpreter does not
1644 // reorder volatile references, the hardware also must not reorder them).
1645 //
1646 // According to the new Java Memory Model (JMM):
1647 // (1) All volatiles are serialized wrt to each other.
1648 // ALSO reads & writes act as acquire & release, so:
1649 // (2) A read cannot let unrelated NON-volatile memory refs that happen after
1650 // the read float up to before the read.  It's OK for non-volatile memory refs
1651 // that happen before the volatile read to float down below it.
1652 // (3) Similar a volatile write cannot let unrelated NON-volatile memory refs
1653 // that happen BEFORE the write float down to after the write.  It's OK for
1654 // non-volatile memory refs that happen after the volatile write to float up
1655 // before it.
1656 //
1657 // We only put in barriers around volatile refs (they are expensive), not
1658 // _between_ memory refs (that would require us to track the flavor of the
1659 // previous memory refs).  Requirements (2) and (3) require some barriers
1660 // before volatile stores and after volatile loads.  These nearly cover
1661 // requirement (1) but miss the volatile-store-volatile-load case.  This final
1662 // case is placed after volatile-stores although it could just as well go
1663 // before volatile-loads.
1664 
1665 
1666 void LIRGenerator::do_StoreField(StoreField* x) {
1667   bool needs_patching = x->needs_patching();
1668   bool is_volatile = x->field()->is_volatile();
1669   BasicType field_type = x->field_type();
1670 
1671   CodeEmitInfo* info = nullptr;
1672   if (needs_patching) {
1673     assert(x->explicit_null_check() == nullptr, "can't fold null check into patching field access");
1674     info = state_for(x, x->state_before());
1675   } else if (x->needs_null_check()) {
1676     NullCheck* nc = x->explicit_null_check();
1677     if (nc == nullptr) {
1678       info = state_for(x);
1679     } else {
1680       info = state_for(nc);
1681     }
1682   }
1683 
1684   LIRItem object(x->obj(), this);
1685   LIRItem value(x->value(),  this);
1686 
1687   object.load_item();
1688 
1689   if (is_volatile || needs_patching) {
1690     // load item if field is volatile (fewer special cases for volatiles)
1691     // load item if field not initialized
1692     // load item if field not constant
1693     // because of code patching we cannot inline constants
1694     if (field_type == T_BYTE || field_type == T_BOOLEAN) {
1695       value.load_byte_item();
1696     } else  {
1697       value.load_item();
1698     }
1699   } else {
1700     value.load_for_store(field_type);
1701   }
1702 
1703   set_no_result(x);
1704 
1705 #ifndef PRODUCT
1706   if (PrintNotLoaded && needs_patching) {
1707     tty->print_cr("   ###class not loaded at store_%s bci %d",
1708                   x->is_static() ?  "static" : "field", x->printable_bci());
1709   }
1710 #endif
1711 
1712   if (x->needs_null_check() &&
1713       (needs_patching ||
1714        MacroAssembler::needs_explicit_null_check(x->offset()))) {
1715     // Emit an explicit null check because the offset is too large.
1716     // If the class is not loaded and the object is null, we need to deoptimize to throw a
1717     // NoClassDefFoundError in the interpreter instead of an implicit NPE from compiled code.
1718     __ null_check(object.result(), new CodeEmitInfo(info), /* deoptimize */ needs_patching);
1719   }
1720 
1721   DecoratorSet decorators = IN_HEAP;
1722   if (is_volatile) {
1723     decorators |= MO_SEQ_CST;
1724   }
1725   if (needs_patching) {
1726     decorators |= C1_NEEDS_PATCHING;
1727   }
1728 
1729   access_store_at(decorators, field_type, object, LIR_OprFact::intConst(x->offset()),
1730                   value.result(), info != nullptr ? new CodeEmitInfo(info) : nullptr, info);
1731 }
1732 
1733 // FIXME -- I can't find any other way to pass an address to access_load_at().
1734 class TempResolvedAddress: public Instruction {
1735  public:
1736   TempResolvedAddress(ValueType* type, LIR_Opr addr) : Instruction(type) {
1737     set_operand(addr);
1738   }
1739   virtual void input_values_do(ValueVisitor*) {}
1740   virtual void visit(InstructionVisitor* v)   {}
1741   virtual const char* name() const  { return "TempResolvedAddress"; }
1742 };
1743 
1744 LIR_Opr LIRGenerator::get_and_load_element_address(LIRItem& array, LIRItem& index) {
1745   ciType* array_type = array.value()->declared_type();
1746   ciFlatArrayKlass* flat_array_klass = array_type->as_flat_array_klass();
1747   assert(flat_array_klass->is_loaded(), "must be");
1748 
1749   int array_header_size = flat_array_klass->array_header_in_bytes();
1750   int shift = flat_array_klass->log2_element_size();
1751 
1752 #ifndef _LP64
1753   LIR_Opr index_op = new_register(T_INT);
1754   // FIXME -- on 32-bit, the shift below can overflow, so we need to check that
1755   // the top (shift+1) bits of index_op must be zero, or
1756   // else throw ArrayIndexOutOfBoundsException
1757   if (index.result()->is_constant()) {
1758     jint const_index = index.result()->as_jint();
1759     __ move(LIR_OprFact::intConst(const_index << shift), index_op);
1760   } else {
1761     __ shift_left(index_op, shift, index.result());
1762   }
1763 #else
1764   LIR_Opr index_op = new_register(T_LONG);
1765   if (index.result()->is_constant()) {
1766     jint const_index = index.result()->as_jint();
1767     __ move(LIR_OprFact::longConst(const_index << shift), index_op);
1768   } else {
1769     __ convert(Bytecodes::_i2l, index.result(), index_op);
1770     // Need to shift manually, as LIR_Address can scale only up to 3.
1771     __ shift_left(index_op, shift, index_op);
1772   }
1773 #endif
1774 
1775   LIR_Opr elm_op = new_pointer_register();
1776   LIR_Address* elm_address = generate_address(array.result(), index_op, 0, array_header_size, T_ADDRESS);
1777   __ leal(LIR_OprFact::address(elm_address), elm_op);
1778   return elm_op;
1779 }
1780 
1781 void LIRGenerator::access_sub_element(LIRItem& array, LIRItem& index, LIR_Opr& result, ciField* field, int sub_offset) {
1782   assert(field != nullptr, "Need a subelement type specified");
1783 
1784   // Find the starting address of the source (inside the array)
1785   LIR_Opr elm_op = get_and_load_element_address(array, index);
1786 
1787   BasicType subelt_type = field->type()->basic_type();
1788   TempResolvedAddress* elm_resolved_addr = new TempResolvedAddress(as_ValueType(subelt_type), elm_op);
1789   LIRItem elm_item(elm_resolved_addr, this);
1790 
1791   DecoratorSet decorators = IN_HEAP;
1792   access_load_at(decorators, subelt_type,
1793                      elm_item, LIR_OprFact::intConst(sub_offset), result,
1794                      nullptr, nullptr);
1795 
1796   if (field->is_null_free()) {
1797     assert(field->type()->is_loaded(), "Must be");
1798     assert(field->type()->is_inlinetype(), "Must be if loaded");
1799     assert(field->type()->as_inline_klass()->is_initialized(), "Must be");
1800     LabelObj* L_end = new LabelObj();
1801     __ cmp(lir_cond_notEqual, result, LIR_OprFact::oopConst(nullptr));
1802     __ branch(lir_cond_notEqual, L_end->label());
1803     set_in_conditional_code(true);
1804     Constant* default_value = new Constant(new InstanceConstant(field->type()->as_inline_klass()->default_instance()));
1805     if (default_value->is_pinned()) {
1806       __ move(LIR_OprFact::value_type(default_value->type()), result);
1807     } else {
1808       __ move(load_constant(default_value), result);
1809     }
1810     __ branch_destination(L_end->label());
1811     set_in_conditional_code(false);
1812   }
1813 }
1814 
1815 void LIRGenerator::access_flat_array(bool is_load, LIRItem& array, LIRItem& index, LIRItem& obj_item,
1816                                           ciField* field, int sub_offset) {
1817   assert(sub_offset == 0 || field != nullptr, "Sanity check");
1818 
1819   // Find the starting address of the source (inside the array)
1820   LIR_Opr elm_op = get_and_load_element_address(array, index);
1821 
1822   ciInlineKlass* elem_klass = nullptr;
1823   if (field != nullptr) {
1824     elem_klass = field->type()->as_inline_klass();
1825   } else {
1826     elem_klass = array.value()->declared_type()->as_flat_array_klass()->element_klass()->as_inline_klass();
1827   }
1828   for (int i = 0; i < elem_klass->nof_nonstatic_fields(); i++) {
1829     ciField* inner_field = elem_klass->nonstatic_field_at(i);
1830     assert(!inner_field->is_flat(), "flat fields must have been expanded");
1831     int obj_offset = inner_field->offset_in_bytes();
1832     int elm_offset = obj_offset - elem_klass->first_field_offset() + sub_offset; // object header is not stored in array.
1833     BasicType field_type = inner_field->type()->basic_type();
1834 
1835     // Types which are smaller than int are still passed in an int register.
1836     BasicType reg_type = field_type;
1837     switch (reg_type) {
1838     case T_BYTE:
1839     case T_BOOLEAN:
1840     case T_SHORT:
1841     case T_CHAR:
1842       reg_type = T_INT;
1843       break;
1844     default:
1845       break;
1846     }
1847 
1848     LIR_Opr temp = new_register(reg_type);
1849     TempResolvedAddress* elm_resolved_addr = new TempResolvedAddress(as_ValueType(field_type), elm_op);
1850     LIRItem elm_item(elm_resolved_addr, this);
1851 
1852     DecoratorSet decorators = IN_HEAP;
1853     if (is_load) {
1854       access_load_at(decorators, field_type,
1855                      elm_item, LIR_OprFact::intConst(elm_offset), temp,
1856                      nullptr, nullptr);
1857       access_store_at(decorators, field_type,
1858                       obj_item, LIR_OprFact::intConst(obj_offset), temp,
1859                       nullptr, nullptr);
1860     } else {
1861       access_load_at(decorators, field_type,
1862                      obj_item, LIR_OprFact::intConst(obj_offset), temp,
1863                      nullptr, nullptr);
1864       access_store_at(decorators, field_type,
1865                       elm_item, LIR_OprFact::intConst(elm_offset), temp,
1866                       nullptr, nullptr);
1867     }
1868   }
1869 }
1870 
1871 void LIRGenerator::check_flat_array(LIR_Opr array, LIR_Opr value, CodeStub* slow_path) {
1872   LIR_Opr tmp = new_register(T_METADATA);
1873   __ check_flat_array(array, value, tmp, slow_path);
1874 }
1875 
1876 void LIRGenerator::check_null_free_array(LIRItem& array, LIRItem& value, CodeEmitInfo* info) {
1877   LabelObj* L_end = new LabelObj();
1878   LIR_Opr tmp = new_register(T_METADATA);
1879   __ check_null_free_array(array.result(), tmp);
1880   __ branch(lir_cond_equal, L_end->label());
1881   __ null_check(value.result(), info);
1882   __ branch_destination(L_end->label());
1883 }
1884 
1885 bool LIRGenerator::needs_flat_array_store_check(StoreIndexed* x) {
1886   if (x->elt_type() == T_OBJECT && x->array()->maybe_flat_array()) {
1887     ciType* type = x->value()->declared_type();
1888     if (type != nullptr && type->is_klass()) {
1889       ciKlass* klass = type->as_klass();
1890       if (!klass->can_be_inline_klass() || (klass->is_inlinetype() && !klass->as_inline_klass()->flat_in_array())) {
1891         // This is known to be a non-flat object. If the array is a flat array,
1892         // it will be caught by the code generated by array_store_check().
1893         return false;
1894       }
1895     }
1896     // We're not 100% sure, so let's do the flat_array_store_check.
1897     return true;
1898   }
1899   return false;
1900 }
1901 
1902 bool LIRGenerator::needs_null_free_array_store_check(StoreIndexed* x) {
1903   return x->elt_type() == T_OBJECT && x->array()->maybe_null_free_array();
1904 }
1905 
1906 void LIRGenerator::do_StoreIndexed(StoreIndexed* x) {
1907   assert(x->is_pinned(),"");
1908   assert(x->elt_type() != T_ARRAY, "never used");
1909   bool is_loaded_flat_array = x->array()->is_loaded_flat_array();
1910   bool needs_range_check = x->compute_needs_range_check();
1911   bool use_length = x->length() != nullptr;
1912   bool obj_store = is_reference_type(x->elt_type());
1913   bool needs_store_check = obj_store && !(is_loaded_flat_array && x->is_exact_flat_array_store()) &&
1914                                         (x->value()->as_Constant() == nullptr ||
1915                                          !get_jobject_constant(x->value())->is_null_object());
1916 
1917   LIRItem array(x->array(), this);
1918   LIRItem index(x->index(), this);
1919   LIRItem value(x->value(), this);
1920   LIRItem length(this);
1921 
1922   array.load_item();
1923   index.load_nonconstant();
1924 
1925   if (use_length && needs_range_check) {
1926     length.set_instruction(x->length());
1927     length.load_item();
1928   }
1929 
1930   if (needs_store_check || x->check_boolean()
1931       || is_loaded_flat_array || needs_flat_array_store_check(x) || needs_null_free_array_store_check(x)) {
1932     value.load_item();
1933   } else {
1934     value.load_for_store(x->elt_type());
1935   }
1936 
1937   set_no_result(x);
1938 
1939   // the CodeEmitInfo must be duplicated for each different
1940   // LIR-instruction because spilling can occur anywhere between two
1941   // instructions and so the debug information must be different
1942   CodeEmitInfo* range_check_info = state_for(x);
1943   CodeEmitInfo* null_check_info = nullptr;
1944   if (x->needs_null_check()) {
1945     null_check_info = new CodeEmitInfo(range_check_info);
1946   }
1947 
1948   if (needs_range_check) {
1949     if (use_length) {
1950       __ cmp(lir_cond_belowEqual, length.result(), index.result());
1951       __ branch(lir_cond_belowEqual, new RangeCheckStub(range_check_info, index.result(), array.result()));
1952     } else {
1953       array_range_check(array.result(), index.result(), null_check_info, range_check_info);
1954       // range_check also does the null check
1955       null_check_info = nullptr;
1956     }
1957   }
1958 
1959   if (x->should_profile()) {
1960     if (x->array()->is_loaded_flat_array()) {
1961       // No need to profile a store to a flat array of known type. This can happen if
1962       // the type only became known after optimizations (for example, after the PhiSimplifier).
1963       x->set_should_profile(false);
1964     } else {
1965       int bci = x->profiled_bci();
1966       ciMethodData* md = x->profiled_method()->method_data();
1967       assert(md != nullptr, "Sanity");
1968       ciProfileData* data = md->bci_to_data(bci);
1969       assert(data != nullptr && data->is_ArrayStoreData(), "incorrect profiling entry");
1970       ciArrayStoreData* store_data = (ciArrayStoreData*)data;
1971       profile_array_type(x, md, store_data);
1972       assert(store_data->is_ArrayStoreData(), "incorrect profiling entry");
1973       if (x->array()->maybe_null_free_array()) {
1974         profile_null_free_array(array, md, store_data);
1975       }
1976     }
1977   }
1978 
1979   if (GenerateArrayStoreCheck && needs_store_check) {
1980     CodeEmitInfo* store_check_info = new CodeEmitInfo(range_check_info);
1981     array_store_check(value.result(), array.result(), store_check_info, x->profiled_method(), x->profiled_bci());
1982   }
1983 
1984   if (is_loaded_flat_array) {
1985     if (!x->value()->is_null_free()) {
1986       __ null_check(value.result(), new CodeEmitInfo(range_check_info));
1987     }
1988     // If array element is an empty inline type, no need to copy anything
1989     if (!x->array()->declared_type()->as_flat_array_klass()->element_klass()->as_inline_klass()->is_empty()) {
1990       access_flat_array(false, array, index, value);
1991     }
1992   } else {
1993     StoreFlattenedArrayStub* slow_path = nullptr;
1994 
1995     if (needs_flat_array_store_check(x)) {
1996       // Check if we indeed have a flat array
1997       index.load_item();
1998       slow_path = new StoreFlattenedArrayStub(array.result(), index.result(), value.result(), state_for(x, x->state_before()));
1999       check_flat_array(array.result(), value.result(), slow_path);
2000       set_in_conditional_code(true);
2001     } else if (needs_null_free_array_store_check(x)) {
2002       CodeEmitInfo* info = new CodeEmitInfo(range_check_info);
2003       check_null_free_array(array, value, info);
2004     }
2005 
2006     DecoratorSet decorators = IN_HEAP | IS_ARRAY;
2007     if (x->check_boolean()) {
2008       decorators |= C1_MASK_BOOLEAN;
2009     }
2010 
2011     access_store_at(decorators, x->elt_type(), array, index.result(), value.result(),
2012                     nullptr, null_check_info);
2013     if (slow_path != nullptr) {
2014       __ branch_destination(slow_path->continuation());
2015       set_in_conditional_code(false);
2016     }
2017   }
2018 }
2019 
2020 void LIRGenerator::access_load_at(DecoratorSet decorators, BasicType type,
2021                                   LIRItem& base, LIR_Opr offset, LIR_Opr result,
2022                                   CodeEmitInfo* patch_info, CodeEmitInfo* load_emit_info) {
2023   decorators |= ACCESS_READ;
2024   LIRAccess access(this, decorators, base, offset, type, patch_info, load_emit_info);
2025   if (access.is_raw()) {
2026     _barrier_set->BarrierSetC1::load_at(access, result);
2027   } else {
2028     _barrier_set->load_at(access, result);
2029   }
2030 }
2031 
2032 void LIRGenerator::access_load(DecoratorSet decorators, BasicType type,
2033                                LIR_Opr addr, LIR_Opr result) {
2034   decorators |= ACCESS_READ;
2035   LIRAccess access(this, decorators, LIR_OprFact::illegalOpr, LIR_OprFact::illegalOpr, type);
2036   access.set_resolved_addr(addr);
2037   if (access.is_raw()) {
2038     _barrier_set->BarrierSetC1::load(access, result);
2039   } else {
2040     _barrier_set->load(access, result);
2041   }
2042 }
2043 
2044 void LIRGenerator::access_store_at(DecoratorSet decorators, BasicType type,
2045                                    LIRItem& base, LIR_Opr offset, LIR_Opr value,
2046                                    CodeEmitInfo* patch_info, CodeEmitInfo* store_emit_info) {
2047   decorators |= ACCESS_WRITE;
2048   LIRAccess access(this, decorators, base, offset, type, patch_info, store_emit_info);
2049   if (access.is_raw()) {
2050     _barrier_set->BarrierSetC1::store_at(access, value);
2051   } else {
2052     _barrier_set->store_at(access, value);
2053   }
2054 }
2055 
2056 LIR_Opr LIRGenerator::access_atomic_cmpxchg_at(DecoratorSet decorators, BasicType type,
2057                                                LIRItem& base, LIRItem& offset, LIRItem& cmp_value, LIRItem& new_value) {
2058   decorators |= ACCESS_READ;
2059   decorators |= ACCESS_WRITE;
2060   // Atomic operations are SEQ_CST by default
2061   decorators |= ((decorators & MO_DECORATOR_MASK) == 0) ? MO_SEQ_CST : 0;
2062   LIRAccess access(this, decorators, base, offset, type);
2063   if (access.is_raw()) {
2064     return _barrier_set->BarrierSetC1::atomic_cmpxchg_at(access, cmp_value, new_value);
2065   } else {
2066     return _barrier_set->atomic_cmpxchg_at(access, cmp_value, new_value);
2067   }
2068 }
2069 
2070 LIR_Opr LIRGenerator::access_atomic_xchg_at(DecoratorSet decorators, BasicType type,
2071                                             LIRItem& base, LIRItem& offset, LIRItem& value) {
2072   decorators |= ACCESS_READ;
2073   decorators |= ACCESS_WRITE;
2074   // Atomic operations are SEQ_CST by default
2075   decorators |= ((decorators & MO_DECORATOR_MASK) == 0) ? MO_SEQ_CST : 0;
2076   LIRAccess access(this, decorators, base, offset, type);
2077   if (access.is_raw()) {
2078     return _barrier_set->BarrierSetC1::atomic_xchg_at(access, value);
2079   } else {
2080     return _barrier_set->atomic_xchg_at(access, value);
2081   }
2082 }
2083 
2084 LIR_Opr LIRGenerator::access_atomic_add_at(DecoratorSet decorators, BasicType type,
2085                                            LIRItem& base, LIRItem& offset, LIRItem& value) {
2086   decorators |= ACCESS_READ;
2087   decorators |= ACCESS_WRITE;
2088   // Atomic operations are SEQ_CST by default
2089   decorators |= ((decorators & MO_DECORATOR_MASK) == 0) ? MO_SEQ_CST : 0;
2090   LIRAccess access(this, decorators, base, offset, type);
2091   if (access.is_raw()) {
2092     return _barrier_set->BarrierSetC1::atomic_add_at(access, value);
2093   } else {
2094     return _barrier_set->atomic_add_at(access, value);
2095   }
2096 }
2097 
2098 void LIRGenerator::do_LoadField(LoadField* x) {
2099   bool needs_patching = x->needs_patching();
2100   bool is_volatile = x->field()->is_volatile();
2101   BasicType field_type = x->field_type();
2102 
2103   CodeEmitInfo* info = nullptr;
2104   if (needs_patching) {
2105     assert(x->explicit_null_check() == nullptr, "can't fold null check into patching field access");
2106     info = state_for(x, x->state_before());
2107   } else if (x->needs_null_check()) {
2108     NullCheck* nc = x->explicit_null_check();
2109     if (nc == nullptr) {
2110       info = state_for(x);
2111     } else {
2112       info = state_for(nc);
2113     }
2114   }
2115 
2116   LIRItem object(x->obj(), this);
2117 
2118   object.load_item();
2119 
2120 #ifndef PRODUCT
2121   if (PrintNotLoaded && needs_patching) {
2122     tty->print_cr("   ###class not loaded at load_%s bci %d",
2123                   x->is_static() ?  "static" : "field", x->printable_bci());
2124   }
2125 #endif
2126 
2127   bool stress_deopt = StressLoopInvariantCodeMotion && info && info->deoptimize_on_exception();
2128   if (x->needs_null_check() &&
2129       (needs_patching ||
2130        MacroAssembler::needs_explicit_null_check(x->offset()) ||
2131        stress_deopt)) {
2132     LIR_Opr obj = object.result();
2133     if (stress_deopt) {
2134       obj = new_register(T_OBJECT);
2135       __ move(LIR_OprFact::oopConst(nullptr), obj);
2136     }
2137     // Emit an explicit null check because the offset is too large.
2138     // If the class is not loaded and the object is null, we need to deoptimize to throw a
2139     // NoClassDefFoundError in the interpreter instead of an implicit NPE from compiled code.
2140     __ null_check(obj, new CodeEmitInfo(info), /* deoptimize */ needs_patching);
2141   }
2142 
2143   DecoratorSet decorators = IN_HEAP;
2144   if (is_volatile) {
2145     decorators |= MO_SEQ_CST;
2146   }
2147   if (needs_patching) {
2148     decorators |= C1_NEEDS_PATCHING;
2149   }
2150 
2151   LIR_Opr result = rlock_result(x, field_type);
2152   access_load_at(decorators, field_type,
2153                  object, LIR_OprFact::intConst(x->offset()), result,
2154                  info ? new CodeEmitInfo(info) : nullptr, info);
2155 
2156   ciField* field = x->field();
2157   if (field->is_null_free()) {
2158     // Load from non-flat inline type field requires
2159     // a null check to replace null with the default value.
2160     ciInstanceKlass* holder = field->holder();
2161     if (field->is_static() && holder->is_loaded()) {
2162       ciObject* val = holder->java_mirror()->field_value(field).as_object();
2163       if (!val->is_null_object()) {
2164         // Static field is initialized, we don't need to perform a null check.
2165         return;
2166       }
2167     }
2168     ciInlineKlass* inline_klass = field->type()->as_inline_klass();
2169     if (inline_klass->is_initialized()) {
2170       LabelObj* L_end = new LabelObj();
2171       __ cmp(lir_cond_notEqual, result, LIR_OprFact::oopConst(nullptr));
2172       __ branch(lir_cond_notEqual, L_end->label());
2173       set_in_conditional_code(true);
2174       Constant* default_value = new Constant(new InstanceConstant(inline_klass->default_instance()));
2175       if (default_value->is_pinned()) {
2176         __ move(LIR_OprFact::value_type(default_value->type()), result);
2177       } else {
2178         __ move(load_constant(default_value), result);
2179       }
2180       __ branch_destination(L_end->label());
2181       set_in_conditional_code(false);
2182     } else {
2183       info = state_for(x, x->state_before());
2184       __ cmp(lir_cond_equal, result, LIR_OprFact::oopConst(nullptr));
2185       __ branch(lir_cond_equal, new DeoptimizeStub(info, Deoptimization::Reason_uninitialized,
2186                                                          Deoptimization::Action_make_not_entrant));
2187     }
2188   }
2189 }
2190 
2191 // int/long jdk.internal.util.Preconditions.checkIndex
2192 void LIRGenerator::do_PreconditionsCheckIndex(Intrinsic* x, BasicType type) {
2193   assert(x->number_of_arguments() == 3, "wrong type");
2194   LIRItem index(x->argument_at(0), this);
2195   LIRItem length(x->argument_at(1), this);
2196   LIRItem oobef(x->argument_at(2), this);
2197 
2198   index.load_item();
2199   length.load_item();
2200   oobef.load_item();
2201 
2202   LIR_Opr result = rlock_result(x);
2203   // x->state() is created from copy_state_for_exception, it does not contains arguments
2204   // we should prepare them before entering into interpreter mode due to deoptimization.
2205   ValueStack* state = x->state();
2206   for (int i = 0; i < x->number_of_arguments(); i++) {
2207     Value arg = x->argument_at(i);
2208     state->push(arg->type(), arg);
2209   }
2210   CodeEmitInfo* info = state_for(x, state);
2211 
2212   LIR_Opr len = length.result();
2213   LIR_Opr zero;
2214   if (type == T_INT) {
2215     zero = LIR_OprFact::intConst(0);
2216     if (length.result()->is_constant()){
2217       len = LIR_OprFact::intConst(length.result()->as_jint());
2218     }
2219   } else {
2220     assert(type == T_LONG, "sanity check");
2221     zero = LIR_OprFact::longConst(0);
2222     if (length.result()->is_constant()){
2223       len = LIR_OprFact::longConst(length.result()->as_jlong());
2224     }
2225   }
2226   // C1 can not handle the case that comparing index with constant value while condition
2227   // is neither lir_cond_equal nor lir_cond_notEqual, see LIR_Assembler::comp_op.
2228   LIR_Opr zero_reg = new_register(type);
2229   __ move(zero, zero_reg);
2230 #if defined(X86) && !defined(_LP64)
2231   // BEWARE! On 32-bit x86 cmp clobbers its left argument so we need a temp copy.
2232   LIR_Opr index_copy = new_register(index.type());
2233   // index >= 0
2234   __ move(index.result(), index_copy);
2235   __ cmp(lir_cond_less, index_copy, zero_reg);
2236   __ branch(lir_cond_less, new DeoptimizeStub(info, Deoptimization::Reason_range_check,
2237                                                     Deoptimization::Action_make_not_entrant));
2238   // index < length
2239   __ move(index.result(), index_copy);
2240   __ cmp(lir_cond_greaterEqual, index_copy, len);
2241   __ branch(lir_cond_greaterEqual, new DeoptimizeStub(info, Deoptimization::Reason_range_check,
2242                                                             Deoptimization::Action_make_not_entrant));
2243 #else
2244   // index >= 0
2245   __ cmp(lir_cond_less, index.result(), zero_reg);
2246   __ branch(lir_cond_less, new DeoptimizeStub(info, Deoptimization::Reason_range_check,
2247                                                     Deoptimization::Action_make_not_entrant));
2248   // index < length
2249   __ cmp(lir_cond_greaterEqual, index.result(), len);
2250   __ branch(lir_cond_greaterEqual, new DeoptimizeStub(info, Deoptimization::Reason_range_check,
2251                                                             Deoptimization::Action_make_not_entrant));
2252 #endif
2253   __ move(index.result(), result);
2254 }
2255 
2256 //------------------------array access--------------------------------------
2257 
2258 
2259 void LIRGenerator::do_ArrayLength(ArrayLength* x) {
2260   LIRItem array(x->array(), this);
2261   array.load_item();
2262   LIR_Opr reg = rlock_result(x);
2263 
2264   CodeEmitInfo* info = nullptr;
2265   if (x->needs_null_check()) {
2266     NullCheck* nc = x->explicit_null_check();
2267     if (nc == nullptr) {
2268       info = state_for(x);
2269     } else {
2270       info = state_for(nc);
2271     }
2272     if (StressLoopInvariantCodeMotion && info->deoptimize_on_exception()) {
2273       LIR_Opr obj = new_register(T_OBJECT);
2274       __ move(LIR_OprFact::oopConst(nullptr), obj);
2275       __ null_check(obj, new CodeEmitInfo(info));
2276     }
2277   }
2278   __ load(new LIR_Address(array.result(), arrayOopDesc::length_offset_in_bytes(), T_INT), reg, info, lir_patch_none);
2279 }
2280 
2281 
2282 void LIRGenerator::do_LoadIndexed(LoadIndexed* x) {
2283   bool use_length = x->length() != nullptr;
2284   LIRItem array(x->array(), this);
2285   LIRItem index(x->index(), this);
2286   LIRItem length(this);
2287   bool needs_range_check = x->compute_needs_range_check();
2288 
2289   if (use_length && needs_range_check) {
2290     length.set_instruction(x->length());
2291     length.load_item();
2292   }
2293 
2294   array.load_item();
2295   if (index.is_constant() && can_inline_as_constant(x->index())) {
2296     // let it be a constant
2297     index.dont_load_item();
2298   } else {
2299     index.load_item();
2300   }
2301 
2302   CodeEmitInfo* range_check_info = state_for(x);
2303   CodeEmitInfo* null_check_info = nullptr;
2304   if (x->needs_null_check()) {
2305     NullCheck* nc = x->explicit_null_check();
2306     if (nc != nullptr) {
2307       null_check_info = state_for(nc);
2308     } else {
2309       null_check_info = range_check_info;
2310     }
2311     if (StressLoopInvariantCodeMotion && null_check_info->deoptimize_on_exception()) {
2312       LIR_Opr obj = new_register(T_OBJECT);
2313       __ move(LIR_OprFact::oopConst(nullptr), obj);
2314       __ null_check(obj, new CodeEmitInfo(null_check_info));
2315     }
2316   }
2317 
2318   if (needs_range_check) {
2319     if (StressLoopInvariantCodeMotion && range_check_info->deoptimize_on_exception()) {
2320       __ branch(lir_cond_always, new RangeCheckStub(range_check_info, index.result(), array.result()));
2321     } else if (use_length) {
2322       // TODO: use a (modified) version of array_range_check that does not require a
2323       //       constant length to be loaded to a register
2324       __ cmp(lir_cond_belowEqual, length.result(), index.result());
2325       __ branch(lir_cond_belowEqual, new RangeCheckStub(range_check_info, index.result(), array.result()));
2326     } else {
2327       array_range_check(array.result(), index.result(), null_check_info, range_check_info);
2328       // The range check performs the null check, so clear it out for the load
2329       null_check_info = nullptr;
2330     }
2331   }
2332 
2333   ciMethodData* md = nullptr;
2334   ciArrayLoadData* load_data = nullptr;
2335   if (x->should_profile()) {
2336     if (x->array()->is_loaded_flat_array()) {
2337       // No need to profile a load from a flat array of known type. This can happen if
2338       // the type only became known after optimizations (for example, after the PhiSimplifier).
2339       x->set_should_profile(false);
2340     } else {
2341       int bci = x->profiled_bci();
2342       md = x->profiled_method()->method_data();
2343       assert(md != nullptr, "Sanity");
2344       ciProfileData* data = md->bci_to_data(bci);
2345       assert(data != nullptr && data->is_ArrayLoadData(), "incorrect profiling entry");
2346       load_data = (ciArrayLoadData*)data;
2347       profile_array_type(x, md, load_data);
2348     }
2349   }
2350 
2351   Value element;
2352   if (x->vt() != nullptr) {
2353     assert(x->array()->is_loaded_flat_array(), "must be");
2354     // Find the destination address (of the NewInlineTypeInstance).
2355     LIRItem obj_item(x->vt(), this);
2356 
2357     access_flat_array(true, array, index, obj_item,
2358                       x->delayed() == nullptr ? 0 : x->delayed()->field(),
2359                       x->delayed() == nullptr ? 0 : x->delayed()->offset());
2360     set_no_result(x);
2361   } else if (x->delayed() != nullptr) {
2362     assert(x->array()->is_loaded_flat_array(), "must be");
2363     LIR_Opr result = rlock_result(x, x->delayed()->field()->type()->basic_type());
2364     access_sub_element(array, index, result, x->delayed()->field(), x->delayed()->offset());
2365   } else if (x->array() != nullptr && x->array()->is_loaded_flat_array() &&
2366              x->array()->declared_type()->as_flat_array_klass()->element_klass()->as_inline_klass()->is_initialized() &&
2367              x->array()->declared_type()->as_flat_array_klass()->element_klass()->as_inline_klass()->is_empty()) {
2368     // Load the default instance instead of reading the element
2369     ciInlineKlass* elem_klass = x->array()->declared_type()->as_flat_array_klass()->element_klass()->as_inline_klass();
2370     LIR_Opr result = rlock_result(x, x->elt_type());
2371     assert(elem_klass->is_initialized(), "Must be");
2372     Constant* default_value = new Constant(new InstanceConstant(elem_klass->default_instance()));
2373     if (default_value->is_pinned()) {
2374       __ move(LIR_OprFact::value_type(default_value->type()), result);
2375     } else {
2376       __ move(load_constant(default_value), result);
2377     }
2378   } else {
2379     LIR_Opr result = rlock_result(x, x->elt_type());
2380     LoadFlattenedArrayStub* slow_path = nullptr;
2381 
2382     if (x->should_profile() && x->array()->maybe_null_free_array()) {
2383       profile_null_free_array(array, md, load_data);
2384     }
2385 
2386     if (x->elt_type() == T_OBJECT && x->array()->maybe_flat_array()) {
2387       assert(x->delayed() == nullptr, "Delayed LoadIndexed only apply to loaded_flat_arrays");
2388       index.load_item();
2389       // if we are loading from a flat array, load it using a runtime call
2390       slow_path = new LoadFlattenedArrayStub(array.result(), index.result(), result, state_for(x, x->state_before()));
2391       check_flat_array(array.result(), LIR_OprFact::illegalOpr, slow_path);
2392       set_in_conditional_code(true);
2393     }
2394 
2395     DecoratorSet decorators = IN_HEAP | IS_ARRAY;
2396     access_load_at(decorators, x->elt_type(),
2397                    array, index.result(), result,
2398                    nullptr, null_check_info);
2399 
2400     if (slow_path != nullptr) {
2401       __ branch_destination(slow_path->continuation());
2402       set_in_conditional_code(false);
2403     }
2404 
2405     element = x;
2406   }
2407 
2408   if (x->should_profile()) {
2409     profile_element_type(element, md, load_data);
2410   }
2411 }
2412 
2413 
2414 void LIRGenerator::do_NullCheck(NullCheck* x) {
2415   if (x->can_trap()) {
2416     LIRItem value(x->obj(), this);
2417     value.load_item();
2418     CodeEmitInfo* info = state_for(x);
2419     __ null_check(value.result(), info);
2420   }
2421 }
2422 
2423 
2424 void LIRGenerator::do_TypeCast(TypeCast* x) {
2425   LIRItem value(x->obj(), this);
2426   value.load_item();
2427   // the result is the same as from the node we are casting
2428   set_result(x, value.result());
2429 }
2430 
2431 
2432 void LIRGenerator::do_Throw(Throw* x) {
2433   LIRItem exception(x->exception(), this);
2434   exception.load_item();
2435   set_no_result(x);
2436   LIR_Opr exception_opr = exception.result();
2437   CodeEmitInfo* info = state_for(x, x->state());
2438 
2439 #ifndef PRODUCT
2440   if (PrintC1Statistics) {
2441     increment_counter(Runtime1::throw_count_address(), T_INT);
2442   }
2443 #endif
2444 
2445   // check if the instruction has an xhandler in any of the nested scopes
2446   bool unwind = false;
2447   if (info->exception_handlers()->length() == 0) {
2448     // this throw is not inside an xhandler
2449     unwind = true;
2450   } else {
2451     // get some idea of the throw type
2452     bool type_is_exact = true;
2453     ciType* throw_type = x->exception()->exact_type();
2454     if (throw_type == nullptr) {
2455       type_is_exact = false;
2456       throw_type = x->exception()->declared_type();
2457     }
2458     if (throw_type != nullptr && throw_type->is_instance_klass()) {
2459       ciInstanceKlass* throw_klass = (ciInstanceKlass*)throw_type;
2460       unwind = !x->exception_handlers()->could_catch(throw_klass, type_is_exact);
2461     }
2462   }
2463 
2464   // do null check before moving exception oop into fixed register
2465   // to avoid a fixed interval with an oop during the null check.
2466   // Use a copy of the CodeEmitInfo because debug information is
2467   // different for null_check and throw.
2468   if (x->exception()->as_NewInstance() == nullptr && x->exception()->as_ExceptionObject() == nullptr) {
2469     // if the exception object wasn't created using new then it might be null.
2470     __ null_check(exception_opr, new CodeEmitInfo(info, x->state()->copy(ValueStack::ExceptionState, x->state()->bci())));
2471   }
2472 
2473   if (compilation()->env()->jvmti_can_post_on_exceptions()) {
2474     // we need to go through the exception lookup path to get JVMTI
2475     // notification done
2476     unwind = false;
2477   }
2478 
2479   // move exception oop into fixed register
2480   __ move(exception_opr, exceptionOopOpr());
2481 
2482   if (unwind) {
2483     __ unwind_exception(exceptionOopOpr());
2484   } else {
2485     __ throw_exception(exceptionPcOpr(), exceptionOopOpr(), info);
2486   }
2487 }
2488 
2489 
2490 void LIRGenerator::do_RoundFP(RoundFP* x) {
2491   assert(strict_fp_requires_explicit_rounding, "not required");
2492 
2493   LIRItem input(x->input(), this);
2494   input.load_item();
2495   LIR_Opr input_opr = input.result();
2496   assert(input_opr->is_register(), "why round if value is not in a register?");
2497   assert(input_opr->is_single_fpu() || input_opr->is_double_fpu(), "input should be floating-point value");
2498   if (input_opr->is_single_fpu()) {
2499     set_result(x, round_item(input_opr)); // This code path not currently taken
2500   } else {
2501     LIR_Opr result = new_register(T_DOUBLE);
2502     set_vreg_flag(result, must_start_in_memory);
2503     __ roundfp(input_opr, LIR_OprFact::illegalOpr, result);
2504     set_result(x, result);
2505   }
2506 }
2507 
2508 
2509 void LIRGenerator::do_UnsafeGet(UnsafeGet* x) {
2510   BasicType type = x->basic_type();
2511   LIRItem src(x->object(), this);
2512   LIRItem off(x->offset(), this);
2513 
2514   off.load_item();
2515   src.load_item();
2516 
2517   DecoratorSet decorators = IN_HEAP | C1_UNSAFE_ACCESS;
2518 
2519   if (x->is_volatile()) {
2520     decorators |= MO_SEQ_CST;
2521   }
2522   if (type == T_BOOLEAN) {
2523     decorators |= C1_MASK_BOOLEAN;
2524   }
2525   if (is_reference_type(type)) {
2526     decorators |= ON_UNKNOWN_OOP_REF;
2527   }
2528 
2529   LIR_Opr result = rlock_result(x, type);
2530   if (!x->is_raw()) {
2531     access_load_at(decorators, type, src, off.result(), result);
2532   } else {
2533     // Currently it is only used in GraphBuilder::setup_osr_entry_block.
2534     // It reads the value from [src + offset] directly.
2535 #ifdef _LP64
2536     LIR_Opr offset = new_register(T_LONG);
2537     __ convert(Bytecodes::_i2l, off.result(), offset);
2538 #else
2539     LIR_Opr offset = off.result();
2540 #endif
2541     LIR_Address* addr = new LIR_Address(src.result(), offset, type);
2542     if (is_reference_type(type)) {
2543       __ move_wide(addr, result);
2544     } else {
2545       __ move(addr, result);
2546     }
2547   }
2548 }
2549 
2550 
2551 void LIRGenerator::do_UnsafePut(UnsafePut* x) {
2552   BasicType type = x->basic_type();
2553   LIRItem src(x->object(), this);
2554   LIRItem off(x->offset(), this);
2555   LIRItem data(x->value(), this);
2556 
2557   src.load_item();
2558   if (type == T_BOOLEAN || type == T_BYTE) {
2559     data.load_byte_item();
2560   } else {
2561     data.load_item();
2562   }
2563   off.load_item();
2564 
2565   set_no_result(x);
2566 
2567   DecoratorSet decorators = IN_HEAP | C1_UNSAFE_ACCESS;
2568   if (is_reference_type(type)) {
2569     decorators |= ON_UNKNOWN_OOP_REF;
2570   }
2571   if (x->is_volatile()) {
2572     decorators |= MO_SEQ_CST;
2573   }
2574   access_store_at(decorators, type, src, off.result(), data.result());
2575 }
2576 
2577 void LIRGenerator::do_UnsafeGetAndSet(UnsafeGetAndSet* x) {
2578   BasicType type = x->basic_type();
2579   LIRItem src(x->object(), this);
2580   LIRItem off(x->offset(), this);
2581   LIRItem value(x->value(), this);
2582 
2583   DecoratorSet decorators = IN_HEAP | C1_UNSAFE_ACCESS | MO_SEQ_CST;
2584 
2585   if (is_reference_type(type)) {
2586     decorators |= ON_UNKNOWN_OOP_REF;
2587   }
2588 
2589   LIR_Opr result;
2590   if (x->is_add()) {
2591     result = access_atomic_add_at(decorators, type, src, off, value);
2592   } else {
2593     result = access_atomic_xchg_at(decorators, type, src, off, value);
2594   }
2595   set_result(x, result);
2596 }
2597 
2598 void LIRGenerator::do_SwitchRanges(SwitchRangeArray* x, LIR_Opr value, BlockBegin* default_sux) {
2599   int lng = x->length();
2600 
2601   for (int i = 0; i < lng; i++) {
2602     C1SwitchRange* one_range = x->at(i);
2603     int low_key = one_range->low_key();
2604     int high_key = one_range->high_key();
2605     BlockBegin* dest = one_range->sux();
2606     if (low_key == high_key) {
2607       __ cmp(lir_cond_equal, value, low_key);
2608       __ branch(lir_cond_equal, dest);
2609     } else if (high_key - low_key == 1) {
2610       __ cmp(lir_cond_equal, value, low_key);
2611       __ branch(lir_cond_equal, dest);
2612       __ cmp(lir_cond_equal, value, high_key);
2613       __ branch(lir_cond_equal, dest);
2614     } else {
2615       LabelObj* L = new LabelObj();
2616       __ cmp(lir_cond_less, value, low_key);
2617       __ branch(lir_cond_less, L->label());
2618       __ cmp(lir_cond_lessEqual, value, high_key);
2619       __ branch(lir_cond_lessEqual, dest);
2620       __ branch_destination(L->label());
2621     }
2622   }
2623   __ jump(default_sux);
2624 }
2625 
2626 
2627 SwitchRangeArray* LIRGenerator::create_lookup_ranges(TableSwitch* x) {
2628   SwitchRangeList* res = new SwitchRangeList();
2629   int len = x->length();
2630   if (len > 0) {
2631     BlockBegin* sux = x->sux_at(0);
2632     int low = x->lo_key();
2633     BlockBegin* default_sux = x->default_sux();
2634     C1SwitchRange* range = new C1SwitchRange(low, sux);
2635     for (int i = 0; i < len; i++) {
2636       int key = low + i;
2637       BlockBegin* new_sux = x->sux_at(i);
2638       if (sux == new_sux) {
2639         // still in same range
2640         range->set_high_key(key);
2641       } else {
2642         // skip tests which explicitly dispatch to the default
2643         if (sux != default_sux) {
2644           res->append(range);
2645         }
2646         range = new C1SwitchRange(key, new_sux);
2647       }
2648       sux = new_sux;
2649     }
2650     if (res->length() == 0 || res->last() != range)  res->append(range);
2651   }
2652   return res;
2653 }
2654 
2655 
2656 // we expect the keys to be sorted by increasing value
2657 SwitchRangeArray* LIRGenerator::create_lookup_ranges(LookupSwitch* x) {
2658   SwitchRangeList* res = new SwitchRangeList();
2659   int len = x->length();
2660   if (len > 0) {
2661     BlockBegin* default_sux = x->default_sux();
2662     int key = x->key_at(0);
2663     BlockBegin* sux = x->sux_at(0);
2664     C1SwitchRange* range = new C1SwitchRange(key, sux);
2665     for (int i = 1; i < len; i++) {
2666       int new_key = x->key_at(i);
2667       BlockBegin* new_sux = x->sux_at(i);
2668       if (key+1 == new_key && sux == new_sux) {
2669         // still in same range
2670         range->set_high_key(new_key);
2671       } else {
2672         // skip tests which explicitly dispatch to the default
2673         if (range->sux() != default_sux) {
2674           res->append(range);
2675         }
2676         range = new C1SwitchRange(new_key, new_sux);
2677       }
2678       key = new_key;
2679       sux = new_sux;
2680     }
2681     if (res->length() == 0 || res->last() != range)  res->append(range);
2682   }
2683   return res;
2684 }
2685 
2686 
2687 void LIRGenerator::do_TableSwitch(TableSwitch* x) {
2688   LIRItem tag(x->tag(), this);
2689   tag.load_item();
2690   set_no_result(x);
2691 
2692   if (x->is_safepoint()) {
2693     __ safepoint(safepoint_poll_register(), state_for(x, x->state_before()));
2694   }
2695 
2696   // move values into phi locations
2697   move_to_phi(x->state());
2698 
2699   int lo_key = x->lo_key();
2700   int len = x->length();
2701   assert(lo_key <= (lo_key + (len - 1)), "integer overflow");
2702   LIR_Opr value = tag.result();
2703 
2704   if (compilation()->env()->comp_level() == CompLevel_full_profile && UseSwitchProfiling) {
2705     ciMethod* method = x->state()->scope()->method();
2706     ciMethodData* md = method->method_data_or_null();
2707     assert(md != nullptr, "Sanity");
2708     ciProfileData* data = md->bci_to_data(x->state()->bci());
2709     assert(data != nullptr, "must have profiling data");
2710     assert(data->is_MultiBranchData(), "bad profile data?");
2711     int default_count_offset = md->byte_offset_of_slot(data, MultiBranchData::default_count_offset());
2712     LIR_Opr md_reg = new_register(T_METADATA);
2713     __ metadata2reg(md->constant_encoding(), md_reg);
2714     LIR_Opr data_offset_reg = new_pointer_register();
2715     LIR_Opr tmp_reg = new_pointer_register();
2716 
2717     __ move(LIR_OprFact::intptrConst(default_count_offset), data_offset_reg);
2718     for (int i = 0; i < len; i++) {
2719       int count_offset = md->byte_offset_of_slot(data, MultiBranchData::case_count_offset(i));
2720       __ cmp(lir_cond_equal, value, i + lo_key);
2721       __ move(data_offset_reg, tmp_reg);
2722       __ cmove(lir_cond_equal,
2723                LIR_OprFact::intptrConst(count_offset),
2724                tmp_reg,
2725                data_offset_reg, T_INT);
2726     }
2727 
2728     LIR_Opr data_reg = new_pointer_register();
2729     LIR_Address* data_addr = new LIR_Address(md_reg, data_offset_reg, data_reg->type());
2730     __ move(data_addr, data_reg);
2731     __ add(data_reg, LIR_OprFact::intptrConst(1), data_reg);
2732     __ move(data_reg, data_addr);
2733   }
2734 
2735   if (UseTableRanges) {
2736     do_SwitchRanges(create_lookup_ranges(x), value, x->default_sux());
2737   } else {
2738     for (int i = 0; i < len; i++) {
2739       __ cmp(lir_cond_equal, value, i + lo_key);
2740       __ branch(lir_cond_equal, x->sux_at(i));
2741     }
2742     __ jump(x->default_sux());
2743   }
2744 }
2745 
2746 
2747 void LIRGenerator::do_LookupSwitch(LookupSwitch* x) {
2748   LIRItem tag(x->tag(), this);
2749   tag.load_item();
2750   set_no_result(x);
2751 
2752   if (x->is_safepoint()) {
2753     __ safepoint(safepoint_poll_register(), state_for(x, x->state_before()));
2754   }
2755 
2756   // move values into phi locations
2757   move_to_phi(x->state());
2758 
2759   LIR_Opr value = tag.result();
2760   int len = x->length();
2761 
2762   if (compilation()->env()->comp_level() == CompLevel_full_profile && UseSwitchProfiling) {
2763     ciMethod* method = x->state()->scope()->method();
2764     ciMethodData* md = method->method_data_or_null();
2765     assert(md != nullptr, "Sanity");
2766     ciProfileData* data = md->bci_to_data(x->state()->bci());
2767     assert(data != nullptr, "must have profiling data");
2768     assert(data->is_MultiBranchData(), "bad profile data?");
2769     int default_count_offset = md->byte_offset_of_slot(data, MultiBranchData::default_count_offset());
2770     LIR_Opr md_reg = new_register(T_METADATA);
2771     __ metadata2reg(md->constant_encoding(), md_reg);
2772     LIR_Opr data_offset_reg = new_pointer_register();
2773     LIR_Opr tmp_reg = new_pointer_register();
2774 
2775     __ move(LIR_OprFact::intptrConst(default_count_offset), data_offset_reg);
2776     for (int i = 0; i < len; i++) {
2777       int count_offset = md->byte_offset_of_slot(data, MultiBranchData::case_count_offset(i));
2778       __ cmp(lir_cond_equal, value, x->key_at(i));
2779       __ move(data_offset_reg, tmp_reg);
2780       __ cmove(lir_cond_equal,
2781                LIR_OprFact::intptrConst(count_offset),
2782                tmp_reg,
2783                data_offset_reg, T_INT);
2784     }
2785 
2786     LIR_Opr data_reg = new_pointer_register();
2787     LIR_Address* data_addr = new LIR_Address(md_reg, data_offset_reg, data_reg->type());
2788     __ move(data_addr, data_reg);
2789     __ add(data_reg, LIR_OprFact::intptrConst(1), data_reg);
2790     __ move(data_reg, data_addr);
2791   }
2792 
2793   if (UseTableRanges) {
2794     do_SwitchRanges(create_lookup_ranges(x), value, x->default_sux());
2795   } else {
2796     int len = x->length();
2797     for (int i = 0; i < len; i++) {
2798       __ cmp(lir_cond_equal, value, x->key_at(i));
2799       __ branch(lir_cond_equal, x->sux_at(i));
2800     }
2801     __ jump(x->default_sux());
2802   }
2803 }
2804 
2805 
2806 void LIRGenerator::do_Goto(Goto* x) {
2807   set_no_result(x);
2808 
2809   if (block()->next()->as_OsrEntry()) {
2810     // need to free up storage used for OSR entry point
2811     LIR_Opr osrBuffer = block()->next()->operand();
2812     BasicTypeList signature;
2813     signature.append(NOT_LP64(T_INT) LP64_ONLY(T_LONG)); // pass a pointer to osrBuffer
2814     CallingConvention* cc = frame_map()->c_calling_convention(&signature);
2815     __ move(osrBuffer, cc->args()->at(0));
2816     __ call_runtime_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::OSR_migration_end),
2817                          getThreadTemp(), LIR_OprFact::illegalOpr, cc->args());
2818   }
2819 
2820   if (x->is_safepoint()) {
2821     ValueStack* state = x->state_before() ? x->state_before() : x->state();
2822 
2823     // increment backedge counter if needed
2824     CodeEmitInfo* info = state_for(x, state);
2825     increment_backedge_counter(info, x->profiled_bci());
2826     CodeEmitInfo* safepoint_info = state_for(x, state);
2827     __ safepoint(safepoint_poll_register(), safepoint_info);
2828   }
2829 
2830   // Gotos can be folded Ifs, handle this case.
2831   if (x->should_profile()) {
2832     ciMethod* method = x->profiled_method();
2833     assert(method != nullptr, "method should be set if branch is profiled");
2834     ciMethodData* md = method->method_data_or_null();
2835     assert(md != nullptr, "Sanity");
2836     ciProfileData* data = md->bci_to_data(x->profiled_bci());
2837     assert(data != nullptr, "must have profiling data");
2838     int offset;
2839     if (x->direction() == Goto::taken) {
2840       assert(data->is_BranchData(), "need BranchData for two-way branches");
2841       offset = md->byte_offset_of_slot(data, BranchData::taken_offset());
2842     } else if (x->direction() == Goto::not_taken) {
2843       assert(data->is_BranchData(), "need BranchData for two-way branches");
2844       offset = md->byte_offset_of_slot(data, BranchData::not_taken_offset());
2845     } else {
2846       assert(data->is_JumpData(), "need JumpData for branches");
2847       offset = md->byte_offset_of_slot(data, JumpData::taken_offset());
2848     }
2849     LIR_Opr md_reg = new_register(T_METADATA);
2850     __ metadata2reg(md->constant_encoding(), md_reg);
2851 
2852     increment_counter(new LIR_Address(md_reg, offset,
2853                                       NOT_LP64(T_INT) LP64_ONLY(T_LONG)), DataLayout::counter_increment);
2854   }
2855 
2856   // emit phi-instruction move after safepoint since this simplifies
2857   // describing the state as the safepoint.
2858   move_to_phi(x->state());
2859 
2860   __ jump(x->default_sux());
2861 }
2862 
2863 /**
2864  * Emit profiling code if needed for arguments, parameters, return value types
2865  *
2866  * @param md                    MDO the code will update at runtime
2867  * @param md_base_offset        common offset in the MDO for this profile and subsequent ones
2868  * @param md_offset             offset in the MDO (on top of md_base_offset) for this profile
2869  * @param profiled_k            current profile
2870  * @param obj                   IR node for the object to be profiled
2871  * @param mdp                   register to hold the pointer inside the MDO (md + md_base_offset).
2872  *                              Set once we find an update to make and use for next ones.
2873  * @param not_null              true if we know obj cannot be null
2874  * @param signature_at_call_k   signature at call for obj
2875  * @param callee_signature_k    signature of callee for obj
2876  *                              at call and callee signatures differ at method handle call
2877  * @return                      the only klass we know will ever be seen at this profile point
2878  */
2879 ciKlass* LIRGenerator::profile_type(ciMethodData* md, int md_base_offset, int md_offset, intptr_t profiled_k,
2880                                     Value obj, LIR_Opr& mdp, bool not_null, ciKlass* signature_at_call_k,
2881                                     ciKlass* callee_signature_k) {
2882   ciKlass* result = nullptr;
2883   bool do_null = !not_null && !TypeEntries::was_null_seen(profiled_k);
2884   bool do_update = !TypeEntries::is_type_unknown(profiled_k);
2885   // known not to be null or null bit already set and already set to
2886   // unknown: nothing we can do to improve profiling
2887   if (!do_null && !do_update) {
2888     return result;
2889   }
2890 
2891   ciKlass* exact_klass = nullptr;
2892   Compilation* comp = Compilation::current();
2893   if (do_update) {
2894     // try to find exact type, using CHA if possible, so that loading
2895     // the klass from the object can be avoided
2896     ciType* type = obj->exact_type();
2897     if (type == nullptr) {
2898       type = obj->declared_type();
2899       type = comp->cha_exact_type(type);
2900     }
2901     assert(type == nullptr || type->is_klass(), "type should be class");
2902     exact_klass = (type != nullptr && type->is_loaded()) ? (ciKlass*)type : nullptr;
2903 
2904     do_update = exact_klass == nullptr || ciTypeEntries::valid_ciklass(profiled_k) != exact_klass;
2905   }
2906 
2907   if (!do_null && !do_update) {
2908     return result;
2909   }
2910 
2911   ciKlass* exact_signature_k = nullptr;
2912   if (do_update && signature_at_call_k != nullptr) {
2913     // Is the type from the signature exact (the only one possible)?
2914     exact_signature_k = signature_at_call_k->exact_klass();
2915     if (exact_signature_k == nullptr) {
2916       exact_signature_k = comp->cha_exact_type(signature_at_call_k);
2917     } else {
2918       result = exact_signature_k;
2919       // Known statically. No need to emit any code: prevent
2920       // LIR_Assembler::emit_profile_type() from emitting useless code
2921       profiled_k = ciTypeEntries::with_status(result, profiled_k);
2922     }
2923     // exact_klass and exact_signature_k can be both non null but
2924     // different if exact_klass is loaded after the ciObject for
2925     // exact_signature_k is created.
2926     if (exact_klass == nullptr && exact_signature_k != nullptr && exact_klass != exact_signature_k) {
2927       // sometimes the type of the signature is better than the best type
2928       // the compiler has
2929       exact_klass = exact_signature_k;
2930     }
2931     if (callee_signature_k != nullptr &&
2932         callee_signature_k != signature_at_call_k) {
2933       ciKlass* improved_klass = callee_signature_k->exact_klass();
2934       if (improved_klass == nullptr) {
2935         improved_klass = comp->cha_exact_type(callee_signature_k);
2936       }
2937       if (exact_klass == nullptr && improved_klass != nullptr && exact_klass != improved_klass) {
2938         exact_klass = exact_signature_k;
2939       }
2940     }
2941     do_update = exact_klass == nullptr || ciTypeEntries::valid_ciklass(profiled_k) != exact_klass;
2942   }
2943 
2944   if (!do_null && !do_update) {
2945     return result;
2946   }
2947 
2948   if (mdp == LIR_OprFact::illegalOpr) {
2949     mdp = new_register(T_METADATA);
2950     __ metadata2reg(md->constant_encoding(), mdp);
2951     if (md_base_offset != 0) {
2952       LIR_Address* base_type_address = new LIR_Address(mdp, md_base_offset, T_ADDRESS);
2953       mdp = new_pointer_register();
2954       __ leal(LIR_OprFact::address(base_type_address), mdp);
2955     }
2956   }
2957   LIRItem value(obj, this);
2958   value.load_item();
2959   __ profile_type(new LIR_Address(mdp, md_offset, T_METADATA),
2960                   value.result(), exact_klass, profiled_k, new_pointer_register(), not_null, exact_signature_k != nullptr);
2961   return result;
2962 }
2963 
2964 // profile parameters on entry to the root of the compilation
2965 void LIRGenerator::profile_parameters(Base* x) {
2966   if (compilation()->profile_parameters()) {
2967     CallingConvention* args = compilation()->frame_map()->incoming_arguments();
2968     ciMethodData* md = scope()->method()->method_data_or_null();
2969     assert(md != nullptr, "Sanity");
2970 
2971     if (md->parameters_type_data() != nullptr) {
2972       ciParametersTypeData* parameters_type_data = md->parameters_type_data();
2973       ciTypeStackSlotEntries* parameters =  parameters_type_data->parameters();
2974       LIR_Opr mdp = LIR_OprFact::illegalOpr;
2975       for (int java_index = 0, i = 0, j = 0; j < parameters_type_data->number_of_parameters(); i++) {
2976         LIR_Opr src = args->at(i);
2977         assert(!src->is_illegal(), "check");
2978         BasicType t = src->type();
2979         if (is_reference_type(t)) {
2980           intptr_t profiled_k = parameters->type(j);
2981           Local* local = x->state()->local_at(java_index)->as_Local();
2982           ciKlass* exact = profile_type(md, md->byte_offset_of_slot(parameters_type_data, ParametersTypeData::type_offset(0)),
2983                                         in_bytes(ParametersTypeData::type_offset(j)) - in_bytes(ParametersTypeData::type_offset(0)),
2984                                         profiled_k, local, mdp, false, local->declared_type()->as_klass(), nullptr);
2985           // If the profile is known statically set it once for all and do not emit any code
2986           if (exact != nullptr) {
2987             md->set_parameter_type(j, exact);
2988           }
2989           j++;
2990         }
2991         java_index += type2size[t];
2992       }
2993     }
2994   }
2995 }
2996 
2997 void LIRGenerator::profile_flags(ciMethodData* md, ciProfileData* data, int flag, LIR_Condition condition) {
2998   assert(md != nullptr && data != nullptr, "should have been initialized");
2999   LIR_Opr mdp = new_register(T_METADATA);
3000   __ metadata2reg(md->constant_encoding(), mdp);
3001   LIR_Address* addr = new LIR_Address(mdp, md->byte_offset_of_slot(data, DataLayout::flags_offset()), T_BYTE);
3002   LIR_Opr flags = new_register(T_INT);
3003   __ move(addr, flags);
3004   if (condition != lir_cond_always) {
3005     LIR_Opr update = new_register(T_INT);
3006     __ cmove(condition, LIR_OprFact::intConst(0), LIR_OprFact::intConst(flag), update, T_INT);
3007   } else {
3008     __ logical_or(flags, LIR_OprFact::intConst(flag), flags);
3009   }
3010   __ store(flags, addr);
3011 }
3012 
3013 template <class ArrayData> void LIRGenerator::profile_null_free_array(LIRItem array, ciMethodData* md, ArrayData* load_store) {
3014   assert(compilation()->profile_array_accesses(), "array access profiling is disabled");
3015   LabelObj* L_end = new LabelObj();
3016   LIR_Opr tmp = new_register(T_METADATA);
3017   __ check_null_free_array(array.result(), tmp);
3018 
3019   profile_flags(md, load_store, ArrayStoreData::null_free_array_byte_constant(), lir_cond_equal);
3020 }
3021 
3022 template <class ArrayData> void LIRGenerator::profile_array_type(AccessIndexed* x, ciMethodData*& md, ArrayData*& load_store) {
3023   assert(compilation()->profile_array_accesses(), "array access profiling is disabled");
3024   LIR_Opr mdp = LIR_OprFact::illegalOpr;
3025   profile_type(md, md->byte_offset_of_slot(load_store, ArrayData::array_offset()), 0,
3026                load_store->array()->type(), x->array(), mdp, true, nullptr, nullptr);
3027 }
3028 
3029 void LIRGenerator::profile_element_type(Value element, ciMethodData* md, ciArrayLoadData* load_data) {
3030   assert(compilation()->profile_array_accesses(), "array access profiling is disabled");
3031   assert(md != nullptr && load_data != nullptr, "should have been initialized");
3032   LIR_Opr mdp = LIR_OprFact::illegalOpr;
3033   profile_type(md, md->byte_offset_of_slot(load_data, ArrayLoadData::element_offset()), 0,
3034                load_data->element()->type(), element, mdp, false, nullptr, nullptr);
3035 }
3036 
3037 void LIRGenerator::do_Base(Base* x) {
3038   __ std_entry(LIR_OprFact::illegalOpr);
3039   // Emit moves from physical registers / stack slots to virtual registers
3040   CallingConvention* args = compilation()->frame_map()->incoming_arguments();
3041   IRScope* irScope = compilation()->hir()->top_scope();
3042   int java_index = 0;
3043   for (int i = 0; i < args->length(); i++) {
3044     LIR_Opr src = args->at(i);
3045     assert(!src->is_illegal(), "check");
3046     BasicType t = src->type();
3047 
3048     // Types which are smaller than int are passed as int, so
3049     // correct the type which passed.
3050     switch (t) {
3051     case T_BYTE:
3052     case T_BOOLEAN:
3053     case T_SHORT:
3054     case T_CHAR:
3055       t = T_INT;
3056       break;
3057     default:
3058       break;
3059     }
3060 
3061     LIR_Opr dest = new_register(t);
3062     __ move(src, dest);
3063 
3064     // Assign new location to Local instruction for this local
3065     Local* local = x->state()->local_at(java_index)->as_Local();
3066     assert(local != nullptr, "Locals for incoming arguments must have been created");
3067 #ifndef __SOFTFP__
3068     // The java calling convention passes double as long and float as int.
3069     assert(as_ValueType(t)->tag() == local->type()->tag(), "check");
3070 #endif // __SOFTFP__
3071     local->set_operand(dest);
3072 #ifdef ASSERT
3073     _instruction_for_operand.at_put_grow(dest->vreg_number(), local, nullptr);
3074 #endif
3075     java_index += type2size[t];
3076   }
3077 
3078   if (compilation()->env()->dtrace_method_probes()) {
3079     BasicTypeList signature;
3080     signature.append(LP64_ONLY(T_LONG) NOT_LP64(T_INT));    // thread
3081     signature.append(T_METADATA); // Method*
3082     LIR_OprList* args = new LIR_OprList();
3083     args->append(getThreadPointer());
3084     LIR_Opr meth = new_register(T_METADATA);
3085     __ metadata2reg(method()->constant_encoding(), meth);
3086     args->append(meth);
3087     call_runtime(&signature, args, CAST_FROM_FN_PTR(address, SharedRuntime::dtrace_method_entry), voidType, nullptr);
3088   }
3089 
3090   if (method()->is_synchronized()) {
3091     LIR_Opr obj;
3092     if (method()->is_static()) {
3093       obj = new_register(T_OBJECT);
3094       __ oop2reg(method()->holder()->java_mirror()->constant_encoding(), obj);
3095     } else {
3096       Local* receiver = x->state()->local_at(0)->as_Local();
3097       assert(receiver != nullptr, "must already exist");
3098       obj = receiver->operand();
3099     }
3100     assert(obj->is_valid(), "must be valid");
3101 
3102     if (method()->is_synchronized() && GenerateSynchronizationCode) {
3103       LIR_Opr lock = syncLockOpr();
3104       __ load_stack_address_monitor(0, lock);
3105 
3106       CodeEmitInfo* info = new CodeEmitInfo(scope()->start()->state()->copy(ValueStack::StateBefore, SynchronizationEntryBCI), nullptr, x->check_flag(Instruction::DeoptimizeOnException));
3107       CodeStub* slow_path = new MonitorEnterStub(obj, lock, info);
3108 
3109       // receiver is guaranteed non-null so don't need CodeEmitInfo
3110       __ lock_object(syncTempOpr(), obj, lock, new_register(T_OBJECT), slow_path, nullptr);
3111     }
3112   }
3113   // increment invocation counters if needed
3114   if (!method()->is_accessor()) { // Accessors do not have MDOs, so no counting.
3115     profile_parameters(x);
3116     CodeEmitInfo* info = new CodeEmitInfo(scope()->start()->state()->copy(ValueStack::StateBefore, SynchronizationEntryBCI), nullptr, false);
3117     increment_invocation_counter(info);
3118   }
3119   if (method()->has_scalarized_args()) {
3120     // Check if deoptimization was triggered (i.e. orig_pc was set) while buffering scalarized inline type arguments
3121     // in the entry point (see comments in frame::deoptimize). If so, deoptimize only now that we have the right state.
3122     CodeEmitInfo* info = new CodeEmitInfo(scope()->start()->state()->copy(ValueStack::StateBefore, 0), nullptr, false);
3123     CodeStub* deopt_stub = new DeoptimizeStub(info, Deoptimization::Reason_none, Deoptimization::Action_none);
3124     __ append(new LIR_Op0(lir_check_orig_pc));
3125     __ branch(lir_cond_notEqual, deopt_stub);
3126   }
3127 
3128   // all blocks with a successor must end with an unconditional jump
3129   // to the successor even if they are consecutive
3130   __ jump(x->default_sux());
3131 }
3132 
3133 
3134 void LIRGenerator::do_OsrEntry(OsrEntry* x) {
3135   // construct our frame and model the production of incoming pointer
3136   // to the OSR buffer.
3137   __ osr_entry(LIR_Assembler::osrBufferPointer());
3138   LIR_Opr result = rlock_result(x);
3139   __ move(LIR_Assembler::osrBufferPointer(), result);
3140 }
3141 
3142 void LIRGenerator::invoke_load_one_argument(LIRItem* param, LIR_Opr loc) {
3143   if (loc->is_register()) {
3144     param->load_item_force(loc);
3145   } else {
3146     LIR_Address* addr = loc->as_address_ptr();
3147     param->load_for_store(addr->type());
3148     if (addr->type() == T_OBJECT) {
3149       __ move_wide(param->result(), addr);
3150     } else {
3151       __ move(param->result(), addr);
3152     }
3153   }
3154 }
3155 
3156 void LIRGenerator::invoke_load_arguments(Invoke* x, LIRItemList* args, const LIR_OprList* arg_list) {
3157   assert(args->length() == arg_list->length(),
3158          "args=%d, arg_list=%d", args->length(), arg_list->length());
3159   for (int i = x->has_receiver() ? 1 : 0; i < args->length(); i++) {
3160     LIRItem* param = args->at(i);
3161     LIR_Opr loc = arg_list->at(i);
3162     invoke_load_one_argument(param, loc);
3163   }
3164 
3165   if (x->has_receiver()) {
3166     LIRItem* receiver = args->at(0);
3167     LIR_Opr loc = arg_list->at(0);
3168     if (loc->is_register()) {
3169       receiver->load_item_force(loc);
3170     } else {
3171       assert(loc->is_address(), "just checking");
3172       receiver->load_for_store(T_OBJECT);
3173       __ move_wide(receiver->result(), loc->as_address_ptr());
3174     }
3175   }
3176 }
3177 
3178 
3179 // Visits all arguments, returns appropriate items without loading them
3180 LIRItemList* LIRGenerator::invoke_visit_arguments(Invoke* x) {
3181   LIRItemList* argument_items = new LIRItemList();
3182   if (x->has_receiver()) {
3183     LIRItem* receiver = new LIRItem(x->receiver(), this);
3184     argument_items->append(receiver);
3185   }
3186   for (int i = 0; i < x->number_of_arguments(); i++) {
3187     LIRItem* param = new LIRItem(x->argument_at(i), this);
3188     argument_items->append(param);
3189   }
3190   return argument_items;
3191 }
3192 
3193 
3194 // The invoke with receiver has following phases:
3195 //   a) traverse and load/lock receiver;
3196 //   b) traverse all arguments -> item-array (invoke_visit_argument)
3197 //   c) push receiver on stack
3198 //   d) load each of the items and push on stack
3199 //   e) unlock receiver
3200 //   f) move receiver into receiver-register %o0
3201 //   g) lock result registers and emit call operation
3202 //
3203 // Before issuing a call, we must spill-save all values on stack
3204 // that are in caller-save register. "spill-save" moves those registers
3205 // either in a free callee-save register or spills them if no free
3206 // callee save register is available.
3207 //
3208 // The problem is where to invoke spill-save.
3209 // - if invoked between e) and f), we may lock callee save
3210 //   register in "spill-save" that destroys the receiver register
3211 //   before f) is executed
3212 // - if we rearrange f) to be earlier (by loading %o0) it
3213 //   may destroy a value on the stack that is currently in %o0
3214 //   and is waiting to be spilled
3215 // - if we keep the receiver locked while doing spill-save,
3216 //   we cannot spill it as it is spill-locked
3217 //
3218 void LIRGenerator::do_Invoke(Invoke* x) {
3219   CallingConvention* cc = frame_map()->java_calling_convention(x->signature(), true);
3220 
3221   LIR_OprList* arg_list = cc->args();
3222   LIRItemList* args = invoke_visit_arguments(x);
3223   LIR_Opr receiver = LIR_OprFact::illegalOpr;
3224 
3225   // setup result register
3226   LIR_Opr result_register = LIR_OprFact::illegalOpr;
3227   if (x->type() != voidType) {
3228     result_register = result_register_for(x->type());
3229   }
3230 
3231   CodeEmitInfo* info = state_for(x, x->state());
3232 
3233   invoke_load_arguments(x, args, arg_list);
3234 
3235   if (x->has_receiver()) {
3236     args->at(0)->load_item_force(LIR_Assembler::receiverOpr());
3237     receiver = args->at(0)->result();
3238   }
3239 
3240   // emit invoke code
3241   assert(receiver->is_illegal() || receiver->is_equal(LIR_Assembler::receiverOpr()), "must match");
3242 
3243   // JSR 292
3244   // Preserve the SP over MethodHandle call sites, if needed.
3245   ciMethod* target = x->target();
3246   bool is_method_handle_invoke = (// %%% FIXME: Are both of these relevant?
3247                                   target->is_method_handle_intrinsic() ||
3248                                   target->is_compiled_lambda_form());
3249   if (is_method_handle_invoke) {
3250     info->set_is_method_handle_invoke(true);
3251     if(FrameMap::method_handle_invoke_SP_save_opr() != LIR_OprFact::illegalOpr) {
3252         __ move(FrameMap::stack_pointer(), FrameMap::method_handle_invoke_SP_save_opr());
3253     }
3254   }
3255 
3256   switch (x->code()) {
3257     case Bytecodes::_invokestatic:
3258       __ call_static(target, result_register,
3259                      SharedRuntime::get_resolve_static_call_stub(),
3260                      arg_list, info);
3261       break;
3262     case Bytecodes::_invokespecial:
3263     case Bytecodes::_invokevirtual:
3264     case Bytecodes::_invokeinterface:
3265       // for loaded and final (method or class) target we still produce an inline cache,
3266       // in order to be able to call mixed mode
3267       if (x->code() == Bytecodes::_invokespecial || x->target_is_final()) {
3268         __ call_opt_virtual(target, receiver, result_register,
3269                             SharedRuntime::get_resolve_opt_virtual_call_stub(),
3270                             arg_list, info);
3271       } else {
3272         __ call_icvirtual(target, receiver, result_register,
3273                           SharedRuntime::get_resolve_virtual_call_stub(),
3274                           arg_list, info);
3275       }
3276       break;
3277     case Bytecodes::_invokedynamic: {
3278       __ call_dynamic(target, receiver, result_register,
3279                       SharedRuntime::get_resolve_static_call_stub(),
3280                       arg_list, info);
3281       break;
3282     }
3283     default:
3284       fatal("unexpected bytecode: %s", Bytecodes::name(x->code()));
3285       break;
3286   }
3287 
3288   // JSR 292
3289   // Restore the SP after MethodHandle call sites, if needed.
3290   if (is_method_handle_invoke
3291       && FrameMap::method_handle_invoke_SP_save_opr() != LIR_OprFact::illegalOpr) {
3292     __ move(FrameMap::method_handle_invoke_SP_save_opr(), FrameMap::stack_pointer());
3293   }
3294 
3295   if (result_register->is_valid()) {
3296     LIR_Opr result = rlock_result(x);
3297     __ move(result_register, result);
3298   }
3299 }
3300 
3301 
3302 void LIRGenerator::do_FPIntrinsics(Intrinsic* x) {
3303   assert(x->number_of_arguments() == 1, "wrong type");
3304   LIRItem value       (x->argument_at(0), this);
3305   LIR_Opr reg = rlock_result(x);
3306   value.load_item();
3307   LIR_Opr tmp = force_to_spill(value.result(), as_BasicType(x->type()));
3308   __ move(tmp, reg);
3309 }
3310 
3311 
3312 
3313 // Code for  :  x->x() {x->cond()} x->y() ? x->tval() : x->fval()
3314 void LIRGenerator::do_IfOp(IfOp* x) {
3315 #ifdef ASSERT
3316   {
3317     ValueTag xtag = x->x()->type()->tag();
3318     ValueTag ttag = x->tval()->type()->tag();
3319     assert(xtag == intTag || xtag == objectTag, "cannot handle others");
3320     assert(ttag == addressTag || ttag == intTag || ttag == objectTag || ttag == longTag, "cannot handle others");
3321     assert(ttag == x->fval()->type()->tag(), "cannot handle others");
3322   }
3323 #endif
3324 
3325   LIRItem left(x->x(), this);
3326   LIRItem right(x->y(), this);
3327   left.load_item();
3328   if (can_inline_as_constant(right.value()) && !x->substitutability_check()) {
3329     right.dont_load_item();
3330   } else {
3331     // substitutability_check() needs to use right as a base register.
3332     right.load_item();
3333   }
3334 
3335   LIRItem t_val(x->tval(), this);
3336   LIRItem f_val(x->fval(), this);
3337   t_val.dont_load_item();
3338   f_val.dont_load_item();
3339 
3340   if (x->substitutability_check()) {
3341     substitutability_check(x, left, right, t_val, f_val);
3342   } else {
3343     LIR_Opr reg = rlock_result(x);
3344     __ cmp(lir_cond(x->cond()), left.result(), right.result());
3345     __ cmove(lir_cond(x->cond()), t_val.result(), f_val.result(), reg, as_BasicType(x->x()->type()));
3346   }
3347 }
3348 
3349 void LIRGenerator::substitutability_check(IfOp* x, LIRItem& left, LIRItem& right, LIRItem& t_val, LIRItem& f_val) {
3350   assert(x->cond() == If::eql || x->cond() == If::neq, "must be");
3351   bool is_acmpeq = (x->cond() == If::eql);
3352   LIR_Opr equal_result     = is_acmpeq ? t_val.result() : f_val.result();
3353   LIR_Opr not_equal_result = is_acmpeq ? f_val.result() : t_val.result();
3354   LIR_Opr result = rlock_result(x);
3355   CodeEmitInfo* info = state_for(x, x->state_before());
3356 
3357   substitutability_check_common(x->x(), x->y(), left, right, equal_result, not_equal_result, result, info);
3358 }
3359 
3360 void LIRGenerator::substitutability_check(If* x, LIRItem& left, LIRItem& right) {
3361   LIR_Opr equal_result     = LIR_OprFact::intConst(1);
3362   LIR_Opr not_equal_result = LIR_OprFact::intConst(0);
3363   LIR_Opr result = new_register(T_INT);
3364   CodeEmitInfo* info = state_for(x, x->state_before());
3365 
3366   substitutability_check_common(x->x(), x->y(), left, right, equal_result, not_equal_result, result, info);
3367 
3368   assert(x->cond() == If::eql || x->cond() == If::neq, "must be");
3369   __ cmp(lir_cond(x->cond()), result, equal_result);
3370 }
3371 
3372 void LIRGenerator::substitutability_check_common(Value left_val, Value right_val, LIRItem& left, LIRItem& right,
3373                                                  LIR_Opr equal_result, LIR_Opr not_equal_result, LIR_Opr result,
3374                                                  CodeEmitInfo* info) {
3375   LIR_Opr tmp1 = LIR_OprFact::illegalOpr;
3376   LIR_Opr tmp2 = LIR_OprFact::illegalOpr;
3377   LIR_Opr left_klass_op = LIR_OprFact::illegalOpr;
3378   LIR_Opr right_klass_op = LIR_OprFact::illegalOpr;
3379 
3380   ciKlass* left_klass  = left_val ->as_loaded_klass_or_null();
3381   ciKlass* right_klass = right_val->as_loaded_klass_or_null();
3382 
3383   if ((left_klass == nullptr || right_klass == nullptr) ||// The klass is still unloaded, or came from a Phi node.
3384       !left_klass->is_inlinetype() || !right_klass->is_inlinetype()) {
3385     init_temps_for_substitutability_check(tmp1, tmp2);
3386   }
3387 
3388   if (left_klass != nullptr && left_klass->is_inlinetype() && left_klass == right_klass) {
3389     // No need to load klass -- the operands are statically known to be the same inline klass.
3390   } else {
3391     BasicType t_klass = UseCompressedOops ? T_INT : T_METADATA;
3392     left_klass_op = new_register(t_klass);
3393     right_klass_op = new_register(t_klass);
3394   }
3395 
3396   CodeStub* slow_path = new SubstitutabilityCheckStub(left.result(), right.result(), info);
3397   __ substitutability_check(result, left.result(), right.result(), equal_result, not_equal_result,
3398                             tmp1, tmp2,
3399                             left_klass, right_klass, left_klass_op, right_klass_op, info, slow_path);
3400 }
3401 
3402 void LIRGenerator::do_RuntimeCall(address routine, Intrinsic* x) {
3403   assert(x->number_of_arguments() == 0, "wrong type");
3404   // Enforce computation of _reserved_argument_area_size which is required on some platforms.
3405   BasicTypeList signature;
3406   CallingConvention* cc = frame_map()->c_calling_convention(&signature);
3407   LIR_Opr reg = result_register_for(x->type());
3408   __ call_runtime_leaf(routine, getThreadTemp(),
3409                        reg, new LIR_OprList());
3410   LIR_Opr result = rlock_result(x);
3411   __ move(reg, result);
3412 }
3413 
3414 
3415 
3416 void LIRGenerator::do_Intrinsic(Intrinsic* x) {
3417   switch (x->id()) {
3418   case vmIntrinsics::_intBitsToFloat      :
3419   case vmIntrinsics::_doubleToRawLongBits :
3420   case vmIntrinsics::_longBitsToDouble    :
3421   case vmIntrinsics::_floatToRawIntBits   : {
3422     do_FPIntrinsics(x);
3423     break;
3424   }
3425 
3426 #ifdef JFR_HAVE_INTRINSICS
3427   case vmIntrinsics::_counterTime:
3428     do_RuntimeCall(CAST_FROM_FN_PTR(address, JfrTime::time_function()), x);
3429     break;
3430 #endif
3431 
3432   case vmIntrinsics::_currentTimeMillis:
3433     do_RuntimeCall(CAST_FROM_FN_PTR(address, os::javaTimeMillis), x);
3434     break;
3435 
3436   case vmIntrinsics::_nanoTime:
3437     do_RuntimeCall(CAST_FROM_FN_PTR(address, os::javaTimeNanos), x);
3438     break;
3439 
3440   case vmIntrinsics::_Object_init:    do_RegisterFinalizer(x); break;
3441   case vmIntrinsics::_isInstance:     do_isInstance(x);    break;
3442   case vmIntrinsics::_isPrimitive:    do_isPrimitive(x);   break;
3443   case vmIntrinsics::_getModifiers:   do_getModifiers(x);  break;
3444   case vmIntrinsics::_getClass:       do_getClass(x);      break;
3445   case vmIntrinsics::_getObjectSize:  do_getObjectSize(x); break;
3446   case vmIntrinsics::_currentCarrierThread: do_currentCarrierThread(x); break;
3447   case vmIntrinsics::_currentThread:  do_vthread(x);       break;
3448   case vmIntrinsics::_scopedValueCache: do_scopedValueCache(x); break;
3449 
3450   case vmIntrinsics::_dlog:           // fall through
3451   case vmIntrinsics::_dlog10:         // fall through
3452   case vmIntrinsics::_dabs:           // fall through
3453   case vmIntrinsics::_dsqrt:          // fall through
3454   case vmIntrinsics::_dsqrt_strict:   // fall through
3455   case vmIntrinsics::_dtan:           // fall through
3456   case vmIntrinsics::_dsin :          // fall through
3457   case vmIntrinsics::_dcos :          // fall through
3458   case vmIntrinsics::_dexp :          // fall through
3459   case vmIntrinsics::_dpow :          do_MathIntrinsic(x); break;
3460   case vmIntrinsics::_arraycopy:      do_ArrayCopy(x);     break;
3461 
3462   case vmIntrinsics::_fmaD:           do_FmaIntrinsic(x); break;
3463   case vmIntrinsics::_fmaF:           do_FmaIntrinsic(x); break;
3464 
3465   // Use java.lang.Math intrinsics code since it works for these intrinsics too.
3466   case vmIntrinsics::_floatToFloat16: // fall through
3467   case vmIntrinsics::_float16ToFloat: do_MathIntrinsic(x); break;
3468 
3469   case vmIntrinsics::_Preconditions_checkIndex:
3470     do_PreconditionsCheckIndex(x, T_INT);
3471     break;
3472   case vmIntrinsics::_Preconditions_checkLongIndex:
3473     do_PreconditionsCheckIndex(x, T_LONG);
3474     break;
3475 
3476   case vmIntrinsics::_compareAndSetReference:
3477     do_CompareAndSwap(x, objectType);
3478     break;
3479   case vmIntrinsics::_compareAndSetInt:
3480     do_CompareAndSwap(x, intType);
3481     break;
3482   case vmIntrinsics::_compareAndSetLong:
3483     do_CompareAndSwap(x, longType);
3484     break;
3485 
3486   case vmIntrinsics::_loadFence :
3487     __ membar_acquire();
3488     break;
3489   case vmIntrinsics::_storeFence:
3490     __ membar_release();
3491     break;
3492   case vmIntrinsics::_storeStoreFence:
3493     __ membar_storestore();
3494     break;
3495   case vmIntrinsics::_fullFence :
3496     __ membar();
3497     break;
3498   case vmIntrinsics::_onSpinWait:
3499     __ on_spin_wait();
3500     break;
3501   case vmIntrinsics::_Reference_get:
3502     do_Reference_get(x);
3503     break;
3504 
3505   case vmIntrinsics::_updateCRC32:
3506   case vmIntrinsics::_updateBytesCRC32:
3507   case vmIntrinsics::_updateByteBufferCRC32:
3508     do_update_CRC32(x);
3509     break;
3510 
3511   case vmIntrinsics::_updateBytesCRC32C:
3512   case vmIntrinsics::_updateDirectByteBufferCRC32C:
3513     do_update_CRC32C(x);
3514     break;
3515 
3516   case vmIntrinsics::_vectorizedMismatch:
3517     do_vectorizedMismatch(x);
3518     break;
3519 
3520   case vmIntrinsics::_blackhole:
3521     do_blackhole(x);
3522     break;
3523 
3524   default: ShouldNotReachHere(); break;
3525   }
3526 }
3527 
3528 void LIRGenerator::profile_arguments(ProfileCall* x) {
3529   if (compilation()->profile_arguments()) {
3530     int bci = x->bci_of_invoke();
3531     ciMethodData* md = x->method()->method_data_or_null();
3532     assert(md != nullptr, "Sanity");
3533     ciProfileData* data = md->bci_to_data(bci);
3534     if (data != nullptr) {
3535       if ((data->is_CallTypeData() && data->as_CallTypeData()->has_arguments()) ||
3536           (data->is_VirtualCallTypeData() && data->as_VirtualCallTypeData()->has_arguments())) {
3537         ByteSize extra = data->is_CallTypeData() ? CallTypeData::args_data_offset() : VirtualCallTypeData::args_data_offset();
3538         int base_offset = md->byte_offset_of_slot(data, extra);
3539         LIR_Opr mdp = LIR_OprFact::illegalOpr;
3540         ciTypeStackSlotEntries* args = data->is_CallTypeData() ? ((ciCallTypeData*)data)->args() : ((ciVirtualCallTypeData*)data)->args();
3541 
3542         Bytecodes::Code bc = x->method()->java_code_at_bci(bci);
3543         int start = 0;
3544         int stop = data->is_CallTypeData() ? ((ciCallTypeData*)data)->number_of_arguments() : ((ciVirtualCallTypeData*)data)->number_of_arguments();
3545         if (x->callee()->is_loaded() && x->callee()->is_static() && Bytecodes::has_receiver(bc)) {
3546           // first argument is not profiled at call (method handle invoke)
3547           assert(x->method()->raw_code_at_bci(bci) == Bytecodes::_invokehandle, "invokehandle expected");
3548           start = 1;
3549         }
3550         ciSignature* callee_signature = x->callee()->signature();
3551         // method handle call to virtual method
3552         bool has_receiver = x->callee()->is_loaded() && !x->callee()->is_static() && !Bytecodes::has_receiver(bc);
3553         ciSignatureStream callee_signature_stream(callee_signature, has_receiver ? x->callee()->holder() : nullptr);
3554 
3555         bool ignored_will_link;
3556         ciSignature* signature_at_call = nullptr;
3557         x->method()->get_method_at_bci(bci, ignored_will_link, &signature_at_call);
3558         ciSignatureStream signature_at_call_stream(signature_at_call);
3559 
3560         // if called through method handle invoke, some arguments may have been popped
3561         for (int i = 0; i < stop && i+start < x->nb_profiled_args(); i++) {
3562           int off = in_bytes(TypeEntriesAtCall::argument_type_offset(i)) - in_bytes(TypeEntriesAtCall::args_data_offset());
3563           ciKlass* exact = profile_type(md, base_offset, off,
3564               args->type(i), x->profiled_arg_at(i+start), mdp,
3565               !x->arg_needs_null_check(i+start),
3566               signature_at_call_stream.next_klass(), callee_signature_stream.next_klass());
3567           if (exact != nullptr) {
3568             md->set_argument_type(bci, i, exact);
3569           }
3570         }
3571       } else {
3572 #ifdef ASSERT
3573         Bytecodes::Code code = x->method()->raw_code_at_bci(x->bci_of_invoke());
3574         int n = x->nb_profiled_args();
3575         assert(MethodData::profile_parameters() && (MethodData::profile_arguments_jsr292_only() ||
3576             (x->inlined() && ((code == Bytecodes::_invokedynamic && n <= 1) || (code == Bytecodes::_invokehandle && n <= 2)))),
3577             "only at JSR292 bytecodes");
3578 #endif
3579       }
3580     }
3581   }
3582 }
3583 
3584 // profile parameters on entry to an inlined method
3585 void LIRGenerator::profile_parameters_at_call(ProfileCall* x) {
3586   if (compilation()->profile_parameters() && x->inlined()) {
3587     ciMethodData* md = x->callee()->method_data_or_null();
3588     if (md != nullptr) {
3589       ciParametersTypeData* parameters_type_data = md->parameters_type_data();
3590       if (parameters_type_data != nullptr) {
3591         ciTypeStackSlotEntries* parameters =  parameters_type_data->parameters();
3592         LIR_Opr mdp = LIR_OprFact::illegalOpr;
3593         bool has_receiver = !x->callee()->is_static();
3594         ciSignature* sig = x->callee()->signature();
3595         ciSignatureStream sig_stream(sig, has_receiver ? x->callee()->holder() : nullptr);
3596         int i = 0; // to iterate on the Instructions
3597         Value arg = x->recv();
3598         bool not_null = false;
3599         int bci = x->bci_of_invoke();
3600         Bytecodes::Code bc = x->method()->java_code_at_bci(bci);
3601         // The first parameter is the receiver so that's what we start
3602         // with if it exists. One exception is method handle call to
3603         // virtual method: the receiver is in the args list
3604         if (arg == nullptr || !Bytecodes::has_receiver(bc)) {
3605           i = 1;
3606           arg = x->profiled_arg_at(0);
3607           not_null = !x->arg_needs_null_check(0);
3608         }
3609         int k = 0; // to iterate on the profile data
3610         for (;;) {
3611           intptr_t profiled_k = parameters->type(k);
3612           ciKlass* exact = profile_type(md, md->byte_offset_of_slot(parameters_type_data, ParametersTypeData::type_offset(0)),
3613                                         in_bytes(ParametersTypeData::type_offset(k)) - in_bytes(ParametersTypeData::type_offset(0)),
3614                                         profiled_k, arg, mdp, not_null, sig_stream.next_klass(), nullptr);
3615           // If the profile is known statically set it once for all and do not emit any code
3616           if (exact != nullptr) {
3617             md->set_parameter_type(k, exact);
3618           }
3619           k++;
3620           if (k >= parameters_type_data->number_of_parameters()) {
3621 #ifdef ASSERT
3622             int extra = 0;
3623             if (MethodData::profile_arguments() && TypeProfileParmsLimit != -1 &&
3624                 x->nb_profiled_args() >= TypeProfileParmsLimit &&
3625                 x->recv() != nullptr && Bytecodes::has_receiver(bc)) {
3626               extra += 1;
3627             }
3628             assert(i == x->nb_profiled_args() - extra || (TypeProfileParmsLimit != -1 && TypeProfileArgsLimit > TypeProfileParmsLimit), "unused parameters?");
3629 #endif
3630             break;
3631           }
3632           arg = x->profiled_arg_at(i);
3633           not_null = !x->arg_needs_null_check(i);
3634           i++;
3635         }
3636       }
3637     }
3638   }
3639 }
3640 
3641 void LIRGenerator::do_ProfileCall(ProfileCall* x) {
3642   // Need recv in a temporary register so it interferes with the other temporaries
3643   LIR_Opr recv = LIR_OprFact::illegalOpr;
3644   LIR_Opr mdo = new_register(T_METADATA);
3645   // tmp is used to hold the counters on SPARC
3646   LIR_Opr tmp = new_pointer_register();
3647 
3648   if (x->nb_profiled_args() > 0) {
3649     profile_arguments(x);
3650   }
3651 
3652   // profile parameters on inlined method entry including receiver
3653   if (x->recv() != nullptr || x->nb_profiled_args() > 0) {
3654     profile_parameters_at_call(x);
3655   }
3656 
3657   if (x->recv() != nullptr) {
3658     LIRItem value(x->recv(), this);
3659     value.load_item();
3660     recv = new_register(T_OBJECT);
3661     __ move(value.result(), recv);
3662   }
3663   __ profile_call(x->method(), x->bci_of_invoke(), x->callee(), mdo, recv, tmp, x->known_holder());
3664 }
3665 
3666 void LIRGenerator::do_ProfileReturnType(ProfileReturnType* x) {
3667   int bci = x->bci_of_invoke();
3668   ciMethodData* md = x->method()->method_data_or_null();
3669   assert(md != nullptr, "Sanity");
3670   ciProfileData* data = md->bci_to_data(bci);
3671   if (data != nullptr) {
3672     assert(data->is_CallTypeData() || data->is_VirtualCallTypeData(), "wrong profile data type");
3673     ciSingleTypeEntry* ret = data->is_CallTypeData() ? ((ciCallTypeData*)data)->ret() : ((ciVirtualCallTypeData*)data)->ret();
3674     LIR_Opr mdp = LIR_OprFact::illegalOpr;
3675 
3676     bool ignored_will_link;
3677     ciSignature* signature_at_call = nullptr;
3678     x->method()->get_method_at_bci(bci, ignored_will_link, &signature_at_call);
3679 
3680     // The offset within the MDO of the entry to update may be too large
3681     // to be used in load/store instructions on some platforms. So have
3682     // profile_type() compute the address of the profile in a register.
3683     ciKlass* exact = profile_type(md, md->byte_offset_of_slot(data, ret->type_offset()), 0,
3684         ret->type(), x->ret(), mdp,
3685         !x->needs_null_check(),
3686         signature_at_call->return_type()->as_klass(),
3687         x->callee()->signature()->return_type()->as_klass());
3688     if (exact != nullptr) {
3689       md->set_return_type(bci, exact);
3690     }
3691   }
3692 }
3693 
3694 bool LIRGenerator::profile_inline_klass(ciMethodData* md, ciProfileData* data, Value value, int flag) {
3695   ciKlass* klass = value->as_loaded_klass_or_null();
3696   if (klass != nullptr) {
3697     if (klass->is_inlinetype()) {
3698       profile_flags(md, data, flag, lir_cond_always);
3699     } else if (klass->can_be_inline_klass()) {
3700       return false;
3701     }
3702   } else {
3703     return false;
3704   }
3705   return true;
3706 }
3707 
3708 
3709 void LIRGenerator::do_ProfileACmpTypes(ProfileACmpTypes* x) {
3710   ciMethod* method = x->method();
3711   assert(method != nullptr, "method should be set if branch is profiled");
3712   ciMethodData* md = method->method_data_or_null();
3713   assert(md != nullptr, "Sanity");
3714   ciProfileData* data = md->bci_to_data(x->bci());
3715   assert(data != nullptr, "must have profiling data");
3716   assert(data->is_ACmpData(), "need BranchData for two-way branches");
3717   ciACmpData* acmp = (ciACmpData*)data;
3718   LIR_Opr mdp = LIR_OprFact::illegalOpr;
3719   profile_type(md, md->byte_offset_of_slot(acmp, ACmpData::left_offset()), 0,
3720                acmp->left()->type(), x->left(), mdp, !x->left_maybe_null(), nullptr, nullptr);
3721   int flags_offset = md->byte_offset_of_slot(data, DataLayout::flags_offset());
3722   if (!profile_inline_klass(md, acmp, x->left(), ACmpData::left_inline_type_byte_constant())) {
3723     LIR_Opr mdp = new_register(T_METADATA);
3724     __ metadata2reg(md->constant_encoding(), mdp);
3725     LIRItem value(x->left(), this);
3726     value.load_item();
3727     __ profile_inline_type(new LIR_Address(mdp, flags_offset, T_INT), value.result(), ACmpData::left_inline_type_byte_constant(), new_register(T_INT), !x->left_maybe_null());
3728   }
3729   profile_type(md, md->byte_offset_of_slot(acmp, ACmpData::left_offset()),
3730                in_bytes(ACmpData::right_offset()) - in_bytes(ACmpData::left_offset()),
3731                acmp->right()->type(), x->right(), mdp, !x->right_maybe_null(), nullptr, nullptr);
3732   if (!profile_inline_klass(md, acmp, x->right(), ACmpData::right_inline_type_byte_constant())) {
3733     LIR_Opr mdp = new_register(T_METADATA);
3734     __ metadata2reg(md->constant_encoding(), mdp);
3735     LIRItem value(x->right(), this);
3736     value.load_item();
3737     __ profile_inline_type(new LIR_Address(mdp, flags_offset, T_INT), value.result(), ACmpData::right_inline_type_byte_constant(), new_register(T_INT), !x->left_maybe_null());
3738   }
3739 }
3740 
3741 void LIRGenerator::do_ProfileInvoke(ProfileInvoke* x) {
3742   // We can safely ignore accessors here, since c2 will inline them anyway,
3743   // accessors are also always mature.
3744   if (!x->inlinee()->is_accessor()) {
3745     CodeEmitInfo* info = state_for(x, x->state(), true);
3746     // Notify the runtime very infrequently only to take care of counter overflows
3747     int freq_log = Tier23InlineeNotifyFreqLog;
3748     double scale;
3749     if (_method->has_option_value(CompileCommandEnum::CompileThresholdScaling, scale)) {
3750       freq_log = CompilerConfig::scaled_freq_log(freq_log, scale);
3751     }
3752     increment_event_counter_impl(info, x->inlinee(), LIR_OprFact::intConst(InvocationCounter::count_increment), right_n_bits(freq_log), InvocationEntryBci, false, true);
3753   }
3754 }
3755 
3756 void LIRGenerator::increment_backedge_counter_conditionally(LIR_Condition cond, LIR_Opr left, LIR_Opr right, CodeEmitInfo* info, int left_bci, int right_bci, int bci) {
3757   if (compilation()->is_profiling()) {
3758 #if defined(X86) && !defined(_LP64)
3759     // BEWARE! On 32-bit x86 cmp clobbers its left argument so we need a temp copy.
3760     LIR_Opr left_copy = new_register(left->type());
3761     __ move(left, left_copy);
3762     __ cmp(cond, left_copy, right);
3763 #else
3764     __ cmp(cond, left, right);
3765 #endif
3766     LIR_Opr step = new_register(T_INT);
3767     LIR_Opr plus_one = LIR_OprFact::intConst(InvocationCounter::count_increment);
3768     LIR_Opr zero = LIR_OprFact::intConst(0);
3769     __ cmove(cond,
3770         (left_bci < bci) ? plus_one : zero,
3771         (right_bci < bci) ? plus_one : zero,
3772         step, left->type());
3773     increment_backedge_counter(info, step, bci);
3774   }
3775 }
3776 
3777 
3778 void LIRGenerator::increment_event_counter(CodeEmitInfo* info, LIR_Opr step, int bci, bool backedge) {
3779   int freq_log = 0;
3780   int level = compilation()->env()->comp_level();
3781   if (level == CompLevel_limited_profile) {
3782     freq_log = (backedge ? Tier2BackedgeNotifyFreqLog : Tier2InvokeNotifyFreqLog);
3783   } else if (level == CompLevel_full_profile) {
3784     freq_log = (backedge ? Tier3BackedgeNotifyFreqLog : Tier3InvokeNotifyFreqLog);
3785   } else {
3786     ShouldNotReachHere();
3787   }
3788   // Increment the appropriate invocation/backedge counter and notify the runtime.
3789   double scale;
3790   if (_method->has_option_value(CompileCommandEnum::CompileThresholdScaling, scale)) {
3791     freq_log = CompilerConfig::scaled_freq_log(freq_log, scale);
3792   }
3793   increment_event_counter_impl(info, info->scope()->method(), step, right_n_bits(freq_log), bci, backedge, true);
3794 }
3795 
3796 void LIRGenerator::increment_event_counter_impl(CodeEmitInfo* info,
3797                                                 ciMethod *method, LIR_Opr step, int frequency,
3798                                                 int bci, bool backedge, bool notify) {
3799   assert(frequency == 0 || is_power_of_2(frequency + 1), "Frequency must be x^2 - 1 or 0");
3800   int level = _compilation->env()->comp_level();
3801   assert(level > CompLevel_simple, "Shouldn't be here");
3802 
3803   int offset = -1;
3804   LIR_Opr counter_holder;
3805   if (level == CompLevel_limited_profile) {
3806     MethodCounters* counters_adr = method->ensure_method_counters();
3807     if (counters_adr == nullptr) {
3808       bailout("method counters allocation failed");
3809       return;
3810     }
3811     counter_holder = new_pointer_register();
3812     __ move(LIR_OprFact::intptrConst(counters_adr), counter_holder);
3813     offset = in_bytes(backedge ? MethodCounters::backedge_counter_offset() :
3814                                  MethodCounters::invocation_counter_offset());
3815   } else if (level == CompLevel_full_profile) {
3816     counter_holder = new_register(T_METADATA);
3817     offset = in_bytes(backedge ? MethodData::backedge_counter_offset() :
3818                                  MethodData::invocation_counter_offset());
3819     ciMethodData* md = method->method_data_or_null();
3820     assert(md != nullptr, "Sanity");
3821     __ metadata2reg(md->constant_encoding(), counter_holder);
3822   } else {
3823     ShouldNotReachHere();
3824   }
3825   LIR_Address* counter = new LIR_Address(counter_holder, offset, T_INT);
3826   LIR_Opr result = new_register(T_INT);
3827   __ load(counter, result);
3828   __ add(result, step, result);
3829   __ store(result, counter);
3830   if (notify && (!backedge || UseOnStackReplacement)) {
3831     LIR_Opr meth = LIR_OprFact::metadataConst(method->constant_encoding());
3832     // The bci for info can point to cmp for if's we want the if bci
3833     CodeStub* overflow = new CounterOverflowStub(info, bci, meth);
3834     int freq = frequency << InvocationCounter::count_shift;
3835     if (freq == 0) {
3836       if (!step->is_constant()) {
3837         __ cmp(lir_cond_notEqual, step, LIR_OprFact::intConst(0));
3838         __ branch(lir_cond_notEqual, overflow);
3839       } else {
3840         __ branch(lir_cond_always, overflow);
3841       }
3842     } else {
3843       LIR_Opr mask = load_immediate(freq, T_INT);
3844       if (!step->is_constant()) {
3845         // If step is 0, make sure the overflow check below always fails
3846         __ cmp(lir_cond_notEqual, step, LIR_OprFact::intConst(0));
3847         __ cmove(lir_cond_notEqual, result, LIR_OprFact::intConst(InvocationCounter::count_increment), result, T_INT);
3848       }
3849       __ logical_and(result, mask, result);
3850       __ cmp(lir_cond_equal, result, LIR_OprFact::intConst(0));
3851       __ branch(lir_cond_equal, overflow);
3852     }
3853     __ branch_destination(overflow->continuation());
3854   }
3855 }
3856 
3857 void LIRGenerator::do_RuntimeCall(RuntimeCall* x) {
3858   LIR_OprList* args = new LIR_OprList(x->number_of_arguments());
3859   BasicTypeList* signature = new BasicTypeList(x->number_of_arguments());
3860 
3861   if (x->pass_thread()) {
3862     signature->append(LP64_ONLY(T_LONG) NOT_LP64(T_INT));    // thread
3863     args->append(getThreadPointer());
3864   }
3865 
3866   for (int i = 0; i < x->number_of_arguments(); i++) {
3867     Value a = x->argument_at(i);
3868     LIRItem* item = new LIRItem(a, this);
3869     item->load_item();
3870     args->append(item->result());
3871     signature->append(as_BasicType(a->type()));
3872   }
3873 
3874   LIR_Opr result = call_runtime(signature, args, x->entry(), x->type(), nullptr);
3875   if (x->type() == voidType) {
3876     set_no_result(x);
3877   } else {
3878     __ move(result, rlock_result(x));
3879   }
3880 }
3881 
3882 #ifdef ASSERT
3883 void LIRGenerator::do_Assert(Assert *x) {
3884   ValueTag tag = x->x()->type()->tag();
3885   If::Condition cond = x->cond();
3886 
3887   LIRItem xitem(x->x(), this);
3888   LIRItem yitem(x->y(), this);
3889   LIRItem* xin = &xitem;
3890   LIRItem* yin = &yitem;
3891 
3892   assert(tag == intTag, "Only integer assertions are valid!");
3893 
3894   xin->load_item();
3895   yin->dont_load_item();
3896 
3897   set_no_result(x);
3898 
3899   LIR_Opr left = xin->result();
3900   LIR_Opr right = yin->result();
3901 
3902   __ lir_assert(lir_cond(x->cond()), left, right, x->message(), true);
3903 }
3904 #endif
3905 
3906 void LIRGenerator::do_RangeCheckPredicate(RangeCheckPredicate *x) {
3907 
3908 
3909   Instruction *a = x->x();
3910   Instruction *b = x->y();
3911   if (!a || StressRangeCheckElimination) {
3912     assert(!b || StressRangeCheckElimination, "B must also be null");
3913 
3914     CodeEmitInfo *info = state_for(x, x->state());
3915     CodeStub* stub = new PredicateFailedStub(info);
3916 
3917     __ jump(stub);
3918   } else if (a->type()->as_IntConstant() && b->type()->as_IntConstant()) {
3919     int a_int = a->type()->as_IntConstant()->value();
3920     int b_int = b->type()->as_IntConstant()->value();
3921 
3922     bool ok = false;
3923 
3924     switch(x->cond()) {
3925       case Instruction::eql: ok = (a_int == b_int); break;
3926       case Instruction::neq: ok = (a_int != b_int); break;
3927       case Instruction::lss: ok = (a_int < b_int); break;
3928       case Instruction::leq: ok = (a_int <= b_int); break;
3929       case Instruction::gtr: ok = (a_int > b_int); break;
3930       case Instruction::geq: ok = (a_int >= b_int); break;
3931       case Instruction::aeq: ok = ((unsigned int)a_int >= (unsigned int)b_int); break;
3932       case Instruction::beq: ok = ((unsigned int)a_int <= (unsigned int)b_int); break;
3933       default: ShouldNotReachHere();
3934     }
3935 
3936     if (ok) {
3937 
3938       CodeEmitInfo *info = state_for(x, x->state());
3939       CodeStub* stub = new PredicateFailedStub(info);
3940 
3941       __ jump(stub);
3942     }
3943   } else {
3944 
3945     ValueTag tag = x->x()->type()->tag();
3946     If::Condition cond = x->cond();
3947     LIRItem xitem(x->x(), this);
3948     LIRItem yitem(x->y(), this);
3949     LIRItem* xin = &xitem;
3950     LIRItem* yin = &yitem;
3951 
3952     assert(tag == intTag, "Only integer deoptimizations are valid!");
3953 
3954     xin->load_item();
3955     yin->dont_load_item();
3956     set_no_result(x);
3957 
3958     LIR_Opr left = xin->result();
3959     LIR_Opr right = yin->result();
3960 
3961     CodeEmitInfo *info = state_for(x, x->state());
3962     CodeStub* stub = new PredicateFailedStub(info);
3963 
3964     __ cmp(lir_cond(cond), left, right);
3965     __ branch(lir_cond(cond), stub);
3966   }
3967 }
3968 
3969 void LIRGenerator::do_blackhole(Intrinsic *x) {
3970   assert(!x->has_receiver(), "Should have been checked before: only static methods here");
3971   for (int c = 0; c < x->number_of_arguments(); c++) {
3972     // Load the argument
3973     LIRItem vitem(x->argument_at(c), this);
3974     vitem.load_item();
3975     // ...and leave it unused.
3976   }
3977 }
3978 
3979 LIR_Opr LIRGenerator::call_runtime(Value arg1, address entry, ValueType* result_type, CodeEmitInfo* info) {
3980   LIRItemList args(1);
3981   LIRItem value(arg1, this);
3982   args.append(&value);
3983   BasicTypeList signature;
3984   signature.append(as_BasicType(arg1->type()));
3985 
3986   return call_runtime(&signature, &args, entry, result_type, info);
3987 }
3988 
3989 
3990 LIR_Opr LIRGenerator::call_runtime(Value arg1, Value arg2, address entry, ValueType* result_type, CodeEmitInfo* info) {
3991   LIRItemList args(2);
3992   LIRItem value1(arg1, this);
3993   LIRItem value2(arg2, this);
3994   args.append(&value1);
3995   args.append(&value2);
3996   BasicTypeList signature;
3997   signature.append(as_BasicType(arg1->type()));
3998   signature.append(as_BasicType(arg2->type()));
3999 
4000   return call_runtime(&signature, &args, entry, result_type, info);
4001 }
4002 
4003 
4004 LIR_Opr LIRGenerator::call_runtime(BasicTypeArray* signature, LIR_OprList* args,
4005                                    address entry, ValueType* result_type, CodeEmitInfo* info) {
4006   // get a result register
4007   LIR_Opr phys_reg = LIR_OprFact::illegalOpr;
4008   LIR_Opr result = LIR_OprFact::illegalOpr;
4009   if (result_type->tag() != voidTag) {
4010     result = new_register(result_type);
4011     phys_reg = result_register_for(result_type);
4012   }
4013 
4014   // move the arguments into the correct location
4015   CallingConvention* cc = frame_map()->c_calling_convention(signature);
4016   assert(cc->length() == args->length(), "argument mismatch");
4017   for (int i = 0; i < args->length(); i++) {
4018     LIR_Opr arg = args->at(i);
4019     LIR_Opr loc = cc->at(i);
4020     if (loc->is_register()) {
4021       __ move(arg, loc);
4022     } else {
4023       LIR_Address* addr = loc->as_address_ptr();
4024 //           if (!can_store_as_constant(arg)) {
4025 //             LIR_Opr tmp = new_register(arg->type());
4026 //             __ move(arg, tmp);
4027 //             arg = tmp;
4028 //           }
4029       __ move(arg, addr);
4030     }
4031   }
4032 
4033   if (info) {
4034     __ call_runtime(entry, getThreadTemp(), phys_reg, cc->args(), info);
4035   } else {
4036     __ call_runtime_leaf(entry, getThreadTemp(), phys_reg, cc->args());
4037   }
4038   if (result->is_valid()) {
4039     __ move(phys_reg, result);
4040   }
4041   return result;
4042 }
4043 
4044 
4045 LIR_Opr LIRGenerator::call_runtime(BasicTypeArray* signature, LIRItemList* args,
4046                                    address entry, ValueType* result_type, CodeEmitInfo* info) {
4047   // get a result register
4048   LIR_Opr phys_reg = LIR_OprFact::illegalOpr;
4049   LIR_Opr result = LIR_OprFact::illegalOpr;
4050   if (result_type->tag() != voidTag) {
4051     result = new_register(result_type);
4052     phys_reg = result_register_for(result_type);
4053   }
4054 
4055   // move the arguments into the correct location
4056   CallingConvention* cc = frame_map()->c_calling_convention(signature);
4057 
4058   assert(cc->length() == args->length(), "argument mismatch");
4059   for (int i = 0; i < args->length(); i++) {
4060     LIRItem* arg = args->at(i);
4061     LIR_Opr loc = cc->at(i);
4062     if (loc->is_register()) {
4063       arg->load_item_force(loc);
4064     } else {
4065       LIR_Address* addr = loc->as_address_ptr();
4066       arg->load_for_store(addr->type());
4067       __ move(arg->result(), addr);
4068     }
4069   }
4070 
4071   if (info) {
4072     __ call_runtime(entry, getThreadTemp(), phys_reg, cc->args(), info);
4073   } else {
4074     __ call_runtime_leaf(entry, getThreadTemp(), phys_reg, cc->args());
4075   }
4076   if (result->is_valid()) {
4077     __ move(phys_reg, result);
4078   }
4079   return result;
4080 }
4081 
4082 void LIRGenerator::do_MemBar(MemBar* x) {
4083   LIR_Code code = x->code();
4084   switch(code) {
4085   case lir_membar_acquire   : __ membar_acquire(); break;
4086   case lir_membar_release   : __ membar_release(); break;
4087   case lir_membar           : __ membar(); break;
4088   case lir_membar_loadload  : __ membar_loadload(); break;
4089   case lir_membar_storestore: __ membar_storestore(); break;
4090   case lir_membar_loadstore : __ membar_loadstore(); break;
4091   case lir_membar_storeload : __ membar_storeload(); break;
4092   default                   : ShouldNotReachHere(); break;
4093   }
4094 }
4095 
4096 LIR_Opr LIRGenerator::mask_boolean(LIR_Opr array, LIR_Opr value, CodeEmitInfo*& null_check_info) {
4097   LIR_Opr value_fixed = rlock_byte(T_BYTE);
4098   if (two_operand_lir_form) {
4099     __ move(value, value_fixed);
4100     __ logical_and(value_fixed, LIR_OprFact::intConst(1), value_fixed);
4101   } else {
4102     __ logical_and(value, LIR_OprFact::intConst(1), value_fixed);
4103   }
4104   LIR_Opr klass = new_register(T_METADATA);
4105   load_klass(array, klass, null_check_info);
4106   null_check_info = nullptr;
4107   LIR_Opr layout = new_register(T_INT);
4108   __ move(new LIR_Address(klass, in_bytes(Klass::layout_helper_offset()), T_INT), layout);
4109   int diffbit = Klass::layout_helper_boolean_diffbit();
4110   __ logical_and(layout, LIR_OprFact::intConst(diffbit), layout);
4111   __ cmp(lir_cond_notEqual, layout, LIR_OprFact::intConst(0));
4112   __ cmove(lir_cond_notEqual, value_fixed, value, value_fixed, T_BYTE);
4113   value = value_fixed;
4114   return value;
4115 }