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