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