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