1 /*
   2  * Copyright (c) 2005, 2010, 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 "incls/_precompiled.incl"
  26 # include "incls/_c1_LIRGenerator.cpp.incl"
  27 
  28 #ifdef ASSERT
  29 #define __ gen()->lir(__FILE__, __LINE__)->
  30 #else
  31 #define __ gen()->lir()->
  32 #endif
  33 
  34 // TODO: ARM - Use some recognizable constant which still fits architectural constraints
  35 #ifdef ARM
  36 #define PATCHED_ADDR  (204)
  37 #else
  38 #define PATCHED_ADDR  (max_jint)
  39 #endif
  40 
  41 void PhiResolverState::reset(int max_vregs) {
  42   // Initialize array sizes
  43   _virtual_operands.at_put_grow(max_vregs - 1, NULL, NULL);
  44   _virtual_operands.trunc_to(0);
  45   _other_operands.at_put_grow(max_vregs - 1, NULL, NULL);
  46   _other_operands.trunc_to(0);
  47   _vreg_table.at_put_grow(max_vregs - 1, NULL, NULL);
  48   _vreg_table.trunc_to(0);
  49 }
  50 
  51 
  52 
  53 //--------------------------------------------------------------
  54 // PhiResolver
  55 
  56 // Resolves cycles:
  57 //
  58 //  r1 := r2  becomes  temp := r1
  59 //  r2 := r1           r1 := r2
  60 //                     r2 := temp
  61 // and orders moves:
  62 //
  63 //  r2 := r3  becomes  r1 := r2
  64 //  r1 := r2           r2 := r3
  65 
  66 PhiResolver::PhiResolver(LIRGenerator* gen, int max_vregs)
  67  : _gen(gen)
  68  , _state(gen->resolver_state())
  69  , _temp(LIR_OprFact::illegalOpr)
  70 {
  71   // reinitialize the shared state arrays
  72   _state.reset(max_vregs);
  73 }
  74 
  75 
  76 void PhiResolver::emit_move(LIR_Opr src, LIR_Opr dest) {
  77   assert(src->is_valid(), "");
  78   assert(dest->is_valid(), "");
  79   __ move(src, dest);
  80 }
  81 
  82 
  83 void PhiResolver::move_temp_to(LIR_Opr dest) {
  84   assert(_temp->is_valid(), "");
  85   emit_move(_temp, dest);
  86   NOT_PRODUCT(_temp = LIR_OprFact::illegalOpr);
  87 }
  88 
  89 
  90 void PhiResolver::move_to_temp(LIR_Opr src) {
  91   assert(_temp->is_illegal(), "");
  92   _temp = _gen->new_register(src->type());
  93   emit_move(src, _temp);
  94 }
  95 
  96 
  97 // Traverse assignment graph in depth first order and generate moves in post order
  98 // ie. two assignments: b := c, a := b start with node c:
  99 // Call graph: move(NULL, c) -> move(c, b) -> move(b, a)
 100 // Generates moves in this order: move b to a and move c to b
 101 // ie. cycle a := b, b := a start with node a
 102 // Call graph: move(NULL, a) -> move(a, b) -> move(b, a)
 103 // Generates moves in this order: move b to temp, move a to b, move temp to a
 104 void PhiResolver::move(ResolveNode* src, ResolveNode* dest) {
 105   if (!dest->visited()) {
 106     dest->set_visited();
 107     for (int i = dest->no_of_destinations()-1; i >= 0; i --) {
 108       move(dest, dest->destination_at(i));
 109     }
 110   } else if (!dest->start_node()) {
 111     // cylce in graph detected
 112     assert(_loop == NULL, "only one loop valid!");
 113     _loop = dest;
 114     move_to_temp(src->operand());
 115     return;
 116   } // else dest is a start node
 117 
 118   if (!dest->assigned()) {
 119     if (_loop == dest) {
 120       move_temp_to(dest->operand());
 121       dest->set_assigned();
 122     } else if (src != NULL) {
 123       emit_move(src->operand(), dest->operand());
 124       dest->set_assigned();
 125     }
 126   }
 127 }
 128 
 129 
 130 PhiResolver::~PhiResolver() {
 131   int i;
 132   // resolve any cycles in moves from and to virtual registers
 133   for (i = virtual_operands().length() - 1; i >= 0; i --) {
 134     ResolveNode* node = virtual_operands()[i];
 135     if (!node->visited()) {
 136       _loop = NULL;
 137       move(NULL, node);
 138       node->set_start_node();
 139       assert(_temp->is_illegal(), "move_temp_to() call missing");
 140     }
 141   }
 142 
 143   // generate move for move from non virtual register to abitrary destination
 144   for (i = other_operands().length() - 1; i >= 0; i --) {
 145     ResolveNode* node = other_operands()[i];
 146     for (int j = node->no_of_destinations() - 1; j >= 0; j --) {
 147       emit_move(node->operand(), node->destination_at(j)->operand());
 148     }
 149   }
 150 }
 151 
 152 
 153 ResolveNode* PhiResolver::create_node(LIR_Opr opr, bool source) {
 154   ResolveNode* node;
 155   if (opr->is_virtual()) {
 156     int vreg_num = opr->vreg_number();
 157     node = vreg_table().at_grow(vreg_num, NULL);
 158     assert(node == NULL || node->operand() == opr, "");
 159     if (node == NULL) {
 160       node = new ResolveNode(opr);
 161       vreg_table()[vreg_num] = node;
 162     }
 163     // Make sure that all virtual operands show up in the list when
 164     // they are used as the source of a move.
 165     if (source && !virtual_operands().contains(node)) {
 166       virtual_operands().append(node);
 167     }
 168   } else {
 169     assert(source, "");
 170     node = new ResolveNode(opr);
 171     other_operands().append(node);
 172   }
 173   return node;
 174 }
 175 
 176 
 177 void PhiResolver::move(LIR_Opr src, LIR_Opr dest) {
 178   assert(dest->is_virtual(), "");
 179   // tty->print("move "); src->print(); tty->print(" to "); dest->print(); tty->cr();
 180   assert(src->is_valid(), "");
 181   assert(dest->is_valid(), "");
 182   ResolveNode* source = source_node(src);
 183   source->append(destination_node(dest));
 184 }
 185 
 186 
 187 //--------------------------------------------------------------
 188 // LIRItem
 189 
 190 void LIRItem::set_result(LIR_Opr opr) {
 191   assert(value()->operand()->is_illegal() || value()->operand()->is_constant(), "operand should never change");
 192   value()->set_operand(opr);
 193 
 194   if (opr->is_virtual()) {
 195     _gen->_instruction_for_operand.at_put_grow(opr->vreg_number(), value(), NULL);
 196   }
 197 
 198   _result = opr;
 199 }
 200 
 201 void LIRItem::load_item() {
 202   if (result()->is_illegal()) {
 203     // update the items result
 204     _result = value()->operand();
 205   }
 206   if (!result()->is_register()) {
 207     LIR_Opr reg = _gen->new_register(value()->type());
 208     __ move(result(), reg);
 209     if (result()->is_constant()) {
 210       _result = reg;
 211     } else {
 212       set_result(reg);
 213     }
 214   }
 215 }
 216 
 217 
 218 void LIRItem::load_for_store(BasicType type) {
 219   if (_gen->can_store_as_constant(value(), type)) {
 220     _result = value()->operand();
 221     if (!_result->is_constant()) {
 222       _result = LIR_OprFact::value_type(value()->type());
 223     }
 224   } else if (type == T_BYTE || type == T_BOOLEAN) {
 225     load_byte_item();
 226   } else {
 227     load_item();
 228   }
 229 }
 230 
 231 void LIRItem::load_item_force(LIR_Opr reg) {
 232   LIR_Opr r = result();
 233   if (r != reg) {
 234 #if !defined(ARM) && !defined(E500V2)
 235     if (r->type() != reg->type()) {
 236       // moves between different types need an intervening spill slot
 237       r = _gen->force_to_spill(r, reg->type());
 238     }
 239 #endif
 240     __ move(r, reg);
 241     _result = reg;
 242   }
 243 }
 244 
 245 ciObject* LIRItem::get_jobject_constant() const {
 246   ObjectType* oc = type()->as_ObjectType();
 247   if (oc) {
 248     return oc->constant_value();
 249   }
 250   return NULL;
 251 }
 252 
 253 
 254 jint LIRItem::get_jint_constant() const {
 255   assert(is_constant() && value() != NULL, "");
 256   assert(type()->as_IntConstant() != NULL, "type check");
 257   return type()->as_IntConstant()->value();
 258 }
 259 
 260 
 261 jint LIRItem::get_address_constant() const {
 262   assert(is_constant() && value() != NULL, "");
 263   assert(type()->as_AddressConstant() != NULL, "type check");
 264   return type()->as_AddressConstant()->value();
 265 }
 266 
 267 
 268 jfloat LIRItem::get_jfloat_constant() const {
 269   assert(is_constant() && value() != NULL, "");
 270   assert(type()->as_FloatConstant() != NULL, "type check");
 271   return type()->as_FloatConstant()->value();
 272 }
 273 
 274 
 275 jdouble LIRItem::get_jdouble_constant() const {
 276   assert(is_constant() && value() != NULL, "");
 277   assert(type()->as_DoubleConstant() != NULL, "type check");
 278   return type()->as_DoubleConstant()->value();
 279 }
 280 
 281 
 282 jlong LIRItem::get_jlong_constant() const {
 283   assert(is_constant() && value() != NULL, "");
 284   assert(type()->as_LongConstant() != NULL, "type check");
 285   return type()->as_LongConstant()->value();
 286 }
 287 
 288 
 289 
 290 //--------------------------------------------------------------
 291 
 292 
 293 void LIRGenerator::init() {
 294   _bs = Universe::heap()->barrier_set();
 295 }
 296 
 297 
 298 void LIRGenerator::block_do_prolog(BlockBegin* block) {
 299 #ifndef PRODUCT
 300   if (PrintIRWithLIR) {
 301     block->print();
 302   }
 303 #endif
 304 
 305   // set up the list of LIR instructions
 306   assert(block->lir() == NULL, "LIR list already computed for this block");
 307   _lir = new LIR_List(compilation(), block);
 308   block->set_lir(_lir);
 309 
 310   __ branch_destination(block->label());
 311 
 312   if (LIRTraceExecution &&
 313       Compilation::current()->hir()->start()->block_id() != block->block_id() &&
 314       !block->is_set(BlockBegin::exception_entry_flag)) {
 315     assert(block->lir()->instructions_list()->length() == 1, "should come right after br_dst");
 316     trace_block_entry(block);
 317   }
 318 }
 319 
 320 
 321 void LIRGenerator::block_do_epilog(BlockBegin* block) {
 322 #ifndef PRODUCT
 323   if (PrintIRWithLIR) {
 324     tty->cr();
 325   }
 326 #endif
 327 
 328   // LIR_Opr for unpinned constants shouldn't be referenced by other
 329   // blocks so clear them out after processing the block.
 330   for (int i = 0; i < _unpinned_constants.length(); i++) {
 331     _unpinned_constants.at(i)->clear_operand();
 332   }
 333   _unpinned_constants.trunc_to(0);
 334 
 335   // clear our any registers for other local constants
 336   _constants.trunc_to(0);
 337   _reg_for_constants.trunc_to(0);
 338 }
 339 
 340 
 341 void LIRGenerator::block_do(BlockBegin* block) {
 342   CHECK_BAILOUT();
 343 
 344   block_do_prolog(block);
 345   set_block(block);
 346 
 347   for (Instruction* instr = block; instr != NULL; instr = instr->next()) {
 348     if (instr->is_pinned()) do_root(instr);
 349   }
 350 
 351   set_block(NULL);
 352   block_do_epilog(block);
 353 }
 354 
 355 
 356 //-------------------------LIRGenerator-----------------------------
 357 
 358 // This is where the tree-walk starts; instr must be root;
 359 void LIRGenerator::do_root(Value instr) {
 360   CHECK_BAILOUT();
 361 
 362   InstructionMark im(compilation(), instr);
 363 
 364   assert(instr->is_pinned(), "use only with roots");
 365   assert(instr->subst() == instr, "shouldn't have missed substitution");
 366 
 367   instr->visit(this);
 368 
 369   assert(!instr->has_uses() || instr->operand()->is_valid() ||
 370          instr->as_Constant() != NULL || bailed_out(), "invalid item set");
 371 }
 372 
 373 
 374 // This is called for each node in tree; the walk stops if a root is reached
 375 void LIRGenerator::walk(Value instr) {
 376   InstructionMark im(compilation(), instr);
 377   //stop walk when encounter a root
 378   if (instr->is_pinned() && instr->as_Phi() == NULL || instr->operand()->is_valid()) {
 379     assert(instr->operand() != LIR_OprFact::illegalOpr || instr->as_Constant() != NULL, "this root has not yet been visited");
 380   } else {
 381     assert(instr->subst() == instr, "shouldn't have missed substitution");
 382     instr->visit(this);
 383     // assert(instr->use_count() > 0 || instr->as_Phi() != NULL, "leaf instruction must have a use");
 384   }
 385 }
 386 
 387 
 388 CodeEmitInfo* LIRGenerator::state_for(Instruction* x, ValueStack* state, bool ignore_xhandler) {
 389   int index;
 390   Value value;
 391   for_each_stack_value(state, index, value) {
 392     assert(value->subst() == value, "missed substition");
 393     if (!value->is_pinned() && value->as_Constant() == NULL && value->as_Local() == NULL) {
 394       walk(value);
 395       assert(value->operand()->is_valid(), "must be evaluated now");
 396     }
 397   }
 398   ValueStack* s = state;
 399   int bci = x->bci();
 400   for_each_state(s) {
 401     IRScope* scope = s->scope();
 402     ciMethod* method = scope->method();
 403 
 404     MethodLivenessResult liveness = method->liveness_at_bci(bci);
 405     if (bci == SynchronizationEntryBCI) {
 406       if (x->as_ExceptionObject() || x->as_Throw()) {
 407         // all locals are dead on exit from the synthetic unlocker
 408         liveness.clear();
 409       } else {
 410         assert(x->as_MonitorEnter(), "only other case is MonitorEnter");
 411       }
 412     }
 413     if (!liveness.is_valid()) {
 414       // Degenerate or breakpointed method.
 415       bailout("Degenerate or breakpointed method");
 416     } else {
 417       assert((int)liveness.size() == s->locals_size(), "error in use of liveness");
 418       for_each_local_value(s, index, value) {
 419         assert(value->subst() == value, "missed substition");
 420         if (liveness.at(index) && !value->type()->is_illegal()) {
 421           if (!value->is_pinned() && value->as_Constant() == NULL && value->as_Local() == NULL) {
 422             walk(value);
 423             assert(value->operand()->is_valid(), "must be evaluated now");
 424           }
 425         } else {
 426           // NULL out this local so that linear scan can assume that all non-NULL values are live.
 427           s->invalidate_local(index);
 428         }
 429       }
 430     }
 431     bci = scope->caller_bci();
 432   }
 433 
 434   return new CodeEmitInfo(x->bci(), state, ignore_xhandler ? NULL : x->exception_handlers());
 435 }
 436 
 437 
 438 CodeEmitInfo* LIRGenerator::state_for(Instruction* x) {
 439   return state_for(x, x->lock_stack());
 440 }
 441 
 442 
 443 void LIRGenerator::jobject2reg_with_patching(LIR_Opr r, ciObject* obj, CodeEmitInfo* info) {
 444   if (!obj->is_loaded() || PatchALot) {
 445     assert(info != NULL, "info must be set if class is not loaded");
 446     __ oop2reg_patch(NULL, r, info);
 447   } else {
 448     // no patching needed
 449     __ oop2reg(obj->constant_encoding(), r);
 450   }
 451 }
 452 
 453 
 454 void LIRGenerator::array_range_check(LIR_Opr array, LIR_Opr index,
 455                                     CodeEmitInfo* null_check_info, CodeEmitInfo* range_check_info) {
 456   CodeStub* stub = new RangeCheckStub(range_check_info, index);
 457   if (index->is_constant()) {
 458     cmp_mem_int(lir_cond_belowEqual, array, arrayOopDesc::length_offset_in_bytes(),
 459                 index->as_jint(), null_check_info);
 460     __ branch(lir_cond_belowEqual, T_INT, stub); // forward branch
 461   } else {
 462     cmp_reg_mem(lir_cond_aboveEqual, index, array,
 463                 arrayOopDesc::length_offset_in_bytes(), T_INT, null_check_info);
 464     __ branch(lir_cond_aboveEqual, T_INT, stub); // forward branch
 465   }
 466 }
 467 
 468 
 469 void LIRGenerator::nio_range_check(LIR_Opr buffer, LIR_Opr index, LIR_Opr result, CodeEmitInfo* info) {
 470   CodeStub* stub = new RangeCheckStub(info, index, true);
 471   if (index->is_constant()) {
 472     cmp_mem_int(lir_cond_belowEqual, buffer, java_nio_Buffer::limit_offset(), index->as_jint(), info);
 473     __ branch(lir_cond_belowEqual, T_INT, stub); // forward branch
 474   } else {
 475     cmp_reg_mem(lir_cond_aboveEqual, index, buffer,
 476                 java_nio_Buffer::limit_offset(), T_INT, info);
 477     __ branch(lir_cond_aboveEqual, T_INT, stub); // forward branch
 478   }
 479   __ move(index, result);
 480 }
 481 
 482 
 483 
 484 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) {
 485   LIR_Opr result_op = result;
 486   LIR_Opr left_op   = left;
 487   LIR_Opr right_op  = right;
 488 
 489   if (TwoOperandLIRForm && left_op != result_op) {
 490     assert(right_op != result_op, "malformed");
 491     __ move(left_op, result_op);
 492     left_op = result_op;
 493   }
 494 
 495   switch(code) {
 496     case Bytecodes::_dadd:
 497     case Bytecodes::_fadd:
 498     case Bytecodes::_ladd:
 499     case Bytecodes::_iadd:  __ add(left_op, right_op, result_op); break;
 500     case Bytecodes::_fmul:
 501     case Bytecodes::_lmul:  __ mul(left_op, right_op, result_op); break;
 502 
 503     case Bytecodes::_dmul:
 504       {
 505         if (is_strictfp) {
 506           __ mul_strictfp(left_op, right_op, result_op, tmp_op); break;
 507         } else {
 508           __ mul(left_op, right_op, result_op); break;
 509         }
 510       }
 511       break;
 512 
 513     case Bytecodes::_imul:
 514       {
 515         bool    did_strength_reduce = false;
 516 
 517         if (right->is_constant()) {
 518           int c = right->as_jint();
 519           if (is_power_of_2(c)) {
 520             // do not need tmp here
 521             __ shift_left(left_op, exact_log2(c), result_op);
 522             did_strength_reduce = true;
 523           } else {
 524             did_strength_reduce = strength_reduce_multiply(left_op, c, result_op, tmp_op);
 525           }
 526         }
 527         // we couldn't strength reduce so just emit the multiply
 528         if (!did_strength_reduce) {
 529           __ mul(left_op, right_op, result_op);
 530         }
 531       }
 532       break;
 533 
 534     case Bytecodes::_dsub:
 535     case Bytecodes::_fsub:
 536     case Bytecodes::_lsub:
 537     case Bytecodes::_isub: __ sub(left_op, right_op, result_op); break;
 538 
 539     case Bytecodes::_fdiv: __ div (left_op, right_op, result_op); break;
 540     // ldiv and lrem are implemented with a direct runtime call
 541 
 542     case Bytecodes::_ddiv:
 543       {
 544         if (is_strictfp) {
 545           __ div_strictfp (left_op, right_op, result_op, tmp_op); break;
 546         } else {
 547           __ div (left_op, right_op, result_op); break;
 548         }
 549       }
 550       break;
 551 
 552     case Bytecodes::_drem:
 553     case Bytecodes::_frem: __ rem (left_op, right_op, result_op); break;
 554 
 555     default: ShouldNotReachHere();
 556   }
 557 }
 558 
 559 
 560 void LIRGenerator::arithmetic_op_int(Bytecodes::Code code, LIR_Opr result, LIR_Opr left, LIR_Opr right, LIR_Opr tmp) {
 561   arithmetic_op(code, result, left, right, false, tmp);
 562 }
 563 
 564 
 565 void LIRGenerator::arithmetic_op_long(Bytecodes::Code code, LIR_Opr result, LIR_Opr left, LIR_Opr right, CodeEmitInfo* info) {
 566   arithmetic_op(code, result, left, right, false, LIR_OprFact::illegalOpr, info);
 567 }
 568 
 569 
 570 void LIRGenerator::arithmetic_op_fpu(Bytecodes::Code code, LIR_Opr result, LIR_Opr left, LIR_Opr right, bool is_strictfp, LIR_Opr tmp) {
 571   arithmetic_op(code, result, left, right, is_strictfp, tmp);
 572 }
 573 
 574 
 575 void LIRGenerator::shift_op(Bytecodes::Code code, LIR_Opr result_op, LIR_Opr value, LIR_Opr count, LIR_Opr tmp) {
 576   if (TwoOperandLIRForm && value != result_op) {
 577     assert(count != result_op, "malformed");
 578     __ move(value, result_op);
 579     value = result_op;
 580   }
 581 
 582   assert(count->is_constant() || count->is_register(), "must be");
 583   switch(code) {
 584   case Bytecodes::_ishl:
 585   case Bytecodes::_lshl: __ shift_left(value, count, result_op, tmp); break;
 586   case Bytecodes::_ishr:
 587   case Bytecodes::_lshr: __ shift_right(value, count, result_op, tmp); break;
 588   case Bytecodes::_iushr:
 589   case Bytecodes::_lushr: __ unsigned_shift_right(value, count, result_op, tmp); break;
 590   default: ShouldNotReachHere();
 591   }
 592 }
 593 
 594 
 595 void LIRGenerator::logic_op (Bytecodes::Code code, LIR_Opr result_op, LIR_Opr left_op, LIR_Opr right_op) {
 596   if (TwoOperandLIRForm && left_op != result_op) {
 597     assert(right_op != result_op, "malformed");
 598     __ move(left_op, result_op);
 599     left_op = result_op;
 600   }
 601 
 602   switch(code) {
 603     case Bytecodes::_iand:
 604     case Bytecodes::_land:  __ logical_and(left_op, right_op, result_op); break;
 605 
 606     case Bytecodes::_ior:
 607     case Bytecodes::_lor:   __ logical_or(left_op, right_op, result_op);  break;
 608 
 609     case Bytecodes::_ixor:
 610     case Bytecodes::_lxor:  __ logical_xor(left_op, right_op, result_op); break;
 611 
 612     default: ShouldNotReachHere();
 613   }
 614 }
 615 
 616 
 617 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) {
 618   if (!GenerateSynchronizationCode) return;
 619   // for slow path, use debug info for state after successful locking
 620   CodeStub* slow_path = new MonitorEnterStub(object, lock, info);
 621   __ load_stack_address_monitor(monitor_no, lock);
 622   // for handling NullPointerException, use debug info representing just the lock stack before this monitorenter
 623   __ lock_object(hdr, object, lock, scratch, slow_path, info_for_exception);
 624 }
 625 
 626 
 627 void LIRGenerator::monitor_exit(LIR_Opr object, LIR_Opr lock, LIR_Opr new_hdr, LIR_Opr scratch, int monitor_no) {
 628   if (!GenerateSynchronizationCode) return;
 629   // setup registers
 630   LIR_Opr hdr = lock;
 631   lock = new_hdr;
 632   CodeStub* slow_path = new MonitorExitStub(lock, UseFastLocking, monitor_no);
 633   __ load_stack_address_monitor(monitor_no, lock);
 634   __ unlock_object(hdr, object, lock, scratch, slow_path);
 635 }
 636 
 637 
 638 void LIRGenerator::new_instance(LIR_Opr dst, ciInstanceKlass* klass, LIR_Opr scratch1, LIR_Opr scratch2, LIR_Opr scratch3, LIR_Opr scratch4, LIR_Opr klass_reg, CodeEmitInfo* info) {
 639   jobject2reg_with_patching(klass_reg, klass, info);
 640   // If klass is not loaded we do not know if the klass has finalizers:
 641   if (UseFastNewInstance && klass->is_loaded()
 642       && !Klass::layout_helper_needs_slow_path(klass->layout_helper())) {
 643 
 644     Runtime1::StubID stub_id = klass->is_initialized() ? Runtime1::fast_new_instance_id : Runtime1::fast_new_instance_init_check_id;
 645 
 646     CodeStub* slow_path = new NewInstanceStub(klass_reg, dst, klass, info, stub_id);
 647 
 648     assert(klass->is_loaded(), "must be loaded");
 649     // allocate space for instance
 650     assert(klass->size_helper() >= 0, "illegal instance size");
 651     const int instance_size = align_object_size(klass->size_helper());
 652     __ allocate_object(dst, scratch1, scratch2, scratch3, scratch4,
 653                        oopDesc::header_size(), instance_size, klass_reg, !klass->is_initialized(), slow_path);
 654   } else {
 655     CodeStub* slow_path = new NewInstanceStub(klass_reg, dst, klass, info, Runtime1::new_instance_id);
 656     __ branch(lir_cond_always, T_ILLEGAL, slow_path);
 657     __ branch_destination(slow_path->continuation());
 658   }
 659 }
 660 
 661 
 662 static bool is_constant_zero(Instruction* inst) {
 663   IntConstant* c = inst->type()->as_IntConstant();
 664   if (c) {
 665     return (c->value() == 0);
 666   }
 667   return false;
 668 }
 669 
 670 
 671 static bool positive_constant(Instruction* inst) {
 672   IntConstant* c = inst->type()->as_IntConstant();
 673   if (c) {
 674     return (c->value() >= 0);
 675   }
 676   return false;
 677 }
 678 
 679 
 680 static ciArrayKlass* as_array_klass(ciType* type) {
 681   if (type != NULL && type->is_array_klass() && type->is_loaded()) {
 682     return (ciArrayKlass*)type;
 683   } else {
 684     return NULL;
 685   }
 686 }
 687 
 688 void LIRGenerator::arraycopy_helper(Intrinsic* x, int* flagsp, ciArrayKlass** expected_typep) {
 689   Instruction* src     = x->argument_at(0);
 690   Instruction* src_pos = x->argument_at(1);
 691   Instruction* dst     = x->argument_at(2);
 692   Instruction* dst_pos = x->argument_at(3);
 693   Instruction* length  = x->argument_at(4);
 694 
 695   // first try to identify the likely type of the arrays involved
 696   ciArrayKlass* expected_type = NULL;
 697   bool is_exact = false;
 698   {
 699     ciArrayKlass* src_exact_type    = as_array_klass(src->exact_type());
 700     ciArrayKlass* src_declared_type = as_array_klass(src->declared_type());
 701     ciArrayKlass* dst_exact_type    = as_array_klass(dst->exact_type());
 702     ciArrayKlass* dst_declared_type = as_array_klass(dst->declared_type());
 703     if (src_exact_type != NULL && src_exact_type == dst_exact_type) {
 704       // the types exactly match so the type is fully known
 705       is_exact = true;
 706       expected_type = src_exact_type;
 707     } else if (dst_exact_type != NULL && dst_exact_type->is_obj_array_klass()) {
 708       ciArrayKlass* dst_type = (ciArrayKlass*) dst_exact_type;
 709       ciArrayKlass* src_type = NULL;
 710       if (src_exact_type != NULL && src_exact_type->is_obj_array_klass()) {
 711         src_type = (ciArrayKlass*) src_exact_type;
 712       } else if (src_declared_type != NULL && src_declared_type->is_obj_array_klass()) {
 713         src_type = (ciArrayKlass*) src_declared_type;
 714       }
 715       if (src_type != NULL) {
 716         if (src_type->element_type()->is_subtype_of(dst_type->element_type())) {
 717           is_exact = true;
 718           expected_type = dst_type;
 719         }
 720       }
 721     }
 722     // at least pass along a good guess
 723     if (expected_type == NULL) expected_type = dst_exact_type;
 724     if (expected_type == NULL) expected_type = src_declared_type;
 725     if (expected_type == NULL) expected_type = dst_declared_type;
 726   }
 727 
 728   // if a probable array type has been identified, figure out if any
 729   // of the required checks for a fast case can be elided.
 730   int flags = LIR_OpArrayCopy::all_flags;
 731   if (expected_type != NULL) {
 732     // try to skip null checks
 733     if (src->as_NewArray() != NULL)
 734       flags &= ~LIR_OpArrayCopy::src_null_check;
 735     if (dst->as_NewArray() != NULL)
 736       flags &= ~LIR_OpArrayCopy::dst_null_check;
 737 
 738     // check from incoming constant values
 739     if (positive_constant(src_pos))
 740       flags &= ~LIR_OpArrayCopy::src_pos_positive_check;
 741     if (positive_constant(dst_pos))
 742       flags &= ~LIR_OpArrayCopy::dst_pos_positive_check;
 743     if (positive_constant(length))
 744       flags &= ~LIR_OpArrayCopy::length_positive_check;
 745 
 746     // see if the range check can be elided, which might also imply
 747     // that src or dst is non-null.
 748     ArrayLength* al = length->as_ArrayLength();
 749     if (al != NULL) {
 750       if (al->array() == src) {
 751         // it's the length of the source array
 752         flags &= ~LIR_OpArrayCopy::length_positive_check;
 753         flags &= ~LIR_OpArrayCopy::src_null_check;
 754         if (is_constant_zero(src_pos))
 755           flags &= ~LIR_OpArrayCopy::src_range_check;
 756       }
 757       if (al->array() == dst) {
 758         // it's the length of the destination array
 759         flags &= ~LIR_OpArrayCopy::length_positive_check;
 760         flags &= ~LIR_OpArrayCopy::dst_null_check;
 761         if (is_constant_zero(dst_pos))
 762           flags &= ~LIR_OpArrayCopy::dst_range_check;
 763       }
 764     }
 765     if (is_exact) {
 766       flags &= ~LIR_OpArrayCopy::type_check;
 767     }
 768   }
 769 
 770   if (src == dst) {
 771     // moving within a single array so no type checks are needed
 772     if (flags & LIR_OpArrayCopy::type_check) {
 773       flags &= ~LIR_OpArrayCopy::type_check;
 774     }
 775   }
 776   *flagsp = flags;
 777   *expected_typep = (ciArrayKlass*)expected_type;
 778 }
 779 
 780 
 781 LIR_Opr LIRGenerator::round_item(LIR_Opr opr) {
 782   assert(opr->is_register(), "why spill if item is not register?");
 783 
 784   if (RoundFPResults && UseSSE < 1 && opr->is_single_fpu()) {
 785     LIR_Opr result = new_register(T_FLOAT);
 786     set_vreg_flag(result, must_start_in_memory);
 787     assert(opr->is_register(), "only a register can be spilled");
 788     assert(opr->value_type()->is_float(), "rounding only for floats available");
 789     __ roundfp(opr, LIR_OprFact::illegalOpr, result);
 790     return result;
 791   }
 792   return opr;
 793 }
 794 
 795 
 796 LIR_Opr LIRGenerator::force_to_spill(LIR_Opr value, BasicType t) {
 797   assert(type2size[t] == type2size[value->type()], "size mismatch");
 798   if (!value->is_register()) {
 799     // force into a register
 800     LIR_Opr r = new_register(value->type());
 801     __ move(value, r);
 802     value = r;
 803   }
 804 
 805   // create a spill location
 806   LIR_Opr tmp = new_register(t);
 807   set_vreg_flag(tmp, LIRGenerator::must_start_in_memory);
 808 
 809   // move from register to spill
 810   __ move(value, tmp);
 811   return tmp;
 812 }
 813 
 814 void LIRGenerator::profile_branch(If* if_instr, If::Condition cond) {
 815   if (if_instr->should_profile()) {
 816     ciMethod* method = if_instr->profiled_method();
 817     assert(method != NULL, "method should be set if branch is profiled");
 818     ciMethodData* md = method->method_data();
 819     if (md == NULL) {
 820       bailout("out of memory building methodDataOop");
 821       return;
 822     }
 823     ciProfileData* data = md->bci_to_data(if_instr->profiled_bci());
 824     assert(data != NULL, "must have profiling data");
 825     assert(data->is_BranchData(), "need BranchData for two-way branches");
 826     int taken_count_offset     = md->byte_offset_of_slot(data, BranchData::taken_offset());
 827     int not_taken_count_offset = md->byte_offset_of_slot(data, BranchData::not_taken_offset());
 828     if (if_instr->is_swapped()) {
 829       int t = taken_count_offset;
 830       taken_count_offset = not_taken_count_offset;
 831       not_taken_count_offset = t;
 832     }
 833 
 834     LIR_Opr md_reg = new_register(T_OBJECT);
 835     __ oop2reg(md->constant_encoding(), md_reg);
 836 
 837     LIR_Opr data_offset_reg = new_pointer_register();
 838     __ cmove(lir_cond(cond),
 839              LIR_OprFact::intptrConst(taken_count_offset),
 840              LIR_OprFact::intptrConst(not_taken_count_offset),
 841              data_offset_reg);
 842 
 843     // MDO cells are intptr_t, so the data_reg width is arch-dependent.
 844     LIR_Opr data_reg = new_pointer_register();
 845     LIR_Address* data_addr = new LIR_Address(md_reg, data_offset_reg, data_reg->type());
 846     __ move(LIR_OprFact::address(data_addr), data_reg);
 847     // Use leal instead of add to avoid destroying condition codes on x86
 848     LIR_Address* fake_incr_value = new LIR_Address(data_reg, DataLayout::counter_increment, T_INT);
 849     __ leal(LIR_OprFact::address(fake_incr_value), data_reg);
 850     __ move(data_reg, LIR_OprFact::address(data_addr));
 851   }
 852 }
 853 
 854 // Phi technique:
 855 // This is about passing live values from one basic block to the other.
 856 // In code generated with Java it is rather rare that more than one
 857 // value is on the stack from one basic block to the other.
 858 // We optimize our technique for efficient passing of one value
 859 // (of type long, int, double..) but it can be extended.
 860 // When entering or leaving a basic block, all registers and all spill
 861 // slots are release and empty. We use the released registers
 862 // and spill slots to pass the live values from one block
 863 // to the other. The topmost value, i.e., the value on TOS of expression
 864 // stack is passed in registers. All other values are stored in spilling
 865 // area. Every Phi has an index which designates its spill slot
 866 // At exit of a basic block, we fill the register(s) and spill slots.
 867 // At entry of a basic block, the block_prolog sets up the content of phi nodes
 868 // and locks necessary registers and spilling slots.
 869 
 870 
 871 // move current value to referenced phi function
 872 void LIRGenerator::move_to_phi(PhiResolver* resolver, Value cur_val, Value sux_val) {
 873   Phi* phi = sux_val->as_Phi();
 874   // cur_val can be null without phi being null in conjunction with inlining
 875   if (phi != NULL && cur_val != NULL && cur_val != phi && !phi->is_illegal()) {
 876     LIR_Opr operand = cur_val->operand();
 877     if (cur_val->operand()->is_illegal()) {
 878       assert(cur_val->as_Constant() != NULL || cur_val->as_Local() != NULL,
 879              "these can be produced lazily");
 880       operand = operand_for_instruction(cur_val);
 881     }
 882     resolver->move(operand, operand_for_instruction(phi));
 883   }
 884 }
 885 
 886 
 887 // Moves all stack values into their PHI position
 888 void LIRGenerator::move_to_phi(ValueStack* cur_state) {
 889   BlockBegin* bb = block();
 890   if (bb->number_of_sux() == 1) {
 891     BlockBegin* sux = bb->sux_at(0);
 892     assert(sux->number_of_preds() > 0, "invalid CFG");
 893 
 894     // a block with only one predecessor never has phi functions
 895     if (sux->number_of_preds() > 1) {
 896       int max_phis = cur_state->stack_size() + cur_state->locals_size();
 897       PhiResolver resolver(this, _virtual_register_number + max_phis * 2);
 898 
 899       ValueStack* sux_state = sux->state();
 900       Value sux_value;
 901       int index;
 902 
 903       for_each_stack_value(sux_state, index, sux_value) {
 904         move_to_phi(&resolver, cur_state->stack_at(index), sux_value);
 905       }
 906 
 907       // Inlining may cause the local state not to match up, so walk up
 908       // the caller state until we get to the same scope as the
 909       // successor and then start processing from there.
 910       while (cur_state->scope() != sux_state->scope()) {
 911         cur_state = cur_state->caller_state();
 912         assert(cur_state != NULL, "scopes don't match up");
 913       }
 914 
 915       for_each_local_value(sux_state, index, sux_value) {
 916         move_to_phi(&resolver, cur_state->local_at(index), sux_value);
 917       }
 918 
 919       assert(cur_state->caller_state() == sux_state->caller_state(), "caller states must be equal");
 920     }
 921   }
 922 }
 923 
 924 
 925 LIR_Opr LIRGenerator::new_register(BasicType type) {
 926   int vreg = _virtual_register_number;
 927   // add a little fudge factor for the bailout, since the bailout is
 928   // only checked periodically.  This gives a few extra registers to
 929   // hand out before we really run out, which helps us keep from
 930   // tripping over assertions.
 931   if (vreg + 20 >= LIR_OprDesc::vreg_max) {
 932     bailout("out of virtual registers");
 933     if (vreg + 2 >= LIR_OprDesc::vreg_max) {
 934       // wrap it around
 935       _virtual_register_number = LIR_OprDesc::vreg_base;
 936     }
 937   }
 938   _virtual_register_number += 1;
 939   if (type == T_ADDRESS) type = T_INT;
 940   return LIR_OprFact::virtual_register(vreg, type);
 941 }
 942 
 943 
 944 // Try to lock using register in hint
 945 LIR_Opr LIRGenerator::rlock(Value instr) {
 946   return new_register(instr->type());
 947 }
 948 
 949 
 950 // does an rlock and sets result
 951 LIR_Opr LIRGenerator::rlock_result(Value x) {
 952   LIR_Opr reg = rlock(x);
 953   set_result(x, reg);
 954   return reg;
 955 }
 956 
 957 
 958 // does an rlock and sets result
 959 LIR_Opr LIRGenerator::rlock_result(Value x, BasicType type) {
 960   LIR_Opr reg;
 961   switch (type) {
 962   case T_BYTE:
 963   case T_BOOLEAN:
 964     reg = rlock_byte(type);
 965     break;
 966   default:
 967     reg = rlock(x);
 968     break;
 969   }
 970 
 971   set_result(x, reg);
 972   return reg;
 973 }
 974 
 975 
 976 //---------------------------------------------------------------------
 977 ciObject* LIRGenerator::get_jobject_constant(Value value) {
 978   ObjectType* oc = value->type()->as_ObjectType();
 979   if (oc) {
 980     return oc->constant_value();
 981   }
 982   return NULL;
 983 }
 984 
 985 
 986 void LIRGenerator::do_ExceptionObject(ExceptionObject* x) {
 987   assert(block()->is_set(BlockBegin::exception_entry_flag), "ExceptionObject only allowed in exception handler block");
 988   assert(block()->next() == x, "ExceptionObject must be first instruction of block");
 989 
 990   // no moves are created for phi functions at the begin of exception
 991   // handlers, so assign operands manually here
 992   for_each_phi_fun(block(), phi,
 993                    operand_for_instruction(phi));
 994 
 995   LIR_Opr thread_reg = getThreadPointer();
 996   __ move(new LIR_Address(thread_reg, in_bytes(JavaThread::exception_oop_offset()), T_OBJECT),
 997           exceptionOopOpr());
 998   __ move(LIR_OprFact::oopConst(NULL),
 999           new LIR_Address(thread_reg, in_bytes(JavaThread::exception_oop_offset()), T_OBJECT));
1000   __ move(LIR_OprFact::oopConst(NULL),
1001           new LIR_Address(thread_reg, in_bytes(JavaThread::exception_pc_offset()), T_OBJECT));
1002 
1003   LIR_Opr result = new_register(T_OBJECT);
1004   __ move(exceptionOopOpr(), result);
1005   set_result(x, result);
1006 }
1007 
1008 
1009 //----------------------------------------------------------------------
1010 //----------------------------------------------------------------------
1011 //----------------------------------------------------------------------
1012 //----------------------------------------------------------------------
1013 //                        visitor functions
1014 //----------------------------------------------------------------------
1015 //----------------------------------------------------------------------
1016 //----------------------------------------------------------------------
1017 //----------------------------------------------------------------------
1018 
1019 void LIRGenerator::do_Phi(Phi* x) {
1020   // phi functions are never visited directly
1021   ShouldNotReachHere();
1022 }
1023 
1024 
1025 // Code for a constant is generated lazily unless the constant is frequently used and can't be inlined.
1026 void LIRGenerator::do_Constant(Constant* x) {
1027   if (x->state() != NULL) {
1028     // Any constant with a ValueStack requires patching so emit the patch here
1029     LIR_Opr reg = rlock_result(x);
1030     CodeEmitInfo* info = state_for(x, x->state());
1031     __ oop2reg_patch(NULL, reg, info);
1032   } else if (x->use_count() > 1 && !can_inline_as_constant(x)) {
1033     if (!x->is_pinned()) {
1034       // unpinned constants are handled specially so that they can be
1035       // put into registers when they are used multiple times within a
1036       // block.  After the block completes their operand will be
1037       // cleared so that other blocks can't refer to that register.
1038       set_result(x, load_constant(x));
1039     } else {
1040       LIR_Opr res = x->operand();
1041       if (!res->is_valid()) {
1042         res = LIR_OprFact::value_type(x->type());
1043       }
1044       if (res->is_constant()) {
1045         LIR_Opr reg = rlock_result(x);
1046         __ move(res, reg);
1047       } else {
1048         set_result(x, res);
1049       }
1050     }
1051   } else {
1052     set_result(x, LIR_OprFact::value_type(x->type()));
1053   }
1054 }
1055 
1056 
1057 void LIRGenerator::do_Local(Local* x) {
1058   // operand_for_instruction has the side effect of setting the result
1059   // so there's no need to do it here.
1060   operand_for_instruction(x);
1061 }
1062 
1063 
1064 void LIRGenerator::do_IfInstanceOf(IfInstanceOf* x) {
1065   Unimplemented();
1066 }
1067 
1068 
1069 void LIRGenerator::do_Return(Return* x) {
1070   if (compilation()->env()->dtrace_method_probes()) {
1071     BasicTypeList signature;
1072     signature.append(T_INT);    // thread
1073     signature.append(T_OBJECT); // methodOop
1074     LIR_OprList* args = new LIR_OprList();
1075     args->append(getThreadPointer());
1076     LIR_Opr meth = new_register(T_OBJECT);
1077     __ oop2reg(method()->constant_encoding(), meth);
1078     args->append(meth);
1079     call_runtime(&signature, args, CAST_FROM_FN_PTR(address, SharedRuntime::dtrace_method_exit), voidType, NULL);
1080   }
1081 
1082   if (x->type()->is_void()) {
1083     __ return_op(LIR_OprFact::illegalOpr);
1084   } else {
1085     LIR_Opr reg = result_register_for(x->type(), /*callee=*/true);
1086     LIRItem result(x->result(), this);
1087 
1088     result.load_item_force(reg);
1089     __ return_op(result.result());
1090   }
1091   set_no_result(x);
1092 }
1093 
1094 
1095 // Example: object.getClass ()
1096 void LIRGenerator::do_getClass(Intrinsic* x) {
1097   assert(x->number_of_arguments() == 1, "wrong type");
1098 
1099   LIRItem rcvr(x->argument_at(0), this);
1100   rcvr.load_item();
1101   LIR_Opr result = rlock_result(x);
1102 
1103   // need to perform the null check on the rcvr
1104   CodeEmitInfo* info = NULL;
1105   if (x->needs_null_check()) {
1106     info = state_for(x, x->state()->copy_locks());
1107   }
1108   __ move(new LIR_Address(rcvr.result(), oopDesc::klass_offset_in_bytes(), T_OBJECT), result, info);
1109   __ move(new LIR_Address(result, Klass::java_mirror_offset_in_bytes() +
1110                           klassOopDesc::klass_part_offset_in_bytes(), T_OBJECT), result);
1111 }
1112 
1113 
1114 // Example: Thread.currentThread()
1115 void LIRGenerator::do_currentThread(Intrinsic* x) {
1116   assert(x->number_of_arguments() == 0, "wrong type");
1117   LIR_Opr reg = rlock_result(x);
1118   __ load(new LIR_Address(getThreadPointer(), in_bytes(JavaThread::threadObj_offset()), T_OBJECT), reg);
1119 }
1120 
1121 
1122 void LIRGenerator::do_RegisterFinalizer(Intrinsic* x) {
1123   assert(x->number_of_arguments() == 1, "wrong type");
1124   LIRItem receiver(x->argument_at(0), this);
1125 
1126   receiver.load_item();
1127   BasicTypeList signature;
1128   signature.append(T_OBJECT); // receiver
1129   LIR_OprList* args = new LIR_OprList();
1130   args->append(receiver.result());
1131   CodeEmitInfo* info = state_for(x, x->state());
1132   call_runtime(&signature, args,
1133                CAST_FROM_FN_PTR(address, Runtime1::entry_for(Runtime1::register_finalizer_id)),
1134                voidType, info);
1135 
1136   set_no_result(x);
1137 }
1138 
1139 
1140 //------------------------local access--------------------------------------
1141 
1142 LIR_Opr LIRGenerator::operand_for_instruction(Instruction* x) {
1143   if (x->operand()->is_illegal()) {
1144     Constant* c = x->as_Constant();
1145     if (c != NULL) {
1146       x->set_operand(LIR_OprFact::value_type(c->type()));
1147     } else {
1148       assert(x->as_Phi() || x->as_Local() != NULL, "only for Phi and Local");
1149       // allocate a virtual register for this local or phi
1150       x->set_operand(rlock(x));
1151       _instruction_for_operand.at_put_grow(x->operand()->vreg_number(), x, NULL);
1152     }
1153   }
1154   return x->operand();
1155 }
1156 
1157 
1158 Instruction* LIRGenerator::instruction_for_opr(LIR_Opr opr) {
1159   if (opr->is_virtual()) {
1160     return instruction_for_vreg(opr->vreg_number());
1161   }
1162   return NULL;
1163 }
1164 
1165 
1166 Instruction* LIRGenerator::instruction_for_vreg(int reg_num) {
1167   if (reg_num < _instruction_for_operand.length()) {
1168     return _instruction_for_operand.at(reg_num);
1169   }
1170   return NULL;
1171 }
1172 
1173 
1174 void LIRGenerator::set_vreg_flag(int vreg_num, VregFlag f) {
1175   if (_vreg_flags.size_in_bits() == 0) {
1176     BitMap2D temp(100, num_vreg_flags);
1177     temp.clear();
1178     _vreg_flags = temp;
1179   }
1180   _vreg_flags.at_put_grow(vreg_num, f, true);
1181 }
1182 
1183 bool LIRGenerator::is_vreg_flag_set(int vreg_num, VregFlag f) {
1184   if (!_vreg_flags.is_valid_index(vreg_num, f)) {
1185     return false;
1186   }
1187   return _vreg_flags.at(vreg_num, f);
1188 }
1189 
1190 
1191 // Block local constant handling.  This code is useful for keeping
1192 // unpinned constants and constants which aren't exposed in the IR in
1193 // registers.  Unpinned Constant instructions have their operands
1194 // cleared when the block is finished so that other blocks can't end
1195 // up referring to their registers.
1196 
1197 LIR_Opr LIRGenerator::load_constant(Constant* x) {
1198   assert(!x->is_pinned(), "only for unpinned constants");
1199   _unpinned_constants.append(x);
1200   return load_constant(LIR_OprFact::value_type(x->type())->as_constant_ptr());
1201 }
1202 
1203 
1204 LIR_Opr LIRGenerator::load_constant(LIR_Const* c) {
1205   BasicType t = c->type();
1206   for (int i = 0; i < _constants.length(); i++) {
1207     LIR_Const* other = _constants.at(i);
1208     if (t == other->type()) {
1209       switch (t) {
1210       case T_INT:
1211       case T_FLOAT:
1212         if (c->as_jint_bits() != other->as_jint_bits()) continue;
1213         break;
1214       case T_LONG:
1215       case T_DOUBLE:
1216         if (c->as_jint_hi_bits() != other->as_jint_hi_bits()) continue;
1217         if (c->as_jint_lo_bits() != other->as_jint_lo_bits()) continue;
1218         break;
1219       case T_OBJECT:
1220         if (c->as_jobject() != other->as_jobject()) continue;
1221         break;
1222       }
1223       return _reg_for_constants.at(i);
1224     }
1225   }
1226 
1227   LIR_Opr result = new_register(t);
1228   __ move((LIR_Opr)c, result);
1229   _constants.append(c);
1230   _reg_for_constants.append(result);
1231   return result;
1232 }
1233 
1234 // Various barriers
1235 
1236 void LIRGenerator::pre_barrier(LIR_Opr addr_opr, bool patch,  CodeEmitInfo* info) {
1237   // Do the pre-write barrier, if any.
1238   switch (_bs->kind()) {
1239 #ifndef SERIALGC
1240     case BarrierSet::G1SATBCT:
1241     case BarrierSet::G1SATBCTLogging:
1242       G1SATBCardTableModRef_pre_barrier(addr_opr, patch, info);
1243       break;
1244 #endif // SERIALGC
1245     case BarrierSet::CardTableModRef:
1246     case BarrierSet::CardTableExtension:
1247       // No pre barriers
1248       break;
1249     case BarrierSet::ModRef:
1250     case BarrierSet::Other:
1251       // No pre barriers
1252       break;
1253     default      :
1254       ShouldNotReachHere();
1255 
1256   }
1257 }
1258 
1259 void LIRGenerator::post_barrier(LIR_OprDesc* addr, LIR_OprDesc* new_val) {
1260   switch (_bs->kind()) {
1261 #ifndef SERIALGC
1262     case BarrierSet::G1SATBCT:
1263     case BarrierSet::G1SATBCTLogging:
1264       G1SATBCardTableModRef_post_barrier(addr,  new_val);
1265       break;
1266 #endif // SERIALGC
1267     case BarrierSet::CardTableModRef:
1268     case BarrierSet::CardTableExtension:
1269       CardTableModRef_post_barrier(addr,  new_val);
1270       break;
1271     case BarrierSet::ModRef:
1272     case BarrierSet::Other:
1273       // No post barriers
1274       break;
1275     default      :
1276       ShouldNotReachHere();
1277     }
1278 }
1279 
1280 ////////////////////////////////////////////////////////////////////////
1281 #ifndef SERIALGC
1282 
1283 void LIRGenerator::G1SATBCardTableModRef_pre_barrier(LIR_Opr addr_opr, bool patch,  CodeEmitInfo* info) {
1284   if (G1DisablePreBarrier) return;
1285 
1286   // First we test whether marking is in progress.
1287   BasicType flag_type;
1288   if (in_bytes(PtrQueue::byte_width_of_active()) == 4) {
1289     flag_type = T_INT;
1290   } else {
1291     guarantee(in_bytes(PtrQueue::byte_width_of_active()) == 1,
1292               "Assumption");
1293     flag_type = T_BYTE;
1294   }
1295   LIR_Opr thrd = getThreadPointer();
1296   LIR_Address* mark_active_flag_addr =
1297     new LIR_Address(thrd,
1298                     in_bytes(JavaThread::satb_mark_queue_offset() +
1299                              PtrQueue::byte_offset_of_active()),
1300                     flag_type);
1301   // Read the marking-in-progress flag.
1302   LIR_Opr flag_val = new_register(T_INT);
1303   __ load(mark_active_flag_addr, flag_val);
1304 
1305   LIR_PatchCode pre_val_patch_code =
1306     patch ? lir_patch_normal : lir_patch_none;
1307 
1308   LIR_Opr pre_val = new_register(T_OBJECT);
1309 
1310   __ cmp(lir_cond_notEqual, flag_val, LIR_OprFact::intConst(0));
1311   if (!addr_opr->is_address()) {
1312     assert(addr_opr->is_register(), "must be");
1313     addr_opr = LIR_OprFact::address(new LIR_Address(addr_opr, T_OBJECT));
1314   }
1315   CodeStub* slow = new G1PreBarrierStub(addr_opr, pre_val, pre_val_patch_code,
1316                                         info);
1317   __ branch(lir_cond_notEqual, T_INT, slow);
1318   __ branch_destination(slow->continuation());
1319 }
1320 
1321 void LIRGenerator::G1SATBCardTableModRef_post_barrier(LIR_OprDesc* addr, LIR_OprDesc* new_val) {
1322   if (G1DisablePostBarrier) return;
1323 
1324   // If the "new_val" is a constant NULL, no barrier is necessary.
1325   if (new_val->is_constant() &&
1326       new_val->as_constant_ptr()->as_jobject() == NULL) return;
1327 
1328   if (!new_val->is_register()) {
1329     LIR_Opr new_val_reg = new_register(T_OBJECT);
1330     if (new_val->is_constant()) {
1331       __ move(new_val, new_val_reg);
1332     } else {
1333       __ leal(new_val, new_val_reg);
1334     }
1335     new_val = new_val_reg;
1336   }
1337   assert(new_val->is_register(), "must be a register at this point");
1338 
1339   if (addr->is_address()) {
1340     LIR_Address* address = addr->as_address_ptr();
1341     LIR_Opr ptr = new_register(T_OBJECT);
1342     if (!address->index()->is_valid() && address->disp() == 0) {
1343       __ move(address->base(), ptr);
1344     } else {
1345       assert(address->disp() != max_jint, "lea doesn't support patched addresses!");
1346       __ leal(addr, ptr);
1347     }
1348     addr = ptr;
1349   }
1350   assert(addr->is_register(), "must be a register at this point");
1351 
1352   LIR_Opr xor_res = new_pointer_register();
1353   LIR_Opr xor_shift_res = new_pointer_register();
1354   if (TwoOperandLIRForm ) {
1355     __ move(addr, xor_res);
1356     __ logical_xor(xor_res, new_val, xor_res);
1357     __ move(xor_res, xor_shift_res);
1358     __ unsigned_shift_right(xor_shift_res,
1359                             LIR_OprFact::intConst(HeapRegion::LogOfHRGrainBytes),
1360                             xor_shift_res,
1361                             LIR_OprDesc::illegalOpr());
1362   } else {
1363     __ logical_xor(addr, new_val, xor_res);
1364     __ unsigned_shift_right(xor_res,
1365                             LIR_OprFact::intConst(HeapRegion::LogOfHRGrainBytes),
1366                             xor_shift_res,
1367                             LIR_OprDesc::illegalOpr());
1368   }
1369 
1370   if (!new_val->is_register()) {
1371     LIR_Opr new_val_reg = new_register(T_OBJECT);
1372     __ leal(new_val, new_val_reg);
1373     new_val = new_val_reg;
1374   }
1375   assert(new_val->is_register(), "must be a register at this point");
1376 
1377   __ cmp(lir_cond_notEqual, xor_shift_res, LIR_OprFact::intptrConst(NULL_WORD));
1378 
1379   CodeStub* slow = new G1PostBarrierStub(addr, new_val);
1380   __ branch(lir_cond_notEqual, LP64_ONLY(T_LONG) NOT_LP64(T_INT), slow);
1381   __ branch_destination(slow->continuation());
1382 }
1383 
1384 #endif // SERIALGC
1385 ////////////////////////////////////////////////////////////////////////
1386 
1387 void LIRGenerator::CardTableModRef_post_barrier(LIR_OprDesc* addr, LIR_OprDesc* new_val) {
1388 
1389   assert(sizeof(*((CardTableModRefBS*)_bs)->byte_map_base) == sizeof(jbyte), "adjust this code");
1390   LIR_Const* card_table_base = new LIR_Const(((CardTableModRefBS*)_bs)->byte_map_base);
1391   if (addr->is_address()) {
1392     LIR_Address* address = addr->as_address_ptr();
1393     LIR_Opr ptr = new_register(T_OBJECT);
1394     if (!address->index()->is_valid() && address->disp() == 0) {
1395       __ move(address->base(), ptr);
1396     } else {
1397       assert(address->disp() != max_jint, "lea doesn't support patched addresses!");
1398       __ leal(addr, ptr);
1399     }
1400     addr = ptr;
1401   }
1402   assert(addr->is_register(), "must be a register at this point");
1403 
1404 #ifdef ARM
1405   // TODO: ARM - move to platform-dependent code
1406   LIR_Opr tmp = FrameMap::R14_opr;
1407   if (VM_Version::supports_movw()) {
1408     __ move((LIR_Opr)card_table_base, tmp);
1409   } else {
1410     __ move(new LIR_Address(FrameMap::Rthread_opr, in_bytes(JavaThread::card_table_base_offset()), T_ADDRESS), tmp);
1411   }
1412 
1413   CardTableModRefBS* ct = (CardTableModRefBS*)_bs;
1414   LIR_Address *card_addr = new LIR_Address(tmp, addr, (LIR_Address::Scale) -CardTableModRefBS::card_shift, 0, T_BYTE);
1415   if(((int)ct->byte_map_base & 0xff) == 0) {
1416     __ move(tmp, card_addr);
1417   } else {
1418     LIR_Opr tmp_zero = new_register(T_INT);
1419     __ move(LIR_OprFact::intConst(0), tmp_zero);
1420     __ move(tmp_zero, card_addr);
1421   }
1422 #else // ARM
1423   LIR_Opr tmp = new_pointer_register();
1424   if (TwoOperandLIRForm) {
1425     __ move(addr, tmp);
1426     __ unsigned_shift_right(tmp, CardTableModRefBS::card_shift, tmp);
1427   } else {
1428     __ unsigned_shift_right(addr, CardTableModRefBS::card_shift, tmp);
1429   }
1430   if (can_inline_as_constant(card_table_base)) {
1431     __ move(LIR_OprFact::intConst(0),
1432               new LIR_Address(tmp, card_table_base->as_jint(), T_BYTE));
1433   } else {
1434     __ move(LIR_OprFact::intConst(0),
1435               new LIR_Address(tmp, load_constant(card_table_base),
1436                               T_BYTE));
1437   }
1438 #endif // ARM
1439 }
1440 
1441 
1442 //------------------------field access--------------------------------------
1443 
1444 // Comment copied form templateTable_i486.cpp
1445 // ----------------------------------------------------------------------------
1446 // Volatile variables demand their effects be made known to all CPU's in
1447 // order.  Store buffers on most chips allow reads & writes to reorder; the
1448 // JMM's ReadAfterWrite.java test fails in -Xint mode without some kind of
1449 // memory barrier (i.e., it's not sufficient that the interpreter does not
1450 // reorder volatile references, the hardware also must not reorder them).
1451 //
1452 // According to the new Java Memory Model (JMM):
1453 // (1) All volatiles are serialized wrt to each other.
1454 // ALSO reads & writes act as aquire & release, so:
1455 // (2) A read cannot let unrelated NON-volatile memory refs that happen after
1456 // the read float up to before the read.  It's OK for non-volatile memory refs
1457 // that happen before the volatile read to float down below it.
1458 // (3) Similar a volatile write cannot let unrelated NON-volatile memory refs
1459 // that happen BEFORE the write float down to after the write.  It's OK for
1460 // non-volatile memory refs that happen after the volatile write to float up
1461 // before it.
1462 //
1463 // We only put in barriers around volatile refs (they are expensive), not
1464 // _between_ memory refs (that would require us to track the flavor of the
1465 // previous memory refs).  Requirements (2) and (3) require some barriers
1466 // before volatile stores and after volatile loads.  These nearly cover
1467 // requirement (1) but miss the volatile-store-volatile-load case.  This final
1468 // case is placed after volatile-stores although it could just as well go
1469 // before volatile-loads.
1470 
1471 
1472 void LIRGenerator::do_StoreField(StoreField* x) {
1473   bool needs_patching = x->needs_patching();
1474   bool is_volatile = x->field()->is_volatile();
1475   BasicType field_type = x->field_type();
1476   bool is_oop = (field_type == T_ARRAY || field_type == T_OBJECT);
1477 
1478   CodeEmitInfo* info = NULL;
1479   if (needs_patching) {
1480     assert(x->explicit_null_check() == NULL, "can't fold null check into patching field access");
1481     info = state_for(x, x->state_before());
1482   } else if (x->needs_null_check()) {
1483     NullCheck* nc = x->explicit_null_check();
1484     if (nc == NULL) {
1485       info = state_for(x, x->lock_stack());
1486     } else {
1487       info = state_for(nc);
1488     }
1489   }
1490 
1491 
1492   LIRItem object(x->obj(), this);
1493   LIRItem value(x->value(),  this);
1494 
1495   object.load_item();
1496 
1497   if (is_volatile || needs_patching) {
1498     // load item if field is volatile (fewer special cases for volatiles)
1499     // load item if field not initialized
1500     // load item if field not constant
1501     // because of code patching we cannot inline constants
1502     if (field_type == T_BYTE || field_type == T_BOOLEAN) {
1503       value.load_byte_item();
1504     } else  {
1505       value.load_item();
1506     }
1507   } else {
1508     value.load_for_store(field_type);
1509   }
1510 
1511   set_no_result(x);
1512 
1513   if (PrintNotLoaded && needs_patching) {
1514     tty->print_cr("   ###class not loaded at store_%s bci %d",
1515                   x->is_static() ?  "static" : "field", x->bci());
1516   }
1517 
1518   if (x->needs_null_check() &&
1519       (needs_patching ||
1520        MacroAssembler::needs_explicit_null_check(x->offset()))) {
1521     // emit an explicit null check because the offset is too large
1522     __ null_check(object.result(), new CodeEmitInfo(info));
1523   }
1524 
1525   LIR_Address* address;
1526   if (needs_patching) {
1527     // we need to patch the offset in the instruction so don't allow
1528     // generate_address to try to be smart about emitting the -1.
1529     // Otherwise the patching code won't know how to find the
1530     // instruction to patch.
1531     address = new LIR_Address(object.result(), PATCHED_ADDR, field_type);
1532   } else {
1533     address = generate_address(object.result(), x->offset(), field_type);
1534   }
1535 
1536   if (is_volatile && os::is_MP()) {
1537     __ membar_release();
1538   }
1539 
1540   if (is_oop) {
1541     // Do the pre-write barrier, if any.
1542     pre_barrier(LIR_OprFact::address(address),
1543                 needs_patching,
1544                 (info ? new CodeEmitInfo(info) : NULL));
1545   }
1546 
1547   if (is_volatile) {
1548     assert(!needs_patching && x->is_loaded(),
1549            "how do we know it's volatile if it's not loaded");
1550     volatile_field_store(value.result(), address, info);
1551   } else {
1552     LIR_PatchCode patch_code = needs_patching ? lir_patch_normal : lir_patch_none;
1553     __ store(value.result(), address, info, patch_code);
1554   }
1555 
1556   if (is_oop) {
1557     // Store to object so mark the card of the header
1558     post_barrier(object.result(), value.result());
1559   }
1560 
1561   if (is_volatile && os::is_MP()) {
1562     __ membar();
1563   }
1564 }
1565 
1566 
1567 void LIRGenerator::do_LoadField(LoadField* x) {
1568   bool needs_patching = x->needs_patching();
1569   bool is_volatile = x->field()->is_volatile();
1570   BasicType field_type = x->field_type();
1571 
1572   CodeEmitInfo* info = NULL;
1573   if (needs_patching) {
1574     assert(x->explicit_null_check() == NULL, "can't fold null check into patching field access");
1575     info = state_for(x, x->state_before());
1576   } else if (x->needs_null_check()) {
1577     NullCheck* nc = x->explicit_null_check();
1578     if (nc == NULL) {
1579       info = state_for(x, x->lock_stack());
1580     } else {
1581       info = state_for(nc);
1582     }
1583   }
1584 
1585   LIRItem object(x->obj(), this);
1586 
1587   object.load_item();
1588 
1589   if (PrintNotLoaded && needs_patching) {
1590     tty->print_cr("   ###class not loaded at load_%s bci %d",
1591                   x->is_static() ?  "static" : "field", x->bci());
1592   }
1593 
1594   if (x->needs_null_check() &&
1595       (needs_patching ||
1596        MacroAssembler::needs_explicit_null_check(x->offset()))) {
1597     // emit an explicit null check because the offset is too large
1598     __ null_check(object.result(), new CodeEmitInfo(info));
1599   }
1600 
1601   LIR_Opr reg = rlock_result(x, field_type);
1602   LIR_Address* address;
1603   if (needs_patching) {
1604     // we need to patch the offset in the instruction so don't allow
1605     // generate_address to try to be smart about emitting the -1.
1606     // Otherwise the patching code won't know how to find the
1607     // instruction to patch.
1608     address = new LIR_Address(object.result(), PATCHED_ADDR, field_type);
1609   } else {
1610     address = generate_address(object.result(), x->offset(), field_type);
1611   }
1612 
1613   if (is_volatile) {
1614     assert(!needs_patching && x->is_loaded(),
1615            "how do we know it's volatile if it's not loaded");
1616     volatile_field_load(address, reg, info);
1617   } else {
1618     LIR_PatchCode patch_code = needs_patching ? lir_patch_normal : lir_patch_none;
1619     __ load(address, reg, info, patch_code);
1620   }
1621 
1622   if (is_volatile && os::is_MP()) {
1623     __ membar_acquire();
1624   }
1625 }
1626 
1627 
1628 //------------------------java.nio.Buffer.checkIndex------------------------
1629 
1630 // int java.nio.Buffer.checkIndex(int)
1631 void LIRGenerator::do_NIOCheckIndex(Intrinsic* x) {
1632   // NOTE: by the time we are in checkIndex() we are guaranteed that
1633   // the buffer is non-null (because checkIndex is package-private and
1634   // only called from within other methods in the buffer).
1635   assert(x->number_of_arguments() == 2, "wrong type");
1636   LIRItem buf  (x->argument_at(0), this);
1637   LIRItem index(x->argument_at(1), this);
1638   buf.load_item();
1639   index.load_item();
1640 
1641   LIR_Opr result = rlock_result(x);
1642   if (GenerateRangeChecks) {
1643     CodeEmitInfo* info = state_for(x);
1644     CodeStub* stub = new RangeCheckStub(info, index.result(), true);
1645     if (index.result()->is_constant()) {
1646       cmp_mem_int(lir_cond_belowEqual, buf.result(), java_nio_Buffer::limit_offset(), index.result()->as_jint(), info);
1647       __ branch(lir_cond_belowEqual, T_INT, stub);
1648     } else {
1649       cmp_reg_mem(lir_cond_aboveEqual, index.result(), buf.result(),
1650                   java_nio_Buffer::limit_offset(), T_INT, info);
1651       __ branch(lir_cond_aboveEqual, T_INT, stub);
1652     }
1653     __ move(index.result(), result);
1654   } else {
1655     // Just load the index into the result register
1656     __ move(index.result(), result);
1657   }
1658 }
1659 
1660 
1661 //------------------------array access--------------------------------------
1662 
1663 
1664 void LIRGenerator::do_ArrayLength(ArrayLength* x) {
1665   LIRItem array(x->array(), this);
1666   array.load_item();
1667   LIR_Opr reg = rlock_result(x);
1668 
1669   CodeEmitInfo* info = NULL;
1670   if (x->needs_null_check()) {
1671     NullCheck* nc = x->explicit_null_check();
1672     if (nc == NULL) {
1673       info = state_for(x);
1674     } else {
1675       info = state_for(nc);
1676     }
1677   }
1678   __ load(new LIR_Address(array.result(), arrayOopDesc::length_offset_in_bytes(), T_INT), reg, info, lir_patch_none);
1679 }
1680 
1681 
1682 void LIRGenerator::do_LoadIndexed(LoadIndexed* x) {
1683   bool use_length = x->length() != NULL;
1684   LIRItem array(x->array(), this);
1685   LIRItem index(x->index(), this);
1686   LIRItem length(this);
1687   bool needs_range_check = true;
1688 
1689   if (use_length) {
1690     needs_range_check = x->compute_needs_range_check();
1691     if (needs_range_check) {
1692       length.set_instruction(x->length());
1693       length.load_item();
1694     }
1695   }
1696 
1697   array.load_item();
1698   if (index.is_constant() && can_inline_as_constant(x->index())) {
1699     // let it be a constant
1700     index.dont_load_item();
1701   } else {
1702     index.load_item();
1703   }
1704 
1705   CodeEmitInfo* range_check_info = state_for(x);
1706   CodeEmitInfo* null_check_info = NULL;
1707   if (x->needs_null_check()) {
1708     NullCheck* nc = x->explicit_null_check();
1709     if (nc != NULL) {
1710       null_check_info = state_for(nc);
1711     } else {
1712       null_check_info = range_check_info;
1713     }
1714   }
1715 
1716   // emit array address setup early so it schedules better
1717   LIR_Address* array_addr = emit_array_address(array.result(), index.result(), x->elt_type(), false);
1718 
1719   if (GenerateRangeChecks && needs_range_check) {
1720     if (use_length) {
1721       // TODO: use a (modified) version of array_range_check that does not require a
1722       //       constant length to be loaded to a register
1723       __ cmp(lir_cond_belowEqual, length.result(), index.result());
1724       __ branch(lir_cond_belowEqual, T_INT, new RangeCheckStub(range_check_info, index.result()));
1725     } else {
1726       array_range_check(array.result(), index.result(), null_check_info, range_check_info);
1727       // The range check performs the null check, so clear it out for the load
1728       null_check_info = NULL;
1729     }
1730   }
1731 
1732   __ move(array_addr, rlock_result(x, x->elt_type()), null_check_info);
1733 }
1734 
1735 
1736 void LIRGenerator::do_NullCheck(NullCheck* x) {
1737   if (x->can_trap()) {
1738     LIRItem value(x->obj(), this);
1739     value.load_item();
1740     CodeEmitInfo* info = state_for(x);
1741     __ null_check(value.result(), info);
1742   }
1743 }
1744 
1745 
1746 void LIRGenerator::do_Throw(Throw* x) {
1747   LIRItem exception(x->exception(), this);
1748   exception.load_item();
1749   set_no_result(x);
1750   LIR_Opr exception_opr = exception.result();
1751   CodeEmitInfo* info = state_for(x, x->state());
1752 
1753 #ifndef PRODUCT
1754   if (PrintC1Statistics) {
1755     increment_counter(Runtime1::throw_count_address(), T_INT);
1756   }
1757 #endif
1758 
1759   // check if the instruction has an xhandler in any of the nested scopes
1760   bool unwind = false;
1761   if (info->exception_handlers()->length() == 0) {
1762     // this throw is not inside an xhandler
1763     unwind = true;
1764   } else {
1765     // get some idea of the throw type
1766     bool type_is_exact = true;
1767     ciType* throw_type = x->exception()->exact_type();
1768     if (throw_type == NULL) {
1769       type_is_exact = false;
1770       throw_type = x->exception()->declared_type();
1771     }
1772     if (throw_type != NULL && throw_type->is_instance_klass()) {
1773       ciInstanceKlass* throw_klass = (ciInstanceKlass*)throw_type;
1774       unwind = !x->exception_handlers()->could_catch(throw_klass, type_is_exact);
1775     }
1776   }
1777 
1778   // do null check before moving exception oop into fixed register
1779   // to avoid a fixed interval with an oop during the null check.
1780   // Use a copy of the CodeEmitInfo because debug information is
1781   // different for null_check and throw.
1782   if (GenerateCompilerNullChecks &&
1783       (x->exception()->as_NewInstance() == NULL && x->exception()->as_ExceptionObject() == NULL)) {
1784     // if the exception object wasn't created using new then it might be null.
1785     __ null_check(exception_opr, new CodeEmitInfo(info, true));
1786   }
1787 
1788   if (compilation()->env()->jvmti_can_post_on_exceptions()) {
1789     // we need to go through the exception lookup path to get JVMTI
1790     // notification done
1791     unwind = false;
1792   }
1793 
1794   // move exception oop into fixed register
1795   __ move(exception_opr, exceptionOopOpr());
1796 
1797   if (unwind) {
1798     __ unwind_exception(exceptionOopOpr());
1799   } else {
1800     __ throw_exception(exceptionPcOpr(), exceptionOopOpr(), info);
1801   }
1802 }
1803 
1804 
1805 void LIRGenerator::do_RoundFP(RoundFP* x) {
1806   LIRItem input(x->input(), this);
1807   input.load_item();
1808   LIR_Opr input_opr = input.result();
1809   assert(input_opr->is_register(), "why round if value is not in a register?");
1810   assert(input_opr->is_single_fpu() || input_opr->is_double_fpu(), "input should be floating-point value");
1811   if (input_opr->is_single_fpu()) {
1812     set_result(x, round_item(input_opr)); // This code path not currently taken
1813   } else {
1814     LIR_Opr result = new_register(T_DOUBLE);
1815     set_vreg_flag(result, must_start_in_memory);
1816     __ roundfp(input_opr, LIR_OprFact::illegalOpr, result);
1817     set_result(x, result);
1818   }
1819 }
1820 
1821 void LIRGenerator::do_UnsafeGetRaw(UnsafeGetRaw* x) {
1822   LIRItem base(x->base(), this);
1823   LIRItem idx(this);
1824 
1825   base.load_item();
1826   if (x->has_index()) {
1827     idx.set_instruction(x->index());
1828     idx.load_nonconstant();
1829   }
1830 
1831   LIR_Opr reg = rlock_result(x, x->basic_type());
1832 
1833   int   log2_scale = 0;
1834   if (x->has_index()) {
1835     assert(x->index()->type()->tag() == intTag, "should not find non-int index");
1836     log2_scale = x->log2_scale();
1837   }
1838 
1839   assert(!x->has_index() || idx.value() == x->index(), "should match");
1840 
1841   LIR_Opr base_op = base.result();
1842 #ifndef _LP64
1843   if (x->base()->type()->tag() == longTag) {
1844     base_op = new_register(T_INT);
1845     __ convert(Bytecodes::_l2i, base.result(), base_op);
1846   } else {
1847     assert(x->base()->type()->tag() == intTag, "must be");
1848   }
1849 #endif
1850 
1851   BasicType dst_type = x->basic_type();
1852   LIR_Opr index_op = idx.result();
1853 
1854   LIR_Address* addr;
1855   if (index_op->is_constant()) {
1856     assert(log2_scale == 0, "must not have a scale");
1857     addr = new LIR_Address(base_op, index_op->as_jint(), dst_type);
1858   } else {
1859 #ifdef X86
1860 #ifdef _LP64
1861     if (!index_op->is_illegal() && index_op->type() == T_INT) {
1862       LIR_Opr tmp = new_pointer_register();
1863       __ convert(Bytecodes::_i2l, index_op, tmp);
1864       index_op = tmp;
1865     }
1866 #endif
1867     addr = new LIR_Address(base_op, index_op, LIR_Address::Scale(log2_scale), 0, dst_type);
1868 #elif defined(ARM)
1869     addr = generate_address(base_op, index_op, log2_scale, 0, dst_type);
1870 #else
1871     if (index_op->is_illegal() || log2_scale == 0) {
1872 #ifdef _LP64
1873       if (!index_op->is_illegal() && index_op->type() == T_INT) {
1874         LIR_Opr tmp = new_pointer_register();
1875         __ convert(Bytecodes::_i2l, index_op, tmp);
1876         index_op = tmp;
1877       }
1878 #endif
1879       addr = new LIR_Address(base_op, index_op, dst_type);
1880     } else {
1881       LIR_Opr tmp = new_pointer_register();
1882       __ shift_left(index_op, log2_scale, tmp);
1883       addr = new LIR_Address(base_op, tmp, dst_type);
1884     }
1885 #endif
1886   }
1887 
1888   if (x->may_be_unaligned() && (dst_type == T_LONG || dst_type == T_DOUBLE)) {
1889     __ unaligned_move(addr, reg);
1890   } else {
1891     __ move(addr, reg);
1892   }
1893 }
1894 
1895 
1896 void LIRGenerator::do_UnsafePutRaw(UnsafePutRaw* x) {
1897   int  log2_scale = 0;
1898   BasicType type = x->basic_type();
1899 
1900   if (x->has_index()) {
1901     assert(x->index()->type()->tag() == intTag, "should not find non-int index");
1902     log2_scale = x->log2_scale();
1903   }
1904 
1905   LIRItem base(x->base(), this);
1906   LIRItem value(x->value(), this);
1907   LIRItem idx(this);
1908 
1909   base.load_item();
1910   if (x->has_index()) {
1911     idx.set_instruction(x->index());
1912     idx.load_item();
1913   }
1914 
1915   if (type == T_BYTE || type == T_BOOLEAN) {
1916     value.load_byte_item();
1917   } else {
1918     value.load_item();
1919   }
1920 
1921   set_no_result(x);
1922 
1923   LIR_Opr base_op = base.result();
1924 #ifndef _LP64
1925   if (x->base()->type()->tag() == longTag) {
1926     base_op = new_register(T_INT);
1927     __ convert(Bytecodes::_l2i, base.result(), base_op);
1928   } else {
1929     assert(x->base()->type()->tag() == intTag, "must be");
1930   }
1931 #endif
1932 
1933   LIR_Opr index_op = idx.result();
1934   if (log2_scale != 0) {
1935     // temporary fix (platform dependent code without shift on Intel would be better)
1936     index_op = new_pointer_register();
1937 #ifdef _LP64
1938     if(idx.result()->type() == T_INT) {
1939       __ convert(Bytecodes::_i2l, idx.result(), index_op);
1940     } else {
1941 #endif
1942       // TODO: ARM also allows embedded shift in the address
1943       __ move(idx.result(), index_op);
1944 #ifdef _LP64
1945     }
1946 #endif
1947     __ shift_left(index_op, log2_scale, index_op);
1948   }
1949 #ifdef _LP64
1950   else if(!index_op->is_illegal() && index_op->type() == T_INT) {
1951     LIR_Opr tmp = new_pointer_register();
1952     __ convert(Bytecodes::_i2l, index_op, tmp);
1953     index_op = tmp;
1954   }
1955 #endif
1956 
1957   LIR_Address* addr = new LIR_Address(base_op, index_op, x->basic_type());
1958   __ move(value.result(), addr);
1959 }
1960 
1961 
1962 void LIRGenerator::do_UnsafeGetObject(UnsafeGetObject* x) {
1963   BasicType type = x->basic_type();
1964   LIRItem src(x->object(), this);
1965   LIRItem off(x->offset(), this);
1966 
1967   off.load_item();
1968   src.load_item();
1969 
1970   LIR_Opr reg = reg = rlock_result(x, x->basic_type());
1971 
1972   if (x->is_volatile() && os::is_MP()) __ membar_acquire();
1973   get_Object_unsafe(reg, src.result(), off.result(), type, x->is_volatile());
1974   if (x->is_volatile() && os::is_MP()) __ membar();
1975 }
1976 
1977 
1978 void LIRGenerator::do_UnsafePutObject(UnsafePutObject* x) {
1979   BasicType type = x->basic_type();
1980   LIRItem src(x->object(), this);
1981   LIRItem off(x->offset(), this);
1982   LIRItem data(x->value(), this);
1983 
1984   src.load_item();
1985   if (type == T_BOOLEAN || type == T_BYTE) {
1986     data.load_byte_item();
1987   } else {
1988     data.load_item();
1989   }
1990   off.load_item();
1991 
1992   set_no_result(x);
1993 
1994   if (x->is_volatile() && os::is_MP()) __ membar_release();
1995   put_Object_unsafe(src.result(), off.result(), data.result(), type, x->is_volatile());
1996 }
1997 
1998 
1999 void LIRGenerator::do_UnsafePrefetch(UnsafePrefetch* x, bool is_store) {
2000   LIRItem src(x->object(), this);
2001   LIRItem off(x->offset(), this);
2002 
2003   src.load_item();
2004   if (off.is_constant() && can_inline_as_constant(x->offset())) {
2005     // let it be a constant
2006     off.dont_load_item();
2007   } else {
2008     off.load_item();
2009   }
2010 
2011   set_no_result(x);
2012 
2013   LIR_Address* addr = generate_address(src.result(), off.result(), 0, 0, T_BYTE);
2014   __ prefetch(addr, is_store);
2015 }
2016 
2017 
2018 void LIRGenerator::do_UnsafePrefetchRead(UnsafePrefetchRead* x) {
2019   do_UnsafePrefetch(x, false);
2020 }
2021 
2022 
2023 void LIRGenerator::do_UnsafePrefetchWrite(UnsafePrefetchWrite* x) {
2024   do_UnsafePrefetch(x, true);
2025 }
2026 
2027 
2028 void LIRGenerator::do_SwitchRanges(SwitchRangeArray* x, LIR_Opr value, BlockBegin* default_sux) {
2029   int lng = x->length();
2030 
2031   for (int i = 0; i < lng; i++) {
2032     SwitchRange* one_range = x->at(i);
2033     int low_key = one_range->low_key();
2034     int high_key = one_range->high_key();
2035     BlockBegin* dest = one_range->sux();
2036     if (low_key == high_key) {
2037       __ cmp(lir_cond_equal, value, low_key);
2038       __ branch(lir_cond_equal, T_INT, dest);
2039     } else if (high_key - low_key == 1) {
2040       __ cmp(lir_cond_equal, value, low_key);
2041       __ branch(lir_cond_equal, T_INT, dest);
2042       __ cmp(lir_cond_equal, value, high_key);
2043       __ branch(lir_cond_equal, T_INT, dest);
2044     } else {
2045       LabelObj* L = new LabelObj();
2046       __ cmp(lir_cond_less, value, low_key);
2047       __ branch(lir_cond_less, L->label());
2048       __ cmp(lir_cond_lessEqual, value, high_key);
2049       __ branch(lir_cond_lessEqual, T_INT, dest);
2050       __ branch_destination(L->label());
2051     }
2052   }
2053   __ jump(default_sux);
2054 }
2055 
2056 
2057 SwitchRangeArray* LIRGenerator::create_lookup_ranges(TableSwitch* x) {
2058   SwitchRangeList* res = new SwitchRangeList();
2059   int len = x->length();
2060   if (len > 0) {
2061     BlockBegin* sux = x->sux_at(0);
2062     int key = x->lo_key();
2063     BlockBegin* default_sux = x->default_sux();
2064     SwitchRange* range = new SwitchRange(key, sux);
2065     for (int i = 0; i < len; i++, key++) {
2066       BlockBegin* new_sux = x->sux_at(i);
2067       if (sux == new_sux) {
2068         // still in same range
2069         range->set_high_key(key);
2070       } else {
2071         // skip tests which explicitly dispatch to the default
2072         if (sux != default_sux) {
2073           res->append(range);
2074         }
2075         range = new SwitchRange(key, new_sux);
2076       }
2077       sux = new_sux;
2078     }
2079     if (res->length() == 0 || res->last() != range)  res->append(range);
2080   }
2081   return res;
2082 }
2083 
2084 
2085 // we expect the keys to be sorted by increasing value
2086 SwitchRangeArray* LIRGenerator::create_lookup_ranges(LookupSwitch* x) {
2087   SwitchRangeList* res = new SwitchRangeList();
2088   int len = x->length();
2089   if (len > 0) {
2090     BlockBegin* default_sux = x->default_sux();
2091     int key = x->key_at(0);
2092     BlockBegin* sux = x->sux_at(0);
2093     SwitchRange* range = new SwitchRange(key, sux);
2094     for (int i = 1; i < len; i++) {
2095       int new_key = x->key_at(i);
2096       BlockBegin* new_sux = x->sux_at(i);
2097       if (key+1 == new_key && sux == new_sux) {
2098         // still in same range
2099         range->set_high_key(new_key);
2100       } else {
2101         // skip tests which explicitly dispatch to the default
2102         if (range->sux() != default_sux) {
2103           res->append(range);
2104         }
2105         range = new SwitchRange(new_key, new_sux);
2106       }
2107       key = new_key;
2108       sux = new_sux;
2109     }
2110     if (res->length() == 0 || res->last() != range)  res->append(range);
2111   }
2112   return res;
2113 }
2114 
2115 
2116 void LIRGenerator::do_TableSwitch(TableSwitch* x) {
2117   LIRItem tag(x->tag(), this);
2118   tag.load_item();
2119   set_no_result(x);
2120 
2121   if (x->is_safepoint()) {
2122     __ safepoint(safepoint_poll_register(), state_for(x, x->state_before()));
2123   }
2124 
2125   // move values into phi locations
2126   move_to_phi(x->state());
2127 
2128   int lo_key = x->lo_key();
2129   int hi_key = x->hi_key();
2130   int len = x->length();
2131   CodeEmitInfo* info = state_for(x, x->state());
2132   LIR_Opr value = tag.result();
2133   if (UseTableRanges) {
2134     do_SwitchRanges(create_lookup_ranges(x), value, x->default_sux());
2135   } else {
2136     for (int i = 0; i < len; i++) {
2137       __ cmp(lir_cond_equal, value, i + lo_key);
2138       __ branch(lir_cond_equal, T_INT, x->sux_at(i));
2139     }
2140     __ jump(x->default_sux());
2141   }
2142 }
2143 
2144 
2145 void LIRGenerator::do_LookupSwitch(LookupSwitch* x) {
2146   LIRItem tag(x->tag(), this);
2147   tag.load_item();
2148   set_no_result(x);
2149 
2150   if (x->is_safepoint()) {
2151     __ safepoint(safepoint_poll_register(), state_for(x, x->state_before()));
2152   }
2153 
2154   // move values into phi locations
2155   move_to_phi(x->state());
2156 
2157   LIR_Opr value = tag.result();
2158   if (UseTableRanges) {
2159     do_SwitchRanges(create_lookup_ranges(x), value, x->default_sux());
2160   } else {
2161     int len = x->length();
2162     for (int i = 0; i < len; i++) {
2163       __ cmp(lir_cond_equal, value, x->key_at(i));
2164       __ branch(lir_cond_equal, T_INT, x->sux_at(i));
2165     }
2166     __ jump(x->default_sux());
2167   }
2168 }
2169 
2170 
2171 void LIRGenerator::do_Goto(Goto* x) {
2172   set_no_result(x);
2173 
2174   if (block()->next()->as_OsrEntry()) {
2175     // need to free up storage used for OSR entry point
2176     LIR_Opr osrBuffer = block()->next()->operand();
2177     BasicTypeList signature;
2178     signature.append(T_INT);
2179     CallingConvention* cc = frame_map()->c_calling_convention(&signature);
2180     __ move(osrBuffer, cc->args()->at(0));
2181     __ call_runtime_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::OSR_migration_end),
2182                          getThreadTemp(), LIR_OprFact::illegalOpr, cc->args());
2183   }
2184 
2185   if (x->is_safepoint()) {
2186     ValueStack* state = x->state_before() ? x->state_before() : x->state();
2187 
2188     // increment backedge counter if needed
2189     CodeEmitInfo* info = state_for(x, state);
2190     increment_backedge_counter(info, info->bci());
2191     CodeEmitInfo* safepoint_info = state_for(x, state);
2192     __ safepoint(safepoint_poll_register(), safepoint_info);
2193   }
2194 
2195   // Gotos can be folded Ifs, handle this case.
2196   if (x->should_profile()) {
2197     ciMethod* method = x->profiled_method();
2198     assert(method != NULL, "method should be set if branch is profiled");
2199     ciMethodData* md = method->method_data();
2200     if (md == NULL) {
2201       bailout("out of memory building methodDataOop");
2202       return;
2203     }
2204     ciProfileData* data = md->bci_to_data(x->profiled_bci());
2205     assert(data != NULL, "must have profiling data");
2206     int offset;
2207     if (x->direction() == Goto::taken) {
2208       assert(data->is_BranchData(), "need BranchData for two-way branches");
2209       offset = md->byte_offset_of_slot(data, BranchData::taken_offset());
2210     } else if (x->direction() == Goto::not_taken) {
2211       assert(data->is_BranchData(), "need BranchData for two-way branches");
2212       offset = md->byte_offset_of_slot(data, BranchData::not_taken_offset());
2213     } else {
2214       assert(data->is_JumpData(), "need JumpData for branches");
2215       offset = md->byte_offset_of_slot(data, JumpData::taken_offset());
2216     }
2217     LIR_Opr md_reg = new_register(T_OBJECT);
2218     __ oop2reg(md->constant_encoding(), md_reg);
2219 
2220     increment_counter(new LIR_Address(md_reg, offset,
2221                                       NOT_LP64(T_INT) LP64_ONLY(T_LONG)), DataLayout::counter_increment);
2222   }
2223 
2224   // emit phi-instruction move after safepoint since this simplifies
2225   // describing the state as the safepoint.
2226   move_to_phi(x->state());
2227 
2228   __ jump(x->default_sux());
2229 }
2230 
2231 
2232 void LIRGenerator::do_Base(Base* x) {
2233   __ std_entry(LIR_OprFact::illegalOpr);
2234   // Emit moves from physical registers / stack slots to virtual registers
2235   CallingConvention* args = compilation()->frame_map()->incoming_arguments();
2236   IRScope* irScope = compilation()->hir()->top_scope();
2237   int java_index = 0;
2238   for (int i = 0; i < args->length(); i++) {
2239     LIR_Opr src = args->at(i);
2240     assert(!src->is_illegal(), "check");
2241     BasicType t = src->type();
2242 
2243     // Types which are smaller than int are passed as int, so
2244     // correct the type which passed.
2245     switch (t) {
2246     case T_BYTE:
2247     case T_BOOLEAN:
2248     case T_SHORT:
2249     case T_CHAR:
2250       t = T_INT;
2251       break;
2252     }
2253 
2254     LIR_Opr dest = new_register(t);
2255     __ move(src, dest);
2256 
2257     // Assign new location to Local instruction for this local
2258     Local* local = x->state()->local_at(java_index)->as_Local();
2259     assert(local != NULL, "Locals for incoming arguments must have been created");
2260 #ifndef __SOFTFP__
2261     // The java calling convention passes double as long and float as int.
2262     assert(as_ValueType(t)->tag() == local->type()->tag(), "check");
2263 #endif // __SOFTFP__
2264     local->set_operand(dest);
2265     _instruction_for_operand.at_put_grow(dest->vreg_number(), local, NULL);
2266     java_index += type2size[t];
2267   }
2268 
2269   if (compilation()->env()->dtrace_method_probes()) {
2270     BasicTypeList signature;
2271     signature.append(T_INT);    // thread
2272     signature.append(T_OBJECT); // methodOop
2273     LIR_OprList* args = new LIR_OprList();
2274     args->append(getThreadPointer());
2275     LIR_Opr meth = new_register(T_OBJECT);
2276     __ oop2reg(method()->constant_encoding(), meth);
2277     args->append(meth);
2278     call_runtime(&signature, args, CAST_FROM_FN_PTR(address, SharedRuntime::dtrace_method_entry), voidType, NULL);
2279   }
2280 
2281   if (method()->is_synchronized()) {
2282     LIR_Opr obj;
2283     if (method()->is_static()) {
2284       obj = new_register(T_OBJECT);
2285       __ oop2reg(method()->holder()->java_mirror()->constant_encoding(), obj);
2286     } else {
2287       Local* receiver = x->state()->local_at(0)->as_Local();
2288       assert(receiver != NULL, "must already exist");
2289       obj = receiver->operand();
2290     }
2291     assert(obj->is_valid(), "must be valid");
2292 
2293     if (method()->is_synchronized() && GenerateSynchronizationCode) {
2294       LIR_Opr lock = new_register(T_INT);
2295       __ load_stack_address_monitor(0, lock);
2296 
2297       CodeEmitInfo* info = new CodeEmitInfo(SynchronizationEntryBCI, scope()->start()->state(), NULL);
2298       CodeStub* slow_path = new MonitorEnterStub(obj, lock, info);
2299 
2300       // receiver is guaranteed non-NULL so don't need CodeEmitInfo
2301       __ lock_object(syncTempOpr(), obj, lock, new_register(T_OBJECT), slow_path, NULL);
2302     }
2303   }
2304 
2305   // increment invocation counters if needed
2306   if (!method()->is_accessor()) { // Accessors do not have MDOs, so no counting.
2307     CodeEmitInfo* info = new CodeEmitInfo(InvocationEntryBci, scope()->start()->state(), NULL);
2308     increment_invocation_counter(info);
2309   }
2310 
2311   // all blocks with a successor must end with an unconditional jump
2312   // to the successor even if they are consecutive
2313   __ jump(x->default_sux());
2314 }
2315 
2316 
2317 void LIRGenerator::do_OsrEntry(OsrEntry* x) {
2318   // construct our frame and model the production of incoming pointer
2319   // to the OSR buffer.
2320   __ osr_entry(LIR_Assembler::osrBufferPointer());
2321   LIR_Opr result = rlock_result(x);
2322   __ move(LIR_Assembler::osrBufferPointer(), result);
2323 }
2324 
2325 
2326 void LIRGenerator::invoke_load_arguments(Invoke* x, LIRItemList* args, const LIR_OprList* arg_list) {
2327   int i = (x->has_receiver() || x->is_invokedynamic()) ? 1 : 0;
2328   for (; i < args->length(); i++) {
2329     LIRItem* param = args->at(i);
2330     LIR_Opr loc = arg_list->at(i);
2331     if (loc->is_register()) {
2332       param->load_item_force(loc);
2333     } else {
2334       LIR_Address* addr = loc->as_address_ptr();
2335       param->load_for_store(addr->type());
2336       if (addr->type() == T_LONG || addr->type() == T_DOUBLE) {
2337         __ unaligned_move(param->result(), addr);
2338       } else {
2339         __ move(param->result(), addr);
2340       }
2341     }
2342   }
2343 
2344   if (x->has_receiver()) {
2345     LIRItem* receiver = args->at(0);
2346     LIR_Opr loc = arg_list->at(0);
2347     if (loc->is_register()) {
2348       receiver->load_item_force(loc);
2349     } else {
2350       assert(loc->is_address(), "just checking");
2351       receiver->load_for_store(T_OBJECT);
2352       __ move(receiver->result(), loc);
2353     }
2354   }
2355 }
2356 
2357 
2358 // Visits all arguments, returns appropriate items without loading them
2359 LIRItemList* LIRGenerator::invoke_visit_arguments(Invoke* x) {
2360   LIRItemList* argument_items = new LIRItemList();
2361   if (x->has_receiver()) {
2362     LIRItem* receiver = new LIRItem(x->receiver(), this);
2363     argument_items->append(receiver);
2364   }
2365   if (x->is_invokedynamic()) {
2366     // Insert a dummy for the synthetic MethodHandle argument.
2367     argument_items->append(NULL);
2368   }
2369   int idx = x->has_receiver() ? 1 : 0;
2370   for (int i = 0; i < x->number_of_arguments(); i++) {
2371     LIRItem* param = new LIRItem(x->argument_at(i), this);
2372     argument_items->append(param);
2373     idx += (param->type()->is_double_word() ? 2 : 1);
2374   }
2375   return argument_items;
2376 }
2377 
2378 
2379 // The invoke with receiver has following phases:
2380 //   a) traverse and load/lock receiver;
2381 //   b) traverse all arguments -> item-array (invoke_visit_argument)
2382 //   c) push receiver on stack
2383 //   d) load each of the items and push on stack
2384 //   e) unlock receiver
2385 //   f) move receiver into receiver-register %o0
2386 //   g) lock result registers and emit call operation
2387 //
2388 // Before issuing a call, we must spill-save all values on stack
2389 // that are in caller-save register. "spill-save" moves thos registers
2390 // either in a free callee-save register or spills them if no free
2391 // callee save register is available.
2392 //
2393 // The problem is where to invoke spill-save.
2394 // - if invoked between e) and f), we may lock callee save
2395 //   register in "spill-save" that destroys the receiver register
2396 //   before f) is executed
2397 // - if we rearange the f) to be earlier, by loading %o0, it
2398 //   may destroy a value on the stack that is currently in %o0
2399 //   and is waiting to be spilled
2400 // - if we keep the receiver locked while doing spill-save,
2401 //   we cannot spill it as it is spill-locked
2402 //
2403 void LIRGenerator::do_Invoke(Invoke* x) {
2404   CallingConvention* cc = frame_map()->java_calling_convention(x->signature(), true);
2405 
2406   LIR_OprList* arg_list = cc->args();
2407   LIRItemList* args = invoke_visit_arguments(x);
2408   LIR_Opr receiver = LIR_OprFact::illegalOpr;
2409 
2410   // setup result register
2411   LIR_Opr result_register = LIR_OprFact::illegalOpr;
2412   if (x->type() != voidType) {
2413     result_register = result_register_for(x->type());
2414   }
2415 
2416   CodeEmitInfo* info = state_for(x, x->state());
2417 
2418   // invokedynamics can deoptimize.
2419   CodeEmitInfo* deopt_info = x->is_invokedynamic() ? state_for(x, x->state_before()) : NULL;
2420 
2421   invoke_load_arguments(x, args, arg_list);
2422 
2423   if (x->has_receiver()) {
2424     args->at(0)->load_item_force(LIR_Assembler::receiverOpr());
2425     receiver = args->at(0)->result();
2426   }
2427 
2428   // emit invoke code
2429   bool optimized = x->target_is_loaded() && x->target_is_final();
2430   assert(receiver->is_illegal() || receiver->is_equal(LIR_Assembler::receiverOpr()), "must match");
2431 
2432   // JSR 292
2433   // Preserve the SP over MethodHandle call sites.
2434   ciMethod* target = x->target();
2435   if (target->is_method_handle_invoke()) {
2436     info->set_is_method_handle_invoke(true);
2437     __ move(FrameMap::stack_pointer(), FrameMap::method_handle_invoke_SP_save_opr());
2438   }
2439 
2440   switch (x->code()) {
2441     case Bytecodes::_invokestatic:
2442       __ call_static(target, result_register,
2443                      SharedRuntime::get_resolve_static_call_stub(),
2444                      arg_list, info);
2445       break;
2446     case Bytecodes::_invokespecial:
2447     case Bytecodes::_invokevirtual:
2448     case Bytecodes::_invokeinterface:
2449       // for final target we still produce an inline cache, in order
2450       // to be able to call mixed mode
2451       if (x->code() == Bytecodes::_invokespecial || optimized) {
2452         __ call_opt_virtual(target, receiver, result_register,
2453                             SharedRuntime::get_resolve_opt_virtual_call_stub(),
2454                             arg_list, info);
2455       } else if (x->vtable_index() < 0) {
2456         __ call_icvirtual(target, receiver, result_register,
2457                           SharedRuntime::get_resolve_virtual_call_stub(),
2458                           arg_list, info);
2459       } else {
2460         int entry_offset = instanceKlass::vtable_start_offset() + x->vtable_index() * vtableEntry::size();
2461         int vtable_offset = entry_offset * wordSize + vtableEntry::method_offset_in_bytes();
2462         __ call_virtual(target, receiver, result_register, vtable_offset, arg_list, info);
2463       }
2464       break;
2465     case Bytecodes::_invokedynamic: {
2466       ciBytecodeStream bcs(x->scope()->method());
2467       bcs.force_bci(x->bci());
2468       assert(bcs.cur_bc() == Bytecodes::_invokedynamic, "wrong stream");
2469       ciCPCache* cpcache = bcs.get_cpcache();
2470 
2471       // Get CallSite offset from constant pool cache pointer.
2472       int index = bcs.get_method_index();
2473       size_t call_site_offset = cpcache->get_f1_offset(index);
2474 
2475       // If this invokedynamic call site hasn't been executed yet in
2476       // the interpreter, the CallSite object in the constant pool
2477       // cache is still null and we need to deoptimize.
2478       if (cpcache->is_f1_null_at(index)) {
2479         // Cannot re-use same xhandlers for multiple CodeEmitInfos, so
2480         // clone all handlers.  This is handled transparently in other
2481         // places by the CodeEmitInfo cloning logic but is handled
2482         // specially here because a stub isn't being used.
2483         x->set_exception_handlers(new XHandlers(x->exception_handlers()));
2484 
2485         DeoptimizeStub* deopt_stub = new DeoptimizeStub(deopt_info);
2486         __ jump(deopt_stub);
2487       }
2488 
2489       // Use the receiver register for the synthetic MethodHandle
2490       // argument.
2491       receiver = LIR_Assembler::receiverOpr();
2492       LIR_Opr tmp = new_register(objectType);
2493 
2494       // Load CallSite object from constant pool cache.
2495       __ oop2reg(cpcache->constant_encoding(), tmp);
2496       __ load(new LIR_Address(tmp, call_site_offset, T_OBJECT), tmp);
2497 
2498       // Load target MethodHandle from CallSite object.
2499       __ load(new LIR_Address(tmp, java_dyn_CallSite::target_offset_in_bytes(), T_OBJECT), receiver);
2500 
2501       __ call_dynamic(target, receiver, result_register,
2502                       SharedRuntime::get_resolve_opt_virtual_call_stub(),
2503                       arg_list, info);
2504       break;
2505     }
2506     default:
2507       ShouldNotReachHere();
2508       break;
2509   }
2510 
2511   // JSR 292
2512   // Restore the SP after MethodHandle call sites.
2513   if (target->is_method_handle_invoke()) {
2514     __ move(FrameMap::method_handle_invoke_SP_save_opr(), FrameMap::stack_pointer());
2515   }
2516 
2517   if (x->type()->is_float() || x->type()->is_double()) {
2518     // Force rounding of results from non-strictfp when in strictfp
2519     // scope (or when we don't know the strictness of the callee, to
2520     // be safe.)
2521     if (method()->is_strict()) {
2522       if (!x->target_is_loaded() || !x->target_is_strictfp()) {
2523         result_register = round_item(result_register);
2524       }
2525     }
2526   }
2527 
2528   if (result_register->is_valid()) {
2529     LIR_Opr result = rlock_result(x);
2530     __ move(result_register, result);
2531   }
2532 }
2533 
2534 
2535 void LIRGenerator::do_FPIntrinsics(Intrinsic* x) {
2536   assert(x->number_of_arguments() == 1, "wrong type");
2537   LIRItem value       (x->argument_at(0), this);
2538   LIR_Opr reg = rlock_result(x);
2539   value.load_item();
2540   LIR_Opr tmp = force_to_spill(value.result(), as_BasicType(x->type()));
2541   __ move(tmp, reg);
2542 }
2543 
2544 
2545 
2546 // Code for  :  x->x() {x->cond()} x->y() ? x->tval() : x->fval()
2547 void LIRGenerator::do_IfOp(IfOp* x) {
2548 #ifdef ASSERT
2549   {
2550     ValueTag xtag = x->x()->type()->tag();
2551     ValueTag ttag = x->tval()->type()->tag();
2552     assert(xtag == intTag || xtag == objectTag, "cannot handle others");
2553     assert(ttag == addressTag || ttag == intTag || ttag == objectTag || ttag == longTag, "cannot handle others");
2554     assert(ttag == x->fval()->type()->tag(), "cannot handle others");
2555   }
2556 #endif
2557 
2558   LIRItem left(x->x(), this);
2559   LIRItem right(x->y(), this);
2560   left.load_item();
2561   if (can_inline_as_constant(right.value())) {
2562     right.dont_load_item();
2563   } else {
2564     right.load_item();
2565   }
2566 
2567   LIRItem t_val(x->tval(), this);
2568   LIRItem f_val(x->fval(), this);
2569   t_val.dont_load_item();
2570   f_val.dont_load_item();
2571   LIR_Opr reg = rlock_result(x);
2572 
2573   __ cmp(lir_cond(x->cond()), left.result(), right.result());
2574   __ cmove(lir_cond(x->cond()), t_val.result(), f_val.result(), reg);
2575 }
2576 
2577 
2578 void LIRGenerator::do_Intrinsic(Intrinsic* x) {
2579   switch (x->id()) {
2580   case vmIntrinsics::_intBitsToFloat      :
2581   case vmIntrinsics::_doubleToRawLongBits :
2582   case vmIntrinsics::_longBitsToDouble    :
2583   case vmIntrinsics::_floatToRawIntBits   : {
2584     do_FPIntrinsics(x);
2585     break;
2586   }
2587 
2588   case vmIntrinsics::_currentTimeMillis: {
2589     assert(x->number_of_arguments() == 0, "wrong type");
2590     LIR_Opr reg = result_register_for(x->type());
2591     __ call_runtime_leaf(CAST_FROM_FN_PTR(address, os::javaTimeMillis), getThreadTemp(),
2592                          reg, new LIR_OprList());
2593     LIR_Opr result = rlock_result(x);
2594     __ move(reg, result);
2595     break;
2596   }
2597 
2598   case vmIntrinsics::_nanoTime: {
2599     assert(x->number_of_arguments() == 0, "wrong type");
2600     LIR_Opr reg = result_register_for(x->type());
2601     __ call_runtime_leaf(CAST_FROM_FN_PTR(address, os::javaTimeNanos), getThreadTemp(),
2602                          reg, new LIR_OprList());
2603     LIR_Opr result = rlock_result(x);
2604     __ move(reg, result);
2605     break;
2606   }
2607 
2608   case vmIntrinsics::_Object_init:    do_RegisterFinalizer(x); break;
2609   case vmIntrinsics::_getClass:       do_getClass(x);      break;
2610   case vmIntrinsics::_currentThread:  do_currentThread(x); break;
2611 
2612   case vmIntrinsics::_dlog:           // fall through
2613   case vmIntrinsics::_dlog10:         // fall through
2614   case vmIntrinsics::_dabs:           // fall through
2615   case vmIntrinsics::_dsqrt:          // fall through
2616   case vmIntrinsics::_dtan:           // fall through
2617   case vmIntrinsics::_dsin :          // fall through
2618   case vmIntrinsics::_dcos :          do_MathIntrinsic(x); break;
2619   case vmIntrinsics::_arraycopy:      do_ArrayCopy(x);     break;
2620 
2621   // java.nio.Buffer.checkIndex
2622   case vmIntrinsics::_checkIndex:     do_NIOCheckIndex(x); break;
2623 
2624   case vmIntrinsics::_compareAndSwapObject:
2625     do_CompareAndSwap(x, objectType);
2626     break;
2627   case vmIntrinsics::_compareAndSwapInt:
2628     do_CompareAndSwap(x, intType);
2629     break;
2630   case vmIntrinsics::_compareAndSwapLong:
2631     do_CompareAndSwap(x, longType);
2632     break;
2633 
2634     // sun.misc.AtomicLongCSImpl.attemptUpdate
2635   case vmIntrinsics::_attemptUpdate:
2636     do_AttemptUpdate(x);
2637     break;
2638 
2639   default: ShouldNotReachHere(); break;
2640   }
2641 }
2642 
2643 void LIRGenerator::do_ProfileCall(ProfileCall* x) {
2644   // Need recv in a temporary register so it interferes with the other temporaries
2645   LIR_Opr recv = LIR_OprFact::illegalOpr;
2646   LIR_Opr mdo = new_register(T_OBJECT);
2647   // tmp is used to hold the counters on SPARC
2648   LIR_Opr tmp = new_pointer_register();
2649   if (x->recv() != NULL) {
2650     LIRItem value(x->recv(), this);
2651     value.load_item();
2652     recv = new_register(T_OBJECT);
2653     __ move(value.result(), recv);
2654   }
2655   __ profile_call(x->method(), x->bci_of_invoke(), mdo, recv, tmp, x->known_holder());
2656 }
2657 
2658 void LIRGenerator::do_ProfileInvoke(ProfileInvoke* x) {
2659   // We can safely ignore accessors here, since c2 will inline them anyway,
2660   // accessors are also always mature.
2661   if (!x->inlinee()->is_accessor()) {
2662     CodeEmitInfo* info = state_for(x, x->state(), true);
2663     // Increment invocation counter, don't notify the runtime, because we don't inline loops,
2664     increment_event_counter_impl(info, x->inlinee(), 0, InvocationEntryBci, false, false);
2665   }
2666 }
2667 
2668 void LIRGenerator::increment_event_counter(CodeEmitInfo* info, int bci, bool backedge) {
2669   int freq_log;
2670   int level = compilation()->env()->comp_level();
2671   if (level == CompLevel_limited_profile) {
2672     freq_log = (backedge ? Tier2BackedgeNotifyFreqLog : Tier2InvokeNotifyFreqLog);
2673   } else if (level == CompLevel_full_profile) {
2674     freq_log = (backedge ? Tier3BackedgeNotifyFreqLog : Tier3InvokeNotifyFreqLog);
2675   } else {
2676     ShouldNotReachHere();
2677   }
2678   // Increment the appropriate invocation/backedge counter and notify the runtime.
2679   increment_event_counter_impl(info, info->scope()->method(), (1 << freq_log) - 1, bci, backedge, true);
2680 }
2681 
2682 void LIRGenerator::increment_event_counter_impl(CodeEmitInfo* info,
2683                                                 ciMethod *method, int frequency,
2684                                                 int bci, bool backedge, bool notify) {
2685   assert(frequency == 0 || is_power_of_2(frequency + 1), "Frequency must be x^2 - 1 or 0");
2686   int level = _compilation->env()->comp_level();
2687   assert(level > CompLevel_simple, "Shouldn't be here");
2688 
2689   int offset = -1;
2690   LIR_Opr counter_holder = new_register(T_OBJECT);
2691   LIR_Opr meth;
2692   if (level == CompLevel_limited_profile) {
2693     offset = in_bytes(backedge ? methodOopDesc::backedge_counter_offset() :
2694                                  methodOopDesc::invocation_counter_offset());
2695     __ oop2reg(method->constant_encoding(), counter_holder);
2696     meth = counter_holder;
2697   } else if (level == CompLevel_full_profile) {
2698     offset = in_bytes(backedge ? methodDataOopDesc::backedge_counter_offset() :
2699                                  methodDataOopDesc::invocation_counter_offset());
2700     __ oop2reg(method->method_data()->constant_encoding(), counter_holder);
2701     meth = new_register(T_OBJECT);
2702     __ oop2reg(method->constant_encoding(), meth);
2703   } else {
2704     ShouldNotReachHere();
2705   }
2706   LIR_Address* counter = new LIR_Address(counter_holder, offset, T_INT);
2707   LIR_Opr result = new_register(T_INT);
2708   __ load(counter, result);
2709   __ add(result, LIR_OprFact::intConst(InvocationCounter::count_increment), result);
2710   __ store(result, counter);
2711   if (notify) {
2712     LIR_Opr mask = load_immediate(frequency << InvocationCounter::count_shift, T_INT);
2713     __ logical_and(result, mask, result);
2714     __ cmp(lir_cond_equal, result, LIR_OprFact::intConst(0));
2715     // The bci for info can point to cmp for if's we want the if bci
2716     CodeStub* overflow = new CounterOverflowStub(info, bci, meth);
2717     __ branch(lir_cond_equal, T_INT, overflow);
2718     __ branch_destination(overflow->continuation());
2719   }
2720 }
2721 
2722 LIR_Opr LIRGenerator::call_runtime(Value arg1, address entry, ValueType* result_type, CodeEmitInfo* info) {
2723   LIRItemList args(1);
2724   LIRItem value(arg1, this);
2725   args.append(&value);
2726   BasicTypeList signature;
2727   signature.append(as_BasicType(arg1->type()));
2728 
2729   return call_runtime(&signature, &args, entry, result_type, info);
2730 }
2731 
2732 
2733 LIR_Opr LIRGenerator::call_runtime(Value arg1, Value arg2, address entry, ValueType* result_type, CodeEmitInfo* info) {
2734   LIRItemList args(2);
2735   LIRItem value1(arg1, this);
2736   LIRItem value2(arg2, this);
2737   args.append(&value1);
2738   args.append(&value2);
2739   BasicTypeList signature;
2740   signature.append(as_BasicType(arg1->type()));
2741   signature.append(as_BasicType(arg2->type()));
2742 
2743   return call_runtime(&signature, &args, entry, result_type, info);
2744 }
2745 
2746 
2747 LIR_Opr LIRGenerator::call_runtime(BasicTypeArray* signature, LIR_OprList* args,
2748                                    address entry, ValueType* result_type, CodeEmitInfo* info) {
2749   // get a result register
2750   LIR_Opr phys_reg = LIR_OprFact::illegalOpr;
2751   LIR_Opr result = LIR_OprFact::illegalOpr;
2752   if (result_type->tag() != voidTag) {
2753     result = new_register(result_type);
2754     phys_reg = result_register_for(result_type);
2755   }
2756 
2757   // move the arguments into the correct location
2758   CallingConvention* cc = frame_map()->c_calling_convention(signature);
2759   assert(cc->length() == args->length(), "argument mismatch");
2760   for (int i = 0; i < args->length(); i++) {
2761     LIR_Opr arg = args->at(i);
2762     LIR_Opr loc = cc->at(i);
2763     if (loc->is_register()) {
2764       __ move(arg, loc);
2765     } else {
2766       LIR_Address* addr = loc->as_address_ptr();
2767 //           if (!can_store_as_constant(arg)) {
2768 //             LIR_Opr tmp = new_register(arg->type());
2769 //             __ move(arg, tmp);
2770 //             arg = tmp;
2771 //           }
2772       if (addr->type() == T_LONG || addr->type() == T_DOUBLE) {
2773         __ unaligned_move(arg, addr);
2774       } else {
2775         __ move(arg, addr);
2776       }
2777     }
2778   }
2779 
2780   if (info) {
2781     __ call_runtime(entry, getThreadTemp(), phys_reg, cc->args(), info);
2782   } else {
2783     __ call_runtime_leaf(entry, getThreadTemp(), phys_reg, cc->args());
2784   }
2785   if (result->is_valid()) {
2786     __ move(phys_reg, result);
2787   }
2788   return result;
2789 }
2790 
2791 
2792 LIR_Opr LIRGenerator::call_runtime(BasicTypeArray* signature, LIRItemList* args,
2793                                    address entry, ValueType* result_type, CodeEmitInfo* info) {
2794   // get a result register
2795   LIR_Opr phys_reg = LIR_OprFact::illegalOpr;
2796   LIR_Opr result = LIR_OprFact::illegalOpr;
2797   if (result_type->tag() != voidTag) {
2798     result = new_register(result_type);
2799     phys_reg = result_register_for(result_type);
2800   }
2801 
2802   // move the arguments into the correct location
2803   CallingConvention* cc = frame_map()->c_calling_convention(signature);
2804 
2805   assert(cc->length() == args->length(), "argument mismatch");
2806   for (int i = 0; i < args->length(); i++) {
2807     LIRItem* arg = args->at(i);
2808     LIR_Opr loc = cc->at(i);
2809     if (loc->is_register()) {
2810       arg->load_item_force(loc);
2811     } else {
2812       LIR_Address* addr = loc->as_address_ptr();
2813       arg->load_for_store(addr->type());
2814       if (addr->type() == T_LONG || addr->type() == T_DOUBLE) {
2815         __ unaligned_move(arg->result(), addr);
2816       } else {
2817         __ move(arg->result(), addr);
2818       }
2819     }
2820   }
2821 
2822   if (info) {
2823     __ call_runtime(entry, getThreadTemp(), phys_reg, cc->args(), info);
2824   } else {
2825     __ call_runtime_leaf(entry, getThreadTemp(), phys_reg, cc->args());
2826   }
2827   if (result->is_valid()) {
2828     __ move(phys_reg, result);
2829   }
2830   return result;
2831 }
2832