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