1 /* 2 * Copyright (c) 2009, 2016, 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 "compiler/compileLog.hpp" 27 #include "opto/addnode.hpp" 28 #include "opto/callGenerator.hpp" 29 #include "opto/callnode.hpp" 30 #include "opto/divnode.hpp" 31 #include "opto/graphKit.hpp" 32 #include "opto/idealKit.hpp" 33 #include "opto/rootnode.hpp" 34 #include "opto/runtime.hpp" 35 #include "opto/shenandoahSupport.hpp" 36 #include "opto/stringopts.hpp" 37 #include "opto/subnode.hpp" 38 39 #define __ kit. 40 41 class StringConcat : public ResourceObj { 42 private: 43 PhaseStringOpts* _stringopts; 44 Node* _string_alloc; 45 AllocateNode* _begin; // The allocation the begins the pattern 46 CallStaticJavaNode* _end; // The final call of the pattern. Will either be 47 // SB.toString or or String.<init>(SB.toString) 48 bool _multiple; // indicates this is a fusion of two or more 49 // separate StringBuilders 50 51 Node* _arguments; // The list of arguments to be concatenated 52 GrowableArray<int> _mode; // into a String along with a mode flag 53 // indicating how to treat the value. 54 Node_List _constructors; // List of constructors (many in case of stacked concat) 55 Node_List _control; // List of control nodes that will be deleted 56 Node_List _uncommon_traps; // Uncommon traps that needs to be rewritten 57 // to restart at the initial JVMState. 58 59 public: 60 // Mode for converting arguments to Strings 61 enum { 62 StringMode, 63 IntMode, 64 CharMode, 65 StringNullCheckMode 66 }; 67 68 StringConcat(PhaseStringOpts* stringopts, CallStaticJavaNode* end): 69 _end(end), 70 _begin(NULL), 71 _multiple(false), 72 _string_alloc(NULL), 73 _stringopts(stringopts) { 74 _arguments = new (_stringopts->C) Node(1); 75 _arguments->del_req(0); 76 } 77 78 bool validate_mem_flow(); 79 bool validate_control_flow(); 80 81 void merge_add() { 82 #if 0 83 // XXX This is place holder code for reusing an existing String 84 // allocation but the logic for checking the state safety is 85 // probably inadequate at the moment. 86 CallProjections endprojs; 87 sc->end()->extract_projections(&endprojs, false); 88 if (endprojs.resproj != NULL) { 89 for (SimpleDUIterator i(endprojs.resproj); i.has_next(); i.next()) { 90 CallStaticJavaNode *use = i.get()->isa_CallStaticJava(); 91 if (use != NULL && use->method() != NULL && 92 use->method()->intrinsic_id() == vmIntrinsics::_String_String && 93 use->in(TypeFunc::Parms + 1) == endprojs.resproj) { 94 // Found useless new String(sb.toString()) so reuse the newly allocated String 95 // when creating the result instead of allocating a new one. 96 sc->set_string_alloc(use->in(TypeFunc::Parms)); 97 sc->set_end(use); 98 } 99 } 100 } 101 #endif 102 } 103 104 StringConcat* merge(StringConcat* other, Node* arg); 105 106 void set_allocation(AllocateNode* alloc) { 107 _begin = alloc; 108 } 109 110 void append(Node* value, int mode) { 111 _arguments->add_req(value); 112 _mode.append(mode); 113 } 114 void push(Node* value, int mode) { 115 _arguments->ins_req(0, value); 116 _mode.insert_before(0, mode); 117 } 118 119 void push_string(Node* value) { 120 push(value, StringMode); 121 } 122 void push_string_null_check(Node* value) { 123 push(value, StringNullCheckMode); 124 } 125 void push_int(Node* value) { 126 push(value, IntMode); 127 } 128 void push_char(Node* value) { 129 push(value, CharMode); 130 } 131 132 static bool is_SB_toString(Node* call) { 133 if (call->is_CallStaticJava()) { 134 CallStaticJavaNode* csj = call->as_CallStaticJava(); 135 ciMethod* m = csj->method(); 136 if (m != NULL && 137 (m->intrinsic_id() == vmIntrinsics::_StringBuilder_toString || 138 m->intrinsic_id() == vmIntrinsics::_StringBuffer_toString)) { 139 return true; 140 } 141 } 142 return false; 143 } 144 145 static Node* skip_string_null_check(Node* value) { 146 // Look for a diamond shaped Null check of toString() result 147 // (could be code from String.valueOf()): 148 // (Proj == NULL) ? "null":"CastPP(Proj)#NotNULL 149 if (value->is_Phi()) { 150 int true_path = value->as_Phi()->is_diamond_phi(); 151 if (true_path != 0) { 152 // phi->region->if_proj->ifnode->bool 153 BoolNode* b = value->in(0)->in(1)->in(0)->in(1)->as_Bool(); 154 Node* cmp = b->in(1); 155 Node* v1 = cmp->in(1); 156 Node* v2 = cmp->in(2); 157 // Null check of the return of toString which can simply be skipped. 158 if (b->_test._test == BoolTest::ne && 159 v2->bottom_type() == TypePtr::NULL_PTR && 160 value->in(true_path)->Opcode() == Op_CastPP && 161 value->in(true_path)->in(1) == v1 && 162 v1->is_Proj() && is_SB_toString(v1->in(0))) { 163 return v1; 164 } 165 } 166 } 167 return value; 168 } 169 170 Node* argument(int i) { 171 return _arguments->in(i); 172 } 173 Node* argument_uncast(int i) { 174 Node* arg = argument(i); 175 int amode = mode(i); 176 if (amode == StringConcat::StringMode || 177 amode == StringConcat::StringNullCheckMode) { 178 arg = skip_string_null_check(arg); 179 } 180 return arg; 181 } 182 void set_argument(int i, Node* value) { 183 _arguments->set_req(i, value); 184 } 185 int num_arguments() { 186 return _mode.length(); 187 } 188 int mode(int i) { 189 return _mode.at(i); 190 } 191 void add_control(Node* ctrl) { 192 assert(!_control.contains(ctrl), "only push once"); 193 _control.push(ctrl); 194 } 195 void add_constructor(Node* init) { 196 assert(!_constructors.contains(init), "only push once"); 197 _constructors.push(init); 198 } 199 CallStaticJavaNode* end() { return _end; } 200 AllocateNode* begin() { return _begin; } 201 Node* string_alloc() { return _string_alloc; } 202 203 void eliminate_unneeded_control(); 204 void eliminate_initialize(InitializeNode* init); 205 void eliminate_call(CallNode* call); 206 207 void maybe_log_transform() { 208 CompileLog* log = _stringopts->C->log(); 209 if (log != NULL) { 210 log->head("replace_string_concat arguments='%d' string_alloc='%d' multiple='%d'", 211 num_arguments(), 212 _string_alloc != NULL, 213 _multiple); 214 JVMState* p = _begin->jvms(); 215 while (p != NULL) { 216 log->elem("jvms bci='%d' method='%d'", p->bci(), log->identify(p->method())); 217 p = p->caller(); 218 } 219 log->tail("replace_string_concat"); 220 } 221 } 222 223 void convert_uncommon_traps(GraphKit& kit, const JVMState* jvms) { 224 for (uint u = 0; u < _uncommon_traps.size(); u++) { 225 Node* uct = _uncommon_traps.at(u); 226 227 // Build a new call using the jvms state of the allocate 228 address call_addr = SharedRuntime::uncommon_trap_blob()->entry_point(); 229 const TypeFunc* call_type = OptoRuntime::uncommon_trap_Type(); 230 const TypePtr* no_memory_effects = NULL; 231 Compile* C = _stringopts->C; 232 CallStaticJavaNode* call = new (C) CallStaticJavaNode(call_type, call_addr, "uncommon_trap", 233 jvms->bci(), no_memory_effects); 234 for (int e = 0; e < TypeFunc::Parms; e++) { 235 call->init_req(e, uct->in(e)); 236 } 237 // Set the trap request to record intrinsic failure if this trap 238 // is taken too many times. Ideally we would handle then traps by 239 // doing the original bookkeeping in the MDO so that if it caused 240 // the code to be thrown out we could still recompile and use the 241 // optimization. Failing the uncommon traps doesn't really mean 242 // that the optimization is a bad idea but there's no other way to 243 // do the MDO updates currently. 244 int trap_request = Deoptimization::make_trap_request(Deoptimization::Reason_intrinsic, 245 Deoptimization::Action_make_not_entrant); 246 call->init_req(TypeFunc::Parms, __ intcon(trap_request)); 247 kit.add_safepoint_edges(call); 248 249 _stringopts->gvn()->transform(call); 250 C->gvn_replace_by(uct, call); 251 uct->disconnect_inputs(NULL, C); 252 } 253 } 254 255 void cleanup() { 256 // disconnect the hook node 257 _arguments->disconnect_inputs(NULL, _stringopts->C); 258 } 259 }; 260 261 262 void StringConcat::eliminate_unneeded_control() { 263 for (uint i = 0; i < _control.size(); i++) { 264 Node* n = _control.at(i); 265 if (n->is_Allocate()) { 266 eliminate_initialize(n->as_Allocate()->initialization()); 267 } 268 if (n->is_Call()) { 269 if (n != _end) { 270 eliminate_call(n->as_Call()); 271 } 272 } else if (n->is_IfTrue()) { 273 Compile* C = _stringopts->C; 274 C->gvn_replace_by(n, n->in(0)->in(0)); 275 // get rid of the other projection 276 C->gvn_replace_by(n->in(0)->as_If()->proj_out(false), C->top()); 277 } 278 } 279 } 280 281 282 StringConcat* StringConcat::merge(StringConcat* other, Node* arg) { 283 StringConcat* result = new StringConcat(_stringopts, _end); 284 for (uint x = 0; x < _control.size(); x++) { 285 Node* n = _control.at(x); 286 if (n->is_Call()) { 287 result->_control.push(n); 288 } 289 } 290 for (uint x = 0; x < other->_control.size(); x++) { 291 Node* n = other->_control.at(x); 292 if (n->is_Call()) { 293 result->_control.push(n); 294 } 295 } 296 assert(result->_control.contains(other->_end), "what?"); 297 assert(result->_control.contains(_begin), "what?"); 298 for (int x = 0; x < num_arguments(); x++) { 299 Node* argx = argument_uncast(x); 300 if (argx == arg) { 301 // replace the toString result with the all the arguments that 302 // made up the other StringConcat 303 for (int y = 0; y < other->num_arguments(); y++) { 304 result->append(other->argument(y), other->mode(y)); 305 } 306 } else { 307 result->append(argx, mode(x)); 308 } 309 } 310 result->set_allocation(other->_begin); 311 for (uint i = 0; i < _constructors.size(); i++) { 312 result->add_constructor(_constructors.at(i)); 313 } 314 for (uint i = 0; i < other->_constructors.size(); i++) { 315 result->add_constructor(other->_constructors.at(i)); 316 } 317 result->_multiple = true; 318 return result; 319 } 320 321 322 void StringConcat::eliminate_call(CallNode* call) { 323 Compile* C = _stringopts->C; 324 CallProjections projs; 325 call->extract_projections(&projs, false); 326 if (projs.fallthrough_catchproj != NULL) { 327 C->gvn_replace_by(projs.fallthrough_catchproj, call->in(TypeFunc::Control)); 328 } 329 if (projs.fallthrough_memproj != NULL) { 330 C->gvn_replace_by(projs.fallthrough_memproj, call->in(TypeFunc::Memory)); 331 } 332 if (projs.catchall_memproj != NULL) { 333 C->gvn_replace_by(projs.catchall_memproj, C->top()); 334 } 335 if (projs.fallthrough_ioproj != NULL) { 336 C->gvn_replace_by(projs.fallthrough_ioproj, call->in(TypeFunc::I_O)); 337 } 338 if (projs.catchall_ioproj != NULL) { 339 C->gvn_replace_by(projs.catchall_ioproj, C->top()); 340 } 341 if (projs.catchall_catchproj != NULL) { 342 // EA can't cope with the partially collapsed graph this 343 // creates so put it on the worklist to be collapsed later. 344 for (SimpleDUIterator i(projs.catchall_catchproj); i.has_next(); i.next()) { 345 Node *use = i.get(); 346 int opc = use->Opcode(); 347 if (opc == Op_CreateEx || opc == Op_Region) { 348 _stringopts->record_dead_node(use); 349 } 350 } 351 C->gvn_replace_by(projs.catchall_catchproj, C->top()); 352 } 353 if (projs.resproj != NULL) { 354 C->gvn_replace_by(projs.resproj, C->top()); 355 } 356 C->gvn_replace_by(call, C->top()); 357 } 358 359 void StringConcat::eliminate_initialize(InitializeNode* init) { 360 Compile* C = _stringopts->C; 361 362 // Eliminate Initialize node. 363 assert(init->outcnt() <= 2, "only a control and memory projection expected"); 364 assert(init->req() <= InitializeNode::RawStores, "no pending inits"); 365 Node *ctrl_proj = init->proj_out(TypeFunc::Control); 366 if (ctrl_proj != NULL) { 367 C->gvn_replace_by(ctrl_proj, init->in(TypeFunc::Control)); 368 } 369 Node *mem_proj = init->proj_out(TypeFunc::Memory); 370 if (mem_proj != NULL) { 371 Node *mem = init->in(TypeFunc::Memory); 372 C->gvn_replace_by(mem_proj, mem); 373 } 374 C->gvn_replace_by(init, C->top()); 375 init->disconnect_inputs(NULL, C); 376 } 377 378 Node_List PhaseStringOpts::collect_toString_calls() { 379 Node_List string_calls; 380 Node_List worklist; 381 382 _visited.Clear(); 383 384 // Prime the worklist 385 for (uint i = 1; i < C->root()->len(); i++) { 386 Node* n = C->root()->in(i); 387 if (n != NULL && !_visited.test_set(n->_idx)) { 388 worklist.push(n); 389 } 390 } 391 392 while (worklist.size() > 0) { 393 Node* ctrl = worklist.pop(); 394 if (StringConcat::is_SB_toString(ctrl)) { 395 CallStaticJavaNode* csj = ctrl->as_CallStaticJava(); 396 string_calls.push(csj); 397 } 398 if (ctrl->in(0) != NULL && !_visited.test_set(ctrl->in(0)->_idx)) { 399 worklist.push(ctrl->in(0)); 400 } 401 if (ctrl->is_Region()) { 402 for (uint i = 1; i < ctrl->len(); i++) { 403 if (ctrl->in(i) != NULL && !_visited.test_set(ctrl->in(i)->_idx)) { 404 worklist.push(ctrl->in(i)); 405 } 406 } 407 } 408 } 409 return string_calls; 410 } 411 412 413 StringConcat* PhaseStringOpts::build_candidate(CallStaticJavaNode* call) { 414 ciMethod* m = call->method(); 415 ciSymbol* string_sig; 416 ciSymbol* int_sig; 417 ciSymbol* char_sig; 418 if (m->holder() == C->env()->StringBuilder_klass()) { 419 string_sig = ciSymbol::String_StringBuilder_signature(); 420 int_sig = ciSymbol::int_StringBuilder_signature(); 421 char_sig = ciSymbol::char_StringBuilder_signature(); 422 } else if (m->holder() == C->env()->StringBuffer_klass()) { 423 string_sig = ciSymbol::String_StringBuffer_signature(); 424 int_sig = ciSymbol::int_StringBuffer_signature(); 425 char_sig = ciSymbol::char_StringBuffer_signature(); 426 } else { 427 return NULL; 428 } 429 #ifndef PRODUCT 430 if (PrintOptimizeStringConcat) { 431 tty->print("considering toString call in "); 432 call->jvms()->dump_spec(tty); tty->cr(); 433 } 434 #endif 435 436 StringConcat* sc = new StringConcat(this, call); 437 438 AllocateNode* alloc = NULL; 439 InitializeNode* init = NULL; 440 441 // possible opportunity for StringBuilder fusion 442 CallStaticJavaNode* cnode = call; 443 while (cnode) { 444 Node* recv = cnode->in(TypeFunc::Parms)->uncast(); 445 if (recv->is_Proj()) { 446 recv = recv->in(0); 447 } 448 cnode = recv->isa_CallStaticJava(); 449 if (cnode == NULL) { 450 alloc = recv->isa_Allocate(); 451 if (alloc == NULL) { 452 break; 453 } 454 // Find the constructor call 455 Node* result = alloc->result_cast(); 456 if (result == NULL || !result->is_CheckCastPP() || alloc->in(TypeFunc::Memory)->is_top()) { 457 // strange looking allocation 458 #ifndef PRODUCT 459 if (PrintOptimizeStringConcat) { 460 tty->print("giving up because allocation looks strange "); 461 alloc->jvms()->dump_spec(tty); tty->cr(); 462 } 463 #endif 464 break; 465 } 466 Node* constructor = NULL; 467 for (SimpleDUIterator i(result); i.has_next(); i.next()) { 468 CallStaticJavaNode *use = i.get()->isa_CallStaticJava(); 469 if (use != NULL && 470 use->method() != NULL && 471 !use->method()->is_static() && 472 use->method()->name() == ciSymbol::object_initializer_name() && 473 use->method()->holder() == m->holder()) { 474 // Matched the constructor. 475 ciSymbol* sig = use->method()->signature()->as_symbol(); 476 if (sig == ciSymbol::void_method_signature() || 477 sig == ciSymbol::int_void_signature() || 478 sig == ciSymbol::string_void_signature()) { 479 if (sig == ciSymbol::string_void_signature()) { 480 // StringBuilder(String) so pick this up as the first argument 481 assert(use->in(TypeFunc::Parms + 1) != NULL, "what?"); 482 const Type* type = _gvn->type(use->in(TypeFunc::Parms + 1)); 483 if (type == TypePtr::NULL_PTR) { 484 // StringBuilder(null) throws exception. 485 #ifndef PRODUCT 486 if (PrintOptimizeStringConcat) { 487 tty->print("giving up because StringBuilder(null) throws exception"); 488 alloc->jvms()->dump_spec(tty); tty->cr(); 489 } 490 #endif 491 return NULL; 492 } 493 // StringBuilder(str) argument needs null check. 494 sc->push_string_null_check(use->in(TypeFunc::Parms + 1)); 495 } 496 // The int variant takes an initial size for the backing 497 // array so just treat it like the void version. 498 constructor = use; 499 } else { 500 #ifndef PRODUCT 501 if (PrintOptimizeStringConcat) { 502 tty->print("unexpected constructor signature: %s", sig->as_utf8()); 503 } 504 #endif 505 } 506 break; 507 } 508 } 509 if (constructor == NULL) { 510 // couldn't find constructor 511 #ifndef PRODUCT 512 if (PrintOptimizeStringConcat) { 513 tty->print("giving up because couldn't find constructor "); 514 alloc->jvms()->dump_spec(tty); tty->cr(); 515 } 516 #endif 517 break; 518 } 519 520 // Walked all the way back and found the constructor call so see 521 // if this call converted into a direct string concatenation. 522 sc->add_control(call); 523 sc->add_control(constructor); 524 sc->add_control(alloc); 525 sc->set_allocation(alloc); 526 sc->add_constructor(constructor); 527 if (sc->validate_control_flow() && sc->validate_mem_flow()) { 528 return sc; 529 } else { 530 return NULL; 531 } 532 } else if (cnode->method() == NULL) { 533 break; 534 } else if (!cnode->method()->is_static() && 535 cnode->method()->holder() == m->holder() && 536 cnode->method()->name() == ciSymbol::append_name() && 537 (cnode->method()->signature()->as_symbol() == string_sig || 538 cnode->method()->signature()->as_symbol() == char_sig || 539 cnode->method()->signature()->as_symbol() == int_sig)) { 540 sc->add_control(cnode); 541 Node* arg = cnode->in(TypeFunc::Parms + 1); 542 if (cnode->method()->signature()->as_symbol() == int_sig) { 543 sc->push_int(arg); 544 } else if (cnode->method()->signature()->as_symbol() == char_sig) { 545 sc->push_char(arg); 546 } else { 547 if (arg->is_Proj() && arg->in(0)->is_CallStaticJava()) { 548 CallStaticJavaNode* csj = arg->in(0)->as_CallStaticJava(); 549 if (csj->method() != NULL && 550 csj->method()->intrinsic_id() == vmIntrinsics::_Integer_toString && 551 arg->outcnt() == 1) { 552 // _control is the list of StringBuilder calls nodes which 553 // will be replaced by new String code after this optimization. 554 // Integer::toString() call is not part of StringBuilder calls 555 // chain. It could be eliminated only if its result is used 556 // only by this SB calls chain. 557 // Another limitation: it should be used only once because 558 // it is unknown that it is used only by this SB calls chain 559 // until all related SB calls nodes are collected. 560 assert(arg->unique_out() == cnode, "sanity"); 561 sc->add_control(csj); 562 sc->push_int(csj->in(TypeFunc::Parms)); 563 continue; 564 } 565 } 566 sc->push_string(arg); 567 } 568 continue; 569 } else { 570 // some unhandled signature 571 #ifndef PRODUCT 572 if (PrintOptimizeStringConcat) { 573 tty->print("giving up because encountered unexpected signature "); 574 cnode->tf()->dump(); tty->cr(); 575 cnode->in(TypeFunc::Parms + 1)->dump(); 576 } 577 #endif 578 break; 579 } 580 } 581 return NULL; 582 } 583 584 585 PhaseStringOpts::PhaseStringOpts(PhaseGVN* gvn, Unique_Node_List*): 586 Phase(StringOpts), 587 _gvn(gvn), 588 _visited(Thread::current()->resource_area()) { 589 590 assert(OptimizeStringConcat, "shouldn't be here"); 591 592 size_table_field = C->env()->Integer_klass()->get_field_by_name(ciSymbol::make("sizeTable"), 593 ciSymbol::make("[I"), true); 594 if (size_table_field == NULL) { 595 // Something wrong so give up. 596 assert(false, "why can't we find Integer.sizeTable?"); 597 return; 598 } 599 600 // Collect the types needed to talk about the various slices of memory 601 char_adr_idx = C->get_alias_index(TypeAryPtr::CHARS); 602 603 // For each locally allocated StringBuffer see if the usages can be 604 // collapsed into a single String construction. 605 606 // Run through the list of allocation looking for SB.toString to see 607 // if it's possible to fuse the usage of the SB into a single String 608 // construction. 609 GrowableArray<StringConcat*> concats; 610 Node_List toStrings = collect_toString_calls(); 611 while (toStrings.size() > 0) { 612 StringConcat* sc = build_candidate(toStrings.pop()->as_CallStaticJava()); 613 if (sc != NULL) { 614 concats.push(sc); 615 } 616 } 617 618 // try to coalesce separate concats 619 restart: 620 for (int c = 0; c < concats.length(); c++) { 621 StringConcat* sc = concats.at(c); 622 for (int i = 0; i < sc->num_arguments(); i++) { 623 Node* arg = sc->argument_uncast(i); 624 if (arg->is_Proj() && StringConcat::is_SB_toString(arg->in(0))) { 625 CallStaticJavaNode* csj = arg->in(0)->as_CallStaticJava(); 626 for (int o = 0; o < concats.length(); o++) { 627 if (c == o) continue; 628 StringConcat* other = concats.at(o); 629 if (other->end() == csj) { 630 #ifndef PRODUCT 631 if (PrintOptimizeStringConcat) { 632 tty->print_cr("considering stacked concats"); 633 } 634 #endif 635 636 StringConcat* merged = sc->merge(other, arg); 637 if (merged->validate_control_flow() && merged->validate_mem_flow()) { 638 #ifndef PRODUCT 639 if (PrintOptimizeStringConcat) { 640 tty->print_cr("stacking would succeed"); 641 } 642 #endif 643 if (c < o) { 644 concats.remove_at(o); 645 concats.at_put(c, merged); 646 } else { 647 concats.remove_at(c); 648 concats.at_put(o, merged); 649 } 650 goto restart; 651 } else { 652 #ifndef PRODUCT 653 if (PrintOptimizeStringConcat) { 654 tty->print_cr("stacking would fail"); 655 } 656 #endif 657 } 658 } 659 } 660 } 661 } 662 } 663 664 665 for (int c = 0; c < concats.length(); c++) { 666 StringConcat* sc = concats.at(c); 667 replace_string_concat(sc); 668 } 669 670 remove_dead_nodes(); 671 } 672 673 void PhaseStringOpts::record_dead_node(Node* dead) { 674 dead_worklist.push(dead); 675 } 676 677 void PhaseStringOpts::remove_dead_nodes() { 678 // Delete any dead nodes to make things clean enough that escape 679 // analysis doesn't get unhappy. 680 while (dead_worklist.size() > 0) { 681 Node* use = dead_worklist.pop(); 682 int opc = use->Opcode(); 683 switch (opc) { 684 case Op_Region: { 685 uint i = 1; 686 for (i = 1; i < use->req(); i++) { 687 if (use->in(i) != C->top()) { 688 break; 689 } 690 } 691 if (i >= use->req()) { 692 for (SimpleDUIterator i(use); i.has_next(); i.next()) { 693 Node* m = i.get(); 694 if (m->is_Phi()) { 695 dead_worklist.push(m); 696 } 697 } 698 C->gvn_replace_by(use, C->top()); 699 } 700 break; 701 } 702 case Op_AddP: 703 case Op_CreateEx: { 704 // Recurisvely clean up references to CreateEx so EA doesn't 705 // get unhappy about the partially collapsed graph. 706 for (SimpleDUIterator i(use); i.has_next(); i.next()) { 707 Node* m = i.get(); 708 if (m->is_AddP()) { 709 dead_worklist.push(m); 710 } 711 } 712 C->gvn_replace_by(use, C->top()); 713 break; 714 } 715 case Op_Phi: 716 if (use->in(0) == C->top()) { 717 C->gvn_replace_by(use, C->top()); 718 } 719 break; 720 } 721 } 722 } 723 724 725 bool StringConcat::validate_mem_flow() { 726 Compile* C = _stringopts->C; 727 728 for (uint i = 0; i < _control.size(); i++) { 729 #ifndef PRODUCT 730 Node_List path; 731 #endif 732 Node* curr = _control.at(i); 733 if (curr->is_Call() && curr != _begin) { // For all calls except the first allocation 734 // Now here's the main invariant in our case: 735 // For memory between the constructor, and appends, and toString we should only see bottom memory, 736 // produced by the previous call we know about. 737 if (!_constructors.contains(curr)) { 738 NOT_PRODUCT(path.push(curr);) 739 Node* mem = curr->in(TypeFunc::Memory); 740 assert(mem != NULL, "calls should have memory edge"); 741 assert(!mem->is_Phi(), "should be handled by control flow validation"); 742 NOT_PRODUCT(path.push(mem);) 743 while (mem->is_MergeMem()) { 744 for (uint i = 1; i < mem->req(); i++) { 745 if (i != Compile::AliasIdxBot && mem->in(i) != C->top()) { 746 #ifndef PRODUCT 747 if (PrintOptimizeStringConcat) { 748 tty->print("fusion has incorrect memory flow (side effects) for "); 749 _begin->jvms()->dump_spec(tty); tty->cr(); 750 path.dump(); 751 } 752 #endif 753 return false; 754 } 755 } 756 // skip through a potential MergeMem chain, linked through Bot 757 mem = mem->in(Compile::AliasIdxBot); 758 NOT_PRODUCT(path.push(mem);) 759 } 760 // now let it fall through, and see if we have a projection 761 if (mem->is_Proj()) { 762 // Should point to a previous known call 763 Node *prev = mem->in(0); 764 NOT_PRODUCT(path.push(prev);) 765 if (!prev->is_Call() || !_control.contains(prev)) { 766 #ifndef PRODUCT 767 if (PrintOptimizeStringConcat) { 768 tty->print("fusion has incorrect memory flow (unknown call) for "); 769 _begin->jvms()->dump_spec(tty); tty->cr(); 770 path.dump(); 771 } 772 #endif 773 return false; 774 } 775 } else { 776 assert(mem->is_Store() || mem->is_LoadStore(), err_msg_res("unexpected node type: %s", mem->Name())); 777 #ifndef PRODUCT 778 if (PrintOptimizeStringConcat) { 779 tty->print("fusion has incorrect memory flow (unexpected source) for "); 780 _begin->jvms()->dump_spec(tty); tty->cr(); 781 path.dump(); 782 } 783 #endif 784 return false; 785 } 786 } else { 787 // For memory that feeds into constructors it's more complicated. 788 // However the advantage is that any side effect that happens between the Allocate/Initialize and 789 // the constructor will have to be control-dependent on Initialize. 790 // So we actually don't have to do anything, since it's going to be caught by the control flow 791 // analysis. 792 #ifdef ASSERT 793 // Do a quick verification of the control pattern between the constructor and the initialize node 794 assert(curr->is_Call(), "constructor should be a call"); 795 // Go up the control starting from the constructor call 796 Node* ctrl = curr->in(0); 797 IfNode* iff = NULL; 798 RegionNode* copy = NULL; 799 800 while (true) { 801 // skip known check patterns 802 if (ctrl->is_Region()) { 803 if (ctrl->as_Region()->is_copy()) { 804 copy = ctrl->as_Region(); 805 ctrl = copy->is_copy(); 806 } else { // a cast 807 assert(ctrl->req() == 3 && 808 ctrl->in(1) != NULL && ctrl->in(1)->is_Proj() && 809 ctrl->in(2) != NULL && ctrl->in(2)->is_Proj() && 810 ctrl->in(1)->in(0) == ctrl->in(2)->in(0) && 811 ctrl->in(1)->in(0) != NULL && ctrl->in(1)->in(0)->is_If(), 812 "must be a simple diamond"); 813 Node* true_proj = ctrl->in(1)->is_IfTrue() ? ctrl->in(1) : ctrl->in(2); 814 for (SimpleDUIterator i(true_proj); i.has_next(); i.next()) { 815 Node* use = i.get(); 816 assert(use == ctrl || use->is_ConstraintCast(), 817 err_msg_res("unexpected user: %s", use->Name())); 818 } 819 820 iff = ctrl->in(1)->in(0)->as_If(); 821 ctrl = iff->in(0); 822 } 823 } else if (ctrl->is_IfTrue()) { // null checks, class checks 824 iff = ctrl->in(0)->as_If(); 825 assert(iff->is_If(), "must be if"); 826 // Verify that the other arm is an uncommon trap 827 Node* otherproj = iff->proj_out(1 - ctrl->as_Proj()->_con); 828 CallStaticJavaNode* call = otherproj->unique_out()->isa_CallStaticJava(); 829 assert(strcmp(call->_name, "uncommon_trap") == 0, "must be uncommond trap"); 830 ctrl = iff->in(0); 831 } else { 832 break; 833 } 834 } 835 836 assert(ctrl->is_Proj(), "must be a projection"); 837 assert(ctrl->in(0)->is_Initialize(), "should be initialize"); 838 for (SimpleDUIterator i(ctrl); i.has_next(); i.next()) { 839 Node* use = i.get(); 840 assert(use == copy || use == iff || use == curr || use->is_CheckCastPP() || use->is_Load(), 841 err_msg_res("unexpected user: %s", use->Name())); 842 } 843 #endif // ASSERT 844 } 845 } 846 } 847 848 #ifndef PRODUCT 849 if (PrintOptimizeStringConcat) { 850 tty->print("fusion has correct memory flow for "); 851 _begin->jvms()->dump_spec(tty); tty->cr(); 852 tty->cr(); 853 } 854 #endif 855 return true; 856 } 857 858 bool StringConcat::validate_control_flow() { 859 // We found all the calls and arguments now lets see if it's 860 // safe to transform the graph as we would expect. 861 862 // Check to see if this resulted in too many uncommon traps previously 863 if (Compile::current()->too_many_traps(_begin->jvms()->method(), _begin->jvms()->bci(), 864 Deoptimization::Reason_intrinsic)) { 865 return false; 866 } 867 868 // Walk backwards over the control flow from toString to the 869 // allocation and make sure all the control flow is ok. This 870 // means it's either going to be eliminated once the calls are 871 // removed or it can safely be transformed into an uncommon 872 // trap. 873 874 int null_check_count = 0; 875 Unique_Node_List ctrl_path; 876 877 assert(_control.contains(_begin), "missing"); 878 assert(_control.contains(_end), "missing"); 879 880 // Collect the nodes that we know about and will eliminate into ctrl_path 881 for (uint i = 0; i < _control.size(); i++) { 882 // Push the call and it's control projection 883 Node* n = _control.at(i); 884 if (n->is_Allocate()) { 885 AllocateNode* an = n->as_Allocate(); 886 InitializeNode* init = an->initialization(); 887 ctrl_path.push(init); 888 ctrl_path.push(init->as_Multi()->proj_out(0)); 889 } 890 if (n->is_Call()) { 891 CallNode* cn = n->as_Call(); 892 ctrl_path.push(cn); 893 ctrl_path.push(cn->proj_out(0)); 894 ctrl_path.push(cn->proj_out(0)->unique_out()); 895 Node* catchproj = cn->proj_out(0)->unique_out()->as_Catch()->proj_out(0); 896 if (catchproj != NULL) { 897 ctrl_path.push(catchproj); 898 } 899 } else { 900 ShouldNotReachHere(); 901 } 902 } 903 904 // Skip backwards through the control checking for unexpected control flow 905 Node* ptr = _end; 906 bool fail = false; 907 while (ptr != _begin) { 908 if (ptr->is_Call() && ctrl_path.member(ptr)) { 909 ptr = ptr->in(0); 910 } else if (ptr->is_CatchProj() && ctrl_path.member(ptr)) { 911 ptr = ptr->in(0)->in(0)->in(0); 912 assert(ctrl_path.member(ptr), "should be a known piece of control"); 913 } else if (ptr->is_IfTrue()) { 914 IfNode* iff = ptr->in(0)->as_If(); 915 BoolNode* b = iff->in(1)->isa_Bool(); 916 917 if (b == NULL) { 918 fail = true; 919 break; 920 } 921 922 Node* cmp = b->in(1); 923 Node* v1 = cmp->in(1); 924 Node* v2 = cmp->in(2); 925 Node* otherproj = iff->proj_out(1 - ptr->as_Proj()->_con); 926 927 // Null check of the return of append which can simply be eliminated 928 if (b->_test._test == BoolTest::ne && 929 v2->bottom_type() == TypePtr::NULL_PTR && 930 v1->is_Proj() && ctrl_path.member(v1->in(0))) { 931 // NULL check of the return value of the append 932 null_check_count++; 933 if (otherproj->outcnt() == 1) { 934 CallStaticJavaNode* call = otherproj->unique_out()->isa_CallStaticJava(); 935 if (call != NULL && call->_name != NULL && strcmp(call->_name, "uncommon_trap") == 0) { 936 ctrl_path.push(call); 937 } 938 } 939 _control.push(ptr); 940 ptr = ptr->in(0)->in(0); 941 continue; 942 } 943 944 // A test which leads to an uncommon trap which should be safe. 945 // Later this trap will be converted into a trap that restarts 946 // at the beginning. 947 if (otherproj->outcnt() == 1) { 948 CallStaticJavaNode* call = otherproj->unique_out()->isa_CallStaticJava(); 949 if (call != NULL && call->_name != NULL && strcmp(call->_name, "uncommon_trap") == 0) { 950 // control flow leads to uct so should be ok 951 _uncommon_traps.push(call); 952 ctrl_path.push(call); 953 ptr = ptr->in(0)->in(0); 954 continue; 955 } 956 } 957 958 #ifndef PRODUCT 959 // Some unexpected control flow we don't know how to handle. 960 if (PrintOptimizeStringConcat) { 961 tty->print_cr("failing with unknown test"); 962 b->dump(); 963 cmp->dump(); 964 v1->dump(); 965 v2->dump(); 966 tty->cr(); 967 } 968 #endif 969 fail = true; 970 break; 971 } else if (ptr->is_Proj() && ptr->in(0)->is_Initialize()) { 972 ptr = ptr->in(0)->in(0); 973 } else if (ptr->is_Region()) { 974 Node* copy = ptr->as_Region()->is_copy(); 975 if (copy != NULL) { 976 ptr = copy; 977 continue; 978 } 979 if (ptr->req() == 3 && 980 ptr->in(1) != NULL && ptr->in(1)->is_Proj() && 981 ptr->in(2) != NULL && ptr->in(2)->is_Proj() && 982 ptr->in(1)->in(0) == ptr->in(2)->in(0) && 983 ptr->in(1)->in(0) != NULL && ptr->in(1)->in(0)->is_If()) { 984 // Simple diamond. 985 // XXX should check for possibly merging stores. simple data merges are ok. 986 // The IGVN will make this simple diamond go away when it 987 // transforms the Region. Make sure it sees it. 988 Compile::current()->record_for_igvn(ptr); 989 ptr = ptr->in(1)->in(0)->in(0); 990 continue; 991 } 992 #ifndef PRODUCT 993 if (PrintOptimizeStringConcat) { 994 tty->print_cr("fusion would fail for region"); 995 _begin->dump(); 996 ptr->dump(2); 997 } 998 #endif 999 fail = true; 1000 break; 1001 } else { 1002 // other unknown control 1003 if (!fail) { 1004 #ifndef PRODUCT 1005 if (PrintOptimizeStringConcat) { 1006 tty->print_cr("fusion would fail for"); 1007 _begin->dump(); 1008 } 1009 #endif 1010 fail = true; 1011 } 1012 #ifndef PRODUCT 1013 if (PrintOptimizeStringConcat) { 1014 ptr->dump(); 1015 } 1016 #endif 1017 ptr = ptr->in(0); 1018 } 1019 } 1020 #ifndef PRODUCT 1021 if (PrintOptimizeStringConcat && fail) { 1022 tty->cr(); 1023 } 1024 #endif 1025 if (fail) return !fail; 1026 1027 // Validate that all these results produced are contained within 1028 // this cluster of objects. First collect all the results produced 1029 // by calls in the region. 1030 _stringopts->_visited.Clear(); 1031 Node_List worklist; 1032 Node* final_result = _end->proj_out(TypeFunc::Parms); 1033 for (uint i = 0; i < _control.size(); i++) { 1034 CallNode* cnode = _control.at(i)->isa_Call(); 1035 if (cnode != NULL) { 1036 _stringopts->_visited.test_set(cnode->_idx); 1037 } 1038 Node* result = cnode != NULL ? cnode->proj_out(TypeFunc::Parms) : NULL; 1039 if (result != NULL && result != final_result) { 1040 worklist.push(result); 1041 } 1042 } 1043 1044 Node* last_result = NULL; 1045 while (worklist.size() > 0) { 1046 Node* result = worklist.pop(); 1047 if (_stringopts->_visited.test_set(result->_idx)) 1048 continue; 1049 for (SimpleDUIterator i(result); i.has_next(); i.next()) { 1050 Node *use = i.get(); 1051 if (ctrl_path.member(use)) { 1052 // already checked this 1053 continue; 1054 } 1055 int opc = use->Opcode(); 1056 if (opc == Op_CmpP || opc == Op_Node) { 1057 ctrl_path.push(use); 1058 continue; 1059 } 1060 if (opc == Op_CastPP || opc == Op_CheckCastPP) { 1061 for (SimpleDUIterator j(use); j.has_next(); j.next()) { 1062 worklist.push(j.get()); 1063 } 1064 worklist.push(use->in(1)); 1065 ctrl_path.push(use); 1066 continue; 1067 } 1068 #ifndef PRODUCT 1069 if (PrintOptimizeStringConcat) { 1070 if (result != last_result) { 1071 last_result = result; 1072 tty->print_cr("extra uses for result:"); 1073 last_result->dump(); 1074 } 1075 use->dump(); 1076 } 1077 #endif 1078 fail = true; 1079 break; 1080 } 1081 } 1082 1083 #ifndef PRODUCT 1084 if (PrintOptimizeStringConcat && !fail) { 1085 ttyLocker ttyl; 1086 tty->cr(); 1087 tty->print("fusion has correct control flow (%d %d) for ", null_check_count, _uncommon_traps.size()); 1088 _begin->jvms()->dump_spec(tty); tty->cr(); 1089 for (int i = 0; i < num_arguments(); i++) { 1090 argument(i)->dump(); 1091 } 1092 _control.dump(); 1093 tty->cr(); 1094 } 1095 #endif 1096 1097 return !fail; 1098 } 1099 1100 Node* PhaseStringOpts::fetch_static_field(GraphKit& kit, ciField* field) { 1101 const TypeInstPtr* mirror_type = TypeInstPtr::make(field->holder()->java_mirror()); 1102 Node* klass_node = __ makecon(mirror_type); 1103 BasicType bt = field->layout_type(); 1104 ciType* field_klass = field->type(); 1105 1106 const Type *type; 1107 if( bt == T_OBJECT ) { 1108 if (!field->type()->is_loaded()) { 1109 type = TypeInstPtr::BOTTOM; 1110 } else if (field->is_constant()) { 1111 // This can happen if the constant oop is non-perm. 1112 ciObject* con = field->constant_value().as_object(); 1113 // Do not "join" in the previous type; it doesn't add value, 1114 // and may yield a vacuous result if the field is of interface type. 1115 type = TypeOopPtr::make_from_constant(con, true)->isa_oopptr(); 1116 assert(type != NULL, "field singleton type must be consistent"); 1117 return __ makecon(type); 1118 } else { 1119 type = TypeOopPtr::make_from_klass(field_klass->as_klass()); 1120 } 1121 } else { 1122 type = Type::get_const_basic_type(bt); 1123 } 1124 1125 return kit.make_load(NULL, kit.basic_plus_adr(klass_node, field->offset_in_bytes()), 1126 type, T_OBJECT, 1127 C->get_alias_index(mirror_type->add_offset(field->offset_in_bytes())), 1128 MemNode::unordered); 1129 } 1130 1131 Node* PhaseStringOpts::int_stringSize(GraphKit& kit, Node* arg) { 1132 RegionNode *final_merge = new (C) RegionNode(3); 1133 kit.gvn().set_type(final_merge, Type::CONTROL); 1134 Node* final_size = new (C) PhiNode(final_merge, TypeInt::INT); 1135 kit.gvn().set_type(final_size, TypeInt::INT); 1136 1137 IfNode* iff = kit.create_and_map_if(kit.control(), 1138 __ Bool(__ CmpI(arg, __ intcon(0x80000000)), BoolTest::ne), 1139 PROB_FAIR, COUNT_UNKNOWN); 1140 Node* is_min = __ IfFalse(iff); 1141 final_merge->init_req(1, is_min); 1142 final_size->init_req(1, __ intcon(11)); 1143 1144 kit.set_control(__ IfTrue(iff)); 1145 if (kit.stopped()) { 1146 final_merge->init_req(2, C->top()); 1147 final_size->init_req(2, C->top()); 1148 } else { 1149 1150 // int size = (i < 0) ? stringSize(-i) + 1 : stringSize(i); 1151 RegionNode *r = new (C) RegionNode(3); 1152 kit.gvn().set_type(r, Type::CONTROL); 1153 Node *phi = new (C) PhiNode(r, TypeInt::INT); 1154 kit.gvn().set_type(phi, TypeInt::INT); 1155 Node *size = new (C) PhiNode(r, TypeInt::INT); 1156 kit.gvn().set_type(size, TypeInt::INT); 1157 Node* chk = __ CmpI(arg, __ intcon(0)); 1158 Node* p = __ Bool(chk, BoolTest::lt); 1159 IfNode* iff = kit.create_and_map_if(kit.control(), p, PROB_FAIR, COUNT_UNKNOWN); 1160 Node* lessthan = __ IfTrue(iff); 1161 Node* greaterequal = __ IfFalse(iff); 1162 r->init_req(1, lessthan); 1163 phi->init_req(1, __ SubI(__ intcon(0), arg)); 1164 size->init_req(1, __ intcon(1)); 1165 r->init_req(2, greaterequal); 1166 phi->init_req(2, arg); 1167 size->init_req(2, __ intcon(0)); 1168 kit.set_control(r); 1169 C->record_for_igvn(r); 1170 C->record_for_igvn(phi); 1171 C->record_for_igvn(size); 1172 1173 // for (int i=0; ; i++) 1174 // if (x <= sizeTable[i]) 1175 // return i+1; 1176 1177 // Add loop predicate first. 1178 kit.add_predicate(); 1179 1180 RegionNode *loop = new (C) RegionNode(3); 1181 loop->init_req(1, kit.control()); 1182 kit.gvn().set_type(loop, Type::CONTROL); 1183 1184 Node *index = new (C) PhiNode(loop, TypeInt::INT); 1185 index->init_req(1, __ intcon(0)); 1186 kit.gvn().set_type(index, TypeInt::INT); 1187 kit.set_control(loop); 1188 Node* sizeTable = fetch_static_field(kit, size_table_field); 1189 1190 sizeTable = kit.shenandoah_read_barrier(sizeTable); 1191 1192 Node* value = kit.load_array_element(NULL, sizeTable, index, TypeAryPtr::INTS); 1193 C->record_for_igvn(value); 1194 Node* limit = __ CmpI(phi, value); 1195 Node* limitb = __ Bool(limit, BoolTest::le); 1196 IfNode* iff2 = kit.create_and_map_if(kit.control(), limitb, PROB_MIN, COUNT_UNKNOWN); 1197 Node* lessEqual = __ IfTrue(iff2); 1198 Node* greater = __ IfFalse(iff2); 1199 1200 loop->init_req(2, greater); 1201 index->init_req(2, __ AddI(index, __ intcon(1))); 1202 1203 kit.set_control(lessEqual); 1204 C->record_for_igvn(loop); 1205 C->record_for_igvn(index); 1206 1207 final_merge->init_req(2, kit.control()); 1208 final_size->init_req(2, __ AddI(__ AddI(index, size), __ intcon(1))); 1209 } 1210 1211 kit.set_control(final_merge); 1212 C->record_for_igvn(final_merge); 1213 C->record_for_igvn(final_size); 1214 1215 return final_size; 1216 } 1217 1218 void PhaseStringOpts::int_getChars(GraphKit& kit, Node* arg, Node* char_array, Node* start, Node* end) { 1219 RegionNode *final_merge = new (C) RegionNode(4); 1220 kit.gvn().set_type(final_merge, Type::CONTROL); 1221 Node *final_mem = PhiNode::make(final_merge, kit.memory(char_adr_idx), Type::MEMORY, TypeAryPtr::CHARS); 1222 kit.gvn().set_type(final_mem, Type::MEMORY); 1223 1224 // need to handle Integer.MIN_VALUE specially because negating doesn't make it positive 1225 { 1226 // i == MIN_VALUE 1227 IfNode* iff = kit.create_and_map_if(kit.control(), 1228 __ Bool(__ CmpI(arg, __ intcon(0x80000000)), BoolTest::ne), 1229 PROB_FAIR, COUNT_UNKNOWN); 1230 1231 Node* old_mem = kit.memory(char_adr_idx); 1232 1233 kit.set_control(__ IfFalse(iff)); 1234 if (kit.stopped()) { 1235 // Statically not equal to MIN_VALUE so this path is dead 1236 final_merge->init_req(3, kit.control()); 1237 } else { 1238 copy_string(kit, __ makecon(TypeInstPtr::make(C->env()->the_min_jint_string())), 1239 char_array, start); 1240 final_merge->init_req(3, kit.control()); 1241 final_mem->init_req(3, kit.memory(char_adr_idx)); 1242 } 1243 1244 kit.set_control(__ IfTrue(iff)); 1245 kit.set_memory(old_mem, char_adr_idx); 1246 } 1247 1248 1249 // Simplified version of Integer.getChars 1250 1251 // int q, r; 1252 // int charPos = index; 1253 Node* charPos = end; 1254 1255 // char sign = 0; 1256 1257 Node* i = arg; 1258 Node* sign = __ intcon(0); 1259 1260 // if (i < 0) { 1261 // sign = '-'; 1262 // i = -i; 1263 // } 1264 { 1265 IfNode* iff = kit.create_and_map_if(kit.control(), 1266 __ Bool(__ CmpI(arg, __ intcon(0)), BoolTest::lt), 1267 PROB_FAIR, COUNT_UNKNOWN); 1268 1269 RegionNode *merge = new (C) RegionNode(3); 1270 kit.gvn().set_type(merge, Type::CONTROL); 1271 i = new (C) PhiNode(merge, TypeInt::INT); 1272 kit.gvn().set_type(i, TypeInt::INT); 1273 sign = new (C) PhiNode(merge, TypeInt::INT); 1274 kit.gvn().set_type(sign, TypeInt::INT); 1275 1276 merge->init_req(1, __ IfTrue(iff)); 1277 i->init_req(1, __ SubI(__ intcon(0), arg)); 1278 sign->init_req(1, __ intcon('-')); 1279 merge->init_req(2, __ IfFalse(iff)); 1280 i->init_req(2, arg); 1281 sign->init_req(2, __ intcon(0)); 1282 1283 kit.set_control(merge); 1284 1285 C->record_for_igvn(merge); 1286 C->record_for_igvn(i); 1287 C->record_for_igvn(sign); 1288 } 1289 1290 // for (;;) { 1291 // q = i / 10; 1292 // r = i - ((q << 3) + (q << 1)); // r = i-(q*10) ... 1293 // buf [--charPos] = digits [r]; 1294 // i = q; 1295 // if (i == 0) break; 1296 // } 1297 1298 { 1299 // Add loop predicate first. 1300 kit.add_predicate(); 1301 1302 RegionNode *head = new (C) RegionNode(3); 1303 head->init_req(1, kit.control()); 1304 kit.gvn().set_type(head, Type::CONTROL); 1305 Node *i_phi = new (C) PhiNode(head, TypeInt::INT); 1306 i_phi->init_req(1, i); 1307 kit.gvn().set_type(i_phi, TypeInt::INT); 1308 charPos = PhiNode::make(head, charPos); 1309 kit.gvn().set_type(charPos, TypeInt::INT); 1310 Node *mem = PhiNode::make(head, kit.memory(char_adr_idx), Type::MEMORY, TypeAryPtr::CHARS); 1311 kit.gvn().set_type(mem, Type::MEMORY); 1312 kit.set_control(head); 1313 kit.set_memory(mem, char_adr_idx); 1314 1315 Node* q = __ DivI(NULL, i_phi, __ intcon(10)); 1316 Node* r = __ SubI(i_phi, __ AddI(__ LShiftI(q, __ intcon(3)), 1317 __ LShiftI(q, __ intcon(1)))); 1318 Node* m1 = __ SubI(charPos, __ intcon(1)); 1319 Node* ch = __ AddI(r, __ intcon('0')); 1320 1321 Node* st = __ store_to_memory(kit.control(), kit.array_element_address(char_array, m1, T_CHAR), 1322 ch, T_CHAR, char_adr_idx, MemNode::unordered); 1323 1324 1325 IfNode* iff = kit.create_and_map_if(head, __ Bool(__ CmpI(q, __ intcon(0)), BoolTest::ne), 1326 PROB_FAIR, COUNT_UNKNOWN); 1327 Node* ne = __ IfTrue(iff); 1328 Node* eq = __ IfFalse(iff); 1329 1330 head->init_req(2, ne); 1331 mem->init_req(2, st); 1332 i_phi->init_req(2, q); 1333 charPos->init_req(2, m1); 1334 1335 charPos = m1; 1336 1337 kit.set_control(eq); 1338 kit.set_memory(st, char_adr_idx); 1339 1340 C->record_for_igvn(head); 1341 C->record_for_igvn(mem); 1342 C->record_for_igvn(i_phi); 1343 C->record_for_igvn(charPos); 1344 } 1345 1346 { 1347 // if (sign != 0) { 1348 // buf [--charPos] = sign; 1349 // } 1350 IfNode* iff = kit.create_and_map_if(kit.control(), 1351 __ Bool(__ CmpI(sign, __ intcon(0)), BoolTest::ne), 1352 PROB_FAIR, COUNT_UNKNOWN); 1353 1354 final_merge->init_req(2, __ IfFalse(iff)); 1355 final_mem->init_req(2, kit.memory(char_adr_idx)); 1356 1357 kit.set_control(__ IfTrue(iff)); 1358 if (kit.stopped()) { 1359 final_merge->init_req(1, C->top()); 1360 final_mem->init_req(1, C->top()); 1361 } else { 1362 Node* m1 = __ SubI(charPos, __ intcon(1)); 1363 Node* st = __ store_to_memory(kit.control(), kit.array_element_address(char_array, m1, T_CHAR), 1364 sign, T_CHAR, char_adr_idx, MemNode::unordered); 1365 1366 final_merge->init_req(1, kit.control()); 1367 final_mem->init_req(1, st); 1368 } 1369 1370 kit.set_control(final_merge); 1371 kit.set_memory(final_mem, char_adr_idx); 1372 1373 C->record_for_igvn(final_merge); 1374 C->record_for_igvn(final_mem); 1375 } 1376 } 1377 1378 1379 Node* PhaseStringOpts::copy_string(GraphKit& kit, Node* str, Node* char_array, Node* start) { 1380 Node* string = str; 1381 Node* offset = kit.load_String_offset(kit.control(), string); 1382 Node* count = kit.load_String_length(kit.control(), string); 1383 Node* value = kit.load_String_value (kit.control(), string); 1384 1385 value = kit.shenandoah_read_barrier(value); 1386 1387 // copy the contents 1388 assert(!(ShenandoahBarrierNode::skip_through_barrier(value)->is_Con() && !value->is_Con()), "barrier prevents optimization"); 1389 if (offset->is_Con() && count->is_Con() && value->is_Con() && count->get_int() < unroll_string_copy_length) { 1390 // For small constant strings just emit individual stores. 1391 // A length of 6 seems like a good space/speed tradeof. 1392 int c = count->get_int(); 1393 int o = offset->get_int(); 1394 const TypeOopPtr* t = kit.gvn().type(value)->isa_oopptr(); 1395 ciTypeArray* value_array = t->const_oop()->as_type_array(); 1396 for (int e = 0; e < c; e++) { 1397 __ store_to_memory(kit.control(), kit.array_element_address(char_array, start, T_CHAR), 1398 __ intcon(value_array->char_at(o + e)), T_CHAR, char_adr_idx, 1399 MemNode::unordered); 1400 start = __ AddI(start, __ intcon(1)); 1401 } 1402 } else { 1403 Node* src_ptr = kit.array_element_address(value, offset, T_CHAR); 1404 Node* dst_ptr = kit.array_element_address(char_array, start, T_CHAR); 1405 Node* c = count; 1406 Node* extra = NULL; 1407 #ifdef _LP64 1408 c = __ ConvI2L(c); 1409 extra = C->top(); 1410 #endif 1411 Node* call = kit.make_runtime_call(GraphKit::RC_LEAF|GraphKit::RC_NO_FP, 1412 OptoRuntime::fast_arraycopy_Type(), 1413 CAST_FROM_FN_PTR(address, StubRoutines::jshort_disjoint_arraycopy()), 1414 "jshort_disjoint_arraycopy", TypeAryPtr::CHARS, 1415 src_ptr, dst_ptr, c, extra); 1416 start = __ AddI(start, count); 1417 } 1418 return start; 1419 } 1420 1421 1422 void PhaseStringOpts::replace_string_concat(StringConcat* sc) { 1423 // Log a little info about the transformation 1424 sc->maybe_log_transform(); 1425 1426 // pull the JVMState of the allocation into a SafePointNode to serve as 1427 // as a shim for the insertion of the new code. 1428 JVMState* jvms = sc->begin()->jvms()->clone_shallow(C); 1429 uint size = sc->begin()->req(); 1430 SafePointNode* map = new (C) SafePointNode(size, jvms); 1431 1432 // copy the control and memory state from the final call into our 1433 // new starting state. This allows any preceeding tests to feed 1434 // into the new section of code. 1435 for (uint i1 = 0; i1 < TypeFunc::Parms; i1++) { 1436 map->init_req(i1, sc->end()->in(i1)); 1437 } 1438 // blow away old allocation arguments 1439 for (uint i1 = TypeFunc::Parms; i1 < jvms->debug_start(); i1++) { 1440 map->init_req(i1, C->top()); 1441 } 1442 // Copy the rest of the inputs for the JVMState 1443 for (uint i1 = jvms->debug_start(); i1 < sc->begin()->req(); i1++) { 1444 map->init_req(i1, sc->begin()->in(i1)); 1445 } 1446 // Make sure the memory state is a MergeMem for parsing. 1447 if (!map->in(TypeFunc::Memory)->is_MergeMem()) { 1448 map->set_req(TypeFunc::Memory, MergeMemNode::make(C, map->in(TypeFunc::Memory))); 1449 } 1450 1451 jvms->set_map(map); 1452 map->ensure_stack(jvms, jvms->method()->max_stack()); 1453 1454 1455 // disconnect all the old StringBuilder calls from the graph 1456 sc->eliminate_unneeded_control(); 1457 1458 // At this point all the old work has been completely removed from 1459 // the graph and the saved JVMState exists at the point where the 1460 // final toString call used to be. 1461 GraphKit kit(jvms); 1462 1463 // There may be uncommon traps which are still using the 1464 // intermediate states and these need to be rewritten to point at 1465 // the JVMState at the beginning of the transformation. 1466 sc->convert_uncommon_traps(kit, jvms); 1467 1468 // Now insert the logic to compute the size of the string followed 1469 // by all the logic to construct array and resulting string. 1470 1471 Node* null_string = __ makecon(TypeInstPtr::make(C->env()->the_null_string())); 1472 1473 // Create a region for the overflow checks to merge into. 1474 int args = MAX2(sc->num_arguments(), 1); 1475 RegionNode* overflow = new (C) RegionNode(args); 1476 kit.gvn().set_type(overflow, Type::CONTROL); 1477 1478 // Create a hook node to hold onto the individual sizes since they 1479 // are need for the copying phase. 1480 Node* string_sizes = new (C) Node(args); 1481 1482 Node* length = __ intcon(0); 1483 for (int argi = 0; argi < sc->num_arguments(); argi++) { 1484 Node* arg = sc->argument(argi); 1485 switch (sc->mode(argi)) { 1486 case StringConcat::IntMode: { 1487 Node* string_size = int_stringSize(kit, arg); 1488 1489 // accumulate total 1490 length = __ AddI(length, string_size); 1491 1492 // Cache this value for the use by int_toString 1493 string_sizes->init_req(argi, string_size); 1494 break; 1495 } 1496 case StringConcat::StringNullCheckMode: { 1497 const Type* type = kit.gvn().type(arg); 1498 assert(type != TypePtr::NULL_PTR, "missing check"); 1499 if (!type->higher_equal(TypeInstPtr::NOTNULL)) { 1500 // Null check with uncommont trap since 1501 // StringBuilder(null) throws exception. 1502 // Use special uncommon trap instead of 1503 // calling normal do_null_check(). 1504 Node* p = __ Bool(__ CmpP(arg, kit.null()), BoolTest::ne); 1505 IfNode* iff = kit.create_and_map_if(kit.control(), p, PROB_MIN, COUNT_UNKNOWN); 1506 overflow->add_req(__ IfFalse(iff)); 1507 Node* notnull = __ IfTrue(iff); 1508 kit.set_control(notnull); // set control for the cast_not_null 1509 arg = kit.cast_not_null(arg, false); 1510 sc->set_argument(argi, arg); 1511 } 1512 assert(kit.gvn().type(arg)->higher_equal(TypeInstPtr::NOTNULL), "sanity"); 1513 // Fallthrough to add string length. 1514 } 1515 case StringConcat::StringMode: { 1516 const Type* type = kit.gvn().type(arg); 1517 Node* count = NULL; 1518 if (type == TypePtr::NULL_PTR) { 1519 // replace the argument with the null checked version 1520 arg = null_string; 1521 sc->set_argument(argi, arg); 1522 count = kit.load_String_length(kit.control(), arg); 1523 } else if (!type->higher_equal(TypeInstPtr::NOTNULL)) { 1524 // s = s != null ? s : "null"; 1525 // length = length + (s.count - s.offset); 1526 RegionNode *r = new (C) RegionNode(3); 1527 kit.gvn().set_type(r, Type::CONTROL); 1528 Node *phi = new (C) PhiNode(r, type); 1529 kit.gvn().set_type(phi, phi->bottom_type()); 1530 Node* p = __ Bool(__ CmpP(arg, kit.null()), BoolTest::ne); 1531 IfNode* iff = kit.create_and_map_if(kit.control(), p, PROB_MIN, COUNT_UNKNOWN); 1532 Node* notnull = __ IfTrue(iff); 1533 Node* isnull = __ IfFalse(iff); 1534 kit.set_control(notnull); // set control for the cast_not_null 1535 r->init_req(1, notnull); 1536 phi->init_req(1, kit.cast_not_null(arg, false)); 1537 r->init_req(2, isnull); 1538 phi->init_req(2, null_string); 1539 kit.set_control(r); 1540 C->record_for_igvn(r); 1541 C->record_for_igvn(phi); 1542 // replace the argument with the null checked version 1543 arg = phi; 1544 sc->set_argument(argi, arg); 1545 count = kit.load_String_length(kit.control(), arg); 1546 } else { 1547 // A corresponding nullcheck will be connected during IGVN MemNode::Ideal_common_DU_postCCP 1548 // kit.control might be a different test, that can be hoisted above the actual nullcheck 1549 // in case, that the control input is not null, Ideal_common_DU_postCCP will not look for a nullcheck. 1550 count = kit.load_String_length(NULL, arg); 1551 } 1552 length = __ AddI(length, count); 1553 string_sizes->init_req(argi, NULL); 1554 break; 1555 } 1556 case StringConcat::CharMode: { 1557 // one character only 1558 length = __ AddI(length, __ intcon(1)); 1559 break; 1560 } 1561 default: 1562 ShouldNotReachHere(); 1563 } 1564 if (argi > 0) { 1565 // Check that the sum hasn't overflowed 1566 IfNode* iff = kit.create_and_map_if(kit.control(), 1567 __ Bool(__ CmpI(length, __ intcon(0)), BoolTest::lt), 1568 PROB_MIN, COUNT_UNKNOWN); 1569 kit.set_control(__ IfFalse(iff)); 1570 overflow->set_req(argi, __ IfTrue(iff)); 1571 } 1572 } 1573 1574 { 1575 // Hook 1576 PreserveJVMState pjvms(&kit); 1577 kit.set_control(overflow); 1578 C->record_for_igvn(overflow); 1579 kit.uncommon_trap(Deoptimization::Reason_intrinsic, 1580 Deoptimization::Action_make_not_entrant); 1581 } 1582 1583 Node* result; 1584 if (!kit.stopped()) { 1585 1586 // length now contains the number of characters needed for the 1587 // char[] so create a new AllocateArray for the char[] 1588 Node* char_array = NULL; 1589 { 1590 PreserveReexecuteState preexecs(&kit); 1591 // The original jvms is for an allocation of either a String or 1592 // StringBuffer so no stack adjustment is necessary for proper 1593 // reexecution. If we deoptimize in the slow path the bytecode 1594 // will be reexecuted and the char[] allocation will be thrown away. 1595 kit.jvms()->set_should_reexecute(true); 1596 char_array = kit.new_array(__ makecon(TypeKlassPtr::make(ciTypeArrayKlass::make(T_CHAR))), 1597 length, 1); 1598 } 1599 1600 // Mark the allocation so that zeroing is skipped since the code 1601 // below will overwrite the entire array 1602 AllocateArrayNode* char_alloc = AllocateArrayNode::Ideal_array_allocation(char_array, _gvn); 1603 char_alloc->maybe_set_complete(_gvn); 1604 1605 // Now copy the string representations into the final char[] 1606 Node* start = __ intcon(0); 1607 for (int argi = 0; argi < sc->num_arguments(); argi++) { 1608 Node* arg = sc->argument(argi); 1609 switch (sc->mode(argi)) { 1610 case StringConcat::IntMode: { 1611 Node* end = __ AddI(start, string_sizes->in(argi)); 1612 // getChars words backwards so pass the ending point as well as the start 1613 int_getChars(kit, arg, char_array, start, end); 1614 start = end; 1615 break; 1616 } 1617 case StringConcat::StringNullCheckMode: 1618 case StringConcat::StringMode: { 1619 start = copy_string(kit, arg, char_array, start); 1620 break; 1621 } 1622 case StringConcat::CharMode: { 1623 __ store_to_memory(kit.control(), kit.array_element_address(char_array, start, T_CHAR), 1624 arg, T_CHAR, char_adr_idx, MemNode::unordered); 1625 start = __ AddI(start, __ intcon(1)); 1626 break; 1627 } 1628 default: 1629 ShouldNotReachHere(); 1630 } 1631 } 1632 1633 // If we're not reusing an existing String allocation then allocate one here. 1634 result = sc->string_alloc(); 1635 if (result == NULL) { 1636 PreserveReexecuteState preexecs(&kit); 1637 // The original jvms is for an allocation of either a String or 1638 // StringBuffer so no stack adjustment is necessary for proper 1639 // reexecution. 1640 kit.jvms()->set_should_reexecute(true); 1641 result = kit.new_instance(__ makecon(TypeKlassPtr::make(C->env()->String_klass()))); 1642 } 1643 1644 // Intialize the string 1645 if (java_lang_String::has_offset_field()) { 1646 kit.store_String_offset(kit.control(), result, __ intcon(0)); 1647 kit.store_String_length(kit.control(), result, length); 1648 } 1649 kit.store_String_value(kit.control(), result, char_array); 1650 1651 // The value field is final. Emit a barrier here to ensure that the effect 1652 // of the initialization is committed to memory before any code publishes 1653 // a reference to the newly constructed object (see Parse::do_exits()). 1654 assert(AllocateNode::Ideal_allocation(result, _gvn) != NULL, "should be newly allocated"); 1655 kit.insert_mem_bar(Op_MemBarRelease, result); 1656 } else { 1657 result = C->top(); 1658 } 1659 // hook up the outgoing control and result 1660 kit.replace_call(sc->end(), result); 1661 1662 // Unhook any hook nodes 1663 string_sizes->disconnect_inputs(NULL, C); 1664 sc->cleanup(); 1665 }