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