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