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