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