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