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