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