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