1 /* 2 * Copyright (c) 2001, 2023, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. 8 * 9 * This code is distributed in the hope that it will be useful, but WITHOUT 10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 12 * version 2 for more details (a copy is included in the LICENSE file that 13 * accompanied this code). 14 * 15 * You should have received a copy of the GNU General Public License version 16 * 2 along with this work; if not, write to the Free Software Foundation, 17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 18 * 19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 20 * or visit www.oracle.com if you need additional information or have any 21 * questions. 22 * 23 */ 24 25 #include "precompiled.hpp" 26 #include "ci/ciFlatArrayKlass.hpp" 27 #include "ci/ciInlineKlass.hpp" 28 #include "ci/ciUtilities.hpp" 29 #include "classfile/javaClasses.hpp" 30 #include "ci/ciObjArray.hpp" 31 #include "asm/register.hpp" 32 #include "compiler/compileLog.hpp" 33 #include "gc/shared/barrierSet.hpp" 34 #include "gc/shared/c2/barrierSetC2.hpp" 35 #include "interpreter/interpreter.hpp" 36 #include "memory/resourceArea.hpp" 37 #include "opto/addnode.hpp" 38 #include "opto/castnode.hpp" 39 #include "opto/convertnode.hpp" 40 #include "opto/graphKit.hpp" 41 #include "opto/idealKit.hpp" 42 #include "opto/inlinetypenode.hpp" 43 #include "opto/intrinsicnode.hpp" 44 #include "opto/locknode.hpp" 45 #include "opto/machnode.hpp" 46 #include "opto/narrowptrnode.hpp" 47 #include "opto/opaquenode.hpp" 48 #include "opto/parse.hpp" 49 #include "opto/rootnode.hpp" 50 #include "opto/runtime.hpp" 51 #include "opto/subtypenode.hpp" 52 #include "runtime/deoptimization.hpp" 53 #include "runtime/sharedRuntime.hpp" 54 #include "utilities/bitMap.inline.hpp" 55 #include "utilities/powerOfTwo.hpp" 56 #include "utilities/growableArray.hpp" 57 58 //----------------------------GraphKit----------------------------------------- 59 // Main utility constructor. 60 GraphKit::GraphKit(JVMState* jvms, PhaseGVN* gvn) 61 : Phase(Phase::Parser), 62 _env(C->env()), 63 _gvn((gvn != nullptr) ? *gvn : *C->initial_gvn()), 64 _barrier_set(BarrierSet::barrier_set()->barrier_set_c2()) 65 { 66 assert(gvn == nullptr || !gvn->is_IterGVN() || gvn->is_IterGVN()->delay_transform(), "delay transform should be enabled"); 67 _exceptions = jvms->map()->next_exception(); 68 if (_exceptions != nullptr) jvms->map()->set_next_exception(nullptr); 69 set_jvms(jvms); 70 #ifdef ASSERT 71 if (_gvn.is_IterGVN() != nullptr) { 72 assert(_gvn.is_IterGVN()->delay_transform(), "Transformation must be delayed if IterGVN is used"); 73 // Save the initial size of _for_igvn worklist for verification (see ~GraphKit) 74 _worklist_size = _gvn.C->igvn_worklist()->size(); 75 } 76 #endif 77 } 78 79 // Private constructor for parser. 80 GraphKit::GraphKit() 81 : Phase(Phase::Parser), 82 _env(C->env()), 83 _gvn(*C->initial_gvn()), 84 _barrier_set(BarrierSet::barrier_set()->barrier_set_c2()) 85 { 86 _exceptions = nullptr; 87 set_map(nullptr); 88 debug_only(_sp = -99); 89 debug_only(set_bci(-99)); 90 } 91 92 93 94 //---------------------------clean_stack--------------------------------------- 95 // Clear away rubbish from the stack area of the JVM state. 96 // This destroys any arguments that may be waiting on the stack. 97 void GraphKit::clean_stack(int from_sp) { 98 SafePointNode* map = this->map(); 99 JVMState* jvms = this->jvms(); 100 int stk_size = jvms->stk_size(); 101 int stkoff = jvms->stkoff(); 102 Node* top = this->top(); 103 for (int i = from_sp; i < stk_size; i++) { 104 if (map->in(stkoff + i) != top) { 105 map->set_req(stkoff + i, top); 106 } 107 } 108 } 109 110 111 //--------------------------------sync_jvms----------------------------------- 112 // Make sure our current jvms agrees with our parse state. 113 JVMState* GraphKit::sync_jvms() const { 114 JVMState* jvms = this->jvms(); 115 jvms->set_bci(bci()); // Record the new bci in the JVMState 116 jvms->set_sp(sp()); // Record the new sp in the JVMState 117 assert(jvms_in_sync(), "jvms is now in sync"); 118 return jvms; 119 } 120 121 //--------------------------------sync_jvms_for_reexecute--------------------- 122 // Make sure our current jvms agrees with our parse state. This version 123 // uses the reexecute_sp for reexecuting bytecodes. 124 JVMState* GraphKit::sync_jvms_for_reexecute() { 125 JVMState* jvms = this->jvms(); 126 jvms->set_bci(bci()); // Record the new bci in the JVMState 127 jvms->set_sp(reexecute_sp()); // Record the new sp in the JVMState 128 return jvms; 129 } 130 131 #ifdef ASSERT 132 bool GraphKit::jvms_in_sync() const { 133 Parse* parse = is_Parse(); 134 if (parse == nullptr) { 135 if (bci() != jvms()->bci()) return false; 136 if (sp() != (int)jvms()->sp()) return false; 137 return true; 138 } 139 if (jvms()->method() != parse->method()) return false; 140 if (jvms()->bci() != parse->bci()) return false; 141 int jvms_sp = jvms()->sp(); 142 if (jvms_sp != parse->sp()) return false; 143 int jvms_depth = jvms()->depth(); 144 if (jvms_depth != parse->depth()) return false; 145 return true; 146 } 147 148 // Local helper checks for special internal merge points 149 // used to accumulate and merge exception states. 150 // They are marked by the region's in(0) edge being the map itself. 151 // Such merge points must never "escape" into the parser at large, 152 // until they have been handed to gvn.transform. 153 static bool is_hidden_merge(Node* reg) { 154 if (reg == nullptr) return false; 155 if (reg->is_Phi()) { 156 reg = reg->in(0); 157 if (reg == nullptr) return false; 158 } 159 return reg->is_Region() && reg->in(0) != nullptr && reg->in(0)->is_Root(); 160 } 161 162 void GraphKit::verify_map() const { 163 if (map() == nullptr) return; // null map is OK 164 assert(map()->req() <= jvms()->endoff(), "no extra garbage on map"); 165 assert(!map()->has_exceptions(), "call add_exception_states_from 1st"); 166 assert(!is_hidden_merge(control()), "call use_exception_state, not set_map"); 167 } 168 169 void GraphKit::verify_exception_state(SafePointNode* ex_map) { 170 assert(ex_map->next_exception() == nullptr, "not already part of a chain"); 171 assert(has_saved_ex_oop(ex_map), "every exception state has an ex_oop"); 172 } 173 #endif 174 175 //---------------------------stop_and_kill_map--------------------------------- 176 // Set _map to null, signalling a stop to further bytecode execution. 177 // First smash the current map's control to a constant, to mark it dead. 178 void GraphKit::stop_and_kill_map() { 179 SafePointNode* dead_map = stop(); 180 if (dead_map != nullptr) { 181 dead_map->disconnect_inputs(C); // Mark the map as killed. 182 assert(dead_map->is_killed(), "must be so marked"); 183 } 184 } 185 186 187 //--------------------------------stopped-------------------------------------- 188 // Tell if _map is null, or control is top. 189 bool GraphKit::stopped() { 190 if (map() == nullptr) return true; 191 else if (control() == top()) return true; 192 else return false; 193 } 194 195 196 //-----------------------------has_ex_handler---------------------------------- 197 // Tell if this method or any caller method has exception handlers. 198 bool GraphKit::has_ex_handler() { 199 for (JVMState* jvmsp = jvms(); jvmsp != nullptr; jvmsp = jvmsp->caller()) { 200 if (jvmsp->has_method() && jvmsp->method()->has_exception_handlers()) { 201 return true; 202 } 203 } 204 return false; 205 } 206 207 //------------------------------save_ex_oop------------------------------------ 208 // Save an exception without blowing stack contents or other JVM state. 209 void GraphKit::set_saved_ex_oop(SafePointNode* ex_map, Node* ex_oop) { 210 assert(!has_saved_ex_oop(ex_map), "clear ex-oop before setting again"); 211 ex_map->add_req(ex_oop); 212 debug_only(verify_exception_state(ex_map)); 213 } 214 215 inline static Node* common_saved_ex_oop(SafePointNode* ex_map, bool clear_it) { 216 assert(GraphKit::has_saved_ex_oop(ex_map), "ex_oop must be there"); 217 Node* ex_oop = ex_map->in(ex_map->req()-1); 218 if (clear_it) ex_map->del_req(ex_map->req()-1); 219 return ex_oop; 220 } 221 222 //-----------------------------saved_ex_oop------------------------------------ 223 // Recover a saved exception from its map. 224 Node* GraphKit::saved_ex_oop(SafePointNode* ex_map) { 225 return common_saved_ex_oop(ex_map, false); 226 } 227 228 //--------------------------clear_saved_ex_oop--------------------------------- 229 // Erase a previously saved exception from its map. 230 Node* GraphKit::clear_saved_ex_oop(SafePointNode* ex_map) { 231 return common_saved_ex_oop(ex_map, true); 232 } 233 234 #ifdef ASSERT 235 //---------------------------has_saved_ex_oop---------------------------------- 236 // Erase a previously saved exception from its map. 237 bool GraphKit::has_saved_ex_oop(SafePointNode* ex_map) { 238 return ex_map->req() == ex_map->jvms()->endoff()+1; 239 } 240 #endif 241 242 //-------------------------make_exception_state-------------------------------- 243 // Turn the current JVM state into an exception state, appending the ex_oop. 244 SafePointNode* GraphKit::make_exception_state(Node* ex_oop) { 245 sync_jvms(); 246 SafePointNode* ex_map = stop(); // do not manipulate this map any more 247 set_saved_ex_oop(ex_map, ex_oop); 248 return ex_map; 249 } 250 251 252 //--------------------------add_exception_state-------------------------------- 253 // Add an exception to my list of exceptions. 254 void GraphKit::add_exception_state(SafePointNode* ex_map) { 255 if (ex_map == nullptr || ex_map->control() == top()) { 256 return; 257 } 258 #ifdef ASSERT 259 verify_exception_state(ex_map); 260 if (has_exceptions()) { 261 assert(ex_map->jvms()->same_calls_as(_exceptions->jvms()), "all collected exceptions must come from the same place"); 262 } 263 #endif 264 265 // If there is already an exception of exactly this type, merge with it. 266 // In particular, null-checks and other low-level exceptions common up here. 267 Node* ex_oop = saved_ex_oop(ex_map); 268 const Type* ex_type = _gvn.type(ex_oop); 269 if (ex_oop == top()) { 270 // No action needed. 271 return; 272 } 273 assert(ex_type->isa_instptr(), "exception must be an instance"); 274 for (SafePointNode* e2 = _exceptions; e2 != nullptr; e2 = e2->next_exception()) { 275 const Type* ex_type2 = _gvn.type(saved_ex_oop(e2)); 276 // We check sp also because call bytecodes can generate exceptions 277 // both before and after arguments are popped! 278 if (ex_type2 == ex_type 279 && e2->_jvms->sp() == ex_map->_jvms->sp()) { 280 combine_exception_states(ex_map, e2); 281 return; 282 } 283 } 284 285 // No pre-existing exception of the same type. Chain it on the list. 286 push_exception_state(ex_map); 287 } 288 289 //-----------------------add_exception_states_from----------------------------- 290 void GraphKit::add_exception_states_from(JVMState* jvms) { 291 SafePointNode* ex_map = jvms->map()->next_exception(); 292 if (ex_map != nullptr) { 293 jvms->map()->set_next_exception(nullptr); 294 for (SafePointNode* next_map; ex_map != nullptr; ex_map = next_map) { 295 next_map = ex_map->next_exception(); 296 ex_map->set_next_exception(nullptr); 297 add_exception_state(ex_map); 298 } 299 } 300 } 301 302 //-----------------------transfer_exceptions_into_jvms------------------------- 303 JVMState* GraphKit::transfer_exceptions_into_jvms() { 304 if (map() == nullptr) { 305 // We need a JVMS to carry the exceptions, but the map has gone away. 306 // Create a scratch JVMS, cloned from any of the exception states... 307 if (has_exceptions()) { 308 _map = _exceptions; 309 _map = clone_map(); 310 _map->set_next_exception(nullptr); 311 clear_saved_ex_oop(_map); 312 debug_only(verify_map()); 313 } else { 314 // ...or created from scratch 315 JVMState* jvms = new (C) JVMState(_method, nullptr); 316 jvms->set_bci(_bci); 317 jvms->set_sp(_sp); 318 jvms->set_map(new SafePointNode(TypeFunc::Parms, jvms)); 319 set_jvms(jvms); 320 for (uint i = 0; i < map()->req(); i++) map()->init_req(i, top()); 321 set_all_memory(top()); 322 while (map()->req() < jvms->endoff()) map()->add_req(top()); 323 } 324 // (This is a kludge, in case you didn't notice.) 325 set_control(top()); 326 } 327 JVMState* jvms = sync_jvms(); 328 assert(!jvms->map()->has_exceptions(), "no exceptions on this map yet"); 329 jvms->map()->set_next_exception(_exceptions); 330 _exceptions = nullptr; // done with this set of exceptions 331 return jvms; 332 } 333 334 static inline void add_n_reqs(Node* dstphi, Node* srcphi) { 335 assert(is_hidden_merge(dstphi), "must be a special merge node"); 336 assert(is_hidden_merge(srcphi), "must be a special merge node"); 337 uint limit = srcphi->req(); 338 for (uint i = PhiNode::Input; i < limit; i++) { 339 dstphi->add_req(srcphi->in(i)); 340 } 341 } 342 static inline void add_one_req(Node* dstphi, Node* src) { 343 assert(is_hidden_merge(dstphi), "must be a special merge node"); 344 assert(!is_hidden_merge(src), "must not be a special merge node"); 345 dstphi->add_req(src); 346 } 347 348 //-----------------------combine_exception_states------------------------------ 349 // This helper function combines exception states by building phis on a 350 // specially marked state-merging region. These regions and phis are 351 // untransformed, and can build up gradually. The region is marked by 352 // having a control input of its exception map, rather than null. Such 353 // regions do not appear except in this function, and in use_exception_state. 354 void GraphKit::combine_exception_states(SafePointNode* ex_map, SafePointNode* phi_map) { 355 if (failing()) return; // dying anyway... 356 JVMState* ex_jvms = ex_map->_jvms; 357 assert(ex_jvms->same_calls_as(phi_map->_jvms), "consistent call chains"); 358 assert(ex_jvms->stkoff() == phi_map->_jvms->stkoff(), "matching locals"); 359 assert(ex_jvms->sp() == phi_map->_jvms->sp(), "matching stack sizes"); 360 assert(ex_jvms->monoff() == phi_map->_jvms->monoff(), "matching JVMS"); 361 assert(ex_jvms->scloff() == phi_map->_jvms->scloff(), "matching scalar replaced objects"); 362 assert(ex_map->req() == phi_map->req(), "matching maps"); 363 uint tos = ex_jvms->stkoff() + ex_jvms->sp(); 364 Node* hidden_merge_mark = root(); 365 Node* region = phi_map->control(); 366 MergeMemNode* phi_mem = phi_map->merged_memory(); 367 MergeMemNode* ex_mem = ex_map->merged_memory(); 368 if (region->in(0) != hidden_merge_mark) { 369 // The control input is not (yet) a specially-marked region in phi_map. 370 // Make it so, and build some phis. 371 region = new RegionNode(2); 372 _gvn.set_type(region, Type::CONTROL); 373 region->set_req(0, hidden_merge_mark); // marks an internal ex-state 374 region->init_req(1, phi_map->control()); 375 phi_map->set_control(region); 376 Node* io_phi = PhiNode::make(region, phi_map->i_o(), Type::ABIO); 377 record_for_igvn(io_phi); 378 _gvn.set_type(io_phi, Type::ABIO); 379 phi_map->set_i_o(io_phi); 380 for (MergeMemStream mms(phi_mem); mms.next_non_empty(); ) { 381 Node* m = mms.memory(); 382 Node* m_phi = PhiNode::make(region, m, Type::MEMORY, mms.adr_type(C)); 383 record_for_igvn(m_phi); 384 _gvn.set_type(m_phi, Type::MEMORY); 385 mms.set_memory(m_phi); 386 } 387 } 388 389 // Either or both of phi_map and ex_map might already be converted into phis. 390 Node* ex_control = ex_map->control(); 391 // if there is special marking on ex_map also, we add multiple edges from src 392 bool add_multiple = (ex_control->in(0) == hidden_merge_mark); 393 // how wide was the destination phi_map, originally? 394 uint orig_width = region->req(); 395 396 if (add_multiple) { 397 add_n_reqs(region, ex_control); 398 add_n_reqs(phi_map->i_o(), ex_map->i_o()); 399 } else { 400 // ex_map has no merges, so we just add single edges everywhere 401 add_one_req(region, ex_control); 402 add_one_req(phi_map->i_o(), ex_map->i_o()); 403 } 404 for (MergeMemStream mms(phi_mem, ex_mem); mms.next_non_empty2(); ) { 405 if (mms.is_empty()) { 406 // get a copy of the base memory, and patch some inputs into it 407 const TypePtr* adr_type = mms.adr_type(C); 408 Node* phi = mms.force_memory()->as_Phi()->slice_memory(adr_type); 409 assert(phi->as_Phi()->region() == mms.base_memory()->in(0), ""); 410 mms.set_memory(phi); 411 // Prepare to append interesting stuff onto the newly sliced phi: 412 while (phi->req() > orig_width) phi->del_req(phi->req()-1); 413 } 414 // Append stuff from ex_map: 415 if (add_multiple) { 416 add_n_reqs(mms.memory(), mms.memory2()); 417 } else { 418 add_one_req(mms.memory(), mms.memory2()); 419 } 420 } 421 uint limit = ex_map->req(); 422 for (uint i = TypeFunc::Parms; i < limit; i++) { 423 // Skip everything in the JVMS after tos. (The ex_oop follows.) 424 if (i == tos) i = ex_jvms->monoff(); 425 Node* src = ex_map->in(i); 426 Node* dst = phi_map->in(i); 427 if (src != dst) { 428 PhiNode* phi; 429 if (dst->in(0) != region) { 430 dst = phi = PhiNode::make(region, dst, _gvn.type(dst)); 431 record_for_igvn(phi); 432 _gvn.set_type(phi, phi->type()); 433 phi_map->set_req(i, dst); 434 // Prepare to append interesting stuff onto the new phi: 435 while (dst->req() > orig_width) dst->del_req(dst->req()-1); 436 } else { 437 assert(dst->is_Phi(), "nobody else uses a hidden region"); 438 phi = dst->as_Phi(); 439 } 440 if (add_multiple && src->in(0) == ex_control) { 441 // Both are phis. 442 add_n_reqs(dst, src); 443 } else { 444 while (dst->req() < region->req()) add_one_req(dst, src); 445 } 446 const Type* srctype = _gvn.type(src); 447 if (phi->type() != srctype) { 448 const Type* dsttype = phi->type()->meet_speculative(srctype); 449 if (phi->type() != dsttype) { 450 phi->set_type(dsttype); 451 _gvn.set_type(phi, dsttype); 452 } 453 } 454 } 455 } 456 phi_map->merge_replaced_nodes_with(ex_map); 457 } 458 459 //--------------------------use_exception_state-------------------------------- 460 Node* GraphKit::use_exception_state(SafePointNode* phi_map) { 461 if (failing()) { stop(); return top(); } 462 Node* region = phi_map->control(); 463 Node* hidden_merge_mark = root(); 464 assert(phi_map->jvms()->map() == phi_map, "sanity: 1-1 relation"); 465 Node* ex_oop = clear_saved_ex_oop(phi_map); 466 if (region->in(0) == hidden_merge_mark) { 467 // Special marking for internal ex-states. Process the phis now. 468 region->set_req(0, region); // now it's an ordinary region 469 set_jvms(phi_map->jvms()); // ...so now we can use it as a map 470 // Note: Setting the jvms also sets the bci and sp. 471 set_control(_gvn.transform(region)); 472 uint tos = jvms()->stkoff() + sp(); 473 for (uint i = 1; i < tos; i++) { 474 Node* x = phi_map->in(i); 475 if (x->in(0) == region) { 476 assert(x->is_Phi(), "expected a special phi"); 477 phi_map->set_req(i, _gvn.transform(x)); 478 } 479 } 480 for (MergeMemStream mms(merged_memory()); mms.next_non_empty(); ) { 481 Node* x = mms.memory(); 482 if (x->in(0) == region) { 483 assert(x->is_Phi(), "nobody else uses a hidden region"); 484 mms.set_memory(_gvn.transform(x)); 485 } 486 } 487 if (ex_oop->in(0) == region) { 488 assert(ex_oop->is_Phi(), "expected a special phi"); 489 ex_oop = _gvn.transform(ex_oop); 490 } 491 } else { 492 set_jvms(phi_map->jvms()); 493 } 494 495 assert(!is_hidden_merge(phi_map->control()), "hidden ex. states cleared"); 496 assert(!is_hidden_merge(phi_map->i_o()), "hidden ex. states cleared"); 497 return ex_oop; 498 } 499 500 //---------------------------------java_bc------------------------------------- 501 Bytecodes::Code GraphKit::java_bc() const { 502 ciMethod* method = this->method(); 503 int bci = this->bci(); 504 if (method != nullptr && bci != InvocationEntryBci) 505 return method->java_code_at_bci(bci); 506 else 507 return Bytecodes::_illegal; 508 } 509 510 void GraphKit::uncommon_trap_if_should_post_on_exceptions(Deoptimization::DeoptReason reason, 511 bool must_throw) { 512 // if the exception capability is set, then we will generate code 513 // to check the JavaThread.should_post_on_exceptions flag to see 514 // if we actually need to report exception events (for this 515 // thread). If we don't need to report exception events, we will 516 // take the normal fast path provided by add_exception_events. If 517 // exception event reporting is enabled for this thread, we will 518 // take the uncommon_trap in the BuildCutout below. 519 520 // first must access the should_post_on_exceptions_flag in this thread's JavaThread 521 Node* jthread = _gvn.transform(new ThreadLocalNode()); 522 Node* adr = basic_plus_adr(top(), jthread, in_bytes(JavaThread::should_post_on_exceptions_flag_offset())); 523 Node* should_post_flag = make_load(control(), adr, TypeInt::INT, T_INT, Compile::AliasIdxRaw, MemNode::unordered); 524 525 // Test the should_post_on_exceptions_flag vs. 0 526 Node* chk = _gvn.transform( new CmpINode(should_post_flag, intcon(0)) ); 527 Node* tst = _gvn.transform( new BoolNode(chk, BoolTest::eq) ); 528 529 // Branch to slow_path if should_post_on_exceptions_flag was true 530 { BuildCutout unless(this, tst, PROB_MAX); 531 // Do not try anything fancy if we're notifying the VM on every throw. 532 // Cf. case Bytecodes::_athrow in parse2.cpp. 533 uncommon_trap(reason, Deoptimization::Action_none, 534 (ciKlass*)nullptr, (char*)nullptr, must_throw); 535 } 536 537 } 538 539 //------------------------------builtin_throw---------------------------------- 540 void GraphKit::builtin_throw(Deoptimization::DeoptReason reason) { 541 bool must_throw = true; 542 543 // If this particular condition has not yet happened at this 544 // bytecode, then use the uncommon trap mechanism, and allow for 545 // a future recompilation if several traps occur here. 546 // If the throw is hot, try to use a more complicated inline mechanism 547 // which keeps execution inside the compiled code. 548 bool treat_throw_as_hot = false; 549 ciMethodData* md = method()->method_data(); 550 551 if (ProfileTraps) { 552 if (too_many_traps(reason)) { 553 treat_throw_as_hot = true; 554 } 555 // (If there is no MDO at all, assume it is early in 556 // execution, and that any deopts are part of the 557 // startup transient, and don't need to be remembered.) 558 559 // Also, if there is a local exception handler, treat all throws 560 // as hot if there has been at least one in this method. 561 if (C->trap_count(reason) != 0 562 && method()->method_data()->trap_count(reason) != 0 563 && has_ex_handler()) { 564 treat_throw_as_hot = true; 565 } 566 } 567 568 // If this throw happens frequently, an uncommon trap might cause 569 // a performance pothole. If there is a local exception handler, 570 // and if this particular bytecode appears to be deoptimizing often, 571 // let us handle the throw inline, with a preconstructed instance. 572 // Note: If the deopt count has blown up, the uncommon trap 573 // runtime is going to flush this nmethod, not matter what. 574 if (treat_throw_as_hot && method()->can_omit_stack_trace()) { 575 // If the throw is local, we use a pre-existing instance and 576 // punt on the backtrace. This would lead to a missing backtrace 577 // (a repeat of 4292742) if the backtrace object is ever asked 578 // for its backtrace. 579 // Fixing this remaining case of 4292742 requires some flavor of 580 // escape analysis. Leave that for the future. 581 ciInstance* ex_obj = nullptr; 582 switch (reason) { 583 case Deoptimization::Reason_null_check: 584 ex_obj = env()->NullPointerException_instance(); 585 break; 586 case Deoptimization::Reason_div0_check: 587 ex_obj = env()->ArithmeticException_instance(); 588 break; 589 case Deoptimization::Reason_range_check: 590 ex_obj = env()->ArrayIndexOutOfBoundsException_instance(); 591 break; 592 case Deoptimization::Reason_class_check: 593 ex_obj = env()->ClassCastException_instance(); 594 break; 595 case Deoptimization::Reason_array_check: 596 ex_obj = env()->ArrayStoreException_instance(); 597 break; 598 default: 599 break; 600 } 601 if (failing()) { stop(); return; } // exception allocation might fail 602 if (ex_obj != nullptr) { 603 if (env()->jvmti_can_post_on_exceptions()) { 604 // check if we must post exception events, take uncommon trap if so 605 uncommon_trap_if_should_post_on_exceptions(reason, must_throw); 606 // here if should_post_on_exceptions is false 607 // continue on with the normal codegen 608 } 609 610 // Cheat with a preallocated exception object. 611 if (C->log() != nullptr) 612 C->log()->elem("hot_throw preallocated='1' reason='%s'", 613 Deoptimization::trap_reason_name(reason)); 614 const TypeInstPtr* ex_con = TypeInstPtr::make(ex_obj); 615 Node* ex_node = _gvn.transform(ConNode::make(ex_con)); 616 617 // Clear the detail message of the preallocated exception object. 618 // Weblogic sometimes mutates the detail message of exceptions 619 // using reflection. 620 int offset = java_lang_Throwable::get_detailMessage_offset(); 621 const TypePtr* adr_typ = ex_con->add_offset(offset); 622 623 Node *adr = basic_plus_adr(ex_node, ex_node, offset); 624 const TypeOopPtr* val_type = TypeOopPtr::make_from_klass(env()->String_klass()); 625 Node *store = access_store_at(ex_node, adr, adr_typ, null(), val_type, T_OBJECT, IN_HEAP); 626 627 if (!method()->has_exception_handlers()) { 628 // We don't need to preserve the stack if there's no handler as the entire frame is going to be popped anyway. 629 // This prevents issues with exception handling and late inlining. 630 set_sp(0); 631 clean_stack(0); 632 } 633 634 add_exception_state(make_exception_state(ex_node)); 635 return; 636 } 637 } 638 639 // %%% Maybe add entry to OptoRuntime which directly throws the exc.? 640 // It won't be much cheaper than bailing to the interp., since we'll 641 // have to pass up all the debug-info, and the runtime will have to 642 // create the stack trace. 643 644 // Usual case: Bail to interpreter. 645 // Reserve the right to recompile if we haven't seen anything yet. 646 647 ciMethod* m = Deoptimization::reason_is_speculate(reason) ? C->method() : nullptr; 648 Deoptimization::DeoptAction action = Deoptimization::Action_maybe_recompile; 649 if (treat_throw_as_hot 650 && (method()->method_data()->trap_recompiled_at(bci(), m) 651 || C->too_many_traps(reason))) { 652 // We cannot afford to take more traps here. Suffer in the interpreter. 653 if (C->log() != nullptr) 654 C->log()->elem("hot_throw preallocated='0' reason='%s' mcount='%d'", 655 Deoptimization::trap_reason_name(reason), 656 C->trap_count(reason)); 657 action = Deoptimization::Action_none; 658 } 659 660 // "must_throw" prunes the JVM state to include only the stack, if there 661 // are no local exception handlers. This should cut down on register 662 // allocation time and code size, by drastically reducing the number 663 // of in-edges on the call to the uncommon trap. 664 665 uncommon_trap(reason, action, (ciKlass*)nullptr, (char*)nullptr, must_throw); 666 } 667 668 669 //----------------------------PreserveJVMState--------------------------------- 670 PreserveJVMState::PreserveJVMState(GraphKit* kit, bool clone_map) { 671 debug_only(kit->verify_map()); 672 _kit = kit; 673 _map = kit->map(); // preserve the map 674 _sp = kit->sp(); 675 kit->set_map(clone_map ? kit->clone_map() : nullptr); 676 #ifdef ASSERT 677 _bci = kit->bci(); 678 Parse* parser = kit->is_Parse(); 679 int block = (parser == nullptr || parser->block() == nullptr) ? -1 : parser->block()->rpo(); 680 _block = block; 681 #endif 682 } 683 PreserveJVMState::~PreserveJVMState() { 684 GraphKit* kit = _kit; 685 #ifdef ASSERT 686 assert(kit->bci() == _bci, "bci must not shift"); 687 Parse* parser = kit->is_Parse(); 688 int block = (parser == nullptr || parser->block() == nullptr) ? -1 : parser->block()->rpo(); 689 assert(block == _block, "block must not shift"); 690 #endif 691 kit->set_map(_map); 692 kit->set_sp(_sp); 693 } 694 695 696 //-----------------------------BuildCutout------------------------------------- 697 BuildCutout::BuildCutout(GraphKit* kit, Node* p, float prob, float cnt) 698 : PreserveJVMState(kit) 699 { 700 assert(p->is_Con() || p->is_Bool(), "test must be a bool"); 701 SafePointNode* outer_map = _map; // preserved map is caller's 702 SafePointNode* inner_map = kit->map(); 703 IfNode* iff = kit->create_and_map_if(outer_map->control(), p, prob, cnt); 704 outer_map->set_control(kit->gvn().transform( new IfTrueNode(iff) )); 705 inner_map->set_control(kit->gvn().transform( new IfFalseNode(iff) )); 706 } 707 BuildCutout::~BuildCutout() { 708 GraphKit* kit = _kit; 709 assert(kit->stopped(), "cutout code must stop, throw, return, etc."); 710 } 711 712 //---------------------------PreserveReexecuteState---------------------------- 713 PreserveReexecuteState::PreserveReexecuteState(GraphKit* kit) { 714 assert(!kit->stopped(), "must call stopped() before"); 715 _kit = kit; 716 _sp = kit->sp(); 717 _reexecute = kit->jvms()->_reexecute; 718 } 719 PreserveReexecuteState::~PreserveReexecuteState() { 720 if (_kit->stopped()) return; 721 _kit->jvms()->_reexecute = _reexecute; 722 _kit->set_sp(_sp); 723 } 724 725 //------------------------------clone_map-------------------------------------- 726 // Implementation of PreserveJVMState 727 // 728 // Only clone_map(...) here. If this function is only used in the 729 // PreserveJVMState class we may want to get rid of this extra 730 // function eventually and do it all there. 731 732 SafePointNode* GraphKit::clone_map() { 733 if (map() == nullptr) return nullptr; 734 735 // Clone the memory edge first 736 Node* mem = MergeMemNode::make(map()->memory()); 737 gvn().set_type_bottom(mem); 738 739 SafePointNode *clonemap = (SafePointNode*)map()->clone(); 740 JVMState* jvms = this->jvms(); 741 JVMState* clonejvms = jvms->clone_shallow(C); 742 clonemap->set_memory(mem); 743 clonemap->set_jvms(clonejvms); 744 clonejvms->set_map(clonemap); 745 record_for_igvn(clonemap); 746 gvn().set_type_bottom(clonemap); 747 return clonemap; 748 } 749 750 //-----------------------------destruct_map_clone------------------------------ 751 // 752 // Order of destruct is important to increase the likelyhood that memory can be re-used. We need 753 // to destruct/free/delete in the exact opposite order as clone_map(). 754 void GraphKit::destruct_map_clone(SafePointNode* sfp) { 755 if (sfp == nullptr) return; 756 757 Node* mem = sfp->memory(); 758 JVMState* jvms = sfp->jvms(); 759 760 if (jvms != nullptr) { 761 delete jvms; 762 } 763 764 remove_for_igvn(sfp); 765 gvn().clear_type(sfp); 766 sfp->destruct(&_gvn); 767 768 if (mem != nullptr) { 769 gvn().clear_type(mem); 770 mem->destruct(&_gvn); 771 } 772 } 773 774 //-----------------------------set_map_clone----------------------------------- 775 void GraphKit::set_map_clone(SafePointNode* m) { 776 _map = m; 777 _map = clone_map(); 778 _map->set_next_exception(nullptr); 779 debug_only(verify_map()); 780 } 781 782 783 //----------------------------kill_dead_locals--------------------------------- 784 // Detect any locals which are known to be dead, and force them to top. 785 void GraphKit::kill_dead_locals() { 786 // Consult the liveness information for the locals. If any 787 // of them are unused, then they can be replaced by top(). This 788 // should help register allocation time and cut down on the size 789 // of the deoptimization information. 790 791 // This call is made from many of the bytecode handling 792 // subroutines called from the Big Switch in do_one_bytecode. 793 // Every bytecode which might include a slow path is responsible 794 // for killing its dead locals. The more consistent we 795 // are about killing deads, the fewer useless phis will be 796 // constructed for them at various merge points. 797 798 // bci can be -1 (InvocationEntryBci). We return the entry 799 // liveness for the method. 800 801 if (method() == nullptr || method()->code_size() == 0) { 802 // We are building a graph for a call to a native method. 803 // All locals are live. 804 return; 805 } 806 807 ResourceMark rm; 808 809 // Consult the liveness information for the locals. If any 810 // of them are unused, then they can be replaced by top(). This 811 // should help register allocation time and cut down on the size 812 // of the deoptimization information. 813 MethodLivenessResult live_locals = method()->liveness_at_bci(bci()); 814 815 int len = (int)live_locals.size(); 816 assert(len <= jvms()->loc_size(), "too many live locals"); 817 for (int local = 0; local < len; local++) { 818 if (!live_locals.at(local)) { 819 set_local(local, top()); 820 } 821 } 822 } 823 824 #ifdef ASSERT 825 //-------------------------dead_locals_are_killed------------------------------ 826 // Return true if all dead locals are set to top in the map. 827 // Used to assert "clean" debug info at various points. 828 bool GraphKit::dead_locals_are_killed() { 829 if (method() == nullptr || method()->code_size() == 0) { 830 // No locals need to be dead, so all is as it should be. 831 return true; 832 } 833 834 // Make sure somebody called kill_dead_locals upstream. 835 ResourceMark rm; 836 for (JVMState* jvms = this->jvms(); jvms != nullptr; jvms = jvms->caller()) { 837 if (jvms->loc_size() == 0) continue; // no locals to consult 838 SafePointNode* map = jvms->map(); 839 ciMethod* method = jvms->method(); 840 int bci = jvms->bci(); 841 if (jvms == this->jvms()) { 842 bci = this->bci(); // it might not yet be synched 843 } 844 MethodLivenessResult live_locals = method->liveness_at_bci(bci); 845 int len = (int)live_locals.size(); 846 if (!live_locals.is_valid() || len == 0) 847 // This method is trivial, or is poisoned by a breakpoint. 848 return true; 849 assert(len == jvms->loc_size(), "live map consistent with locals map"); 850 for (int local = 0; local < len; local++) { 851 if (!live_locals.at(local) && map->local(jvms, local) != top()) { 852 if (PrintMiscellaneous && (Verbose || WizardMode)) { 853 tty->print_cr("Zombie local %d: ", local); 854 jvms->dump(); 855 } 856 return false; 857 } 858 } 859 } 860 return true; 861 } 862 863 #endif //ASSERT 864 865 // Helper function for enforcing certain bytecodes to reexecute if deoptimization happens. 866 static bool should_reexecute_implied_by_bytecode(JVMState *jvms, bool is_anewarray) { 867 ciMethod* cur_method = jvms->method(); 868 int cur_bci = jvms->bci(); 869 if (cur_method != nullptr && cur_bci != InvocationEntryBci) { 870 Bytecodes::Code code = cur_method->java_code_at_bci(cur_bci); 871 return Interpreter::bytecode_should_reexecute(code) || 872 (is_anewarray && (code == Bytecodes::_multianewarray)); 873 // Reexecute _multianewarray bytecode which was replaced with 874 // sequence of [a]newarray. See Parse::do_multianewarray(). 875 // 876 // Note: interpreter should not have it set since this optimization 877 // is limited by dimensions and guarded by flag so in some cases 878 // multianewarray() runtime calls will be generated and 879 // the bytecode should not be reexecutes (stack will not be reset). 880 } else { 881 return false; 882 } 883 } 884 885 // Helper function for adding JVMState and debug information to node 886 void GraphKit::add_safepoint_edges(SafePointNode* call, bool must_throw) { 887 // Add the safepoint edges to the call (or other safepoint). 888 889 // Make sure dead locals are set to top. This 890 // should help register allocation time and cut down on the size 891 // of the deoptimization information. 892 assert(dead_locals_are_killed(), "garbage in debug info before safepoint"); 893 894 // Walk the inline list to fill in the correct set of JVMState's 895 // Also fill in the associated edges for each JVMState. 896 897 // If the bytecode needs to be reexecuted we need to put 898 // the arguments back on the stack. 899 const bool should_reexecute = jvms()->should_reexecute(); 900 JVMState* youngest_jvms = should_reexecute ? sync_jvms_for_reexecute() : sync_jvms(); 901 902 // NOTE: set_bci (called from sync_jvms) might reset the reexecute bit to 903 // undefined if the bci is different. This is normal for Parse but it 904 // should not happen for LibraryCallKit because only one bci is processed. 905 assert(!is_LibraryCallKit() || (jvms()->should_reexecute() == should_reexecute), 906 "in LibraryCallKit the reexecute bit should not change"); 907 908 // If we are guaranteed to throw, we can prune everything but the 909 // input to the current bytecode. 910 bool can_prune_locals = false; 911 uint stack_slots_not_pruned = 0; 912 int inputs = 0, depth = 0; 913 if (must_throw) { 914 assert(method() == youngest_jvms->method(), "sanity"); 915 if (compute_stack_effects(inputs, depth)) { 916 can_prune_locals = true; 917 stack_slots_not_pruned = inputs; 918 } 919 } 920 921 if (env()->should_retain_local_variables()) { 922 // At any safepoint, this method can get breakpointed, which would 923 // then require an immediate deoptimization. 924 can_prune_locals = false; // do not prune locals 925 stack_slots_not_pruned = 0; 926 } 927 928 // do not scribble on the input jvms 929 JVMState* out_jvms = youngest_jvms->clone_deep(C); 930 call->set_jvms(out_jvms); // Start jvms list for call node 931 932 // For a known set of bytecodes, the interpreter should reexecute them if 933 // deoptimization happens. We set the reexecute state for them here 934 if (out_jvms->is_reexecute_undefined() && //don't change if already specified 935 should_reexecute_implied_by_bytecode(out_jvms, call->is_AllocateArray())) { 936 #ifdef ASSERT 937 int inputs = 0, not_used; // initialized by GraphKit::compute_stack_effects() 938 assert(method() == youngest_jvms->method(), "sanity"); 939 assert(compute_stack_effects(inputs, not_used), "unknown bytecode: %s", Bytecodes::name(java_bc())); 940 assert(out_jvms->sp() >= (uint)inputs, "not enough operands for reexecution"); 941 #endif // ASSERT 942 out_jvms->set_should_reexecute(true); //NOTE: youngest_jvms not changed 943 } 944 945 // Presize the call: 946 DEBUG_ONLY(uint non_debug_edges = call->req()); 947 call->add_req_batch(top(), youngest_jvms->debug_depth()); 948 assert(call->req() == non_debug_edges + youngest_jvms->debug_depth(), ""); 949 950 // Set up edges so that the call looks like this: 951 // Call [state:] ctl io mem fptr retadr 952 // [parms:] parm0 ... parmN 953 // [root:] loc0 ... locN stk0 ... stkSP mon0 obj0 ... monN objN 954 // [...mid:] loc0 ... locN stk0 ... stkSP mon0 obj0 ... monN objN [...] 955 // [young:] loc0 ... locN stk0 ... stkSP mon0 obj0 ... monN objN 956 // Note that caller debug info precedes callee debug info. 957 958 // Fill pointer walks backwards from "young:" to "root:" in the diagram above: 959 uint debug_ptr = call->req(); 960 961 // Loop over the map input edges associated with jvms, add them 962 // to the call node, & reset all offsets to match call node array. 963 for (JVMState* in_jvms = youngest_jvms; in_jvms != nullptr; ) { 964 uint debug_end = debug_ptr; 965 uint debug_start = debug_ptr - in_jvms->debug_size(); 966 debug_ptr = debug_start; // back up the ptr 967 968 uint p = debug_start; // walks forward in [debug_start, debug_end) 969 uint j, k, l; 970 SafePointNode* in_map = in_jvms->map(); 971 out_jvms->set_map(call); 972 973 if (can_prune_locals) { 974 assert(in_jvms->method() == out_jvms->method(), "sanity"); 975 // If the current throw can reach an exception handler in this JVMS, 976 // then we must keep everything live that can reach that handler. 977 // As a quick and dirty approximation, we look for any handlers at all. 978 if (in_jvms->method()->has_exception_handlers()) { 979 can_prune_locals = false; 980 } 981 } 982 983 // Add the Locals 984 k = in_jvms->locoff(); 985 l = in_jvms->loc_size(); 986 out_jvms->set_locoff(p); 987 if (!can_prune_locals) { 988 for (j = 0; j < l; j++) 989 call->set_req(p++, in_map->in(k+j)); 990 } else { 991 p += l; // already set to top above by add_req_batch 992 } 993 994 // Add the Expression Stack 995 k = in_jvms->stkoff(); 996 l = in_jvms->sp(); 997 out_jvms->set_stkoff(p); 998 if (!can_prune_locals) { 999 for (j = 0; j < l; j++) 1000 call->set_req(p++, in_map->in(k+j)); 1001 } else if (can_prune_locals && stack_slots_not_pruned != 0) { 1002 // Divide stack into {S0,...,S1}, where S0 is set to top. 1003 uint s1 = stack_slots_not_pruned; 1004 stack_slots_not_pruned = 0; // for next iteration 1005 if (s1 > l) s1 = l; 1006 uint s0 = l - s1; 1007 p += s0; // skip the tops preinstalled by add_req_batch 1008 for (j = s0; j < l; j++) 1009 call->set_req(p++, in_map->in(k+j)); 1010 } else { 1011 p += l; // already set to top above by add_req_batch 1012 } 1013 1014 // Add the Monitors 1015 k = in_jvms->monoff(); 1016 l = in_jvms->mon_size(); 1017 out_jvms->set_monoff(p); 1018 for (j = 0; j < l; j++) 1019 call->set_req(p++, in_map->in(k+j)); 1020 1021 // Copy any scalar object fields. 1022 k = in_jvms->scloff(); 1023 l = in_jvms->scl_size(); 1024 out_jvms->set_scloff(p); 1025 for (j = 0; j < l; j++) 1026 call->set_req(p++, in_map->in(k+j)); 1027 1028 // Finish the new jvms. 1029 out_jvms->set_endoff(p); 1030 1031 assert(out_jvms->endoff() == debug_end, "fill ptr must match"); 1032 assert(out_jvms->depth() == in_jvms->depth(), "depth must match"); 1033 assert(out_jvms->loc_size() == in_jvms->loc_size(), "size must match"); 1034 assert(out_jvms->mon_size() == in_jvms->mon_size(), "size must match"); 1035 assert(out_jvms->scl_size() == in_jvms->scl_size(), "size must match"); 1036 assert(out_jvms->debug_size() == in_jvms->debug_size(), "size must match"); 1037 1038 // Update the two tail pointers in parallel. 1039 out_jvms = out_jvms->caller(); 1040 in_jvms = in_jvms->caller(); 1041 } 1042 1043 assert(debug_ptr == non_debug_edges, "debug info must fit exactly"); 1044 1045 // Test the correctness of JVMState::debug_xxx accessors: 1046 assert(call->jvms()->debug_start() == non_debug_edges, ""); 1047 assert(call->jvms()->debug_end() == call->req(), ""); 1048 assert(call->jvms()->debug_depth() == call->req() - non_debug_edges, ""); 1049 } 1050 1051 bool GraphKit::compute_stack_effects(int& inputs, int& depth) { 1052 Bytecodes::Code code = java_bc(); 1053 if (code == Bytecodes::_wide) { 1054 code = method()->java_code_at_bci(bci() + 1); 1055 } 1056 1057 if (code != Bytecodes::_illegal) { 1058 depth = Bytecodes::depth(code); // checkcast=0, athrow=-1 1059 } 1060 1061 auto rsize = [&]() { 1062 assert(code != Bytecodes::_illegal, "code is illegal!"); 1063 BasicType rtype = Bytecodes::result_type(code); // checkcast=P, athrow=V 1064 return (rtype < T_CONFLICT) ? type2size[rtype] : 0; 1065 }; 1066 1067 switch (code) { 1068 case Bytecodes::_illegal: 1069 return false; 1070 1071 case Bytecodes::_ldc: 1072 case Bytecodes::_ldc_w: 1073 case Bytecodes::_ldc2_w: 1074 inputs = 0; 1075 break; 1076 1077 case Bytecodes::_dup: inputs = 1; break; 1078 case Bytecodes::_dup_x1: inputs = 2; break; 1079 case Bytecodes::_dup_x2: inputs = 3; break; 1080 case Bytecodes::_dup2: inputs = 2; break; 1081 case Bytecodes::_dup2_x1: inputs = 3; break; 1082 case Bytecodes::_dup2_x2: inputs = 4; break; 1083 case Bytecodes::_swap: inputs = 2; break; 1084 case Bytecodes::_arraylength: inputs = 1; break; 1085 1086 case Bytecodes::_getstatic: 1087 case Bytecodes::_putstatic: 1088 case Bytecodes::_getfield: 1089 case Bytecodes::_putfield: 1090 { 1091 bool ignored_will_link; 1092 ciField* field = method()->get_field_at_bci(bci(), ignored_will_link); 1093 int size = field->type()->size(); 1094 bool is_get = (depth >= 0), is_static = (depth & 1); 1095 inputs = (is_static ? 0 : 1); 1096 if (is_get) { 1097 depth = size - inputs; 1098 } else { 1099 inputs += size; // putxxx pops the value from the stack 1100 depth = - inputs; 1101 } 1102 } 1103 break; 1104 1105 case Bytecodes::_invokevirtual: 1106 case Bytecodes::_invokespecial: 1107 case Bytecodes::_invokestatic: 1108 case Bytecodes::_invokedynamic: 1109 case Bytecodes::_invokeinterface: 1110 { 1111 bool ignored_will_link; 1112 ciSignature* declared_signature = nullptr; 1113 ciMethod* ignored_callee = method()->get_method_at_bci(bci(), ignored_will_link, &declared_signature); 1114 assert(declared_signature != nullptr, "cannot be null"); 1115 inputs = declared_signature->arg_size_for_bc(code); 1116 int size = declared_signature->return_type()->size(); 1117 depth = size - inputs; 1118 } 1119 break; 1120 1121 case Bytecodes::_multianewarray: 1122 { 1123 ciBytecodeStream iter(method()); 1124 iter.reset_to_bci(bci()); 1125 iter.next(); 1126 inputs = iter.get_dimensions(); 1127 assert(rsize() == 1, ""); 1128 depth = 1 - inputs; 1129 } 1130 break; 1131 1132 case Bytecodes::_withfield: { 1133 bool ignored_will_link; 1134 ciField* field = method()->get_field_at_bci(bci(), ignored_will_link); 1135 int size = field->type()->size(); 1136 inputs = size+1; 1137 depth = rsize() - inputs; 1138 break; 1139 } 1140 1141 case Bytecodes::_ireturn: 1142 case Bytecodes::_lreturn: 1143 case Bytecodes::_freturn: 1144 case Bytecodes::_dreturn: 1145 case Bytecodes::_areturn: 1146 assert(rsize() == -depth, ""); 1147 inputs = -depth; 1148 break; 1149 1150 case Bytecodes::_jsr: 1151 case Bytecodes::_jsr_w: 1152 inputs = 0; 1153 depth = 1; // S.B. depth=1, not zero 1154 break; 1155 1156 default: 1157 // bytecode produces a typed result 1158 inputs = rsize() - depth; 1159 assert(inputs >= 0, ""); 1160 break; 1161 } 1162 1163 #ifdef ASSERT 1164 // spot check 1165 int outputs = depth + inputs; 1166 assert(outputs >= 0, "sanity"); 1167 switch (code) { 1168 case Bytecodes::_checkcast: assert(inputs == 1 && outputs == 1, ""); break; 1169 case Bytecodes::_athrow: assert(inputs == 1 && outputs == 0, ""); break; 1170 case Bytecodes::_aload_0: assert(inputs == 0 && outputs == 1, ""); break; 1171 case Bytecodes::_return: assert(inputs == 0 && outputs == 0, ""); break; 1172 case Bytecodes::_drem: assert(inputs == 4 && outputs == 2, ""); break; 1173 default: break; 1174 } 1175 #endif //ASSERT 1176 1177 return true; 1178 } 1179 1180 1181 1182 //------------------------------basic_plus_adr--------------------------------- 1183 Node* GraphKit::basic_plus_adr(Node* base, Node* ptr, Node* offset) { 1184 // short-circuit a common case 1185 if (offset == intcon(0)) return ptr; 1186 return _gvn.transform( new AddPNode(base, ptr, offset) ); 1187 } 1188 1189 Node* GraphKit::ConvI2L(Node* offset) { 1190 // short-circuit a common case 1191 jint offset_con = find_int_con(offset, Type::OffsetBot); 1192 if (offset_con != Type::OffsetBot) { 1193 return longcon((jlong) offset_con); 1194 } 1195 return _gvn.transform( new ConvI2LNode(offset)); 1196 } 1197 1198 Node* GraphKit::ConvI2UL(Node* offset) { 1199 juint offset_con = (juint) find_int_con(offset, Type::OffsetBot); 1200 if (offset_con != (juint) Type::OffsetBot) { 1201 return longcon((julong) offset_con); 1202 } 1203 Node* conv = _gvn.transform( new ConvI2LNode(offset)); 1204 Node* mask = _gvn.transform(ConLNode::make((julong) max_juint)); 1205 return _gvn.transform( new AndLNode(conv, mask) ); 1206 } 1207 1208 Node* GraphKit::ConvL2I(Node* offset) { 1209 // short-circuit a common case 1210 jlong offset_con = find_long_con(offset, (jlong)Type::OffsetBot); 1211 if (offset_con != (jlong)Type::OffsetBot) { 1212 return intcon((int) offset_con); 1213 } 1214 return _gvn.transform( new ConvL2INode(offset)); 1215 } 1216 1217 //-------------------------load_object_klass----------------------------------- 1218 Node* GraphKit::load_object_klass(Node* obj) { 1219 // Special-case a fresh allocation to avoid building nodes: 1220 Node* akls = AllocateNode::Ideal_klass(obj, &_gvn); 1221 if (akls != nullptr) return akls; 1222 Node* k_adr = basic_plus_adr(obj, oopDesc::klass_offset_in_bytes()); 1223 return _gvn.transform(LoadKlassNode::make(_gvn, nullptr, immutable_memory(), k_adr, TypeInstPtr::KLASS, TypeInstKlassPtr::OBJECT)); 1224 } 1225 1226 //-------------------------load_array_length----------------------------------- 1227 Node* GraphKit::load_array_length(Node* array) { 1228 // Special-case a fresh allocation to avoid building nodes: 1229 AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(array); 1230 Node *alen; 1231 if (alloc == nullptr) { 1232 Node *r_adr = basic_plus_adr(array, arrayOopDesc::length_offset_in_bytes()); 1233 alen = _gvn.transform( new LoadRangeNode(0, immutable_memory(), r_adr, TypeInt::POS)); 1234 } else { 1235 alen = array_ideal_length(alloc, _gvn.type(array)->is_oopptr(), false); 1236 } 1237 return alen; 1238 } 1239 1240 Node* GraphKit::array_ideal_length(AllocateArrayNode* alloc, 1241 const TypeOopPtr* oop_type, 1242 bool replace_length_in_map) { 1243 Node* length = alloc->Ideal_length(); 1244 if (replace_length_in_map == false || map()->find_edge(length) >= 0) { 1245 Node* ccast = alloc->make_ideal_length(oop_type, &_gvn); 1246 if (ccast != length) { 1247 // do not transform ccast here, it might convert to top node for 1248 // negative array length and break assumptions in parsing stage. 1249 _gvn.set_type_bottom(ccast); 1250 record_for_igvn(ccast); 1251 if (replace_length_in_map) { 1252 replace_in_map(length, ccast); 1253 } 1254 return ccast; 1255 } 1256 } 1257 return length; 1258 } 1259 1260 //------------------------------do_null_check---------------------------------- 1261 // Helper function to do a null pointer check. Returned value is 1262 // the incoming address with null casted away. You are allowed to use the 1263 // not-null value only if you are control dependent on the test. 1264 #ifndef PRODUCT 1265 extern uint explicit_null_checks_inserted, 1266 explicit_null_checks_elided; 1267 #endif 1268 Node* GraphKit::null_check_common(Node* value, BasicType type, 1269 // optional arguments for variations: 1270 bool assert_null, 1271 Node* *null_control, 1272 bool speculative, 1273 bool is_init_check) { 1274 assert(!assert_null || null_control == nullptr, "not both at once"); 1275 if (stopped()) return top(); 1276 NOT_PRODUCT(explicit_null_checks_inserted++); 1277 1278 if (value->is_InlineType()) { 1279 // Null checking a scalarized but nullable inline type. Check the IsInit 1280 // input instead of the oop input to avoid keeping buffer allocations alive. 1281 InlineTypeNode* vtptr = value->as_InlineType(); 1282 while (vtptr->get_oop()->is_InlineType()) { 1283 vtptr = vtptr->get_oop()->as_InlineType(); 1284 } 1285 null_check_common(vtptr->get_is_init(), T_INT, assert_null, null_control, speculative, true); 1286 if (stopped()) { 1287 return top(); 1288 } 1289 if (assert_null) { 1290 // TODO 8284443 Scalarize here (this currently leads to compilation bailouts) 1291 // vtptr = InlineTypeNode::make_null(_gvn, vtptr->type()->inline_klass()); 1292 // replace_in_map(value, vtptr); 1293 // return vtptr; 1294 return null(); 1295 } 1296 bool do_replace_in_map = (null_control == nullptr || (*null_control) == top()); 1297 return cast_not_null(value, do_replace_in_map); 1298 } 1299 1300 // Construct null check 1301 Node *chk = nullptr; 1302 switch(type) { 1303 case T_LONG : chk = new CmpLNode(value, _gvn.zerocon(T_LONG)); break; 1304 case T_INT : chk = new CmpINode(value, _gvn.intcon(0)); break; 1305 case T_PRIMITIVE_OBJECT : // fall through 1306 case T_ARRAY : // fall through 1307 type = T_OBJECT; // simplify further tests 1308 case T_OBJECT : { 1309 const Type *t = _gvn.type( value ); 1310 1311 const TypeOopPtr* tp = t->isa_oopptr(); 1312 if (tp != nullptr && !tp->is_loaded() 1313 // Only for do_null_check, not any of its siblings: 1314 && !assert_null && null_control == nullptr) { 1315 // Usually, any field access or invocation on an unloaded oop type 1316 // will simply fail to link, since the statically linked class is 1317 // likely also to be unloaded. However, in -Xcomp mode, sometimes 1318 // the static class is loaded but the sharper oop type is not. 1319 // Rather than checking for this obscure case in lots of places, 1320 // we simply observe that a null check on an unloaded class 1321 // will always be followed by a nonsense operation, so we 1322 // can just issue the uncommon trap here. 1323 // Our access to the unloaded class will only be correct 1324 // after it has been loaded and initialized, which requires 1325 // a trip through the interpreter. 1326 ciKlass* klass = tp->unloaded_klass(); 1327 #ifndef PRODUCT 1328 if (WizardMode) { tty->print("Null check of unloaded "); klass->print(); tty->cr(); } 1329 #endif 1330 uncommon_trap(Deoptimization::Reason_unloaded, 1331 Deoptimization::Action_reinterpret, 1332 klass, "!loaded"); 1333 return top(); 1334 } 1335 1336 if (assert_null) { 1337 // See if the type is contained in NULL_PTR. 1338 // If so, then the value is already null. 1339 if (t->higher_equal(TypePtr::NULL_PTR)) { 1340 NOT_PRODUCT(explicit_null_checks_elided++); 1341 return value; // Elided null assert quickly! 1342 } 1343 } else { 1344 // See if mixing in the null pointer changes type. 1345 // If so, then the null pointer was not allowed in the original 1346 // type. In other words, "value" was not-null. 1347 if (t->meet(TypePtr::NULL_PTR) != t->remove_speculative()) { 1348 // same as: if (!TypePtr::NULL_PTR->higher_equal(t)) ... 1349 NOT_PRODUCT(explicit_null_checks_elided++); 1350 return value; // Elided null check quickly! 1351 } 1352 } 1353 chk = new CmpPNode( value, null() ); 1354 break; 1355 } 1356 1357 default: 1358 fatal("unexpected type: %s", type2name(type)); 1359 } 1360 assert(chk != nullptr, "sanity check"); 1361 chk = _gvn.transform(chk); 1362 1363 BoolTest::mask btest = assert_null ? BoolTest::eq : BoolTest::ne; 1364 BoolNode *btst = new BoolNode( chk, btest); 1365 Node *tst = _gvn.transform( btst ); 1366 1367 //----------- 1368 // if peephole optimizations occurred, a prior test existed. 1369 // If a prior test existed, maybe it dominates as we can avoid this test. 1370 if (tst != btst && type == T_OBJECT) { 1371 // At this point we want to scan up the CFG to see if we can 1372 // find an identical test (and so avoid this test altogether). 1373 Node *cfg = control(); 1374 int depth = 0; 1375 while( depth < 16 ) { // Limit search depth for speed 1376 if( cfg->Opcode() == Op_IfTrue && 1377 cfg->in(0)->in(1) == tst ) { 1378 // Found prior test. Use "cast_not_null" to construct an identical 1379 // CastPP (and hence hash to) as already exists for the prior test. 1380 // Return that casted value. 1381 if (assert_null) { 1382 replace_in_map(value, null()); 1383 return null(); // do not issue the redundant test 1384 } 1385 Node *oldcontrol = control(); 1386 set_control(cfg); 1387 Node *res = cast_not_null(value); 1388 set_control(oldcontrol); 1389 NOT_PRODUCT(explicit_null_checks_elided++); 1390 return res; 1391 } 1392 cfg = IfNode::up_one_dom(cfg, /*linear_only=*/ true); 1393 if (cfg == nullptr) break; // Quit at region nodes 1394 depth++; 1395 } 1396 } 1397 1398 //----------- 1399 // Branch to failure if null 1400 float ok_prob = PROB_MAX; // a priori estimate: nulls never happen 1401 Deoptimization::DeoptReason reason; 1402 if (assert_null) { 1403 reason = Deoptimization::reason_null_assert(speculative); 1404 } else if (type == T_OBJECT || is_init_check) { 1405 reason = Deoptimization::reason_null_check(speculative); 1406 } else { 1407 reason = Deoptimization::Reason_div0_check; 1408 } 1409 // %%% Since Reason_unhandled is not recorded on a per-bytecode basis, 1410 // ciMethodData::has_trap_at will return a conservative -1 if any 1411 // must-be-null assertion has failed. This could cause performance 1412 // problems for a method after its first do_null_assert failure. 1413 // Consider using 'Reason_class_check' instead? 1414 1415 // To cause an implicit null check, we set the not-null probability 1416 // to the maximum (PROB_MAX). For an explicit check the probability 1417 // is set to a smaller value. 1418 if (null_control != nullptr || too_many_traps(reason)) { 1419 // probability is less likely 1420 ok_prob = PROB_LIKELY_MAG(3); 1421 } else if (!assert_null && 1422 (ImplicitNullCheckThreshold > 0) && 1423 method() != nullptr && 1424 (method()->method_data()->trap_count(reason) 1425 >= (uint)ImplicitNullCheckThreshold)) { 1426 ok_prob = PROB_LIKELY_MAG(3); 1427 } 1428 1429 if (null_control != nullptr) { 1430 IfNode* iff = create_and_map_if(control(), tst, ok_prob, COUNT_UNKNOWN); 1431 Node* null_true = _gvn.transform( new IfFalseNode(iff)); 1432 set_control( _gvn.transform( new IfTrueNode(iff))); 1433 #ifndef PRODUCT 1434 if (null_true == top()) { 1435 explicit_null_checks_elided++; 1436 } 1437 #endif 1438 (*null_control) = null_true; 1439 } else { 1440 BuildCutout unless(this, tst, ok_prob); 1441 // Check for optimizer eliding test at parse time 1442 if (stopped()) { 1443 // Failure not possible; do not bother making uncommon trap. 1444 NOT_PRODUCT(explicit_null_checks_elided++); 1445 } else if (assert_null) { 1446 uncommon_trap(reason, 1447 Deoptimization::Action_make_not_entrant, 1448 nullptr, "assert_null"); 1449 } else { 1450 replace_in_map(value, zerocon(type)); 1451 builtin_throw(reason); 1452 } 1453 } 1454 1455 // Must throw exception, fall-thru not possible? 1456 if (stopped()) { 1457 return top(); // No result 1458 } 1459 1460 if (assert_null) { 1461 // Cast obj to null on this path. 1462 replace_in_map(value, zerocon(type)); 1463 return zerocon(type); 1464 } 1465 1466 // Cast obj to not-null on this path, if there is no null_control. 1467 // (If there is a null_control, a non-null value may come back to haunt us.) 1468 if (type == T_OBJECT) { 1469 Node* cast = cast_not_null(value, false); 1470 if (null_control == nullptr || (*null_control) == top()) 1471 replace_in_map(value, cast); 1472 value = cast; 1473 } 1474 1475 return value; 1476 } 1477 1478 //------------------------------cast_not_null---------------------------------- 1479 // Cast obj to not-null on this path 1480 Node* GraphKit::cast_not_null(Node* obj, bool do_replace_in_map) { 1481 if (obj->is_InlineType()) { 1482 Node* vt = obj->clone(); 1483 vt->as_InlineType()->set_is_init(_gvn); 1484 vt = _gvn.transform(vt); 1485 if (do_replace_in_map) { 1486 replace_in_map(obj, vt); 1487 } 1488 return vt; 1489 } 1490 const Type *t = _gvn.type(obj); 1491 const Type *t_not_null = t->join_speculative(TypePtr::NOTNULL); 1492 // Object is already not-null? 1493 if( t == t_not_null ) return obj; 1494 1495 Node *cast = new CastPPNode(obj,t_not_null); 1496 cast->init_req(0, control()); 1497 cast = _gvn.transform( cast ); 1498 1499 // Scan for instances of 'obj' in the current JVM mapping. 1500 // These instances are known to be not-null after the test. 1501 if (do_replace_in_map) 1502 replace_in_map(obj, cast); 1503 1504 return cast; // Return casted value 1505 } 1506 1507 // Sometimes in intrinsics, we implicitly know an object is not null 1508 // (there's no actual null check) so we can cast it to not null. In 1509 // the course of optimizations, the input to the cast can become null. 1510 // In that case that data path will die and we need the control path 1511 // to become dead as well to keep the graph consistent. So we have to 1512 // add a check for null for which one branch can't be taken. It uses 1513 // an Opaque4 node that will cause the check to be removed after loop 1514 // opts so the test goes away and the compiled code doesn't execute a 1515 // useless check. 1516 Node* GraphKit::must_be_not_null(Node* value, bool do_replace_in_map) { 1517 if (!TypePtr::NULL_PTR->higher_equal(_gvn.type(value))) { 1518 return value; 1519 } 1520 Node* chk = _gvn.transform(new CmpPNode(value, null())); 1521 Node *tst = _gvn.transform(new BoolNode(chk, BoolTest::ne)); 1522 Node* opaq = _gvn.transform(new Opaque4Node(C, tst, intcon(1))); 1523 IfNode *iff = new IfNode(control(), opaq, PROB_MAX, COUNT_UNKNOWN); 1524 _gvn.set_type(iff, iff->Value(&_gvn)); 1525 Node *if_f = _gvn.transform(new IfFalseNode(iff)); 1526 Node *frame = _gvn.transform(new ParmNode(C->start(), TypeFunc::FramePtr)); 1527 Node* halt = _gvn.transform(new HaltNode(if_f, frame, "unexpected null in intrinsic")); 1528 C->root()->add_req(halt); 1529 Node *if_t = _gvn.transform(new IfTrueNode(iff)); 1530 set_control(if_t); 1531 return cast_not_null(value, do_replace_in_map); 1532 } 1533 1534 1535 //--------------------------replace_in_map------------------------------------- 1536 void GraphKit::replace_in_map(Node* old, Node* neww) { 1537 if (old == neww) { 1538 return; 1539 } 1540 1541 map()->replace_edge(old, neww); 1542 1543 // Note: This operation potentially replaces any edge 1544 // on the map. This includes locals, stack, and monitors 1545 // of the current (innermost) JVM state. 1546 1547 // don't let inconsistent types from profiling escape this 1548 // method 1549 1550 const Type* told = _gvn.type(old); 1551 const Type* tnew = _gvn.type(neww); 1552 1553 if (!tnew->higher_equal(told)) { 1554 return; 1555 } 1556 1557 map()->record_replaced_node(old, neww); 1558 } 1559 1560 1561 //============================================================================= 1562 //--------------------------------memory--------------------------------------- 1563 Node* GraphKit::memory(uint alias_idx) { 1564 MergeMemNode* mem = merged_memory(); 1565 Node* p = mem->memory_at(alias_idx); 1566 assert(p != mem->empty_memory(), "empty"); 1567 _gvn.set_type(p, Type::MEMORY); // must be mapped 1568 return p; 1569 } 1570 1571 //-----------------------------reset_memory------------------------------------ 1572 Node* GraphKit::reset_memory() { 1573 Node* mem = map()->memory(); 1574 // do not use this node for any more parsing! 1575 debug_only( map()->set_memory((Node*)nullptr) ); 1576 return _gvn.transform( mem ); 1577 } 1578 1579 //------------------------------set_all_memory--------------------------------- 1580 void GraphKit::set_all_memory(Node* newmem) { 1581 Node* mergemem = MergeMemNode::make(newmem); 1582 gvn().set_type_bottom(mergemem); 1583 map()->set_memory(mergemem); 1584 } 1585 1586 //------------------------------set_all_memory_call---------------------------- 1587 void GraphKit::set_all_memory_call(Node* call, bool separate_io_proj) { 1588 Node* newmem = _gvn.transform( new ProjNode(call, TypeFunc::Memory, separate_io_proj) ); 1589 set_all_memory(newmem); 1590 } 1591 1592 //============================================================================= 1593 // 1594 // parser factory methods for MemNodes 1595 // 1596 // These are layered on top of the factory methods in LoadNode and StoreNode, 1597 // and integrate with the parser's memory state and _gvn engine. 1598 // 1599 1600 // factory methods in "int adr_idx" 1601 Node* GraphKit::make_load(Node* ctl, Node* adr, const Type* t, BasicType bt, 1602 int adr_idx, 1603 MemNode::MemOrd mo, 1604 LoadNode::ControlDependency control_dependency, 1605 bool require_atomic_access, 1606 bool unaligned, 1607 bool mismatched, 1608 bool unsafe, 1609 uint8_t barrier_data) { 1610 assert(adr_idx != Compile::AliasIdxTop, "use other make_load factory" ); 1611 const TypePtr* adr_type = nullptr; // debug-mode-only argument 1612 debug_only(adr_type = C->get_adr_type(adr_idx)); 1613 Node* mem = memory(adr_idx); 1614 Node* ld = LoadNode::make(_gvn, ctl, mem, adr, adr_type, t, bt, mo, control_dependency, require_atomic_access, unaligned, mismatched, unsafe, barrier_data); 1615 ld = _gvn.transform(ld); 1616 1617 if (((bt == T_OBJECT || bt == T_PRIMITIVE_OBJECT) && C->do_escape_analysis()) || C->eliminate_boxing()) { 1618 // Improve graph before escape analysis and boxing elimination. 1619 record_for_igvn(ld); 1620 } 1621 return ld; 1622 } 1623 1624 Node* GraphKit::store_to_memory(Node* ctl, Node* adr, Node *val, BasicType bt, 1625 int adr_idx, 1626 MemNode::MemOrd mo, 1627 bool require_atomic_access, 1628 bool unaligned, 1629 bool mismatched, 1630 bool unsafe, 1631 int barrier_data) { 1632 assert(adr_idx != Compile::AliasIdxTop, "use other store_to_memory factory" ); 1633 const TypePtr* adr_type = nullptr; 1634 debug_only(adr_type = C->get_adr_type(adr_idx)); 1635 Node *mem = memory(adr_idx); 1636 Node* st = StoreNode::make(_gvn, ctl, mem, adr, adr_type, val, bt, mo, require_atomic_access); 1637 if (unaligned) { 1638 st->as_Store()->set_unaligned_access(); 1639 } 1640 if (mismatched) { 1641 st->as_Store()->set_mismatched_access(); 1642 } 1643 if (unsafe) { 1644 st->as_Store()->set_unsafe_access(); 1645 } 1646 st->as_Store()->set_barrier_data(barrier_data); 1647 st = _gvn.transform(st); 1648 set_memory(st, adr_idx); 1649 // Back-to-back stores can only remove intermediate store with DU info 1650 // so push on worklist for optimizer. 1651 if (mem->req() > MemNode::Address && adr == mem->in(MemNode::Address)) 1652 record_for_igvn(st); 1653 1654 return st; 1655 } 1656 1657 Node* GraphKit::access_store_at(Node* obj, 1658 Node* adr, 1659 const TypePtr* adr_type, 1660 Node* val, 1661 const Type* val_type, 1662 BasicType bt, 1663 DecoratorSet decorators, 1664 bool safe_for_replace) { 1665 // Transformation of a value which could be null pointer (CastPP #null) 1666 // could be delayed during Parse (for example, in adjust_map_after_if()). 1667 // Execute transformation here to avoid barrier generation in such case. 1668 if (_gvn.type(val) == TypePtr::NULL_PTR) { 1669 val = _gvn.makecon(TypePtr::NULL_PTR); 1670 } 1671 1672 if (stopped()) { 1673 return top(); // Dead path ? 1674 } 1675 1676 assert(val != nullptr, "not dead path"); 1677 if (val->is_InlineType()) { 1678 // Store to non-flat field. Buffer the inline type and make sure 1679 // the store is re-executed if the allocation triggers deoptimization. 1680 PreserveReexecuteState preexecs(this); 1681 jvms()->set_should_reexecute(true); 1682 val = val->as_InlineType()->buffer(this, safe_for_replace); 1683 } 1684 1685 C2AccessValuePtr addr(adr, adr_type); 1686 C2AccessValue value(val, val_type); 1687 C2ParseAccess access(this, decorators | C2_WRITE_ACCESS, bt, obj, addr); 1688 if (access.is_raw()) { 1689 return _barrier_set->BarrierSetC2::store_at(access, value); 1690 } else { 1691 return _barrier_set->store_at(access, value); 1692 } 1693 } 1694 1695 Node* GraphKit::access_load_at(Node* obj, // containing obj 1696 Node* adr, // actual address to store val at 1697 const TypePtr* adr_type, 1698 const Type* val_type, 1699 BasicType bt, 1700 DecoratorSet decorators, 1701 Node* ctl) { 1702 if (stopped()) { 1703 return top(); // Dead path ? 1704 } 1705 1706 C2AccessValuePtr addr(adr, adr_type); 1707 C2ParseAccess access(this, decorators | C2_READ_ACCESS, bt, obj, addr, ctl); 1708 if (access.is_raw()) { 1709 return _barrier_set->BarrierSetC2::load_at(access, val_type); 1710 } else { 1711 return _barrier_set->load_at(access, val_type); 1712 } 1713 } 1714 1715 Node* GraphKit::access_load(Node* adr, // actual address to load val at 1716 const Type* val_type, 1717 BasicType bt, 1718 DecoratorSet decorators) { 1719 if (stopped()) { 1720 return top(); // Dead path ? 1721 } 1722 1723 C2AccessValuePtr addr(adr, adr->bottom_type()->is_ptr()); 1724 C2ParseAccess access(this, decorators | C2_READ_ACCESS, bt, nullptr, addr); 1725 if (access.is_raw()) { 1726 return _barrier_set->BarrierSetC2::load_at(access, val_type); 1727 } else { 1728 return _barrier_set->load_at(access, val_type); 1729 } 1730 } 1731 1732 Node* GraphKit::access_atomic_cmpxchg_val_at(Node* obj, 1733 Node* adr, 1734 const TypePtr* adr_type, 1735 int alias_idx, 1736 Node* expected_val, 1737 Node* new_val, 1738 const Type* value_type, 1739 BasicType bt, 1740 DecoratorSet decorators) { 1741 C2AccessValuePtr addr(adr, adr_type); 1742 C2AtomicParseAccess access(this, decorators | C2_READ_ACCESS | C2_WRITE_ACCESS, 1743 bt, obj, addr, alias_idx); 1744 if (access.is_raw()) { 1745 return _barrier_set->BarrierSetC2::atomic_cmpxchg_val_at(access, expected_val, new_val, value_type); 1746 } else { 1747 return _barrier_set->atomic_cmpxchg_val_at(access, expected_val, new_val, value_type); 1748 } 1749 } 1750 1751 Node* GraphKit::access_atomic_cmpxchg_bool_at(Node* obj, 1752 Node* adr, 1753 const TypePtr* adr_type, 1754 int alias_idx, 1755 Node* expected_val, 1756 Node* new_val, 1757 const Type* value_type, 1758 BasicType bt, 1759 DecoratorSet decorators) { 1760 C2AccessValuePtr addr(adr, adr_type); 1761 C2AtomicParseAccess access(this, decorators | C2_READ_ACCESS | C2_WRITE_ACCESS, 1762 bt, obj, addr, alias_idx); 1763 if (access.is_raw()) { 1764 return _barrier_set->BarrierSetC2::atomic_cmpxchg_bool_at(access, expected_val, new_val, value_type); 1765 } else { 1766 return _barrier_set->atomic_cmpxchg_bool_at(access, expected_val, new_val, value_type); 1767 } 1768 } 1769 1770 Node* GraphKit::access_atomic_xchg_at(Node* obj, 1771 Node* adr, 1772 const TypePtr* adr_type, 1773 int alias_idx, 1774 Node* new_val, 1775 const Type* value_type, 1776 BasicType bt, 1777 DecoratorSet decorators) { 1778 C2AccessValuePtr addr(adr, adr_type); 1779 C2AtomicParseAccess access(this, decorators | C2_READ_ACCESS | C2_WRITE_ACCESS, 1780 bt, obj, addr, alias_idx); 1781 if (access.is_raw()) { 1782 return _barrier_set->BarrierSetC2::atomic_xchg_at(access, new_val, value_type); 1783 } else { 1784 return _barrier_set->atomic_xchg_at(access, new_val, value_type); 1785 } 1786 } 1787 1788 Node* GraphKit::access_atomic_add_at(Node* obj, 1789 Node* adr, 1790 const TypePtr* adr_type, 1791 int alias_idx, 1792 Node* new_val, 1793 const Type* value_type, 1794 BasicType bt, 1795 DecoratorSet decorators) { 1796 C2AccessValuePtr addr(adr, adr_type); 1797 C2AtomicParseAccess access(this, decorators | C2_READ_ACCESS | C2_WRITE_ACCESS, bt, obj, addr, alias_idx); 1798 if (access.is_raw()) { 1799 return _barrier_set->BarrierSetC2::atomic_add_at(access, new_val, value_type); 1800 } else { 1801 return _barrier_set->atomic_add_at(access, new_val, value_type); 1802 } 1803 } 1804 1805 void GraphKit::access_clone(Node* src, Node* dst, Node* size, bool is_array) { 1806 return _barrier_set->clone(this, src, dst, size, is_array); 1807 } 1808 1809 //-------------------------array_element_address------------------------- 1810 Node* GraphKit::array_element_address(Node* ary, Node* idx, BasicType elembt, 1811 const TypeInt* sizetype, Node* ctrl) { 1812 const TypeAryPtr* arytype = _gvn.type(ary)->is_aryptr(); 1813 uint shift = arytype->is_flat() ? arytype->flat_log_elem_size() : exact_log2(type2aelembytes(elembt)); 1814 uint header = arrayOopDesc::base_offset_in_bytes(elembt); 1815 1816 // short-circuit a common case (saves lots of confusing waste motion) 1817 jint idx_con = find_int_con(idx, -1); 1818 if (idx_con >= 0) { 1819 intptr_t offset = header + ((intptr_t)idx_con << shift); 1820 return basic_plus_adr(ary, offset); 1821 } 1822 1823 // must be correct type for alignment purposes 1824 Node* base = basic_plus_adr(ary, header); 1825 idx = Compile::conv_I2X_index(&_gvn, idx, sizetype, ctrl); 1826 Node* scale = _gvn.transform( new LShiftXNode(idx, intcon(shift)) ); 1827 return basic_plus_adr(ary, base, scale); 1828 } 1829 1830 //-------------------------load_array_element------------------------- 1831 Node* GraphKit::load_array_element(Node* ary, Node* idx, const TypeAryPtr* arytype, bool set_ctrl) { 1832 const Type* elemtype = arytype->elem(); 1833 BasicType elembt = elemtype->array_element_basic_type(); 1834 assert(elembt != T_PRIMITIVE_OBJECT, "inline types are not supported by this method"); 1835 Node* adr = array_element_address(ary, idx, elembt, arytype->size()); 1836 if (elembt == T_NARROWOOP) { 1837 elembt = T_OBJECT; // To satisfy switch in LoadNode::make() 1838 } 1839 Node* ld = access_load_at(ary, adr, arytype, elemtype, elembt, 1840 IN_HEAP | IS_ARRAY | (set_ctrl ? C2_CONTROL_DEPENDENT_LOAD : 0)); 1841 return ld; 1842 } 1843 1844 //-------------------------set_arguments_for_java_call------------------------- 1845 // Arguments (pre-popped from the stack) are taken from the JVMS. 1846 void GraphKit::set_arguments_for_java_call(CallJavaNode* call, bool is_late_inline) { 1847 PreserveReexecuteState preexecs(this); 1848 if (EnableValhalla) { 1849 // Make sure the call is "re-executed", if buffering of inline type arguments triggers deoptimization. 1850 // At this point, the call hasn't been executed yet, so we will only ever execute the call once. 1851 jvms()->set_should_reexecute(true); 1852 int arg_size = method()->get_declared_signature_at_bci(bci())->arg_size_for_bc(java_bc()); 1853 inc_sp(arg_size); 1854 } 1855 // Add the call arguments 1856 const TypeTuple* domain = call->tf()->domain_sig(); 1857 uint nargs = domain->cnt(); 1858 int arg_num = 0; 1859 for (uint i = TypeFunc::Parms, idx = TypeFunc::Parms; i < nargs; i++) { 1860 Node* arg = argument(i-TypeFunc::Parms); 1861 const Type* t = domain->field_at(i); 1862 // TODO 8284443 A static call to a mismatched method should still be scalarized 1863 if (t->is_inlinetypeptr() && !call->method()->get_Method()->mismatch() && call->method()->is_scalarized_arg(arg_num)) { 1864 // We don't pass inline type arguments by reference but instead pass each field of the inline type 1865 if (!arg->is_InlineType()) { 1866 assert(_gvn.type(arg)->is_zero_type() && !t->inline_klass()->is_null_free(), "Unexpected argument type"); 1867 arg = InlineTypeNode::make_from_oop(this, arg, t->inline_klass(), t->inline_klass()->is_null_free()); 1868 } 1869 InlineTypeNode* vt = arg->as_InlineType(); 1870 vt->pass_fields(this, call, idx, true, !t->maybe_null()); 1871 // If an inline type argument is passed as fields, attach the Method* to the call site 1872 // to be able to access the extended signature later via attached_method_before_pc(). 1873 // For example, see CompiledMethod::preserve_callee_argument_oops(). 1874 call->set_override_symbolic_info(true); 1875 // Register an evol dependency on the callee method to make sure that this method is deoptimized and 1876 // re-compiled with a non-scalarized calling convention if the callee method is later marked as mismatched. 1877 C->dependencies()->assert_evol_method(call->method()); 1878 arg_num++; 1879 continue; 1880 } else if (arg->is_InlineType()) { 1881 // Pass inline type argument via oop to callee 1882 arg = arg->as_InlineType()->buffer(this); 1883 if (!is_late_inline) { 1884 arg = arg->as_InlineType()->get_oop(); 1885 } 1886 } 1887 if (t != Type::HALF) { 1888 arg_num++; 1889 } 1890 call->init_req(idx++, arg); 1891 } 1892 } 1893 1894 //---------------------------set_edges_for_java_call--------------------------- 1895 // Connect a newly created call into the current JVMS. 1896 // A return value node (if any) is returned from set_edges_for_java_call. 1897 void GraphKit::set_edges_for_java_call(CallJavaNode* call, bool must_throw, bool separate_io_proj) { 1898 1899 // Add the predefined inputs: 1900 call->init_req( TypeFunc::Control, control() ); 1901 call->init_req( TypeFunc::I_O , i_o() ); 1902 call->init_req( TypeFunc::Memory , reset_memory() ); 1903 call->init_req( TypeFunc::FramePtr, frameptr() ); 1904 call->init_req( TypeFunc::ReturnAdr, top() ); 1905 1906 add_safepoint_edges(call, must_throw); 1907 1908 Node* xcall = _gvn.transform(call); 1909 1910 if (xcall == top()) { 1911 set_control(top()); 1912 return; 1913 } 1914 assert(xcall == call, "call identity is stable"); 1915 1916 // Re-use the current map to produce the result. 1917 1918 set_control(_gvn.transform(new ProjNode(call, TypeFunc::Control))); 1919 set_i_o( _gvn.transform(new ProjNode(call, TypeFunc::I_O , separate_io_proj))); 1920 set_all_memory_call(xcall, separate_io_proj); 1921 1922 //return xcall; // no need, caller already has it 1923 } 1924 1925 Node* GraphKit::set_results_for_java_call(CallJavaNode* call, bool separate_io_proj, bool deoptimize) { 1926 if (stopped()) return top(); // maybe the call folded up? 1927 1928 // Note: Since any out-of-line call can produce an exception, 1929 // we always insert an I_O projection from the call into the result. 1930 1931 make_slow_call_ex(call, env()->Throwable_klass(), separate_io_proj, deoptimize); 1932 1933 if (separate_io_proj) { 1934 // The caller requested separate projections be used by the fall 1935 // through and exceptional paths, so replace the projections for 1936 // the fall through path. 1937 set_i_o(_gvn.transform( new ProjNode(call, TypeFunc::I_O) )); 1938 set_all_memory(_gvn.transform( new ProjNode(call, TypeFunc::Memory) )); 1939 } 1940 1941 // Capture the return value, if any. 1942 Node* ret; 1943 if (call->method() == nullptr || call->method()->return_type()->basic_type() == T_VOID) { 1944 ret = top(); 1945 } else if (call->tf()->returns_inline_type_as_fields()) { 1946 // Return of multiple values (inline type fields): we create a 1947 // InlineType node, each field is a projection from the call. 1948 ciInlineKlass* vk = call->method()->return_type()->as_inline_klass(); 1949 uint base_input = TypeFunc::Parms; 1950 ret = InlineTypeNode::make_from_multi(this, call, vk, base_input, false, call->method()->signature()->returns_null_free_inline_type()); 1951 } else { 1952 ret = _gvn.transform(new ProjNode(call, TypeFunc::Parms)); 1953 ciType* t = call->method()->return_type(); 1954 if (t->is_klass()) { 1955 const Type* type = TypeOopPtr::make_from_klass(t->as_klass()); 1956 if (type->is_inlinetypeptr()) { 1957 ret = InlineTypeNode::make_from_oop(this, ret, type->inline_klass(), type->inline_klass()->is_null_free()); 1958 } 1959 } 1960 } 1961 1962 return ret; 1963 } 1964 1965 //--------------------set_predefined_input_for_runtime_call-------------------- 1966 // Reading and setting the memory state is way conservative here. 1967 // The real problem is that I am not doing real Type analysis on memory, 1968 // so I cannot distinguish card mark stores from other stores. Across a GC 1969 // point the Store Barrier and the card mark memory has to agree. I cannot 1970 // have a card mark store and its barrier split across the GC point from 1971 // either above or below. Here I get that to happen by reading ALL of memory. 1972 // A better answer would be to separate out card marks from other memory. 1973 // For now, return the input memory state, so that it can be reused 1974 // after the call, if this call has restricted memory effects. 1975 Node* GraphKit::set_predefined_input_for_runtime_call(SafePointNode* call, Node* narrow_mem) { 1976 // Set fixed predefined input arguments 1977 Node* memory = reset_memory(); 1978 Node* m = narrow_mem == nullptr ? memory : narrow_mem; 1979 call->init_req( TypeFunc::Control, control() ); 1980 call->init_req( TypeFunc::I_O, top() ); // does no i/o 1981 call->init_req( TypeFunc::Memory, m ); // may gc ptrs 1982 call->init_req( TypeFunc::FramePtr, frameptr() ); 1983 call->init_req( TypeFunc::ReturnAdr, top() ); 1984 return memory; 1985 } 1986 1987 //-------------------set_predefined_output_for_runtime_call-------------------- 1988 // Set control and memory (not i_o) from the call. 1989 // If keep_mem is not null, use it for the output state, 1990 // except for the RawPtr output of the call, if hook_mem is TypeRawPtr::BOTTOM. 1991 // If hook_mem is null, this call produces no memory effects at all. 1992 // If hook_mem is a Java-visible memory slice (such as arraycopy operands), 1993 // then only that memory slice is taken from the call. 1994 // In the last case, we must put an appropriate memory barrier before 1995 // the call, so as to create the correct anti-dependencies on loads 1996 // preceding the call. 1997 void GraphKit::set_predefined_output_for_runtime_call(Node* call, 1998 Node* keep_mem, 1999 const TypePtr* hook_mem) { 2000 // no i/o 2001 set_control(_gvn.transform( new ProjNode(call,TypeFunc::Control) )); 2002 if (keep_mem) { 2003 // First clone the existing memory state 2004 set_all_memory(keep_mem); 2005 if (hook_mem != nullptr) { 2006 // Make memory for the call 2007 Node* mem = _gvn.transform( new ProjNode(call, TypeFunc::Memory) ); 2008 // Set the RawPtr memory state only. This covers all the heap top/GC stuff 2009 // We also use hook_mem to extract specific effects from arraycopy stubs. 2010 set_memory(mem, hook_mem); 2011 } 2012 // ...else the call has NO memory effects. 2013 2014 // Make sure the call advertises its memory effects precisely. 2015 // This lets us build accurate anti-dependences in gcm.cpp. 2016 assert(C->alias_type(call->adr_type()) == C->alias_type(hook_mem), 2017 "call node must be constructed correctly"); 2018 } else { 2019 assert(hook_mem == nullptr, ""); 2020 // This is not a "slow path" call; all memory comes from the call. 2021 set_all_memory_call(call); 2022 } 2023 } 2024 2025 // Keep track of MergeMems feeding into other MergeMems 2026 static void add_mergemem_users_to_worklist(Unique_Node_List& wl, Node* mem) { 2027 if (!mem->is_MergeMem()) { 2028 return; 2029 } 2030 for (SimpleDUIterator i(mem); i.has_next(); i.next()) { 2031 Node* use = i.get(); 2032 if (use->is_MergeMem()) { 2033 wl.push(use); 2034 } 2035 } 2036 } 2037 2038 // Replace the call with the current state of the kit. 2039 void GraphKit::replace_call(CallNode* call, Node* result, bool do_replaced_nodes) { 2040 JVMState* ejvms = nullptr; 2041 if (has_exceptions()) { 2042 ejvms = transfer_exceptions_into_jvms(); 2043 } 2044 2045 ReplacedNodes replaced_nodes = map()->replaced_nodes(); 2046 ReplacedNodes replaced_nodes_exception; 2047 Node* ex_ctl = top(); 2048 2049 SafePointNode* final_state = stop(); 2050 2051 // Find all the needed outputs of this call 2052 CallProjections* callprojs = call->extract_projections(true); 2053 2054 Unique_Node_List wl; 2055 Node* init_mem = call->in(TypeFunc::Memory); 2056 Node* final_mem = final_state->in(TypeFunc::Memory); 2057 Node* final_ctl = final_state->in(TypeFunc::Control); 2058 Node* final_io = final_state->in(TypeFunc::I_O); 2059 2060 // Replace all the old call edges with the edges from the inlining result 2061 if (callprojs->fallthrough_catchproj != nullptr) { 2062 C->gvn_replace_by(callprojs->fallthrough_catchproj, final_ctl); 2063 } 2064 if (callprojs->fallthrough_memproj != nullptr) { 2065 if (final_mem->is_MergeMem()) { 2066 // Parser's exits MergeMem was not transformed but may be optimized 2067 final_mem = _gvn.transform(final_mem); 2068 } 2069 C->gvn_replace_by(callprojs->fallthrough_memproj, final_mem); 2070 add_mergemem_users_to_worklist(wl, final_mem); 2071 } 2072 if (callprojs->fallthrough_ioproj != nullptr) { 2073 C->gvn_replace_by(callprojs->fallthrough_ioproj, final_io); 2074 } 2075 2076 // Replace the result with the new result if it exists and is used 2077 if (callprojs->resproj[0] != nullptr && result != nullptr) { 2078 // If the inlined code is dead, the result projections for an inline type returned as 2079 // fields have not been replaced. They will go away once the call is replaced by TOP below. 2080 assert(callprojs->nb_resproj == 1 || (call->tf()->returns_inline_type_as_fields() && stopped()), 2081 "unexpected number of results"); 2082 C->gvn_replace_by(callprojs->resproj[0], result); 2083 } 2084 2085 if (ejvms == nullptr) { 2086 // No exception edges to simply kill off those paths 2087 if (callprojs->catchall_catchproj != nullptr) { 2088 C->gvn_replace_by(callprojs->catchall_catchproj, C->top()); 2089 } 2090 if (callprojs->catchall_memproj != nullptr) { 2091 C->gvn_replace_by(callprojs->catchall_memproj, C->top()); 2092 } 2093 if (callprojs->catchall_ioproj != nullptr) { 2094 C->gvn_replace_by(callprojs->catchall_ioproj, C->top()); 2095 } 2096 // Replace the old exception object with top 2097 if (callprojs->exobj != nullptr) { 2098 C->gvn_replace_by(callprojs->exobj, C->top()); 2099 } 2100 } else { 2101 GraphKit ekit(ejvms); 2102 2103 // Load my combined exception state into the kit, with all phis transformed: 2104 SafePointNode* ex_map = ekit.combine_and_pop_all_exception_states(); 2105 replaced_nodes_exception = ex_map->replaced_nodes(); 2106 2107 Node* ex_oop = ekit.use_exception_state(ex_map); 2108 2109 if (callprojs->catchall_catchproj != nullptr) { 2110 C->gvn_replace_by(callprojs->catchall_catchproj, ekit.control()); 2111 ex_ctl = ekit.control(); 2112 } 2113 if (callprojs->catchall_memproj != nullptr) { 2114 Node* ex_mem = ekit.reset_memory(); 2115 C->gvn_replace_by(callprojs->catchall_memproj, ex_mem); 2116 add_mergemem_users_to_worklist(wl, ex_mem); 2117 } 2118 if (callprojs->catchall_ioproj != nullptr) { 2119 C->gvn_replace_by(callprojs->catchall_ioproj, ekit.i_o()); 2120 } 2121 2122 // Replace the old exception object with the newly created one 2123 if (callprojs->exobj != nullptr) { 2124 C->gvn_replace_by(callprojs->exobj, ex_oop); 2125 } 2126 } 2127 2128 // Disconnect the call from the graph 2129 call->disconnect_inputs(C); 2130 C->gvn_replace_by(call, C->top()); 2131 2132 // Clean up any MergeMems that feed other MergeMems since the 2133 // optimizer doesn't like that. 2134 while (wl.size() > 0) { 2135 _gvn.transform(wl.pop()); 2136 } 2137 2138 if (callprojs->fallthrough_catchproj != nullptr && !final_ctl->is_top() && do_replaced_nodes) { 2139 replaced_nodes.apply(C, final_ctl); 2140 } 2141 if (!ex_ctl->is_top() && do_replaced_nodes) { 2142 replaced_nodes_exception.apply(C, ex_ctl); 2143 } 2144 } 2145 2146 2147 //------------------------------increment_counter------------------------------ 2148 // for statistics: increment a VM counter by 1 2149 2150 void GraphKit::increment_counter(address counter_addr) { 2151 Node* adr1 = makecon(TypeRawPtr::make(counter_addr)); 2152 increment_counter(adr1); 2153 } 2154 2155 void GraphKit::increment_counter(Node* counter_addr) { 2156 int adr_type = Compile::AliasIdxRaw; 2157 Node* ctrl = control(); 2158 Node* cnt = make_load(ctrl, counter_addr, TypeLong::LONG, T_LONG, adr_type, MemNode::unordered); 2159 Node* incr = _gvn.transform(new AddLNode(cnt, _gvn.longcon(1))); 2160 store_to_memory(ctrl, counter_addr, incr, T_LONG, adr_type, MemNode::unordered); 2161 } 2162 2163 2164 //------------------------------uncommon_trap---------------------------------- 2165 // Bail out to the interpreter in mid-method. Implemented by calling the 2166 // uncommon_trap blob. This helper function inserts a runtime call with the 2167 // right debug info. 2168 Node* GraphKit::uncommon_trap(int trap_request, 2169 ciKlass* klass, const char* comment, 2170 bool must_throw, 2171 bool keep_exact_action) { 2172 if (failing()) stop(); 2173 if (stopped()) return nullptr; // trap reachable? 2174 2175 // Note: If ProfileTraps is true, and if a deopt. actually 2176 // occurs here, the runtime will make sure an MDO exists. There is 2177 // no need to call method()->ensure_method_data() at this point. 2178 2179 // Set the stack pointer to the right value for reexecution: 2180 set_sp(reexecute_sp()); 2181 2182 #ifdef ASSERT 2183 if (!must_throw) { 2184 // Make sure the stack has at least enough depth to execute 2185 // the current bytecode. 2186 int inputs, ignored_depth; 2187 if (compute_stack_effects(inputs, ignored_depth)) { 2188 assert(sp() >= inputs, "must have enough JVMS stack to execute %s: sp=%d, inputs=%d", 2189 Bytecodes::name(java_bc()), sp(), inputs); 2190 } 2191 } 2192 #endif 2193 2194 Deoptimization::DeoptReason reason = Deoptimization::trap_request_reason(trap_request); 2195 Deoptimization::DeoptAction action = Deoptimization::trap_request_action(trap_request); 2196 2197 switch (action) { 2198 case Deoptimization::Action_maybe_recompile: 2199 case Deoptimization::Action_reinterpret: 2200 // Temporary fix for 6529811 to allow virtual calls to be sure they 2201 // get the chance to go from mono->bi->mega 2202 if (!keep_exact_action && 2203 Deoptimization::trap_request_index(trap_request) < 0 && 2204 too_many_recompiles(reason)) { 2205 // This BCI is causing too many recompilations. 2206 if (C->log() != nullptr) { 2207 C->log()->elem("observe that='trap_action_change' reason='%s' from='%s' to='none'", 2208 Deoptimization::trap_reason_name(reason), 2209 Deoptimization::trap_action_name(action)); 2210 } 2211 action = Deoptimization::Action_none; 2212 trap_request = Deoptimization::make_trap_request(reason, action); 2213 } else { 2214 C->set_trap_can_recompile(true); 2215 } 2216 break; 2217 case Deoptimization::Action_make_not_entrant: 2218 C->set_trap_can_recompile(true); 2219 break; 2220 case Deoptimization::Action_none: 2221 case Deoptimization::Action_make_not_compilable: 2222 break; 2223 default: 2224 #ifdef ASSERT 2225 fatal("unknown action %d: %s", action, Deoptimization::trap_action_name(action)); 2226 #endif 2227 break; 2228 } 2229 2230 if (TraceOptoParse) { 2231 char buf[100]; 2232 tty->print_cr("Uncommon trap %s at bci:%d", 2233 Deoptimization::format_trap_request(buf, sizeof(buf), 2234 trap_request), bci()); 2235 } 2236 2237 CompileLog* log = C->log(); 2238 if (log != nullptr) { 2239 int kid = (klass == nullptr)? -1: log->identify(klass); 2240 log->begin_elem("uncommon_trap bci='%d'", bci()); 2241 char buf[100]; 2242 log->print(" %s", Deoptimization::format_trap_request(buf, sizeof(buf), 2243 trap_request)); 2244 if (kid >= 0) log->print(" klass='%d'", kid); 2245 if (comment != nullptr) log->print(" comment='%s'", comment); 2246 log->end_elem(); 2247 } 2248 2249 // Make sure any guarding test views this path as very unlikely 2250 Node *i0 = control()->in(0); 2251 if (i0 != nullptr && i0->is_If()) { // Found a guarding if test? 2252 IfNode *iff = i0->as_If(); 2253 float f = iff->_prob; // Get prob 2254 if (control()->Opcode() == Op_IfTrue) { 2255 if (f > PROB_UNLIKELY_MAG(4)) 2256 iff->_prob = PROB_MIN; 2257 } else { 2258 if (f < PROB_LIKELY_MAG(4)) 2259 iff->_prob = PROB_MAX; 2260 } 2261 } 2262 2263 // Clear out dead values from the debug info. 2264 kill_dead_locals(); 2265 2266 // Now insert the uncommon trap subroutine call 2267 address call_addr = SharedRuntime::uncommon_trap_blob()->entry_point(); 2268 const TypePtr* no_memory_effects = nullptr; 2269 // Pass the index of the class to be loaded 2270 Node* call = make_runtime_call(RC_NO_LEAF | RC_UNCOMMON | 2271 (must_throw ? RC_MUST_THROW : 0), 2272 OptoRuntime::uncommon_trap_Type(), 2273 call_addr, "uncommon_trap", no_memory_effects, 2274 intcon(trap_request)); 2275 assert(call->as_CallStaticJava()->uncommon_trap_request() == trap_request, 2276 "must extract request correctly from the graph"); 2277 assert(trap_request != 0, "zero value reserved by uncommon_trap_request"); 2278 2279 call->set_req(TypeFunc::ReturnAdr, returnadr()); 2280 // The debug info is the only real input to this call. 2281 2282 // Halt-and-catch fire here. The above call should never return! 2283 HaltNode* halt = new HaltNode(control(), frameptr(), "uncommon trap returned which should never happen" 2284 PRODUCT_ONLY(COMMA /*reachable*/false)); 2285 _gvn.set_type_bottom(halt); 2286 root()->add_req(halt); 2287 2288 stop_and_kill_map(); 2289 return call; 2290 } 2291 2292 2293 //--------------------------just_allocated_object------------------------------ 2294 // Report the object that was just allocated. 2295 // It must be the case that there are no intervening safepoints. 2296 // We use this to determine if an object is so "fresh" that 2297 // it does not require card marks. 2298 Node* GraphKit::just_allocated_object(Node* current_control) { 2299 Node* ctrl = current_control; 2300 // Object::<init> is invoked after allocation, most of invoke nodes 2301 // will be reduced, but a region node is kept in parse time, we check 2302 // the pattern and skip the region node if it degraded to a copy. 2303 if (ctrl != nullptr && ctrl->is_Region() && ctrl->req() == 2 && 2304 ctrl->as_Region()->is_copy()) { 2305 ctrl = ctrl->as_Region()->is_copy(); 2306 } 2307 if (C->recent_alloc_ctl() == ctrl) { 2308 return C->recent_alloc_obj(); 2309 } 2310 return nullptr; 2311 } 2312 2313 2314 /** 2315 * Record profiling data exact_kls for Node n with the type system so 2316 * that it can propagate it (speculation) 2317 * 2318 * @param n node that the type applies to 2319 * @param exact_kls type from profiling 2320 * @param maybe_null did profiling see null? 2321 * 2322 * @return node with improved type 2323 */ 2324 Node* GraphKit::record_profile_for_speculation(Node* n, ciKlass* exact_kls, ProfilePtrKind ptr_kind) { 2325 const Type* current_type = _gvn.type(n); 2326 assert(UseTypeSpeculation, "type speculation must be on"); 2327 2328 const TypePtr* speculative = current_type->speculative(); 2329 2330 // Should the klass from the profile be recorded in the speculative type? 2331 if (current_type->would_improve_type(exact_kls, jvms()->depth())) { 2332 const TypeKlassPtr* tklass = TypeKlassPtr::make(exact_kls, Type::trust_interfaces); 2333 const TypeOopPtr* xtype = tklass->as_instance_type(); 2334 assert(xtype->klass_is_exact(), "Should be exact"); 2335 // Any reason to believe n is not null (from this profiling or a previous one)? 2336 assert(ptr_kind != ProfileAlwaysNull, "impossible here"); 2337 const TypePtr* ptr = (ptr_kind != ProfileNeverNull && current_type->speculative_maybe_null()) ? TypePtr::BOTTOM : TypePtr::NOTNULL; 2338 // record the new speculative type's depth 2339 speculative = xtype->cast_to_ptr_type(ptr->ptr())->is_ptr(); 2340 speculative = speculative->with_inline_depth(jvms()->depth()); 2341 } else if (current_type->would_improve_ptr(ptr_kind)) { 2342 // Profiling report that null was never seen so we can change the 2343 // speculative type to non null ptr. 2344 if (ptr_kind == ProfileAlwaysNull) { 2345 speculative = TypePtr::NULL_PTR; 2346 } else { 2347 assert(ptr_kind == ProfileNeverNull, "nothing else is an improvement"); 2348 const TypePtr* ptr = TypePtr::NOTNULL; 2349 if (speculative != nullptr) { 2350 speculative = speculative->cast_to_ptr_type(ptr->ptr())->is_ptr(); 2351 } else { 2352 speculative = ptr; 2353 } 2354 } 2355 } 2356 2357 if (speculative != current_type->speculative()) { 2358 // Build a type with a speculative type (what we think we know 2359 // about the type but will need a guard when we use it) 2360 const TypeOopPtr* spec_type = TypeOopPtr::make(TypePtr::BotPTR, Type::Offset::bottom, TypeOopPtr::InstanceBot, speculative); 2361 // We're changing the type, we need a new CheckCast node to carry 2362 // the new type. The new type depends on the control: what 2363 // profiling tells us is only valid from here as far as we can 2364 // tell. 2365 Node* cast = new CheckCastPPNode(control(), n, current_type->remove_speculative()->join_speculative(spec_type)); 2366 cast = _gvn.transform(cast); 2367 replace_in_map(n, cast); 2368 n = cast; 2369 } 2370 2371 return n; 2372 } 2373 2374 /** 2375 * Record profiling data from receiver profiling at an invoke with the 2376 * type system so that it can propagate it (speculation) 2377 * 2378 * @param n receiver node 2379 * 2380 * @return node with improved type 2381 */ 2382 Node* GraphKit::record_profiled_receiver_for_speculation(Node* n) { 2383 if (!UseTypeSpeculation) { 2384 return n; 2385 } 2386 ciKlass* exact_kls = profile_has_unique_klass(); 2387 ProfilePtrKind ptr_kind = ProfileMaybeNull; 2388 if ((java_bc() == Bytecodes::_checkcast || 2389 java_bc() == Bytecodes::_instanceof || 2390 java_bc() == Bytecodes::_aastore) && 2391 method()->method_data()->is_mature()) { 2392 ciProfileData* data = method()->method_data()->bci_to_data(bci()); 2393 if (data != nullptr) { 2394 if (java_bc() == Bytecodes::_aastore) { 2395 ciKlass* array_type = nullptr; 2396 ciKlass* element_type = nullptr; 2397 ProfilePtrKind element_ptr = ProfileMaybeNull; 2398 bool flat_array = true; 2399 bool null_free_array = true; 2400 method()->array_access_profiled_type(bci(), array_type, element_type, element_ptr, flat_array, null_free_array); 2401 exact_kls = element_type; 2402 ptr_kind = element_ptr; 2403 } else { 2404 if (!data->as_BitData()->null_seen()) { 2405 ptr_kind = ProfileNeverNull; 2406 } else { 2407 assert(data->is_ReceiverTypeData(), "bad profile data type"); 2408 ciReceiverTypeData* call = (ciReceiverTypeData*)data->as_ReceiverTypeData(); 2409 uint i = 0; 2410 for (; i < call->row_limit(); i++) { 2411 ciKlass* receiver = call->receiver(i); 2412 if (receiver != nullptr) { 2413 break; 2414 } 2415 } 2416 ptr_kind = (i == call->row_limit()) ? ProfileAlwaysNull : ProfileMaybeNull; 2417 } 2418 } 2419 } 2420 } 2421 return record_profile_for_speculation(n, exact_kls, ptr_kind); 2422 } 2423 2424 /** 2425 * Record profiling data from argument profiling at an invoke with the 2426 * type system so that it can propagate it (speculation) 2427 * 2428 * @param dest_method target method for the call 2429 * @param bc what invoke bytecode is this? 2430 */ 2431 void GraphKit::record_profiled_arguments_for_speculation(ciMethod* dest_method, Bytecodes::Code bc) { 2432 if (!UseTypeSpeculation) { 2433 return; 2434 } 2435 const TypeFunc* tf = TypeFunc::make(dest_method); 2436 int nargs = tf->domain_sig()->cnt() - TypeFunc::Parms; 2437 int skip = Bytecodes::has_receiver(bc) ? 1 : 0; 2438 for (int j = skip, i = 0; j < nargs && i < TypeProfileArgsLimit; j++) { 2439 const Type *targ = tf->domain_sig()->field_at(j + TypeFunc::Parms); 2440 if (is_reference_type(targ->basic_type())) { 2441 ProfilePtrKind ptr_kind = ProfileMaybeNull; 2442 ciKlass* better_type = nullptr; 2443 if (method()->argument_profiled_type(bci(), i, better_type, ptr_kind)) { 2444 record_profile_for_speculation(argument(j), better_type, ptr_kind); 2445 } 2446 i++; 2447 } 2448 } 2449 } 2450 2451 /** 2452 * Record profiling data from parameter profiling at an invoke with 2453 * the type system so that it can propagate it (speculation) 2454 */ 2455 void GraphKit::record_profiled_parameters_for_speculation() { 2456 if (!UseTypeSpeculation) { 2457 return; 2458 } 2459 for (int i = 0, j = 0; i < method()->arg_size() ; i++) { 2460 if (_gvn.type(local(i))->isa_oopptr()) { 2461 ProfilePtrKind ptr_kind = ProfileMaybeNull; 2462 ciKlass* better_type = nullptr; 2463 if (method()->parameter_profiled_type(j, better_type, ptr_kind)) { 2464 record_profile_for_speculation(local(i), better_type, ptr_kind); 2465 } 2466 j++; 2467 } 2468 } 2469 } 2470 2471 /** 2472 * Record profiling data from return value profiling at an invoke with 2473 * the type system so that it can propagate it (speculation) 2474 */ 2475 void GraphKit::record_profiled_return_for_speculation() { 2476 if (!UseTypeSpeculation) { 2477 return; 2478 } 2479 ProfilePtrKind ptr_kind = ProfileMaybeNull; 2480 ciKlass* better_type = nullptr; 2481 if (method()->return_profiled_type(bci(), better_type, ptr_kind)) { 2482 // If profiling reports a single type for the return value, 2483 // feed it to the type system so it can propagate it as a 2484 // speculative type 2485 record_profile_for_speculation(stack(sp()-1), better_type, ptr_kind); 2486 } 2487 } 2488 2489 void GraphKit::round_double_arguments(ciMethod* dest_method) { 2490 if (Matcher::strict_fp_requires_explicit_rounding) { 2491 // (Note: TypeFunc::make has a cache that makes this fast.) 2492 const TypeFunc* tf = TypeFunc::make(dest_method); 2493 int nargs = tf->domain_sig()->cnt() - TypeFunc::Parms; 2494 for (int j = 0; j < nargs; j++) { 2495 const Type *targ = tf->domain_sig()->field_at(j + TypeFunc::Parms); 2496 if (targ->basic_type() == T_DOUBLE) { 2497 // If any parameters are doubles, they must be rounded before 2498 // the call, dprecision_rounding does gvn.transform 2499 Node *arg = argument(j); 2500 arg = dprecision_rounding(arg); 2501 set_argument(j, arg); 2502 } 2503 } 2504 } 2505 } 2506 2507 // rounding for strict float precision conformance 2508 Node* GraphKit::precision_rounding(Node* n) { 2509 if (Matcher::strict_fp_requires_explicit_rounding) { 2510 #ifdef IA32 2511 if (UseSSE == 0) { 2512 return _gvn.transform(new RoundFloatNode(0, n)); 2513 } 2514 #else 2515 Unimplemented(); 2516 #endif // IA32 2517 } 2518 return n; 2519 } 2520 2521 // rounding for strict double precision conformance 2522 Node* GraphKit::dprecision_rounding(Node *n) { 2523 if (Matcher::strict_fp_requires_explicit_rounding) { 2524 #ifdef IA32 2525 if (UseSSE < 2) { 2526 return _gvn.transform(new RoundDoubleNode(0, n)); 2527 } 2528 #else 2529 Unimplemented(); 2530 #endif // IA32 2531 } 2532 return n; 2533 } 2534 2535 //============================================================================= 2536 // Generate a fast path/slow path idiom. Graph looks like: 2537 // [foo] indicates that 'foo' is a parameter 2538 // 2539 // [in] null 2540 // \ / 2541 // CmpP 2542 // Bool ne 2543 // If 2544 // / \ 2545 // True False-<2> 2546 // / | 2547 // / cast_not_null 2548 // Load | | ^ 2549 // [fast_test] | | 2550 // gvn to opt_test | | 2551 // / \ | <1> 2552 // True False | 2553 // | \\ | 2554 // [slow_call] \[fast_result] 2555 // Ctl Val \ \ 2556 // | \ \ 2557 // Catch <1> \ \ 2558 // / \ ^ \ \ 2559 // Ex No_Ex | \ \ 2560 // | \ \ | \ <2> \ 2561 // ... \ [slow_res] | | \ [null_result] 2562 // \ \--+--+--- | | 2563 // \ | / \ | / 2564 // --------Region Phi 2565 // 2566 //============================================================================= 2567 // Code is structured as a series of driver functions all called 'do_XXX' that 2568 // call a set of helper functions. Helper functions first, then drivers. 2569 2570 //------------------------------null_check_oop--------------------------------- 2571 // Null check oop. Set null-path control into Region in slot 3. 2572 // Make a cast-not-nullness use the other not-null control. Return cast. 2573 Node* GraphKit::null_check_oop(Node* value, Node* *null_control, 2574 bool never_see_null, 2575 bool safe_for_replace, 2576 bool speculative) { 2577 // Initial null check taken path 2578 (*null_control) = top(); 2579 Node* cast = null_check_common(value, T_OBJECT, false, null_control, speculative); 2580 2581 // Generate uncommon_trap: 2582 if (never_see_null && (*null_control) != top()) { 2583 // If we see an unexpected null at a check-cast we record it and force a 2584 // recompile; the offending check-cast will be compiled to handle nulls. 2585 // If we see more than one offending BCI, then all checkcasts in the 2586 // method will be compiled to handle nulls. 2587 PreserveJVMState pjvms(this); 2588 set_control(*null_control); 2589 replace_in_map(value, null()); 2590 Deoptimization::DeoptReason reason = Deoptimization::reason_null_check(speculative); 2591 uncommon_trap(reason, 2592 Deoptimization::Action_make_not_entrant); 2593 (*null_control) = top(); // null path is dead 2594 } 2595 if ((*null_control) == top() && safe_for_replace) { 2596 replace_in_map(value, cast); 2597 } 2598 2599 // Cast away null-ness on the result 2600 return cast; 2601 } 2602 2603 //------------------------------opt_iff---------------------------------------- 2604 // Optimize the fast-check IfNode. Set the fast-path region slot 2. 2605 // Return slow-path control. 2606 Node* GraphKit::opt_iff(Node* region, Node* iff) { 2607 IfNode *opt_iff = _gvn.transform(iff)->as_If(); 2608 2609 // Fast path taken; set region slot 2 2610 Node *fast_taken = _gvn.transform( new IfFalseNode(opt_iff) ); 2611 region->init_req(2,fast_taken); // Capture fast-control 2612 2613 // Fast path not-taken, i.e. slow path 2614 Node *slow_taken = _gvn.transform( new IfTrueNode(opt_iff) ); 2615 return slow_taken; 2616 } 2617 2618 //-----------------------------make_runtime_call------------------------------- 2619 Node* GraphKit::make_runtime_call(int flags, 2620 const TypeFunc* call_type, address call_addr, 2621 const char* call_name, 2622 const TypePtr* adr_type, 2623 // The following parms are all optional. 2624 // The first null ends the list. 2625 Node* parm0, Node* parm1, 2626 Node* parm2, Node* parm3, 2627 Node* parm4, Node* parm5, 2628 Node* parm6, Node* parm7) { 2629 assert(call_addr != nullptr, "must not call null targets"); 2630 2631 // Slow-path call 2632 bool is_leaf = !(flags & RC_NO_LEAF); 2633 bool has_io = (!is_leaf && !(flags & RC_NO_IO)); 2634 if (call_name == nullptr) { 2635 assert(!is_leaf, "must supply name for leaf"); 2636 call_name = OptoRuntime::stub_name(call_addr); 2637 } 2638 CallNode* call; 2639 if (!is_leaf) { 2640 call = new CallStaticJavaNode(call_type, call_addr, call_name, adr_type); 2641 } else if (flags & RC_NO_FP) { 2642 call = new CallLeafNoFPNode(call_type, call_addr, call_name, adr_type); 2643 } else if (flags & RC_VECTOR){ 2644 uint num_bits = call_type->range_sig()->field_at(TypeFunc::Parms)->is_vect()->length_in_bytes() * BitsPerByte; 2645 call = new CallLeafVectorNode(call_type, call_addr, call_name, adr_type, num_bits); 2646 } else { 2647 call = new CallLeafNode(call_type, call_addr, call_name, adr_type); 2648 } 2649 2650 // The following is similar to set_edges_for_java_call, 2651 // except that the memory effects of the call are restricted to AliasIdxRaw. 2652 2653 // Slow path call has no side-effects, uses few values 2654 bool wide_in = !(flags & RC_NARROW_MEM); 2655 bool wide_out = (C->get_alias_index(adr_type) == Compile::AliasIdxBot); 2656 2657 Node* prev_mem = nullptr; 2658 if (wide_in) { 2659 prev_mem = set_predefined_input_for_runtime_call(call); 2660 } else { 2661 assert(!wide_out, "narrow in => narrow out"); 2662 Node* narrow_mem = memory(adr_type); 2663 prev_mem = set_predefined_input_for_runtime_call(call, narrow_mem); 2664 } 2665 2666 // Hook each parm in order. Stop looking at the first null. 2667 if (parm0 != nullptr) { call->init_req(TypeFunc::Parms+0, parm0); 2668 if (parm1 != nullptr) { call->init_req(TypeFunc::Parms+1, parm1); 2669 if (parm2 != nullptr) { call->init_req(TypeFunc::Parms+2, parm2); 2670 if (parm3 != nullptr) { call->init_req(TypeFunc::Parms+3, parm3); 2671 if (parm4 != nullptr) { call->init_req(TypeFunc::Parms+4, parm4); 2672 if (parm5 != nullptr) { call->init_req(TypeFunc::Parms+5, parm5); 2673 if (parm6 != nullptr) { call->init_req(TypeFunc::Parms+6, parm6); 2674 if (parm7 != nullptr) { call->init_req(TypeFunc::Parms+7, parm7); 2675 /* close each nested if ===> */ } } } } } } } } 2676 assert(call->in(call->req()-1) != nullptr, "must initialize all parms"); 2677 2678 if (!is_leaf) { 2679 // Non-leaves can block and take safepoints: 2680 add_safepoint_edges(call, ((flags & RC_MUST_THROW) != 0)); 2681 } 2682 // Non-leaves can throw exceptions: 2683 if (has_io) { 2684 call->set_req(TypeFunc::I_O, i_o()); 2685 } 2686 2687 if (flags & RC_UNCOMMON) { 2688 // Set the count to a tiny probability. Cf. Estimate_Block_Frequency. 2689 // (An "if" probability corresponds roughly to an unconditional count. 2690 // Sort of.) 2691 call->set_cnt(PROB_UNLIKELY_MAG(4)); 2692 } 2693 2694 Node* c = _gvn.transform(call); 2695 assert(c == call, "cannot disappear"); 2696 2697 if (wide_out) { 2698 // Slow path call has full side-effects. 2699 set_predefined_output_for_runtime_call(call); 2700 } else { 2701 // Slow path call has few side-effects, and/or sets few values. 2702 set_predefined_output_for_runtime_call(call, prev_mem, adr_type); 2703 } 2704 2705 if (has_io) { 2706 set_i_o(_gvn.transform(new ProjNode(call, TypeFunc::I_O))); 2707 } 2708 return call; 2709 2710 } 2711 2712 // i2b 2713 Node* GraphKit::sign_extend_byte(Node* in) { 2714 Node* tmp = _gvn.transform(new LShiftINode(in, _gvn.intcon(24))); 2715 return _gvn.transform(new RShiftINode(tmp, _gvn.intcon(24))); 2716 } 2717 2718 // i2s 2719 Node* GraphKit::sign_extend_short(Node* in) { 2720 Node* tmp = _gvn.transform(new LShiftINode(in, _gvn.intcon(16))); 2721 return _gvn.transform(new RShiftINode(tmp, _gvn.intcon(16))); 2722 } 2723 2724 2725 //------------------------------merge_memory----------------------------------- 2726 // Merge memory from one path into the current memory state. 2727 void GraphKit::merge_memory(Node* new_mem, Node* region, int new_path) { 2728 for (MergeMemStream mms(merged_memory(), new_mem->as_MergeMem()); mms.next_non_empty2(); ) { 2729 Node* old_slice = mms.force_memory(); 2730 Node* new_slice = mms.memory2(); 2731 if (old_slice != new_slice) { 2732 PhiNode* phi; 2733 if (old_slice->is_Phi() && old_slice->as_Phi()->region() == region) { 2734 if (mms.is_empty()) { 2735 // clone base memory Phi's inputs for this memory slice 2736 assert(old_slice == mms.base_memory(), "sanity"); 2737 phi = PhiNode::make(region, nullptr, Type::MEMORY, mms.adr_type(C)); 2738 _gvn.set_type(phi, Type::MEMORY); 2739 for (uint i = 1; i < phi->req(); i++) { 2740 phi->init_req(i, old_slice->in(i)); 2741 } 2742 } else { 2743 phi = old_slice->as_Phi(); // Phi was generated already 2744 } 2745 } else { 2746 phi = PhiNode::make(region, old_slice, Type::MEMORY, mms.adr_type(C)); 2747 _gvn.set_type(phi, Type::MEMORY); 2748 } 2749 phi->set_req(new_path, new_slice); 2750 mms.set_memory(phi); 2751 } 2752 } 2753 } 2754 2755 //------------------------------make_slow_call_ex------------------------------ 2756 // Make the exception handler hookups for the slow call 2757 void GraphKit::make_slow_call_ex(Node* call, ciInstanceKlass* ex_klass, bool separate_io_proj, bool deoptimize) { 2758 if (stopped()) return; 2759 2760 // Make a catch node with just two handlers: fall-through and catch-all 2761 Node* i_o = _gvn.transform( new ProjNode(call, TypeFunc::I_O, separate_io_proj) ); 2762 Node* catc = _gvn.transform( new CatchNode(control(), i_o, 2) ); 2763 Node* norm = new CatchProjNode(catc, CatchProjNode::fall_through_index, CatchProjNode::no_handler_bci); 2764 _gvn.set_type_bottom(norm); 2765 C->record_for_igvn(norm); 2766 Node* excp = _gvn.transform( new CatchProjNode(catc, CatchProjNode::catch_all_index, CatchProjNode::no_handler_bci) ); 2767 2768 { PreserveJVMState pjvms(this); 2769 set_control(excp); 2770 set_i_o(i_o); 2771 2772 if (excp != top()) { 2773 if (deoptimize) { 2774 // Deoptimize if an exception is caught. Don't construct exception state in this case. 2775 uncommon_trap(Deoptimization::Reason_unhandled, 2776 Deoptimization::Action_none); 2777 } else { 2778 // Create an exception state also. 2779 // Use an exact type if the caller has a specific exception. 2780 const Type* ex_type = TypeOopPtr::make_from_klass_unique(ex_klass)->cast_to_ptr_type(TypePtr::NotNull); 2781 Node* ex_oop = new CreateExNode(ex_type, control(), i_o); 2782 add_exception_state(make_exception_state(_gvn.transform(ex_oop))); 2783 } 2784 } 2785 } 2786 2787 // Get the no-exception control from the CatchNode. 2788 set_control(norm); 2789 } 2790 2791 static IfNode* gen_subtype_check_compare(Node* ctrl, Node* in1, Node* in2, BoolTest::mask test, float p, PhaseGVN& gvn, BasicType bt) { 2792 Node* cmp = nullptr; 2793 switch(bt) { 2794 case T_INT: cmp = new CmpINode(in1, in2); break; 2795 case T_ADDRESS: cmp = new CmpPNode(in1, in2); break; 2796 default: fatal("unexpected comparison type %s", type2name(bt)); 2797 } 2798 cmp = gvn.transform(cmp); 2799 Node* bol = gvn.transform(new BoolNode(cmp, test)); 2800 IfNode* iff = new IfNode(ctrl, bol, p, COUNT_UNKNOWN); 2801 gvn.transform(iff); 2802 if (!bol->is_Con()) gvn.record_for_igvn(iff); 2803 return iff; 2804 } 2805 2806 //-------------------------------gen_subtype_check----------------------------- 2807 // Generate a subtyping check. Takes as input the subtype and supertype. 2808 // Returns 2 values: sets the default control() to the true path and returns 2809 // the false path. Only reads invariant memory; sets no (visible) memory. 2810 // The PartialSubtypeCheckNode sets the hidden 1-word cache in the encoding 2811 // but that's not exposed to the optimizer. This call also doesn't take in an 2812 // Object; if you wish to check an Object you need to load the Object's class 2813 // prior to coming here. 2814 Node* Phase::gen_subtype_check(Node* subklass, Node* superklass, Node** ctrl, Node* mem, PhaseGVN& gvn) { 2815 Compile* C = gvn.C; 2816 if ((*ctrl)->is_top()) { 2817 return C->top(); 2818 } 2819 2820 // Fast check for identical types, perhaps identical constants. 2821 // The types can even be identical non-constants, in cases 2822 // involving Array.newInstance, Object.clone, etc. 2823 if (subklass == superklass) 2824 return C->top(); // false path is dead; no test needed. 2825 2826 if (gvn.type(superklass)->singleton()) { 2827 const TypeKlassPtr* superk = gvn.type(superklass)->is_klassptr(); 2828 const TypeKlassPtr* subk = gvn.type(subklass)->is_klassptr(); 2829 2830 // In the common case of an exact superklass, try to fold up the 2831 // test before generating code. You may ask, why not just generate 2832 // the code and then let it fold up? The answer is that the generated 2833 // code will necessarily include null checks, which do not always 2834 // completely fold away. If they are also needless, then they turn 2835 // into a performance loss. Example: 2836 // Foo[] fa = blah(); Foo x = fa[0]; fa[1] = x; 2837 // Here, the type of 'fa' is often exact, so the store check 2838 // of fa[1]=x will fold up, without testing the nullness of x. 2839 switch (C->static_subtype_check(superk, subk)) { 2840 case Compile::SSC_always_false: 2841 { 2842 Node* always_fail = *ctrl; 2843 *ctrl = gvn.C->top(); 2844 return always_fail; 2845 } 2846 case Compile::SSC_always_true: 2847 return C->top(); 2848 case Compile::SSC_easy_test: 2849 { 2850 // Just do a direct pointer compare and be done. 2851 IfNode* iff = gen_subtype_check_compare(*ctrl, subklass, superklass, BoolTest::eq, PROB_STATIC_FREQUENT, gvn, T_ADDRESS); 2852 *ctrl = gvn.transform(new IfTrueNode(iff)); 2853 return gvn.transform(new IfFalseNode(iff)); 2854 } 2855 case Compile::SSC_full_test: 2856 break; 2857 default: 2858 ShouldNotReachHere(); 2859 } 2860 } 2861 2862 // %%% Possible further optimization: Even if the superklass is not exact, 2863 // if the subklass is the unique subtype of the superklass, the check 2864 // will always succeed. We could leave a dependency behind to ensure this. 2865 2866 // First load the super-klass's check-offset 2867 Node *p1 = gvn.transform(new AddPNode(superklass, superklass, gvn.MakeConX(in_bytes(Klass::super_check_offset_offset())))); 2868 Node* m = C->immutable_memory(); 2869 Node *chk_off = gvn.transform(new LoadINode(nullptr, m, p1, gvn.type(p1)->is_ptr(), TypeInt::INT, MemNode::unordered)); 2870 int cacheoff_con = in_bytes(Klass::secondary_super_cache_offset()); 2871 bool might_be_cache = (gvn.find_int_con(chk_off, cacheoff_con) == cacheoff_con); 2872 2873 // Load from the sub-klass's super-class display list, or a 1-word cache of 2874 // the secondary superclass list, or a failing value with a sentinel offset 2875 // if the super-klass is an interface or exceptionally deep in the Java 2876 // hierarchy and we have to scan the secondary superclass list the hard way. 2877 // Worst-case type is a little odd: null is allowed as a result (usually 2878 // klass loads can never produce a null). 2879 Node *chk_off_X = chk_off; 2880 #ifdef _LP64 2881 chk_off_X = gvn.transform(new ConvI2LNode(chk_off_X)); 2882 #endif 2883 Node *p2 = gvn.transform(new AddPNode(subklass,subklass,chk_off_X)); 2884 // For some types like interfaces the following loadKlass is from a 1-word 2885 // cache which is mutable so can't use immutable memory. Other 2886 // types load from the super-class display table which is immutable. 2887 Node *kmem = C->immutable_memory(); 2888 // secondary_super_cache is not immutable but can be treated as such because: 2889 // - no ideal node writes to it in a way that could cause an 2890 // incorrect/missed optimization of the following Load. 2891 // - it's a cache so, worse case, not reading the latest value 2892 // wouldn't cause incorrect execution 2893 if (might_be_cache && mem != nullptr) { 2894 kmem = mem->is_MergeMem() ? mem->as_MergeMem()->memory_at(C->get_alias_index(gvn.type(p2)->is_ptr())) : mem; 2895 } 2896 Node *nkls = gvn.transform(LoadKlassNode::make(gvn, nullptr, kmem, p2, gvn.type(p2)->is_ptr(), TypeInstKlassPtr::OBJECT_OR_NULL)); 2897 2898 // Compile speed common case: ARE a subtype and we canNOT fail 2899 if( superklass == nkls ) 2900 return C->top(); // false path is dead; no test needed. 2901 2902 // See if we get an immediate positive hit. Happens roughly 83% of the 2903 // time. Test to see if the value loaded just previously from the subklass 2904 // is exactly the superklass. 2905 IfNode *iff1 = gen_subtype_check_compare(*ctrl, superklass, nkls, BoolTest::eq, PROB_LIKELY(0.83f), gvn, T_ADDRESS); 2906 Node *iftrue1 = gvn.transform( new IfTrueNode (iff1)); 2907 *ctrl = gvn.transform(new IfFalseNode(iff1)); 2908 2909 // Compile speed common case: Check for being deterministic right now. If 2910 // chk_off is a constant and not equal to cacheoff then we are NOT a 2911 // subklass. In this case we need exactly the 1 test above and we can 2912 // return those results immediately. 2913 if (!might_be_cache) { 2914 Node* not_subtype_ctrl = *ctrl; 2915 *ctrl = iftrue1; // We need exactly the 1 test above 2916 return not_subtype_ctrl; 2917 } 2918 2919 // Gather the various success & failures here 2920 RegionNode *r_ok_subtype = new RegionNode(4); 2921 gvn.record_for_igvn(r_ok_subtype); 2922 RegionNode *r_not_subtype = new RegionNode(3); 2923 gvn.record_for_igvn(r_not_subtype); 2924 2925 r_ok_subtype->init_req(1, iftrue1); 2926 2927 // Check for immediate negative hit. Happens roughly 11% of the time (which 2928 // is roughly 63% of the remaining cases). Test to see if the loaded 2929 // check-offset points into the subklass display list or the 1-element 2930 // cache. If it points to the display (and NOT the cache) and the display 2931 // missed then it's not a subtype. 2932 Node *cacheoff = gvn.intcon(cacheoff_con); 2933 IfNode *iff2 = gen_subtype_check_compare(*ctrl, chk_off, cacheoff, BoolTest::ne, PROB_LIKELY(0.63f), gvn, T_INT); 2934 r_not_subtype->init_req(1, gvn.transform(new IfTrueNode (iff2))); 2935 *ctrl = gvn.transform(new IfFalseNode(iff2)); 2936 2937 // Check for self. Very rare to get here, but it is taken 1/3 the time. 2938 // No performance impact (too rare) but allows sharing of secondary arrays 2939 // which has some footprint reduction. 2940 IfNode *iff3 = gen_subtype_check_compare(*ctrl, subklass, superklass, BoolTest::eq, PROB_LIKELY(0.36f), gvn, T_ADDRESS); 2941 r_ok_subtype->init_req(2, gvn.transform(new IfTrueNode(iff3))); 2942 *ctrl = gvn.transform(new IfFalseNode(iff3)); 2943 2944 // -- Roads not taken here: -- 2945 // We could also have chosen to perform the self-check at the beginning 2946 // of this code sequence, as the assembler does. This would not pay off 2947 // the same way, since the optimizer, unlike the assembler, can perform 2948 // static type analysis to fold away many successful self-checks. 2949 // Non-foldable self checks work better here in second position, because 2950 // the initial primary superclass check subsumes a self-check for most 2951 // types. An exception would be a secondary type like array-of-interface, 2952 // which does not appear in its own primary supertype display. 2953 // Finally, we could have chosen to move the self-check into the 2954 // PartialSubtypeCheckNode, and from there out-of-line in a platform 2955 // dependent manner. But it is worthwhile to have the check here, 2956 // where it can be perhaps be optimized. The cost in code space is 2957 // small (register compare, branch). 2958 2959 // Now do a linear scan of the secondary super-klass array. Again, no real 2960 // performance impact (too rare) but it's gotta be done. 2961 // Since the code is rarely used, there is no penalty for moving it 2962 // out of line, and it can only improve I-cache density. 2963 // The decision to inline or out-of-line this final check is platform 2964 // dependent, and is found in the AD file definition of PartialSubtypeCheck. 2965 Node* psc = gvn.transform( 2966 new PartialSubtypeCheckNode(*ctrl, subklass, superklass)); 2967 2968 IfNode *iff4 = gen_subtype_check_compare(*ctrl, psc, gvn.zerocon(T_OBJECT), BoolTest::ne, PROB_FAIR, gvn, T_ADDRESS); 2969 r_not_subtype->init_req(2, gvn.transform(new IfTrueNode (iff4))); 2970 r_ok_subtype ->init_req(3, gvn.transform(new IfFalseNode(iff4))); 2971 2972 // Return false path; set default control to true path. 2973 *ctrl = gvn.transform(r_ok_subtype); 2974 return gvn.transform(r_not_subtype); 2975 } 2976 2977 Node* GraphKit::gen_subtype_check(Node* obj_or_subklass, Node* superklass) { 2978 const Type* sub_t = _gvn.type(obj_or_subklass); 2979 if (sub_t->make_oopptr() != nullptr && sub_t->make_oopptr()->is_inlinetypeptr()) { 2980 sub_t = TypeKlassPtr::make(sub_t->inline_klass()); 2981 obj_or_subklass = makecon(sub_t); 2982 } 2983 bool expand_subtype_check = C->post_loop_opts_phase() || // macro node expansion is over 2984 ExpandSubTypeCheckAtParseTime; // forced expansion 2985 if (expand_subtype_check) { 2986 MergeMemNode* mem = merged_memory(); 2987 Node* ctrl = control(); 2988 Node* subklass = obj_or_subklass; 2989 if (!sub_t->isa_klassptr()) { 2990 subklass = load_object_klass(obj_or_subklass); 2991 } 2992 Node* n = Phase::gen_subtype_check(subklass, superklass, &ctrl, mem, _gvn); 2993 set_control(ctrl); 2994 return n; 2995 } 2996 2997 Node* check = _gvn.transform(new SubTypeCheckNode(C, obj_or_subklass, superklass)); 2998 Node* bol = _gvn.transform(new BoolNode(check, BoolTest::eq)); 2999 IfNode* iff = create_and_xform_if(control(), bol, PROB_STATIC_FREQUENT, COUNT_UNKNOWN); 3000 set_control(_gvn.transform(new IfTrueNode(iff))); 3001 return _gvn.transform(new IfFalseNode(iff)); 3002 } 3003 3004 // Profile-driven exact type check: 3005 Node* GraphKit::type_check_receiver(Node* receiver, ciKlass* klass, 3006 float prob, Node* *casted_receiver) { 3007 assert(!klass->is_interface(), "no exact type check on interfaces"); 3008 Node* fail = top(); 3009 const Type* rec_t = _gvn.type(receiver); 3010 if (rec_t->is_inlinetypeptr()) { 3011 if (klass->equals(rec_t->inline_klass())) { 3012 (*casted_receiver) = receiver; // Always passes 3013 } else { 3014 (*casted_receiver) = top(); // Always fails 3015 fail = control(); 3016 set_control(top()); 3017 } 3018 return fail; 3019 } 3020 const TypeKlassPtr* tklass = TypeKlassPtr::make(klass, Type::trust_interfaces); 3021 Node* recv_klass = load_object_klass(receiver); 3022 fail = type_check(recv_klass, tklass, prob); 3023 3024 if (!stopped()) { 3025 const TypeOopPtr* receiver_type = _gvn.type(receiver)->isa_oopptr(); 3026 const TypeOopPtr* recv_xtype = tklass->as_instance_type(); 3027 assert(recv_xtype->klass_is_exact(), ""); 3028 3029 if (!receiver_type->higher_equal(recv_xtype)) { // ignore redundant casts 3030 // Subsume downstream occurrences of receiver with a cast to 3031 // recv_xtype, since now we know what the type will be. 3032 Node* cast = new CheckCastPPNode(control(), receiver, recv_xtype); 3033 Node* res = _gvn.transform(cast); 3034 if (recv_xtype->is_inlinetypeptr()) { 3035 assert(!gvn().type(res)->maybe_null(), "receiver should never be null"); 3036 res = InlineTypeNode::make_from_oop(this, res, recv_xtype->inline_klass()); 3037 } 3038 (*casted_receiver) = res; 3039 assert(!(*casted_receiver)->is_top(), "that path should be unreachable"); 3040 // (User must make the replace_in_map call.) 3041 } 3042 } 3043 3044 return fail; 3045 } 3046 3047 Node* GraphKit::type_check(Node* recv_klass, const TypeKlassPtr* tklass, 3048 float prob) { 3049 Node* want_klass = makecon(tklass); 3050 Node* cmp = _gvn.transform(new CmpPNode(recv_klass, want_klass)); 3051 Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::eq)); 3052 IfNode* iff = create_and_xform_if(control(), bol, prob, COUNT_UNKNOWN); 3053 set_control(_gvn.transform(new IfTrueNode (iff))); 3054 Node* fail = _gvn.transform(new IfFalseNode(iff)); 3055 return fail; 3056 } 3057 3058 //------------------------------subtype_check_receiver------------------------- 3059 Node* GraphKit::subtype_check_receiver(Node* receiver, ciKlass* klass, 3060 Node** casted_receiver) { 3061 const TypeKlassPtr* tklass = TypeKlassPtr::make(klass, Type::trust_interfaces)->try_improve(); 3062 Node* want_klass = makecon(tklass); 3063 3064 Node* slow_ctl = gen_subtype_check(receiver, want_klass); 3065 3066 // Ignore interface type information until interface types are properly tracked. 3067 if (!stopped() && !klass->is_interface()) { 3068 const TypeOopPtr* receiver_type = _gvn.type(receiver)->isa_oopptr(); 3069 const TypeOopPtr* recv_type = tklass->cast_to_exactness(false)->is_klassptr()->as_instance_type(); 3070 if (receiver_type != nullptr && !receiver_type->higher_equal(recv_type)) { // ignore redundant casts 3071 Node* cast = _gvn.transform(new CheckCastPPNode(control(), receiver, recv_type)); 3072 if (recv_type->is_inlinetypeptr()) { 3073 cast = InlineTypeNode::make_from_oop(this, cast, recv_type->inline_klass()); 3074 } 3075 (*casted_receiver) = cast; 3076 } 3077 } 3078 3079 return slow_ctl; 3080 } 3081 3082 //------------------------------seems_never_null------------------------------- 3083 // Use null_seen information if it is available from the profile. 3084 // If we see an unexpected null at a type check we record it and force a 3085 // recompile; the offending check will be recompiled to handle nulls. 3086 // If we see several offending BCIs, then all checks in the 3087 // method will be recompiled. 3088 bool GraphKit::seems_never_null(Node* obj, ciProfileData* data, bool& speculating) { 3089 speculating = !_gvn.type(obj)->speculative_maybe_null(); 3090 Deoptimization::DeoptReason reason = Deoptimization::reason_null_check(speculating); 3091 if (UncommonNullCast // Cutout for this technique 3092 && obj != null() // And not the -Xcomp stupid case? 3093 && !too_many_traps(reason) 3094 ) { 3095 if (speculating) { 3096 return true; 3097 } 3098 if (data == nullptr) 3099 // Edge case: no mature data. Be optimistic here. 3100 return true; 3101 // If the profile has not seen a null, assume it won't happen. 3102 assert(java_bc() == Bytecodes::_checkcast || 3103 java_bc() == Bytecodes::_instanceof || 3104 java_bc() == Bytecodes::_aastore, "MDO must collect null_seen bit here"); 3105 if (java_bc() == Bytecodes::_aastore) { 3106 return ((ciArrayLoadStoreData*)data->as_ArrayLoadStoreData())->element()->ptr_kind() == ProfileNeverNull; 3107 } 3108 return !data->as_BitData()->null_seen(); 3109 } 3110 speculating = false; 3111 return false; 3112 } 3113 3114 void GraphKit::guard_klass_being_initialized(Node* klass) { 3115 int init_state_off = in_bytes(InstanceKlass::init_state_offset()); 3116 Node* adr = basic_plus_adr(top(), klass, init_state_off); 3117 Node* init_state = LoadNode::make(_gvn, nullptr, immutable_memory(), adr, 3118 adr->bottom_type()->is_ptr(), TypeInt::BYTE, 3119 T_BYTE, MemNode::unordered); 3120 init_state = _gvn.transform(init_state); 3121 3122 Node* being_initialized_state = makecon(TypeInt::make(InstanceKlass::being_initialized)); 3123 3124 Node* chk = _gvn.transform(new CmpINode(being_initialized_state, init_state)); 3125 Node* tst = _gvn.transform(new BoolNode(chk, BoolTest::eq)); 3126 3127 { BuildCutout unless(this, tst, PROB_MAX); 3128 uncommon_trap(Deoptimization::Reason_initialized, Deoptimization::Action_reinterpret); 3129 } 3130 } 3131 3132 void GraphKit::guard_init_thread(Node* klass) { 3133 int init_thread_off = in_bytes(InstanceKlass::init_thread_offset()); 3134 Node* adr = basic_plus_adr(top(), klass, init_thread_off); 3135 3136 Node* init_thread = LoadNode::make(_gvn, nullptr, immutable_memory(), adr, 3137 adr->bottom_type()->is_ptr(), TypePtr::NOTNULL, 3138 T_ADDRESS, MemNode::unordered); 3139 init_thread = _gvn.transform(init_thread); 3140 3141 Node* cur_thread = _gvn.transform(new ThreadLocalNode()); 3142 3143 Node* chk = _gvn.transform(new CmpPNode(cur_thread, init_thread)); 3144 Node* tst = _gvn.transform(new BoolNode(chk, BoolTest::eq)); 3145 3146 { BuildCutout unless(this, tst, PROB_MAX); 3147 uncommon_trap(Deoptimization::Reason_uninitialized, Deoptimization::Action_none); 3148 } 3149 } 3150 3151 void GraphKit::clinit_barrier(ciInstanceKlass* ik, ciMethod* context) { 3152 if (ik->is_being_initialized()) { 3153 if (C->needs_clinit_barrier(ik, context)) { 3154 Node* klass = makecon(TypeKlassPtr::make(ik)); 3155 guard_klass_being_initialized(klass); 3156 guard_init_thread(klass); 3157 insert_mem_bar(Op_MemBarCPUOrder); 3158 } 3159 } else if (ik->is_initialized()) { 3160 return; // no barrier needed 3161 } else { 3162 uncommon_trap(Deoptimization::Reason_uninitialized, 3163 Deoptimization::Action_reinterpret, 3164 nullptr); 3165 } 3166 } 3167 3168 //------------------------maybe_cast_profiled_receiver------------------------- 3169 // If the profile has seen exactly one type, narrow to exactly that type. 3170 // Subsequent type checks will always fold up. 3171 Node* GraphKit::maybe_cast_profiled_receiver(Node* not_null_obj, 3172 const TypeKlassPtr* require_klass, 3173 ciKlass* spec_klass, 3174 bool safe_for_replace) { 3175 if (!UseTypeProfile || !TypeProfileCasts) return nullptr; 3176 3177 Deoptimization::DeoptReason reason = Deoptimization::reason_class_check(spec_klass != nullptr); 3178 3179 // Make sure we haven't already deoptimized from this tactic. 3180 if (too_many_traps_or_recompiles(reason)) 3181 return nullptr; 3182 3183 // (No, this isn't a call, but it's enough like a virtual call 3184 // to use the same ciMethod accessor to get the profile info...) 3185 // If we have a speculative type use it instead of profiling (which 3186 // may not help us) 3187 ciKlass* exact_kls = spec_klass; 3188 if (exact_kls == nullptr) { 3189 if (java_bc() == Bytecodes::_aastore) { 3190 ciKlass* array_type = nullptr; 3191 ciKlass* element_type = nullptr; 3192 ProfilePtrKind element_ptr = ProfileMaybeNull; 3193 bool flat_array = true; 3194 bool null_free_array = true; 3195 method()->array_access_profiled_type(bci(), array_type, element_type, element_ptr, flat_array, null_free_array); 3196 exact_kls = element_type; 3197 } else { 3198 exact_kls = profile_has_unique_klass(); 3199 } 3200 } 3201 if (exact_kls != nullptr) {// no cast failures here 3202 if (require_klass == nullptr || 3203 C->static_subtype_check(require_klass, TypeKlassPtr::make(exact_kls, Type::trust_interfaces)) == Compile::SSC_always_true) { 3204 // If we narrow the type to match what the type profile sees or 3205 // the speculative type, we can then remove the rest of the 3206 // cast. 3207 // This is a win, even if the exact_kls is very specific, 3208 // because downstream operations, such as method calls, 3209 // will often benefit from the sharper type. 3210 Node* exact_obj = not_null_obj; // will get updated in place... 3211 Node* slow_ctl = type_check_receiver(exact_obj, exact_kls, 1.0, 3212 &exact_obj); 3213 { PreserveJVMState pjvms(this); 3214 set_control(slow_ctl); 3215 uncommon_trap_exact(reason, Deoptimization::Action_maybe_recompile); 3216 } 3217 if (safe_for_replace) { 3218 replace_in_map(not_null_obj, exact_obj); 3219 } 3220 return exact_obj; 3221 } 3222 // assert(ssc == Compile::SSC_always_true)... except maybe the profile lied to us. 3223 } 3224 3225 return nullptr; 3226 } 3227 3228 /** 3229 * Cast obj to type and emit guard unless we had too many traps here 3230 * already 3231 * 3232 * @param obj node being casted 3233 * @param type type to cast the node to 3234 * @param not_null true if we know node cannot be null 3235 */ 3236 Node* GraphKit::maybe_cast_profiled_obj(Node* obj, 3237 ciKlass* type, 3238 bool not_null) { 3239 if (stopped()) { 3240 return obj; 3241 } 3242 3243 // type is null if profiling tells us this object is always null 3244 if (type != nullptr) { 3245 Deoptimization::DeoptReason class_reason = Deoptimization::Reason_speculate_class_check; 3246 Deoptimization::DeoptReason null_reason = Deoptimization::Reason_speculate_null_check; 3247 3248 if (!too_many_traps_or_recompiles(null_reason) && 3249 !too_many_traps_or_recompiles(class_reason)) { 3250 Node* not_null_obj = nullptr; 3251 // not_null is true if we know the object is not null and 3252 // there's no need for a null check 3253 if (!not_null) { 3254 Node* null_ctl = top(); 3255 not_null_obj = null_check_oop(obj, &null_ctl, true, true, true); 3256 assert(null_ctl->is_top(), "no null control here"); 3257 } else { 3258 not_null_obj = obj; 3259 } 3260 3261 Node* exact_obj = not_null_obj; 3262 ciKlass* exact_kls = type; 3263 Node* slow_ctl = type_check_receiver(exact_obj, exact_kls, 1.0, 3264 &exact_obj); 3265 { 3266 PreserveJVMState pjvms(this); 3267 set_control(slow_ctl); 3268 uncommon_trap_exact(class_reason, Deoptimization::Action_maybe_recompile); 3269 } 3270 replace_in_map(not_null_obj, exact_obj); 3271 obj = exact_obj; 3272 } 3273 } else { 3274 if (!too_many_traps_or_recompiles(Deoptimization::Reason_null_assert)) { 3275 Node* exact_obj = null_assert(obj); 3276 replace_in_map(obj, exact_obj); 3277 obj = exact_obj; 3278 } 3279 } 3280 return obj; 3281 } 3282 3283 //-------------------------------gen_instanceof-------------------------------- 3284 // Generate an instance-of idiom. Used by both the instance-of bytecode 3285 // and the reflective instance-of call. 3286 Node* GraphKit::gen_instanceof(Node* obj, Node* superklass, bool safe_for_replace) { 3287 kill_dead_locals(); // Benefit all the uncommon traps 3288 assert( !stopped(), "dead parse path should be checked in callers" ); 3289 assert(!TypePtr::NULL_PTR->higher_equal(_gvn.type(superklass)->is_klassptr()), 3290 "must check for not-null not-dead klass in callers"); 3291 3292 // Make the merge point 3293 enum { _obj_path = 1, _fail_path, _null_path, PATH_LIMIT }; 3294 RegionNode* region = new RegionNode(PATH_LIMIT); 3295 Node* phi = new PhiNode(region, TypeInt::BOOL); 3296 C->set_has_split_ifs(true); // Has chance for split-if optimization 3297 3298 ciProfileData* data = nullptr; 3299 if (java_bc() == Bytecodes::_instanceof) { // Only for the bytecode 3300 data = method()->method_data()->bci_to_data(bci()); 3301 } 3302 bool speculative_not_null = false; 3303 bool never_see_null = (ProfileDynamicTypes // aggressive use of profile 3304 && seems_never_null(obj, data, speculative_not_null)); 3305 3306 // Null check; get casted pointer; set region slot 3 3307 Node* null_ctl = top(); 3308 Node* not_null_obj = null_check_oop(obj, &null_ctl, never_see_null, safe_for_replace, speculative_not_null); 3309 3310 // If not_null_obj is dead, only null-path is taken 3311 if (stopped()) { // Doing instance-of on a null? 3312 set_control(null_ctl); 3313 return intcon(0); 3314 } 3315 region->init_req(_null_path, null_ctl); 3316 phi ->init_req(_null_path, intcon(0)); // Set null path value 3317 if (null_ctl == top()) { 3318 // Do this eagerly, so that pattern matches like is_diamond_phi 3319 // will work even during parsing. 3320 assert(_null_path == PATH_LIMIT-1, "delete last"); 3321 region->del_req(_null_path); 3322 phi ->del_req(_null_path); 3323 } 3324 3325 // Do we know the type check always succeed? 3326 bool known_statically = false; 3327 if (_gvn.type(superklass)->singleton()) { 3328 const TypeKlassPtr* superk = _gvn.type(superklass)->is_klassptr(); 3329 const TypeKlassPtr* subk = _gvn.type(obj)->is_oopptr()->as_klass_type(); 3330 if (subk != nullptr && subk->is_loaded()) { 3331 int static_res = C->static_subtype_check(superk, subk); 3332 known_statically = (static_res == Compile::SSC_always_true || static_res == Compile::SSC_always_false); 3333 } 3334 } 3335 3336 if (!known_statically) { 3337 const TypeOopPtr* obj_type = _gvn.type(obj)->is_oopptr(); 3338 // We may not have profiling here or it may not help us. If we 3339 // have a speculative type use it to perform an exact cast. 3340 ciKlass* spec_obj_type = obj_type->speculative_type(); 3341 if (spec_obj_type != nullptr || (ProfileDynamicTypes && data != nullptr)) { 3342 Node* cast_obj = maybe_cast_profiled_receiver(not_null_obj, nullptr, spec_obj_type, safe_for_replace); 3343 if (stopped()) { // Profile disagrees with this path. 3344 set_control(null_ctl); // Null is the only remaining possibility. 3345 return intcon(0); 3346 } 3347 if (cast_obj != nullptr) { 3348 not_null_obj = cast_obj; 3349 } 3350 } 3351 } 3352 3353 // Generate the subtype check 3354 Node* not_subtype_ctrl = gen_subtype_check(not_null_obj, superklass); 3355 3356 // Plug in the success path to the general merge in slot 1. 3357 region->init_req(_obj_path, control()); 3358 phi ->init_req(_obj_path, intcon(1)); 3359 3360 // Plug in the failing path to the general merge in slot 2. 3361 region->init_req(_fail_path, not_subtype_ctrl); 3362 phi ->init_req(_fail_path, intcon(0)); 3363 3364 // Return final merged results 3365 set_control( _gvn.transform(region) ); 3366 record_for_igvn(region); 3367 3368 // If we know the type check always succeeds then we don't use the 3369 // profiling data at this bytecode. Don't lose it, feed it to the 3370 // type system as a speculative type. 3371 if (safe_for_replace) { 3372 Node* casted_obj = record_profiled_receiver_for_speculation(obj); 3373 replace_in_map(obj, casted_obj); 3374 } 3375 3376 return _gvn.transform(phi); 3377 } 3378 3379 //-------------------------------gen_checkcast--------------------------------- 3380 // Generate a checkcast idiom. Used by both the checkcast bytecode and the 3381 // array store bytecode. Stack must be as-if BEFORE doing the bytecode so the 3382 // uncommon-trap paths work. Adjust stack after this call. 3383 // If failure_control is supplied and not null, it is filled in with 3384 // the control edge for the cast failure. Otherwise, an appropriate 3385 // uncommon trap or exception is thrown. 3386 Node* GraphKit::gen_checkcast(Node *obj, Node* superklass, Node* *failure_control, bool null_free) { 3387 kill_dead_locals(); // Benefit all the uncommon traps 3388 const TypeKlassPtr *tk = _gvn.type(superklass)->is_klassptr()->try_improve(); 3389 const TypeOopPtr *toop = tk->cast_to_exactness(false)->as_instance_type(); 3390 bool safe_for_replace = (failure_control == nullptr); 3391 assert(!null_free || toop->is_inlinetypeptr(), "must be an inline type pointer"); 3392 3393 // Fast cutout: Check the case that the cast is vacuously true. 3394 // This detects the common cases where the test will short-circuit 3395 // away completely. We do this before we perform the null check, 3396 // because if the test is going to turn into zero code, we don't 3397 // want a residual null check left around. (Causes a slowdown, 3398 // for example, in some objArray manipulations, such as a[i]=a[j].) 3399 if (tk->singleton()) { 3400 const TypeKlassPtr* kptr = nullptr; 3401 const Type* t = _gvn.type(obj); 3402 if (t->isa_oop_ptr()) { 3403 kptr = t->is_oopptr()->as_klass_type(); 3404 } else if (obj->is_InlineType()) { 3405 ciInlineKlass* vk = t->inline_klass(); 3406 kptr = TypeInstKlassPtr::make(TypePtr::NotNull, vk, Type::Offset(0)); 3407 } 3408 if (kptr != nullptr) { 3409 switch (C->static_subtype_check(tk, kptr)) { 3410 case Compile::SSC_always_true: 3411 // If we know the type check always succeed then we don't use 3412 // the profiling data at this bytecode. Don't lose it, feed it 3413 // to the type system as a speculative type. 3414 obj = record_profiled_receiver_for_speculation(obj); 3415 if (null_free) { 3416 assert(safe_for_replace, "must be"); 3417 obj = null_check(obj); 3418 } 3419 assert(stopped() || !toop->is_inlinetypeptr() || obj->is_InlineType(), "should have been scalarized"); 3420 return obj; 3421 case Compile::SSC_always_false: 3422 if (null_free) { 3423 assert(safe_for_replace, "must be"); 3424 obj = null_check(obj); 3425 } 3426 // It needs a null check because a null will *pass* the cast check. 3427 if (t->isa_oopptr() != nullptr && !t->is_oopptr()->maybe_null()) { 3428 bool is_aastore = (java_bc() == Bytecodes::_aastore); 3429 Deoptimization::DeoptReason reason = is_aastore ? 3430 Deoptimization::Reason_array_check : Deoptimization::Reason_class_check; 3431 builtin_throw(reason); 3432 return top(); 3433 } else if (!too_many_traps_or_recompiles(Deoptimization::Reason_null_assert)) { 3434 return null_assert(obj); 3435 } 3436 break; // Fall through to full check 3437 default: 3438 break; 3439 } 3440 } 3441 } 3442 3443 ciProfileData* data = nullptr; 3444 if (failure_control == nullptr) { // use MDO in regular case only 3445 assert(java_bc() == Bytecodes::_aastore || 3446 java_bc() == Bytecodes::_checkcast, 3447 "interpreter profiles type checks only for these BCs"); 3448 if (method()->method_data()->is_mature()) { 3449 data = method()->method_data()->bci_to_data(bci()); 3450 } 3451 } 3452 3453 // Make the merge point 3454 enum { _obj_path = 1, _null_path, PATH_LIMIT }; 3455 RegionNode* region = new RegionNode(PATH_LIMIT); 3456 Node* phi = new PhiNode(region, toop); 3457 _gvn.set_type(region, Type::CONTROL); 3458 _gvn.set_type(phi, toop); 3459 3460 C->set_has_split_ifs(true); // Has chance for split-if optimization 3461 3462 // Use null-cast information if it is available 3463 bool speculative_not_null = false; 3464 bool never_see_null = ((failure_control == nullptr) // regular case only 3465 && seems_never_null(obj, data, speculative_not_null)); 3466 3467 if (obj->is_InlineType()) { 3468 // Re-execute if buffering during triggers deoptimization 3469 PreserveReexecuteState preexecs(this); 3470 jvms()->set_should_reexecute(true); 3471 obj = obj->as_InlineType()->buffer(this, safe_for_replace); 3472 } 3473 3474 // Null check; get casted pointer; set region slot 3 3475 Node* null_ctl = top(); 3476 Node* not_null_obj = nullptr; 3477 if (null_free) { 3478 assert(safe_for_replace, "must be"); 3479 not_null_obj = null_check(obj); 3480 } else { 3481 not_null_obj = null_check_oop(obj, &null_ctl, never_see_null, safe_for_replace, speculative_not_null); 3482 } 3483 3484 // If not_null_obj is dead, only null-path is taken 3485 if (stopped()) { // Doing instance-of on a null? 3486 set_control(null_ctl); 3487 if (toop->is_inlinetypeptr()) { 3488 return InlineTypeNode::make_null(_gvn, toop->inline_klass()); 3489 } 3490 return null(); 3491 } 3492 region->init_req(_null_path, null_ctl); 3493 phi ->init_req(_null_path, null()); // Set null path value 3494 if (null_ctl == top()) { 3495 // Do this eagerly, so that pattern matches like is_diamond_phi 3496 // will work even during parsing. 3497 assert(_null_path == PATH_LIMIT-1, "delete last"); 3498 region->del_req(_null_path); 3499 phi ->del_req(_null_path); 3500 } 3501 3502 Node* cast_obj = nullptr; 3503 if (tk->klass_is_exact()) { 3504 // The following optimization tries to statically cast the speculative type of the object 3505 // (for example obtained during profiling) to the type of the superklass and then do a 3506 // dynamic check that the type of the object is what we expect. To work correctly 3507 // for checkcast and aastore the type of superklass should be exact. 3508 const TypeOopPtr* obj_type = _gvn.type(obj)->is_oopptr(); 3509 // We may not have profiling here or it may not help us. If we have 3510 // a speculative type use it to perform an exact cast. 3511 ciKlass* spec_obj_type = obj_type->speculative_type(); 3512 if (spec_obj_type != nullptr || data != nullptr) { 3513 cast_obj = maybe_cast_profiled_receiver(not_null_obj, tk, spec_obj_type, safe_for_replace); 3514 if (cast_obj != nullptr) { 3515 if (failure_control != nullptr) // failure is now impossible 3516 (*failure_control) = top(); 3517 // adjust the type of the phi to the exact klass: 3518 phi->raise_bottom_type(_gvn.type(cast_obj)->meet_speculative(TypePtr::NULL_PTR)); 3519 } 3520 } 3521 } 3522 3523 if (cast_obj == nullptr) { 3524 // Generate the subtype check 3525 Node* not_subtype_ctrl = gen_subtype_check(not_null_obj, superklass); 3526 3527 // Plug in success path into the merge 3528 cast_obj = _gvn.transform(new CheckCastPPNode(control(), not_null_obj, toop)); 3529 // Failure path ends in uncommon trap (or may be dead - failure impossible) 3530 if (failure_control == nullptr) { 3531 if (not_subtype_ctrl != top()) { // If failure is possible 3532 PreserveJVMState pjvms(this); 3533 set_control(not_subtype_ctrl); 3534 Node* obj_klass = nullptr; 3535 if (not_null_obj->is_InlineType()) { 3536 obj_klass = makecon(TypeKlassPtr::make(_gvn.type(not_null_obj)->inline_klass())); 3537 } else { 3538 obj_klass = load_object_klass(not_null_obj); 3539 } 3540 bool is_aastore = (java_bc() == Bytecodes::_aastore); 3541 Deoptimization::DeoptReason reason = is_aastore ? 3542 Deoptimization::Reason_array_check : Deoptimization::Reason_class_check; 3543 builtin_throw(reason); 3544 } 3545 } else { 3546 (*failure_control) = not_subtype_ctrl; 3547 } 3548 } 3549 3550 region->init_req(_obj_path, control()); 3551 phi ->init_req(_obj_path, cast_obj); 3552 3553 // A merge of null or Casted-NotNull obj 3554 Node* res = _gvn.transform(phi); 3555 3556 // Note I do NOT always 'replace_in_map(obj,result)' here. 3557 // if( tk->klass()->can_be_primary_super() ) 3558 // This means that if I successfully store an Object into an array-of-String 3559 // I 'forget' that the Object is really now known to be a String. I have to 3560 // do this because we don't have true union types for interfaces - if I store 3561 // a Baz into an array-of-Interface and then tell the optimizer it's an 3562 // Interface, I forget that it's also a Baz and cannot do Baz-like field 3563 // references to it. FIX THIS WHEN UNION TYPES APPEAR! 3564 // replace_in_map( obj, res ); 3565 3566 // Return final merged results 3567 set_control( _gvn.transform(region) ); 3568 record_for_igvn(region); 3569 3570 bool not_inline = !toop->can_be_inline_type(); 3571 bool not_flat = !UseFlatArray || not_inline || (toop->is_inlinetypeptr() && !toop->inline_klass()->flat_array()); 3572 if (EnableValhalla && not_flat) { 3573 // Check if obj has been loaded from an array 3574 obj = obj->isa_DecodeN() ? obj->in(1) : obj; 3575 Node* array = nullptr; 3576 if (obj->isa_Load()) { 3577 Node* address = obj->in(MemNode::Address); 3578 if (address->isa_AddP()) { 3579 array = address->as_AddP()->in(AddPNode::Base); 3580 } 3581 } else if (obj->is_Phi()) { 3582 Node* region = obj->in(0); 3583 // TODO make this more robust (see JDK-8231346) 3584 if (region->req() == 3 && region->in(2) != nullptr && region->in(2)->in(0) != nullptr) { 3585 IfNode* iff = region->in(2)->in(0)->isa_If(); 3586 if (iff != nullptr) { 3587 iff->is_flat_array_check(&_gvn, &array); 3588 } 3589 } 3590 } 3591 if (array != nullptr) { 3592 const TypeAryPtr* ary_t = _gvn.type(array)->isa_aryptr(); 3593 if (ary_t != nullptr) { 3594 if (!ary_t->is_not_null_free() && not_inline) { 3595 // Casting array element to a non-inline-type, mark array as not null-free. 3596 Node* cast = _gvn.transform(new CheckCastPPNode(control(), array, ary_t->cast_to_not_null_free())); 3597 replace_in_map(array, cast); 3598 } else if (!ary_t->is_not_flat()) { 3599 // Casting array element to a non-flat type, mark array as not flat. 3600 Node* cast = _gvn.transform(new CheckCastPPNode(control(), array, ary_t->cast_to_not_flat())); 3601 replace_in_map(array, cast); 3602 } 3603 } 3604 } 3605 } 3606 3607 if (!stopped() && !res->is_InlineType()) { 3608 res = record_profiled_receiver_for_speculation(res); 3609 if (toop->is_inlinetypeptr()) { 3610 Node* vt = InlineTypeNode::make_from_oop(this, res, toop->inline_klass(), !gvn().type(res)->maybe_null()); 3611 res = vt; 3612 if (safe_for_replace) { 3613 replace_in_map(obj, vt); 3614 replace_in_map(not_null_obj, vt); 3615 replace_in_map(res, vt); 3616 } 3617 } 3618 } 3619 return res; 3620 } 3621 3622 Node* GraphKit::inline_type_test(Node* obj, bool is_inline) { 3623 Node* mark_adr = basic_plus_adr(obj, oopDesc::mark_offset_in_bytes()); 3624 Node* mark = make_load(nullptr, mark_adr, TypeX_X, TypeX_X->basic_type(), MemNode::unordered); 3625 Node* mask = MakeConX(markWord::inline_type_pattern); 3626 Node* masked = _gvn.transform(new AndXNode(mark, mask)); 3627 Node* cmp = _gvn.transform(new CmpXNode(masked, mask)); 3628 return _gvn.transform(new BoolNode(cmp, is_inline ? BoolTest::eq : BoolTest::ne)); 3629 } 3630 3631 Node* GraphKit::is_val_mirror(Node* mirror) { 3632 Node* p = basic_plus_adr(mirror, java_lang_Class::secondary_mirror_offset()); 3633 Node* secondary_mirror = access_load_at(mirror, p, _gvn.type(p)->is_ptr(), TypeInstPtr::MIRROR->cast_to_ptr_type(TypePtr::BotPTR), T_OBJECT, IN_HEAP); 3634 Node* cmp = _gvn.transform(new CmpPNode(mirror, secondary_mirror)); 3635 return _gvn.transform(new BoolNode(cmp, BoolTest::eq)); 3636 } 3637 3638 Node* GraphKit::array_lh_test(Node* klass, jint mask, jint val, bool eq) { 3639 Node* lh_adr = basic_plus_adr(klass, in_bytes(Klass::layout_helper_offset())); 3640 // Make sure to use immutable memory here to enable hoisting the check out of loops 3641 Node* lh_val = _gvn.transform(LoadNode::make(_gvn, nullptr, immutable_memory(), lh_adr, lh_adr->bottom_type()->is_ptr(), TypeInt::INT, T_INT, MemNode::unordered)); 3642 Node* masked = _gvn.transform(new AndINode(lh_val, intcon(mask))); 3643 Node* cmp = _gvn.transform(new CmpINode(masked, intcon(val))); 3644 return _gvn.transform(new BoolNode(cmp, eq ? BoolTest::eq : BoolTest::ne)); 3645 } 3646 3647 Node* GraphKit::flat_array_test(Node* array_or_klass, bool flat) { 3648 // We can't use immutable memory here because the mark word is mutable. 3649 // PhaseIdealLoop::move_flat_array_check_out_of_loop will make sure the 3650 // check is moved out of loops (mainly to enable loop unswitching). 3651 Node* mem = UseArrayMarkWordCheck ? memory(Compile::AliasIdxRaw) : immutable_memory(); 3652 Node* cmp = _gvn.transform(new FlatArrayCheckNode(C, mem, array_or_klass)); 3653 record_for_igvn(cmp); // Give it a chance to be optimized out by IGVN 3654 return _gvn.transform(new BoolNode(cmp, flat ? BoolTest::eq : BoolTest::ne)); 3655 } 3656 3657 Node* GraphKit::null_free_array_test(Node* klass, bool null_free) { 3658 return array_lh_test(klass, Klass::_lh_null_free_array_bit_inplace, 0, !null_free); 3659 } 3660 3661 // Deoptimize if 'ary' is a null-free inline type array and 'val' is null 3662 Node* GraphKit::inline_array_null_guard(Node* ary, Node* val, int nargs, bool safe_for_replace) { 3663 RegionNode* region = new RegionNode(3); 3664 Node* null_ctl = top(); 3665 null_check_oop(val, &null_ctl); 3666 if (null_ctl != top()) { 3667 PreserveJVMState pjvms(this); 3668 set_control(null_ctl); 3669 { 3670 // Deoptimize if null-free array 3671 BuildCutout unless(this, null_free_array_test(load_object_klass(ary), /* null_free = */ false), PROB_MAX); 3672 inc_sp(nargs); 3673 uncommon_trap(Deoptimization::Reason_null_check, 3674 Deoptimization::Action_none); 3675 } 3676 region->init_req(1, control()); 3677 } 3678 region->init_req(2, control()); 3679 set_control(_gvn.transform(region)); 3680 record_for_igvn(region); 3681 if (_gvn.type(val) == TypePtr::NULL_PTR) { 3682 // Since we were just successfully storing null, the array can't be null free. 3683 const TypeAryPtr* ary_t = _gvn.type(ary)->is_aryptr(); 3684 ary_t = ary_t->cast_to_not_null_free(); 3685 Node* cast = _gvn.transform(new CheckCastPPNode(control(), ary, ary_t)); 3686 if (safe_for_replace) { 3687 replace_in_map(ary, cast); 3688 } 3689 ary = cast; 3690 } 3691 return ary; 3692 } 3693 3694 //------------------------------next_monitor----------------------------------- 3695 // What number should be given to the next monitor? 3696 int GraphKit::next_monitor() { 3697 int current = jvms()->monitor_depth()* C->sync_stack_slots(); 3698 int next = current + C->sync_stack_slots(); 3699 // Keep the toplevel high water mark current: 3700 if (C->fixed_slots() < next) C->set_fixed_slots(next); 3701 return current; 3702 } 3703 3704 //------------------------------insert_mem_bar--------------------------------- 3705 // Memory barrier to avoid floating things around 3706 // The membar serves as a pinch point between both control and all memory slices. 3707 Node* GraphKit::insert_mem_bar(int opcode, Node* precedent) { 3708 MemBarNode* mb = MemBarNode::make(C, opcode, Compile::AliasIdxBot, precedent); 3709 mb->init_req(TypeFunc::Control, control()); 3710 mb->init_req(TypeFunc::Memory, reset_memory()); 3711 Node* membar = _gvn.transform(mb); 3712 set_control(_gvn.transform(new ProjNode(membar, TypeFunc::Control))); 3713 set_all_memory_call(membar); 3714 return membar; 3715 } 3716 3717 //-------------------------insert_mem_bar_volatile---------------------------- 3718 // Memory barrier to avoid floating things around 3719 // The membar serves as a pinch point between both control and memory(alias_idx). 3720 // If you want to make a pinch point on all memory slices, do not use this 3721 // function (even with AliasIdxBot); use insert_mem_bar() instead. 3722 Node* GraphKit::insert_mem_bar_volatile(int opcode, int alias_idx, Node* precedent) { 3723 // When Parse::do_put_xxx updates a volatile field, it appends a series 3724 // of MemBarVolatile nodes, one for *each* volatile field alias category. 3725 // The first membar is on the same memory slice as the field store opcode. 3726 // This forces the membar to follow the store. (Bug 6500685 broke this.) 3727 // All the other membars (for other volatile slices, including AliasIdxBot, 3728 // which stands for all unknown volatile slices) are control-dependent 3729 // on the first membar. This prevents later volatile loads or stores 3730 // from sliding up past the just-emitted store. 3731 3732 MemBarNode* mb = MemBarNode::make(C, opcode, alias_idx, precedent); 3733 mb->set_req(TypeFunc::Control,control()); 3734 if (alias_idx == Compile::AliasIdxBot) { 3735 mb->set_req(TypeFunc::Memory, merged_memory()->base_memory()); 3736 } else { 3737 assert(!(opcode == Op_Initialize && alias_idx != Compile::AliasIdxRaw), "fix caller"); 3738 mb->set_req(TypeFunc::Memory, memory(alias_idx)); 3739 } 3740 Node* membar = _gvn.transform(mb); 3741 set_control(_gvn.transform(new ProjNode(membar, TypeFunc::Control))); 3742 if (alias_idx == Compile::AliasIdxBot) { 3743 merged_memory()->set_base_memory(_gvn.transform(new ProjNode(membar, TypeFunc::Memory))); 3744 } else { 3745 set_memory(_gvn.transform(new ProjNode(membar, TypeFunc::Memory)),alias_idx); 3746 } 3747 return membar; 3748 } 3749 3750 //------------------------------shared_lock------------------------------------ 3751 // Emit locking code. 3752 FastLockNode* GraphKit::shared_lock(Node* obj) { 3753 // bci is either a monitorenter bc or InvocationEntryBci 3754 // %%% SynchronizationEntryBCI is redundant; use InvocationEntryBci in interfaces 3755 assert(SynchronizationEntryBCI == InvocationEntryBci, ""); 3756 3757 if( !GenerateSynchronizationCode ) 3758 return nullptr; // Not locking things? 3759 3760 if (stopped()) // Dead monitor? 3761 return nullptr; 3762 3763 assert(dead_locals_are_killed(), "should kill locals before sync. point"); 3764 3765 // Box the stack location 3766 Node* box = _gvn.transform(new BoxLockNode(next_monitor())); 3767 Node* mem = reset_memory(); 3768 3769 FastLockNode * flock = _gvn.transform(new FastLockNode(0, obj, box) )->as_FastLock(); 3770 3771 // Create the rtm counters for this fast lock if needed. 3772 flock->create_rtm_lock_counter(sync_jvms()); // sync_jvms used to get current bci 3773 3774 // Add monitor to debug info for the slow path. If we block inside the 3775 // slow path and de-opt, we need the monitor hanging around 3776 map()->push_monitor( flock ); 3777 3778 const TypeFunc *tf = LockNode::lock_type(); 3779 LockNode *lock = new LockNode(C, tf); 3780 3781 lock->init_req( TypeFunc::Control, control() ); 3782 lock->init_req( TypeFunc::Memory , mem ); 3783 lock->init_req( TypeFunc::I_O , top() ) ; // does no i/o 3784 lock->init_req( TypeFunc::FramePtr, frameptr() ); 3785 lock->init_req( TypeFunc::ReturnAdr, top() ); 3786 3787 lock->init_req(TypeFunc::Parms + 0, obj); 3788 lock->init_req(TypeFunc::Parms + 1, box); 3789 lock->init_req(TypeFunc::Parms + 2, flock); 3790 add_safepoint_edges(lock); 3791 3792 lock = _gvn.transform( lock )->as_Lock(); 3793 3794 // lock has no side-effects, sets few values 3795 set_predefined_output_for_runtime_call(lock, mem, TypeRawPtr::BOTTOM); 3796 3797 insert_mem_bar(Op_MemBarAcquireLock); 3798 3799 // Add this to the worklist so that the lock can be eliminated 3800 record_for_igvn(lock); 3801 3802 #ifndef PRODUCT 3803 if (PrintLockStatistics) { 3804 // Update the counter for this lock. Don't bother using an atomic 3805 // operation since we don't require absolute accuracy. 3806 lock->create_lock_counter(map()->jvms()); 3807 increment_counter(lock->counter()->addr()); 3808 } 3809 #endif 3810 3811 return flock; 3812 } 3813 3814 3815 //------------------------------shared_unlock---------------------------------- 3816 // Emit unlocking code. 3817 void GraphKit::shared_unlock(Node* box, Node* obj) { 3818 // bci is either a monitorenter bc or InvocationEntryBci 3819 // %%% SynchronizationEntryBCI is redundant; use InvocationEntryBci in interfaces 3820 assert(SynchronizationEntryBCI == InvocationEntryBci, ""); 3821 3822 if( !GenerateSynchronizationCode ) 3823 return; 3824 if (stopped()) { // Dead monitor? 3825 map()->pop_monitor(); // Kill monitor from debug info 3826 return; 3827 } 3828 assert(!obj->is_InlineType(), "should not unlock on inline type"); 3829 3830 // Memory barrier to avoid floating things down past the locked region 3831 insert_mem_bar(Op_MemBarReleaseLock); 3832 3833 const TypeFunc *tf = OptoRuntime::complete_monitor_exit_Type(); 3834 UnlockNode *unlock = new UnlockNode(C, tf); 3835 #ifdef ASSERT 3836 unlock->set_dbg_jvms(sync_jvms()); 3837 #endif 3838 uint raw_idx = Compile::AliasIdxRaw; 3839 unlock->init_req( TypeFunc::Control, control() ); 3840 unlock->init_req( TypeFunc::Memory , memory(raw_idx) ); 3841 unlock->init_req( TypeFunc::I_O , top() ) ; // does no i/o 3842 unlock->init_req( TypeFunc::FramePtr, frameptr() ); 3843 unlock->init_req( TypeFunc::ReturnAdr, top() ); 3844 3845 unlock->init_req(TypeFunc::Parms + 0, obj); 3846 unlock->init_req(TypeFunc::Parms + 1, box); 3847 unlock = _gvn.transform(unlock)->as_Unlock(); 3848 3849 Node* mem = reset_memory(); 3850 3851 // unlock has no side-effects, sets few values 3852 set_predefined_output_for_runtime_call(unlock, mem, TypeRawPtr::BOTTOM); 3853 3854 // Kill monitor from debug info 3855 map()->pop_monitor( ); 3856 } 3857 3858 //-------------------------------get_layout_helper----------------------------- 3859 // If the given klass is a constant or known to be an array, 3860 // fetch the constant layout helper value into constant_value 3861 // and return null. Otherwise, load the non-constant 3862 // layout helper value, and return the node which represents it. 3863 // This two-faced routine is useful because allocation sites 3864 // almost always feature constant types. 3865 Node* GraphKit::get_layout_helper(Node* klass_node, jint& constant_value) { 3866 const TypeKlassPtr* klass_t = _gvn.type(klass_node)->isa_klassptr(); 3867 if (!StressReflectiveCode && klass_t != nullptr) { 3868 bool xklass = klass_t->klass_is_exact(); 3869 bool can_be_flat = false; 3870 const TypeAryPtr* ary_type = klass_t->as_instance_type()->isa_aryptr(); 3871 if (UseFlatArray && !xklass && ary_type != nullptr && !ary_type->is_null_free()) { 3872 // The runtime type of [LMyValue might be [QMyValue due to [QMyValue <: [LMyValue. Don't constant fold. 3873 const TypeOopPtr* elem = ary_type->elem()->make_oopptr(); 3874 can_be_flat = ary_type->can_be_inline_array() && (!elem->is_inlinetypeptr() || elem->inline_klass()->flat_array()); 3875 } 3876 if (!can_be_flat && (xklass || (klass_t->isa_aryklassptr() && klass_t->is_aryklassptr()->elem() != Type::BOTTOM))) { 3877 jint lhelper; 3878 if (klass_t->is_flat()) { 3879 lhelper = ary_type->flat_layout_helper(); 3880 } else if (klass_t->isa_aryklassptr()) { 3881 BasicType elem = ary_type->elem()->array_element_basic_type(); 3882 if (is_reference_type(elem, true)) { 3883 elem = T_OBJECT; 3884 } 3885 lhelper = Klass::array_layout_helper(elem); 3886 } else { 3887 lhelper = klass_t->is_instklassptr()->exact_klass()->layout_helper(); 3888 } 3889 if (lhelper != Klass::_lh_neutral_value) { 3890 constant_value = lhelper; 3891 return (Node*) nullptr; 3892 } 3893 } 3894 } 3895 constant_value = Klass::_lh_neutral_value; // put in a known value 3896 Node* lhp = basic_plus_adr(klass_node, klass_node, in_bytes(Klass::layout_helper_offset())); 3897 return make_load(nullptr, lhp, TypeInt::INT, T_INT, MemNode::unordered); 3898 } 3899 3900 // We just put in an allocate/initialize with a big raw-memory effect. 3901 // Hook selected additional alias categories on the initialization. 3902 static void hook_memory_on_init(GraphKit& kit, int alias_idx, 3903 MergeMemNode* init_in_merge, 3904 Node* init_out_raw) { 3905 DEBUG_ONLY(Node* init_in_raw = init_in_merge->base_memory()); 3906 assert(init_in_merge->memory_at(alias_idx) == init_in_raw, ""); 3907 3908 Node* prevmem = kit.memory(alias_idx); 3909 init_in_merge->set_memory_at(alias_idx, prevmem); 3910 if (init_out_raw != nullptr) { 3911 kit.set_memory(init_out_raw, alias_idx); 3912 } 3913 } 3914 3915 //---------------------------set_output_for_allocation------------------------- 3916 Node* GraphKit::set_output_for_allocation(AllocateNode* alloc, 3917 const TypeOopPtr* oop_type, 3918 bool deoptimize_on_exception) { 3919 int rawidx = Compile::AliasIdxRaw; 3920 alloc->set_req( TypeFunc::FramePtr, frameptr() ); 3921 add_safepoint_edges(alloc); 3922 Node* allocx = _gvn.transform(alloc); 3923 set_control( _gvn.transform(new ProjNode(allocx, TypeFunc::Control) ) ); 3924 // create memory projection for i_o 3925 set_memory ( _gvn.transform( new ProjNode(allocx, TypeFunc::Memory, true) ), rawidx ); 3926 make_slow_call_ex(allocx, env()->Throwable_klass(), true, deoptimize_on_exception); 3927 3928 // create a memory projection as for the normal control path 3929 Node* malloc = _gvn.transform(new ProjNode(allocx, TypeFunc::Memory)); 3930 set_memory(malloc, rawidx); 3931 3932 // a normal slow-call doesn't change i_o, but an allocation does 3933 // we create a separate i_o projection for the normal control path 3934 set_i_o(_gvn.transform( new ProjNode(allocx, TypeFunc::I_O, false) ) ); 3935 Node* rawoop = _gvn.transform( new ProjNode(allocx, TypeFunc::Parms) ); 3936 3937 // put in an initialization barrier 3938 InitializeNode* init = insert_mem_bar_volatile(Op_Initialize, rawidx, 3939 rawoop)->as_Initialize(); 3940 assert(alloc->initialization() == init, "2-way macro link must work"); 3941 assert(init ->allocation() == alloc, "2-way macro link must work"); 3942 { 3943 // Extract memory strands which may participate in the new object's 3944 // initialization, and source them from the new InitializeNode. 3945 // This will allow us to observe initializations when they occur, 3946 // and link them properly (as a group) to the InitializeNode. 3947 assert(init->in(InitializeNode::Memory) == malloc, ""); 3948 MergeMemNode* minit_in = MergeMemNode::make(malloc); 3949 init->set_req(InitializeNode::Memory, minit_in); 3950 record_for_igvn(minit_in); // fold it up later, if possible 3951 _gvn.set_type(minit_in, Type::MEMORY); 3952 Node* minit_out = memory(rawidx); 3953 assert(minit_out->is_Proj() && minit_out->in(0) == init, ""); 3954 // Add an edge in the MergeMem for the header fields so an access 3955 // to one of those has correct memory state 3956 set_memory(minit_out, C->get_alias_index(oop_type->add_offset(oopDesc::mark_offset_in_bytes()))); 3957 set_memory(minit_out, C->get_alias_index(oop_type->add_offset(oopDesc::klass_offset_in_bytes()))); 3958 if (oop_type->isa_aryptr()) { 3959 const TypeAryPtr* arytype = oop_type->is_aryptr(); 3960 if (arytype->is_flat()) { 3961 // Initially all flat array accesses share a single slice 3962 // but that changes after parsing. Prepare the memory graph so 3963 // it can optimize flat array accesses properly once they 3964 // don't share a single slice. 3965 assert(C->flat_accesses_share_alias(), "should be set at parse time"); 3966 C->set_flat_accesses_share_alias(false); 3967 ciInlineKlass* vk = arytype->elem()->inline_klass(); 3968 for (int i = 0, len = vk->nof_nonstatic_fields(); i < len; i++) { 3969 ciField* field = vk->nonstatic_field_at(i); 3970 if (field->offset_in_bytes() >= TrackedInitializationLimit * HeapWordSize) 3971 continue; // do not bother to track really large numbers of fields 3972 int off_in_vt = field->offset_in_bytes() - vk->first_field_offset(); 3973 const TypePtr* adr_type = arytype->with_field_offset(off_in_vt)->add_offset(Type::OffsetBot); 3974 int fieldidx = C->get_alias_index(adr_type, true); 3975 // Pass nullptr for init_out. Having per flat array element field memory edges as uses of the Initialize node 3976 // can result in per flat array field Phis to be created which confuses the logic of 3977 // Compile::adjust_flat_array_access_aliases(). 3978 hook_memory_on_init(*this, fieldidx, minit_in, nullptr); 3979 } 3980 C->set_flat_accesses_share_alias(true); 3981 hook_memory_on_init(*this, C->get_alias_index(TypeAryPtr::INLINES), minit_in, minit_out); 3982 } else { 3983 const TypePtr* telemref = oop_type->add_offset(Type::OffsetBot); 3984 int elemidx = C->get_alias_index(telemref); 3985 hook_memory_on_init(*this, elemidx, minit_in, minit_out); 3986 } 3987 } else if (oop_type->isa_instptr()) { 3988 set_memory(minit_out, C->get_alias_index(oop_type)); // mark word 3989 ciInstanceKlass* ik = oop_type->is_instptr()->instance_klass(); 3990 for (int i = 0, len = ik->nof_nonstatic_fields(); i < len; i++) { 3991 ciField* field = ik->nonstatic_field_at(i); 3992 if (field->offset_in_bytes() >= TrackedInitializationLimit * HeapWordSize) 3993 continue; // do not bother to track really large numbers of fields 3994 // Find (or create) the alias category for this field: 3995 int fieldidx = C->alias_type(field)->index(); 3996 hook_memory_on_init(*this, fieldidx, minit_in, minit_out); 3997 } 3998 } 3999 } 4000 4001 // Cast raw oop to the real thing... 4002 Node* javaoop = new CheckCastPPNode(control(), rawoop, oop_type); 4003 javaoop = _gvn.transform(javaoop); 4004 C->set_recent_alloc(control(), javaoop); 4005 assert(just_allocated_object(control()) == javaoop, "just allocated"); 4006 4007 #ifdef ASSERT 4008 { // Verify that the AllocateNode::Ideal_allocation recognizers work: 4009 assert(AllocateNode::Ideal_allocation(rawoop) == alloc, 4010 "Ideal_allocation works"); 4011 assert(AllocateNode::Ideal_allocation(javaoop) == alloc, 4012 "Ideal_allocation works"); 4013 if (alloc->is_AllocateArray()) { 4014 assert(AllocateArrayNode::Ideal_array_allocation(rawoop) == alloc->as_AllocateArray(), 4015 "Ideal_allocation works"); 4016 assert(AllocateArrayNode::Ideal_array_allocation(javaoop) == alloc->as_AllocateArray(), 4017 "Ideal_allocation works"); 4018 } else { 4019 assert(alloc->in(AllocateNode::ALength)->is_top(), "no length, please"); 4020 } 4021 } 4022 #endif //ASSERT 4023 4024 return javaoop; 4025 } 4026 4027 //---------------------------new_instance-------------------------------------- 4028 // This routine takes a klass_node which may be constant (for a static type) 4029 // or may be non-constant (for reflective code). It will work equally well 4030 // for either, and the graph will fold nicely if the optimizer later reduces 4031 // the type to a constant. 4032 // The optional arguments are for specialized use by intrinsics: 4033 // - If 'extra_slow_test' if not null is an extra condition for the slow-path. 4034 // - If 'return_size_val', report the total object size to the caller. 4035 // - deoptimize_on_exception controls how Java exceptions are handled (rethrow vs deoptimize) 4036 Node* GraphKit::new_instance(Node* klass_node, 4037 Node* extra_slow_test, 4038 Node* *return_size_val, 4039 bool deoptimize_on_exception, 4040 InlineTypeNode* inline_type_node) { 4041 // Compute size in doublewords 4042 // The size is always an integral number of doublewords, represented 4043 // as a positive bytewise size stored in the klass's layout_helper. 4044 // The layout_helper also encodes (in a low bit) the need for a slow path. 4045 jint layout_con = Klass::_lh_neutral_value; 4046 Node* layout_val = get_layout_helper(klass_node, layout_con); 4047 bool layout_is_con = (layout_val == nullptr); 4048 4049 if (extra_slow_test == nullptr) extra_slow_test = intcon(0); 4050 // Generate the initial go-slow test. It's either ALWAYS (return a 4051 // Node for 1) or NEVER (return a null) or perhaps (in the reflective 4052 // case) a computed value derived from the layout_helper. 4053 Node* initial_slow_test = nullptr; 4054 if (layout_is_con) { 4055 assert(!StressReflectiveCode, "stress mode does not use these paths"); 4056 bool must_go_slow = Klass::layout_helper_needs_slow_path(layout_con); 4057 initial_slow_test = must_go_slow ? intcon(1) : extra_slow_test; 4058 } else { // reflective case 4059 // This reflective path is used by Unsafe.allocateInstance. 4060 // (It may be stress-tested by specifying StressReflectiveCode.) 4061 // Basically, we want to get into the VM is there's an illegal argument. 4062 Node* bit = intcon(Klass::_lh_instance_slow_path_bit); 4063 initial_slow_test = _gvn.transform( new AndINode(layout_val, bit) ); 4064 if (extra_slow_test != intcon(0)) { 4065 initial_slow_test = _gvn.transform( new OrINode(initial_slow_test, extra_slow_test) ); 4066 } 4067 // (Macro-expander will further convert this to a Bool, if necessary.) 4068 } 4069 4070 // Find the size in bytes. This is easy; it's the layout_helper. 4071 // The size value must be valid even if the slow path is taken. 4072 Node* size = nullptr; 4073 if (layout_is_con) { 4074 size = MakeConX(Klass::layout_helper_size_in_bytes(layout_con)); 4075 } else { // reflective case 4076 // This reflective path is used by clone and Unsafe.allocateInstance. 4077 size = ConvI2X(layout_val); 4078 4079 // Clear the low bits to extract layout_helper_size_in_bytes: 4080 assert((int)Klass::_lh_instance_slow_path_bit < BytesPerLong, "clear bit"); 4081 Node* mask = MakeConX(~ (intptr_t)right_n_bits(LogBytesPerLong)); 4082 size = _gvn.transform( new AndXNode(size, mask) ); 4083 } 4084 if (return_size_val != nullptr) { 4085 (*return_size_val) = size; 4086 } 4087 4088 // This is a precise notnull oop of the klass. 4089 // (Actually, it need not be precise if this is a reflective allocation.) 4090 // It's what we cast the result to. 4091 const TypeKlassPtr* tklass = _gvn.type(klass_node)->isa_klassptr(); 4092 if (!tklass) tklass = TypeInstKlassPtr::OBJECT; 4093 const TypeOopPtr* oop_type = tklass->as_instance_type(); 4094 4095 // Now generate allocation code 4096 4097 // The entire memory state is needed for slow path of the allocation 4098 // since GC and deoptimization can happen. 4099 Node *mem = reset_memory(); 4100 set_all_memory(mem); // Create new memory state 4101 4102 AllocateNode* alloc = new AllocateNode(C, AllocateNode::alloc_type(Type::TOP), 4103 control(), mem, i_o(), 4104 size, klass_node, 4105 initial_slow_test, inline_type_node); 4106 4107 return set_output_for_allocation(alloc, oop_type, deoptimize_on_exception); 4108 } 4109 4110 //-------------------------------new_array------------------------------------- 4111 // helper for newarray and anewarray 4112 // The 'length' parameter is (obviously) the length of the array. 4113 // See comments on new_instance for the meaning of the other arguments. 4114 Node* GraphKit::new_array(Node* klass_node, // array klass (maybe variable) 4115 Node* length, // number of array elements 4116 int nargs, // number of arguments to push back for uncommon trap 4117 Node* *return_size_val, 4118 bool deoptimize_on_exception) { 4119 jint layout_con = Klass::_lh_neutral_value; 4120 Node* layout_val = get_layout_helper(klass_node, layout_con); 4121 bool layout_is_con = (layout_val == nullptr); 4122 4123 if (!layout_is_con && !StressReflectiveCode && 4124 !too_many_traps(Deoptimization::Reason_class_check)) { 4125 // This is a reflective array creation site. 4126 // Optimistically assume that it is a subtype of Object[], 4127 // so that we can fold up all the address arithmetic. 4128 layout_con = Klass::array_layout_helper(T_OBJECT); 4129 Node* cmp_lh = _gvn.transform( new CmpINode(layout_val, intcon(layout_con)) ); 4130 Node* bol_lh = _gvn.transform( new BoolNode(cmp_lh, BoolTest::eq) ); 4131 { BuildCutout unless(this, bol_lh, PROB_MAX); 4132 inc_sp(nargs); 4133 uncommon_trap(Deoptimization::Reason_class_check, 4134 Deoptimization::Action_maybe_recompile); 4135 } 4136 layout_val = nullptr; 4137 layout_is_con = true; 4138 } 4139 4140 // Generate the initial go-slow test. Make sure we do not overflow 4141 // if length is huge (near 2Gig) or negative! We do not need 4142 // exact double-words here, just a close approximation of needed 4143 // double-words. We can't add any offset or rounding bits, lest we 4144 // take a size -1 of bytes and make it positive. Use an unsigned 4145 // compare, so negative sizes look hugely positive. 4146 int fast_size_limit = FastAllocateSizeLimit; 4147 if (layout_is_con) { 4148 assert(!StressReflectiveCode, "stress mode does not use these paths"); 4149 // Increase the size limit if we have exact knowledge of array type. 4150 int log2_esize = Klass::layout_helper_log2_element_size(layout_con); 4151 fast_size_limit <<= MAX2(LogBytesPerLong - log2_esize, 0); 4152 } 4153 4154 Node* initial_slow_cmp = _gvn.transform( new CmpUNode( length, intcon( fast_size_limit ) ) ); 4155 Node* initial_slow_test = _gvn.transform( new BoolNode( initial_slow_cmp, BoolTest::gt ) ); 4156 4157 // --- Size Computation --- 4158 // array_size = round_to_heap(array_header + (length << elem_shift)); 4159 // where round_to_heap(x) == align_to(x, MinObjAlignmentInBytes) 4160 // and align_to(x, y) == ((x + y-1) & ~(y-1)) 4161 // The rounding mask is strength-reduced, if possible. 4162 int round_mask = MinObjAlignmentInBytes - 1; 4163 Node* header_size = nullptr; 4164 int header_size_min = arrayOopDesc::base_offset_in_bytes(T_BYTE); 4165 // (T_BYTE has the weakest alignment and size restrictions...) 4166 if (layout_is_con) { 4167 int hsize = Klass::layout_helper_header_size(layout_con); 4168 int eshift = Klass::layout_helper_log2_element_size(layout_con); 4169 bool is_flat_array = Klass::layout_helper_is_flatArray(layout_con); 4170 if ((round_mask & ~right_n_bits(eshift)) == 0) 4171 round_mask = 0; // strength-reduce it if it goes away completely 4172 assert(is_flat_array || (hsize & right_n_bits(eshift)) == 0, "hsize is pre-rounded"); 4173 assert(header_size_min <= hsize, "generic minimum is smallest"); 4174 header_size_min = hsize; 4175 header_size = intcon(hsize + round_mask); 4176 } else { 4177 Node* hss = intcon(Klass::_lh_header_size_shift); 4178 Node* hsm = intcon(Klass::_lh_header_size_mask); 4179 Node* hsize = _gvn.transform( new URShiftINode(layout_val, hss) ); 4180 hsize = _gvn.transform( new AndINode(hsize, hsm) ); 4181 Node* mask = intcon(round_mask); 4182 header_size = _gvn.transform( new AddINode(hsize, mask) ); 4183 } 4184 4185 Node* elem_shift = nullptr; 4186 if (layout_is_con) { 4187 int eshift = Klass::layout_helper_log2_element_size(layout_con); 4188 if (eshift != 0) 4189 elem_shift = intcon(eshift); 4190 } else { 4191 // There is no need to mask or shift this value. 4192 // The semantics of LShiftINode include an implicit mask to 0x1F. 4193 assert(Klass::_lh_log2_element_size_shift == 0, "use shift in place"); 4194 elem_shift = layout_val; 4195 } 4196 4197 // Transition to native address size for all offset calculations: 4198 Node* lengthx = ConvI2X(length); 4199 Node* headerx = ConvI2X(header_size); 4200 #ifdef _LP64 4201 { const TypeInt* tilen = _gvn.find_int_type(length); 4202 if (tilen != nullptr && tilen->_lo < 0) { 4203 // Add a manual constraint to a positive range. Cf. array_element_address. 4204 jint size_max = fast_size_limit; 4205 if (size_max > tilen->_hi) size_max = tilen->_hi; 4206 const TypeInt* tlcon = TypeInt::make(0, size_max, Type::WidenMin); 4207 4208 // Only do a narrow I2L conversion if the range check passed. 4209 IfNode* iff = new IfNode(control(), initial_slow_test, PROB_MIN, COUNT_UNKNOWN); 4210 _gvn.transform(iff); 4211 RegionNode* region = new RegionNode(3); 4212 _gvn.set_type(region, Type::CONTROL); 4213 lengthx = new PhiNode(region, TypeLong::LONG); 4214 _gvn.set_type(lengthx, TypeLong::LONG); 4215 4216 // Range check passed. Use ConvI2L node with narrow type. 4217 Node* passed = IfFalse(iff); 4218 region->init_req(1, passed); 4219 // Make I2L conversion control dependent to prevent it from 4220 // floating above the range check during loop optimizations. 4221 lengthx->init_req(1, C->constrained_convI2L(&_gvn, length, tlcon, passed)); 4222 4223 // Range check failed. Use ConvI2L with wide type because length may be invalid. 4224 region->init_req(2, IfTrue(iff)); 4225 lengthx->init_req(2, ConvI2X(length)); 4226 4227 set_control(region); 4228 record_for_igvn(region); 4229 record_for_igvn(lengthx); 4230 } 4231 } 4232 #endif 4233 4234 // Combine header size (plus rounding) and body size. Then round down. 4235 // This computation cannot overflow, because it is used only in two 4236 // places, one where the length is sharply limited, and the other 4237 // after a successful allocation. 4238 Node* abody = lengthx; 4239 if (elem_shift != nullptr) 4240 abody = _gvn.transform( new LShiftXNode(lengthx, elem_shift) ); 4241 Node* size = _gvn.transform( new AddXNode(headerx, abody) ); 4242 if (round_mask != 0) { 4243 Node* mask = MakeConX(~round_mask); 4244 size = _gvn.transform( new AndXNode(size, mask) ); 4245 } 4246 // else if round_mask == 0, the size computation is self-rounding 4247 4248 if (return_size_val != nullptr) { 4249 // This is the size 4250 (*return_size_val) = size; 4251 } 4252 4253 // Now generate allocation code 4254 4255 // The entire memory state is needed for slow path of the allocation 4256 // since GC and deoptimization can happen. 4257 Node *mem = reset_memory(); 4258 set_all_memory(mem); // Create new memory state 4259 4260 if (initial_slow_test->is_Bool()) { 4261 // Hide it behind a CMoveI, or else PhaseIdealLoop::split_up will get sick. 4262 initial_slow_test = initial_slow_test->as_Bool()->as_int_value(&_gvn); 4263 } 4264 4265 const TypeKlassPtr* ary_klass = _gvn.type(klass_node)->isa_klassptr(); 4266 const TypeOopPtr* ary_type = ary_klass->as_instance_type(); 4267 const TypeAryPtr* ary_ptr = ary_type->isa_aryptr(); 4268 4269 // Inline type array variants: 4270 // - null-ok: MyValue.ref[] (ciObjArrayKlass "[LMyValue") 4271 // - null-free: MyValue.val[] (ciObjArrayKlass "[QMyValue") 4272 // - null-free, flat : MyValue.val[] (ciFlatArrayKlass "[QMyValue") 4273 // Check if array is a null-free, non-flat inline type array 4274 // that needs to be initialized with the default inline type. 4275 Node* default_value = nullptr; 4276 Node* raw_default_value = nullptr; 4277 if (ary_ptr != nullptr && ary_ptr->klass_is_exact()) { 4278 // Array type is known 4279 if (ary_ptr->is_null_free() && !ary_ptr->is_flat()) { 4280 ciInlineKlass* vk = ary_ptr->elem()->inline_klass(); 4281 default_value = InlineTypeNode::default_oop(gvn(), vk); 4282 } 4283 } else if (ary_type->can_be_inline_array()) { 4284 // Array type is not known, add runtime checks 4285 assert(!ary_klass->klass_is_exact(), "unexpected exact type"); 4286 Node* r = new RegionNode(3); 4287 default_value = new PhiNode(r, TypeInstPtr::BOTTOM); 4288 4289 Node* bol = array_lh_test(klass_node, Klass::_lh_array_tag_flat_value_bit_inplace | Klass::_lh_null_free_array_bit_inplace, Klass::_lh_null_free_array_bit_inplace); 4290 IfNode* iff = create_and_map_if(control(), bol, PROB_FAIR, COUNT_UNKNOWN); 4291 4292 // Null-free, non-flat inline type array, initialize with the default value 4293 set_control(_gvn.transform(new IfTrueNode(iff))); 4294 Node* p = basic_plus_adr(klass_node, in_bytes(ArrayKlass::element_klass_offset())); 4295 Node* eklass = _gvn.transform(LoadKlassNode::make(_gvn, control(), immutable_memory(), p, TypeInstPtr::KLASS)); 4296 Node* adr_fixed_block_addr = basic_plus_adr(eklass, in_bytes(InstanceKlass::adr_inlineklass_fixed_block_offset())); 4297 Node* adr_fixed_block = make_load(control(), adr_fixed_block_addr, TypeRawPtr::NOTNULL, T_ADDRESS, MemNode::unordered); 4298 Node* default_value_offset_addr = basic_plus_adr(adr_fixed_block, in_bytes(InlineKlass::default_value_offset_offset())); 4299 Node* default_value_offset = make_load(control(), default_value_offset_addr, TypeInt::INT, T_INT, MemNode::unordered); 4300 Node* elem_mirror = load_mirror_from_klass(eklass); 4301 Node* default_value_addr = basic_plus_adr(elem_mirror, ConvI2X(default_value_offset)); 4302 Node* val = access_load_at(elem_mirror, default_value_addr, TypeInstPtr::MIRROR, TypeInstPtr::NOTNULL, T_OBJECT, IN_HEAP); 4303 r->init_req(1, control()); 4304 default_value->init_req(1, val); 4305 4306 // Otherwise initialize with all zero 4307 r->init_req(2, _gvn.transform(new IfFalseNode(iff))); 4308 default_value->init_req(2, null()); 4309 4310 set_control(_gvn.transform(r)); 4311 default_value = _gvn.transform(default_value); 4312 } 4313 if (default_value != nullptr) { 4314 if (UseCompressedOops) { 4315 // With compressed oops, the 64-bit init value is built from two 32-bit compressed oops 4316 default_value = _gvn.transform(new EncodePNode(default_value, default_value->bottom_type()->make_narrowoop())); 4317 Node* lower = _gvn.transform(new CastP2XNode(control(), default_value)); 4318 Node* upper = _gvn.transform(new LShiftLNode(lower, intcon(32))); 4319 raw_default_value = _gvn.transform(new OrLNode(lower, upper)); 4320 } else { 4321 raw_default_value = _gvn.transform(new CastP2XNode(control(), default_value)); 4322 } 4323 } 4324 4325 Node* valid_length_test = _gvn.intcon(1); 4326 if (ary_type->isa_aryptr()) { 4327 BasicType bt = ary_type->isa_aryptr()->elem()->array_element_basic_type(); 4328 jint max = TypeAryPtr::max_array_length(bt); 4329 Node* valid_length_cmp = _gvn.transform(new CmpUNode(length, intcon(max))); 4330 valid_length_test = _gvn.transform(new BoolNode(valid_length_cmp, BoolTest::le)); 4331 } 4332 4333 // Create the AllocateArrayNode and its result projections 4334 AllocateArrayNode* alloc 4335 = new AllocateArrayNode(C, AllocateArrayNode::alloc_type(TypeInt::INT), 4336 control(), mem, i_o(), 4337 size, klass_node, 4338 initial_slow_test, 4339 length, valid_length_test, 4340 default_value, raw_default_value); 4341 // Cast to correct type. Note that the klass_node may be constant or not, 4342 // and in the latter case the actual array type will be inexact also. 4343 // (This happens via a non-constant argument to inline_native_newArray.) 4344 // In any case, the value of klass_node provides the desired array type. 4345 const TypeInt* length_type = _gvn.find_int_type(length); 4346 if (ary_type->isa_aryptr() && length_type != nullptr) { 4347 // Try to get a better type than POS for the size 4348 ary_type = ary_type->is_aryptr()->cast_to_size(length_type); 4349 } 4350 4351 Node* javaoop = set_output_for_allocation(alloc, ary_type, deoptimize_on_exception); 4352 4353 array_ideal_length(alloc, ary_type, true); 4354 return javaoop; 4355 } 4356 4357 // The following "Ideal_foo" functions are placed here because they recognize 4358 // the graph shapes created by the functions immediately above. 4359 4360 //---------------------------Ideal_allocation---------------------------------- 4361 // Given an oop pointer or raw pointer, see if it feeds from an AllocateNode. 4362 AllocateNode* AllocateNode::Ideal_allocation(Node* ptr) { 4363 if (ptr == nullptr) { // reduce dumb test in callers 4364 return nullptr; 4365 } 4366 4367 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2(); 4368 ptr = bs->step_over_gc_barrier(ptr); 4369 4370 if (ptr->is_CheckCastPP()) { // strip only one raw-to-oop cast 4371 ptr = ptr->in(1); 4372 if (ptr == nullptr) return nullptr; 4373 } 4374 // Return null for allocations with several casts: 4375 // j.l.reflect.Array.newInstance(jobject, jint) 4376 // Object.clone() 4377 // to keep more precise type from last cast. 4378 if (ptr->is_Proj()) { 4379 Node* allo = ptr->in(0); 4380 if (allo != nullptr && allo->is_Allocate()) { 4381 return allo->as_Allocate(); 4382 } 4383 } 4384 // Report failure to match. 4385 return nullptr; 4386 } 4387 4388 // Fancy version which also strips off an offset (and reports it to caller). 4389 AllocateNode* AllocateNode::Ideal_allocation(Node* ptr, PhaseValues* phase, 4390 intptr_t& offset) { 4391 Node* base = AddPNode::Ideal_base_and_offset(ptr, phase, offset); 4392 if (base == nullptr) return nullptr; 4393 return Ideal_allocation(base); 4394 } 4395 4396 // Trace Initialize <- Proj[Parm] <- Allocate 4397 AllocateNode* InitializeNode::allocation() { 4398 Node* rawoop = in(InitializeNode::RawAddress); 4399 if (rawoop->is_Proj()) { 4400 Node* alloc = rawoop->in(0); 4401 if (alloc->is_Allocate()) { 4402 return alloc->as_Allocate(); 4403 } 4404 } 4405 return nullptr; 4406 } 4407 4408 // Trace Allocate -> Proj[Parm] -> Initialize 4409 InitializeNode* AllocateNode::initialization() { 4410 ProjNode* rawoop = proj_out_or_null(AllocateNode::RawAddress); 4411 if (rawoop == nullptr) return nullptr; 4412 for (DUIterator_Fast imax, i = rawoop->fast_outs(imax); i < imax; i++) { 4413 Node* init = rawoop->fast_out(i); 4414 if (init->is_Initialize()) { 4415 assert(init->as_Initialize()->allocation() == this, "2-way link"); 4416 return init->as_Initialize(); 4417 } 4418 } 4419 return nullptr; 4420 } 4421 4422 // Add a Parse Predicate with an uncommon trap on the failing/false path. Normal control will continue on the true path. 4423 void GraphKit::add_parse_predicate(Deoptimization::DeoptReason reason, const int nargs) { 4424 // Too many traps seen? 4425 if (too_many_traps(reason)) { 4426 #ifdef ASSERT 4427 if (TraceLoopPredicate) { 4428 int tc = C->trap_count(reason); 4429 tty->print("too many traps=%s tcount=%d in ", 4430 Deoptimization::trap_reason_name(reason), tc); 4431 method()->print(); // which method has too many predicate traps 4432 tty->cr(); 4433 } 4434 #endif 4435 // We cannot afford to take more traps here, 4436 // do not generate Parse Predicate. 4437 return; 4438 } 4439 4440 Node* cont = _gvn.intcon(1); 4441 Node* opaq = _gvn.transform(new Opaque1Node(C, cont)); 4442 C->add_parse_predicate_opaq(opaq); 4443 Node* bol = _gvn.transform(new Conv2BNode(opaq)); 4444 ParsePredicateNode* parse_predicate = new ParsePredicateNode(control(), bol, reason); 4445 _gvn.set_type(parse_predicate, parse_predicate->Value(&_gvn)); 4446 Node* if_false = _gvn.transform(new IfFalseNode(parse_predicate)); 4447 { 4448 PreserveJVMState pjvms(this); 4449 set_control(if_false); 4450 inc_sp(nargs); 4451 uncommon_trap(reason, Deoptimization::Action_maybe_recompile); 4452 } 4453 Node* if_true = _gvn.transform(new IfTrueNode(parse_predicate)); 4454 set_control(if_true); 4455 } 4456 4457 // Add Parse Predicates which serve as placeholders to create new Runtime Predicates above them. All 4458 // Runtime Predicates inside a Runtime Predicate block share the same uncommon trap as the Parse Predicate. 4459 void GraphKit::add_parse_predicates(int nargs) { 4460 if (UseLoopPredicate) { 4461 add_parse_predicate(Deoptimization::Reason_predicate, nargs); 4462 } 4463 if (UseProfiledLoopPredicate) { 4464 add_parse_predicate(Deoptimization::Reason_profile_predicate, nargs); 4465 } 4466 // Loop Limit Check Predicate should be near the loop. 4467 add_parse_predicate(Deoptimization::Reason_loop_limit_check, nargs); 4468 } 4469 4470 void GraphKit::sync_kit(IdealKit& ideal) { 4471 set_all_memory(ideal.merged_memory()); 4472 set_i_o(ideal.i_o()); 4473 set_control(ideal.ctrl()); 4474 } 4475 4476 void GraphKit::final_sync(IdealKit& ideal) { 4477 // Final sync IdealKit and graphKit. 4478 sync_kit(ideal); 4479 } 4480 4481 Node* GraphKit::load_String_length(Node* str, bool set_ctrl) { 4482 Node* len = load_array_length(load_String_value(str, set_ctrl)); 4483 Node* coder = load_String_coder(str, set_ctrl); 4484 // Divide length by 2 if coder is UTF16 4485 return _gvn.transform(new RShiftINode(len, coder)); 4486 } 4487 4488 Node* GraphKit::load_String_value(Node* str, bool set_ctrl) { 4489 int value_offset = java_lang_String::value_offset(); 4490 const TypeInstPtr* string_type = TypeInstPtr::make(TypePtr::NotNull, C->env()->String_klass(), 4491 false, nullptr, Type::Offset(0)); 4492 const TypePtr* value_field_type = string_type->add_offset(value_offset); 4493 const TypeAryPtr* value_type = TypeAryPtr::make(TypePtr::NotNull, 4494 TypeAry::make(TypeInt::BYTE, TypeInt::POS, false, false, true, true), 4495 ciTypeArrayKlass::make(T_BYTE), true, Type::Offset(0)); 4496 Node* p = basic_plus_adr(str, str, value_offset); 4497 Node* load = access_load_at(str, p, value_field_type, value_type, T_OBJECT, 4498 IN_HEAP | (set_ctrl ? C2_CONTROL_DEPENDENT_LOAD : 0) | MO_UNORDERED); 4499 return load; 4500 } 4501 4502 Node* GraphKit::load_String_coder(Node* str, bool set_ctrl) { 4503 if (!CompactStrings) { 4504 return intcon(java_lang_String::CODER_UTF16); 4505 } 4506 int coder_offset = java_lang_String::coder_offset(); 4507 const TypeInstPtr* string_type = TypeInstPtr::make(TypePtr::NotNull, C->env()->String_klass(), 4508 false, nullptr, Type::Offset(0)); 4509 const TypePtr* coder_field_type = string_type->add_offset(coder_offset); 4510 4511 Node* p = basic_plus_adr(str, str, coder_offset); 4512 Node* load = access_load_at(str, p, coder_field_type, TypeInt::BYTE, T_BYTE, 4513 IN_HEAP | (set_ctrl ? C2_CONTROL_DEPENDENT_LOAD : 0) | MO_UNORDERED); 4514 return load; 4515 } 4516 4517 void GraphKit::store_String_value(Node* str, Node* value) { 4518 int value_offset = java_lang_String::value_offset(); 4519 const TypeInstPtr* string_type = TypeInstPtr::make(TypePtr::NotNull, C->env()->String_klass(), 4520 false, nullptr, Type::Offset(0)); 4521 const TypePtr* value_field_type = string_type->add_offset(value_offset); 4522 4523 access_store_at(str, basic_plus_adr(str, value_offset), value_field_type, 4524 value, TypeAryPtr::BYTES, T_OBJECT, IN_HEAP | MO_UNORDERED); 4525 } 4526 4527 void GraphKit::store_String_coder(Node* str, Node* value) { 4528 int coder_offset = java_lang_String::coder_offset(); 4529 const TypeInstPtr* string_type = TypeInstPtr::make(TypePtr::NotNull, C->env()->String_klass(), 4530 false, nullptr, Type::Offset(0)); 4531 const TypePtr* coder_field_type = string_type->add_offset(coder_offset); 4532 4533 access_store_at(str, basic_plus_adr(str, coder_offset), coder_field_type, 4534 value, TypeInt::BYTE, T_BYTE, IN_HEAP | MO_UNORDERED); 4535 } 4536 4537 // Capture src and dst memory state with a MergeMemNode 4538 Node* GraphKit::capture_memory(const TypePtr* src_type, const TypePtr* dst_type) { 4539 if (src_type == dst_type) { 4540 // Types are equal, we don't need a MergeMemNode 4541 return memory(src_type); 4542 } 4543 MergeMemNode* merge = MergeMemNode::make(map()->memory()); 4544 record_for_igvn(merge); // fold it up later, if possible 4545 int src_idx = C->get_alias_index(src_type); 4546 int dst_idx = C->get_alias_index(dst_type); 4547 merge->set_memory_at(src_idx, memory(src_idx)); 4548 merge->set_memory_at(dst_idx, memory(dst_idx)); 4549 return merge; 4550 } 4551 4552 Node* GraphKit::compress_string(Node* src, const TypeAryPtr* src_type, Node* dst, Node* count) { 4553 assert(Matcher::match_rule_supported(Op_StrCompressedCopy), "Intrinsic not supported"); 4554 assert(src_type == TypeAryPtr::BYTES || src_type == TypeAryPtr::CHARS, "invalid source type"); 4555 // If input and output memory types differ, capture both states to preserve 4556 // the dependency between preceding and subsequent loads/stores. 4557 // For example, the following program: 4558 // StoreB 4559 // compress_string 4560 // LoadB 4561 // has this memory graph (use->def): 4562 // LoadB -> compress_string -> CharMem 4563 // ... -> StoreB -> ByteMem 4564 // The intrinsic hides the dependency between LoadB and StoreB, causing 4565 // the load to read from memory not containing the result of the StoreB. 4566 // The correct memory graph should look like this: 4567 // LoadB -> compress_string -> MergeMem(CharMem, StoreB(ByteMem)) 4568 Node* mem = capture_memory(src_type, TypeAryPtr::BYTES); 4569 StrCompressedCopyNode* str = new StrCompressedCopyNode(control(), mem, src, dst, count); 4570 Node* res_mem = _gvn.transform(new SCMemProjNode(_gvn.transform(str))); 4571 set_memory(res_mem, TypeAryPtr::BYTES); 4572 return str; 4573 } 4574 4575 void GraphKit::inflate_string(Node* src, Node* dst, const TypeAryPtr* dst_type, Node* count) { 4576 assert(Matcher::match_rule_supported(Op_StrInflatedCopy), "Intrinsic not supported"); 4577 assert(dst_type == TypeAryPtr::BYTES || dst_type == TypeAryPtr::CHARS, "invalid dest type"); 4578 // Capture src and dst memory (see comment in 'compress_string'). 4579 Node* mem = capture_memory(TypeAryPtr::BYTES, dst_type); 4580 StrInflatedCopyNode* str = new StrInflatedCopyNode(control(), mem, src, dst, count); 4581 set_memory(_gvn.transform(str), dst_type); 4582 } 4583 4584 void GraphKit::inflate_string_slow(Node* src, Node* dst, Node* start, Node* count) { 4585 /** 4586 * int i_char = start; 4587 * for (int i_byte = 0; i_byte < count; i_byte++) { 4588 * dst[i_char++] = (char)(src[i_byte] & 0xff); 4589 * } 4590 */ 4591 add_parse_predicates(); 4592 C->set_has_loops(true); 4593 4594 RegionNode* head = new RegionNode(3); 4595 head->init_req(1, control()); 4596 gvn().set_type(head, Type::CONTROL); 4597 record_for_igvn(head); 4598 4599 Node* i_byte = new PhiNode(head, TypeInt::INT); 4600 i_byte->init_req(1, intcon(0)); 4601 gvn().set_type(i_byte, TypeInt::INT); 4602 record_for_igvn(i_byte); 4603 4604 Node* i_char = new PhiNode(head, TypeInt::INT); 4605 i_char->init_req(1, start); 4606 gvn().set_type(i_char, TypeInt::INT); 4607 record_for_igvn(i_char); 4608 4609 Node* mem = PhiNode::make(head, memory(TypeAryPtr::BYTES), Type::MEMORY, TypeAryPtr::BYTES); 4610 gvn().set_type(mem, Type::MEMORY); 4611 record_for_igvn(mem); 4612 set_control(head); 4613 set_memory(mem, TypeAryPtr::BYTES); 4614 Node* ch = load_array_element(src, i_byte, TypeAryPtr::BYTES, /* set_ctrl */ true); 4615 Node* st = store_to_memory(control(), array_element_address(dst, i_char, T_BYTE), 4616 AndI(ch, intcon(0xff)), T_CHAR, TypeAryPtr::BYTES, MemNode::unordered, 4617 false, false, true /* mismatched */); 4618 4619 IfNode* iff = create_and_map_if(head, Bool(CmpI(i_byte, count), BoolTest::lt), PROB_FAIR, COUNT_UNKNOWN); 4620 head->init_req(2, IfTrue(iff)); 4621 mem->init_req(2, st); 4622 i_byte->init_req(2, AddI(i_byte, intcon(1))); 4623 i_char->init_req(2, AddI(i_char, intcon(2))); 4624 4625 set_control(IfFalse(iff)); 4626 set_memory(st, TypeAryPtr::BYTES); 4627 } 4628 4629 Node* GraphKit::make_constant_from_field(ciField* field, Node* obj) { 4630 if (!field->is_constant()) { 4631 return nullptr; // Field not marked as constant. 4632 } 4633 ciInstance* holder = nullptr; 4634 if (!field->is_static()) { 4635 ciObject* const_oop = obj->bottom_type()->is_oopptr()->const_oop(); 4636 if (const_oop != nullptr && const_oop->is_instance()) { 4637 holder = const_oop->as_instance(); 4638 } 4639 } 4640 const Type* con_type = Type::make_constant_from_field(field, holder, field->layout_type(), 4641 /*is_unsigned_load=*/false); 4642 if (con_type != nullptr) { 4643 Node* con = makecon(con_type); 4644 if (field->type()->is_inlinetype()) { 4645 con = InlineTypeNode::make_from_oop(this, con, field->type()->as_inline_klass(), field->is_null_free()); 4646 } else if (con_type->is_inlinetypeptr()) { 4647 con = InlineTypeNode::make_from_oop(this, con, con_type->inline_klass(), field->is_null_free()); 4648 } 4649 return con; 4650 } 4651 return nullptr; 4652 } 4653 4654 //---------------------------load_mirror_from_klass---------------------------- 4655 // Given a klass oop, load its java mirror (a java.lang.Class oop). 4656 Node* GraphKit::load_mirror_from_klass(Node* klass) { 4657 Node* p = basic_plus_adr(klass, in_bytes(Klass::java_mirror_offset())); 4658 Node* load = make_load(nullptr, p, TypeRawPtr::NOTNULL, T_ADDRESS, MemNode::unordered); 4659 // mirror = ((OopHandle)mirror)->resolve(); 4660 return access_load(load, TypeInstPtr::MIRROR, T_OBJECT, IN_NATIVE); 4661 }