1 /*
   2  * Copyright (c) 2009, 2025, 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 "ci/ciSymbols.hpp"
  26 #include "classfile/javaClasses.hpp"
  27 #include "compiler/compileLog.hpp"
  28 #include "opto/callnode.hpp"
  29 #include "opto/graphKit.hpp"
  30 #include "opto/idealKit.hpp"
  31 #include "opto/rootnode.hpp"
  32 #include "opto/runtime.hpp"
  33 #include "opto/stringopts.hpp"
  34 #include "runtime/atomicAccess.hpp"
  35 #include "runtime/stubRoutines.hpp"
  36 
  37 #define __ kit.
  38 
  39 class StringConcat : public ResourceObj {
  40  private:
  41   PhaseStringOpts*    _stringopts;
  42   AllocateNode*       _begin;          // The allocation the begins the pattern
  43   CallStaticJavaNode* _end;            // The final call of the pattern.  Will either be
  44                                        // SB.toString or String.<init>(SB.toString)
  45   bool                _multiple;       // indicates this is a fusion of two or more
  46                                        // separate StringBuilders
  47 
  48   Node*               _arguments;      // The list of arguments to be concatenated
  49   GrowableArray<int>  _mode;           // into a String along with a mode flag
  50                                        // indicating how to treat the value.
  51   Node_List           _constructors;   // List of constructors (many in case of stacked concat)
  52   Node_List           _control;        // List of control nodes that will be deleted
  53   Node_List           _uncommon_traps; // Uncommon traps that needs to be rewritten
  54                                        // to restart at the initial JVMState.
  55 
  56   static constexpr uint STACKED_CONCAT_UPPER_BOUND = 256; // argument limit for a merged concat.
  57                                                           // The value 256 was derived by measuring
  58                                                           // compilation time on variable length sequences
  59                                                           // of stackable concatenations and chosen to keep
  60                                                           // a safe margin to any critical point.
  61  public:
  62   // Mode for converting arguments to Strings
  63   enum {
  64     StringMode,
  65     IntMode,
  66     CharMode,
  67     StringNullCheckMode,
  68     NegativeIntCheckMode
  69   };
  70 
  71   StringConcat(PhaseStringOpts* stringopts, CallStaticJavaNode* end):
  72     _stringopts(stringopts),
  73     _begin(nullptr),
  74     _end(end),
  75     _multiple(false) {
  76     _arguments = new Node(1);
  77     _arguments->del_req(0);
  78   }
  79 
  80   bool validate_mem_flow();
  81   bool validate_control_flow();
  82 
  83   StringConcat* merge(StringConcat* other, Node* arg);
  84 
  85   void set_allocation(AllocateNode* alloc) {
  86     _begin = alloc;
  87   }
  88 
  89   void append(Node* value, int mode) {
  90     _arguments->add_req(value);
  91     _mode.append(mode);
  92   }
  93   void push(Node* value, int mode) {
  94     _arguments->ins_req(0, value);
  95     _mode.insert_before(0, mode);
  96   }
  97 
  98   void push_string(Node* value) {
  99     push(value, StringMode);
 100   }
 101 
 102   void push_string_null_check(Node* value) {
 103     push(value, StringNullCheckMode);
 104   }
 105 
 106   void push_negative_int_check(Node* value) {
 107     push(value, NegativeIntCheckMode);
 108   }
 109 
 110   void push_int(Node* value) {
 111     push(value, IntMode);
 112   }
 113 
 114   void push_char(Node* value) {
 115     push(value, CharMode);
 116   }
 117 
 118   static bool is_SB_toString(Node* call) {
 119     if (call->is_CallStaticJava()) {
 120       CallStaticJavaNode* csj = call->as_CallStaticJava();
 121       ciMethod* m = csj->method();
 122       if (m != nullptr &&
 123           (m->intrinsic_id() == vmIntrinsics::_StringBuilder_toString ||
 124            m->intrinsic_id() == vmIntrinsics::_StringBuffer_toString)) {
 125         return true;
 126       }
 127     }
 128     return false;
 129   }
 130 
 131   static Node* skip_string_null_check(Node* value) {
 132     // Look for a diamond shaped Null check of toString() result
 133     // (could be code from String.valueOf()):
 134     // (Proj == nullptr) ? "null":"CastPP(Proj)#Notnull
 135     if (value->is_Phi()) {
 136       int true_path = value->as_Phi()->is_diamond_phi();
 137       if (true_path != 0) {
 138         // phi->region->if_proj->ifnode->bool
 139         BoolNode* b = value->in(0)->in(1)->in(0)->in(1)->as_Bool();
 140         Node* cmp = b->in(1);
 141         Node* v1 = cmp->in(1);
 142         Node* v2 = cmp->in(2);
 143         // Null check of the return of toString which can simply be skipped.
 144         if (b->_test._test == BoolTest::ne &&
 145             v2->bottom_type() == TypePtr::NULL_PTR &&
 146             value->in(true_path)->Opcode() == Op_CastPP &&
 147             value->in(true_path)->in(1) == v1 &&
 148             v1->is_Proj() && is_SB_toString(v1->in(0))) {
 149           return v1;
 150         }
 151       }
 152     }
 153     return value;
 154   }
 155 
 156   Node* argument(int i) {
 157     return _arguments->in(i);
 158   }
 159   Node* argument_uncast(int i) {
 160     Node* arg = argument(i);
 161     int amode = mode(i);
 162     if (amode == StringConcat::StringMode ||
 163         amode == StringConcat::StringNullCheckMode) {
 164       arg = skip_string_null_check(arg);
 165     }
 166     return arg;
 167   }
 168   void set_argument(int i, Node* value) {
 169     _arguments->set_req(i, value);
 170   }
 171   int num_arguments() {
 172     return _mode.length();
 173   }
 174   int mode(int i) {
 175     return _mode.at(i);
 176   }
 177   void add_control(Node* ctrl) {
 178     assert(!_control.contains(ctrl), "only push once");
 179     _control.push(ctrl);
 180   }
 181   void add_constructor(Node* init) {
 182     assert(!_constructors.contains(init), "only push once");
 183     _constructors.push(init);
 184   }
 185   CallStaticJavaNode* end() { return _end; }
 186   AllocateNode* begin() { return _begin; }
 187 
 188   void eliminate_unneeded_control();
 189   void eliminate_initialize(InitializeNode* init);
 190   void eliminate_call(CallNode* call);
 191 
 192   void maybe_log_transform() {
 193     CompileLog* log = _stringopts->C->log();
 194     if (log != nullptr) {
 195       log->head("replace_string_concat arguments='%d' multiple='%d'", num_arguments(), _multiple);
 196       JVMState* p = _begin->jvms();
 197       while (p != nullptr) {
 198         log->elem("jvms bci='%d' method='%d'", p->bci(), log->identify(p->method()));
 199         p = p->caller();
 200       }
 201       log->tail("replace_string_concat");
 202     }
 203   }
 204 
 205   void convert_uncommon_traps(GraphKit& kit, const JVMState* jvms) {
 206     for (uint u = 0; u < _uncommon_traps.size(); u++) {
 207       Node* uct = _uncommon_traps.at(u);
 208 
 209       // Build a new call using the jvms state of the allocate
 210       address call_addr = OptoRuntime::uncommon_trap_blob()->entry_point();
 211       const TypeFunc* call_type = OptoRuntime::uncommon_trap_Type();
 212       const TypePtr* no_memory_effects = nullptr;
 213       Compile* C = _stringopts->C;
 214       CallStaticJavaNode* call = new CallStaticJavaNode(call_type, call_addr, "uncommon_trap",
 215                                                         no_memory_effects);
 216       for (int e = 0; e < TypeFunc::Parms; e++) {
 217         call->init_req(e, uct->in(e));
 218       }
 219       // Set the trap request to record intrinsic failure if this trap
 220       // is taken too many times.  Ideally we would handle then traps by
 221       // doing the original bookkeeping in the MDO so that if it caused
 222       // the code to be thrown out we could still recompile and use the
 223       // optimization.  Failing the uncommon traps doesn't really mean
 224       // that the optimization is a bad idea but there's no other way to
 225       // do the MDO updates currently.
 226       int trap_request = Deoptimization::make_trap_request(Deoptimization::Reason_intrinsic,
 227                                                            Deoptimization::Action_make_not_entrant);
 228       call->init_req(TypeFunc::Parms, __ intcon(trap_request));
 229       kit.add_safepoint_edges(call);
 230 
 231       _stringopts->gvn()->transform(call);
 232       C->gvn_replace_by(uct, call);
 233       uct->disconnect_inputs(C);
 234     }
 235   }
 236 
 237   void cleanup() {
 238     // disconnect the hook node
 239     _arguments->disconnect_inputs(_stringopts->C);
 240   }
 241 };
 242 
 243 
 244 void StringConcat::eliminate_unneeded_control() {
 245   for (uint i = 0; i < _control.size(); i++) {
 246     Node* n = _control.at(i);
 247     if (n->is_Allocate()) {
 248       eliminate_initialize(n->as_Allocate()->initialization());
 249     }
 250     if (n->is_Call()) {
 251       if (n != _end) {
 252         eliminate_call(n->as_Call());
 253       }
 254     } else if (n->is_IfTrue()) {
 255       Compile* C = _stringopts->C;
 256       C->gvn_replace_by(n, n->in(0)->in(0));
 257       // get rid of the other projection
 258       C->gvn_replace_by(n->in(0)->as_If()->proj_out(false), C->top());
 259     } else if (n->is_Region()) {
 260       Node* iff = n->in(1)->in(0);
 261       assert(n->req() == 3 && n->in(2)->in(0) == iff, "not a diamond");
 262       assert(iff->is_If(), "no if for the diamond");
 263       Node* bol = iff->in(1);
 264       if (bol->is_Con()) {
 265         // A BoolNode shared by two diamond Region/If sub-graphs
 266         // was replaced by a constant zero in a previous call to this method.
 267         // Do nothing as the transformation in the previous call ensures both are folded away.
 268         assert(bol == _stringopts->gvn()->intcon(0), "shared condition should have been set to false");
 269         continue;
 270       }
 271       assert(bol->is_Bool(), "unexpected if shape");
 272       Node* cmp = bol->in(1);
 273       assert(cmp->is_Cmp(), "unexpected if shape");
 274       if (cmp->in(1)->is_top() || cmp->in(2)->is_top()) {
 275         // This region should lose its Phis. They are removed either in PhaseRemoveUseless (for data phis) or in IGVN
 276         // (for memory phis). During IGVN, there is a chance that the If folds to top before the Region is processed
 277         // which then causes a reachable part of the graph to become dead. To prevent this, set the boolean input of
 278         // the If to a constant to nicely let the diamond Region/If fold away.
 279         Compile* C = _stringopts->C;
 280         C->gvn_replace_by(iff->in(1), _stringopts->gvn()->intcon(0));
 281       }
 282     }
 283   }
 284 }
 285 
 286 
 287 StringConcat* StringConcat::merge(StringConcat* other, Node* arg) {
 288   StringConcat* result = new StringConcat(_stringopts, _end);
 289   for (uint x = 0; x < _control.size(); x++) {
 290     Node* n = _control.at(x);
 291     if (n->is_Call()) {
 292       result->_control.push(n);
 293     }
 294   }
 295   for (uint x = 0; x < other->_control.size(); x++) {
 296     Node* n = other->_control.at(x);
 297     if (n->is_Call()) {
 298       result->_control.push(n);
 299     }
 300   }
 301   assert(result->_control.contains(other->_end), "what?");
 302   assert(result->_control.contains(_begin), "what?");
 303 
 304   uint arguments_appended = 0;
 305   for (int x = 0; x < num_arguments(); x++) {
 306     Node* argx = argument_uncast(x);
 307     if (argx == arg) {
 308       // replace the toString result with the all the arguments that
 309       // made up the other StringConcat
 310       for (int y = 0; y < other->num_arguments(); y++) {
 311         result->append(other->argument(y), other->mode(y));
 312       }
 313       arguments_appended += other->num_arguments();
 314     } else {
 315       result->append(argx, mode(x));
 316       arguments_appended++;
 317     }
 318     // Check if this concatenation would result in an excessive number of arguments
 319     // -- leading to high memory use, compilation time, and later, a large number of IR nodes
 320     // -- and bail out in that case.
 321     if (arguments_appended > STACKED_CONCAT_UPPER_BOUND) {
 322 #ifndef PRODUCT
 323       if (PrintOptimizeStringConcat) {
 324         tty->print_cr("Merge candidate of length %d exceeds argument limit", arguments_appended);
 325       }
 326 #endif
 327       return nullptr;
 328     }
 329   }
 330   result->set_allocation(other->_begin);
 331   for (uint i = 0; i < _constructors.size(); i++) {
 332     result->add_constructor(_constructors.at(i));
 333   }
 334   for (uint i = 0; i < other->_constructors.size(); i++) {
 335     result->add_constructor(other->_constructors.at(i));
 336   }
 337   result->_multiple = true;
 338   return result;
 339 }
 340 
 341 
 342 void StringConcat::eliminate_call(CallNode* call) {
 343   Compile* C = _stringopts->C;
 344   CallProjections projs;
 345   call->extract_projections(&projs, false);
 346   if (projs.fallthrough_catchproj != nullptr) {
 347     C->gvn_replace_by(projs.fallthrough_catchproj, call->in(TypeFunc::Control));
 348   }
 349   if (projs.fallthrough_memproj != nullptr) {
 350     C->gvn_replace_by(projs.fallthrough_memproj, call->in(TypeFunc::Memory));
 351   }
 352   if (projs.catchall_memproj != nullptr) {
 353     C->gvn_replace_by(projs.catchall_memproj, C->top());
 354   }
 355   if (projs.fallthrough_ioproj != nullptr) {
 356     C->gvn_replace_by(projs.fallthrough_ioproj, call->in(TypeFunc::I_O));
 357   }
 358   if (projs.catchall_ioproj != nullptr) {
 359     C->gvn_replace_by(projs.catchall_ioproj, C->top());
 360   }
 361   if (projs.catchall_catchproj != nullptr) {
 362     // EA can't cope with the partially collapsed graph this
 363     // creates so put it on the worklist to be collapsed later.
 364     for (SimpleDUIterator i(projs.catchall_catchproj); i.has_next(); i.next()) {
 365       Node *use = i.get();
 366       int opc = use->Opcode();
 367       if (opc == Op_CreateEx || opc == Op_Region) {
 368         _stringopts->record_dead_node(use);
 369       }
 370     }
 371     C->gvn_replace_by(projs.catchall_catchproj, C->top());
 372   }
 373   if (projs.resproj != nullptr) {
 374     C->gvn_replace_by(projs.resproj, C->top());
 375   }
 376   C->gvn_replace_by(call, C->top());
 377 }
 378 
 379 void StringConcat::eliminate_initialize(InitializeNode* init) {
 380   Compile* C = _stringopts->C;
 381 
 382   // Eliminate Initialize node.
 383   assert(init->req() <= InitializeNode::RawStores, "no pending inits");
 384   Node *ctrl_proj = init->proj_out_or_null(TypeFunc::Control);
 385   if (ctrl_proj != nullptr) {
 386     C->gvn_replace_by(ctrl_proj, init->in(TypeFunc::Control));
 387   }
 388   Node* mem = init->in(TypeFunc::Memory);
 389   init->replace_mem_projs_by(mem, C);
 390   C->gvn_replace_by(init, C->top());
 391   init->disconnect_inputs(C);
 392 }
 393 
 394 Node_List PhaseStringOpts::collect_toString_calls() {
 395   Node_List string_calls;
 396   Node_List worklist;
 397 
 398   _visited.clear();
 399 
 400   // Prime the worklist
 401   for (uint i = 1; i < C->root()->len(); i++) {
 402     Node* n = C->root()->in(i);
 403     if (n != nullptr && !_visited.test_set(n->_idx)) {
 404       worklist.push(n);
 405     }
 406   }
 407 
 408   uint encountered = 0;
 409   while (worklist.size() > 0) {
 410     Node* ctrl = worklist.pop();
 411     if (StringConcat::is_SB_toString(ctrl)) {
 412       CallStaticJavaNode* csj = ctrl->as_CallStaticJava();
 413       string_calls.push(csj);
 414       encountered++;
 415     }
 416     if (ctrl->in(0) != nullptr && !_visited.test_set(ctrl->in(0)->_idx)) {
 417       worklist.push(ctrl->in(0));
 418     }
 419     if (ctrl->is_Region()) {
 420       for (uint i = 1; i < ctrl->len(); i++) {
 421         if (ctrl->in(i) != nullptr && !_visited.test_set(ctrl->in(i)->_idx)) {
 422           worklist.push(ctrl->in(i));
 423         }
 424       }
 425     }
 426   }
 427 #ifndef PRODUCT
 428   AtomicAccess::add(&_stropts_total, encountered);
 429 #endif
 430   return string_calls;
 431 }
 432 
 433 // Recognize a fluent-chain of StringBuilder/Buffer. They are either explicit usages
 434 // of them or the legacy bytecodes of string concatenation prior to JEP-280. eg.
 435 //
 436 // String result = new StringBuilder()
 437 //   .append("foo")
 438 //   .append("bar")
 439 //   .append(123)
 440 //   .toString(); // "foobar123"
 441 //
 442 // PS: Only a certain subset of constructor and append methods are acceptable.
 443 // The criterion is that the length of argument is easy to work out in this phrase.
 444 // It will drop complex cases such as Object.
 445 //
 446 // Since it walks along the receivers of fluent-chain, it will give up if the codeshape is
 447 // not "fluent" enough. eg.
 448 //   StringBuilder sb = new StringBuilder();
 449 //   sb.append("foo");
 450 //   sb.toString();
 451 //
 452 // The receiver of toString method is the result of Allocation Node(CheckCastPP).
 453 // The append method is overlooked. It will fail at validate_control_flow() test.
 454 //
 455 StringConcat* PhaseStringOpts::build_candidate(CallStaticJavaNode* call) {
 456   ciMethod* m = call->method();
 457   ciSymbol* string_sig;
 458   ciSymbol* int_sig;
 459   ciSymbol* char_sig;
 460   if (m->holder() == C->env()->StringBuilder_klass()) {
 461     string_sig = ciSymbols::String_StringBuilder_signature();
 462     int_sig = ciSymbols::int_StringBuilder_signature();
 463     char_sig = ciSymbols::char_StringBuilder_signature();
 464   } else if (m->holder() == C->env()->StringBuffer_klass()) {
 465     string_sig = ciSymbols::String_StringBuffer_signature();
 466     int_sig = ciSymbols::int_StringBuffer_signature();
 467     char_sig = ciSymbols::char_StringBuffer_signature();
 468   } else {
 469     return nullptr;
 470   }
 471 #ifndef PRODUCT
 472   if (PrintOptimizeStringConcat) {
 473     tty->print("considering toString call in ");
 474     call->jvms()->dump_spec(tty); tty->cr();
 475   }
 476 #endif
 477 
 478   StringConcat* sc = new StringConcat(this, call);
 479   AllocateNode* alloc = nullptr;
 480 
 481   // possible opportunity for StringBuilder fusion
 482   CallStaticJavaNode* cnode = call;
 483   while (cnode) {
 484     Node* recv = cnode->in(TypeFunc::Parms)->uncast();
 485     if (recv->is_Proj()) {
 486       recv = recv->in(0);
 487     }
 488     cnode = recv->isa_CallStaticJava();
 489     if (cnode == nullptr) {
 490       alloc = recv->isa_Allocate();
 491       if (alloc == nullptr) {
 492         break;
 493       }
 494       // Find the constructor call
 495       Node* result = alloc->result_cast();
 496       if (result == nullptr || !result->is_CheckCastPP() || alloc->in(TypeFunc::Memory)->is_top()) {
 497         // strange looking allocation
 498 #ifndef PRODUCT
 499         if (PrintOptimizeStringConcat) {
 500           tty->print("giving up because allocation looks strange ");
 501           alloc->jvms()->dump_spec(tty); tty->cr();
 502         }
 503 #endif
 504         break;
 505       }
 506       Node* constructor = nullptr;
 507       for (SimpleDUIterator i(result); i.has_next(); i.next()) {
 508         CallStaticJavaNode *use = i.get()->isa_CallStaticJava();
 509         if (use != nullptr &&
 510             use->method() != nullptr &&
 511             !use->method()->is_static() &&
 512             use->method()->name() == ciSymbols::object_initializer_name() &&
 513             use->method()->holder() == m->holder()) {
 514           // Matched the constructor.
 515           ciSymbol* sig = use->method()->signature()->as_symbol();
 516           if (sig == ciSymbols::void_method_signature() ||
 517               sig == ciSymbols::int_void_signature() ||
 518               sig == ciSymbols::string_void_signature()) {
 519             if (sig == ciSymbols::string_void_signature()) {
 520               // StringBuilder(String) so pick this up as the first argument
 521               assert(use->in(TypeFunc::Parms + 1) != nullptr, "what?");
 522               const Type* type = _gvn->type(use->in(TypeFunc::Parms + 1));
 523               if (type == TypePtr::NULL_PTR) {
 524                 // StringBuilder(null) throws exception.
 525 #ifndef PRODUCT
 526                 if (PrintOptimizeStringConcat) {
 527                   tty->print("giving up because StringBuilder(null) throws exception");
 528                   alloc->jvms()->dump_spec(tty);
 529                   tty->cr();
 530                 }
 531 #endif
 532                 return nullptr;
 533               }
 534               // StringBuilder(str) argument needs null check.
 535               sc->push_string_null_check(use->in(TypeFunc::Parms + 1));
 536             } else if (sig == ciSymbols::int_void_signature()) {
 537               // StringBuilder(int) case.
 538               Node* parm = use->in(TypeFunc::Parms + 1);
 539               assert(parm != nullptr, "must exist");
 540               const TypeInt* type = _gvn->type(parm)->is_int();
 541               if (type->_hi < 0) {
 542                 // Initial capacity argument is always negative in which case StringBuilder(int) throws
 543                 // a NegativeArraySizeException. Bail out from string opts.
 544 #ifndef PRODUCT
 545                 if (PrintOptimizeStringConcat) {
 546                   tty->print("giving up because a negative argument is passed to StringBuilder(int) which "
 547                              "throws a NegativeArraySizeException");
 548                   alloc->jvms()->dump_spec(tty);
 549                   tty->cr();
 550                 }
 551 #endif
 552                 return nullptr;
 553               } else if (type->_lo < 0) {
 554                 // Argument could be negative: We need a runtime check to throw NegativeArraySizeException in that case.
 555                 sc->push_negative_int_check(parm);
 556               }
 557             }
 558             // The int variant takes an initial size for the backing
 559             // array so just treat it like the void version.
 560             constructor = use;
 561           } else {
 562 #ifndef PRODUCT
 563             if (PrintOptimizeStringConcat) {
 564               tty->print("unexpected constructor signature: %s", sig->as_utf8());
 565             }
 566 #endif
 567           }
 568           break;
 569         }
 570       }
 571       if (constructor == nullptr) {
 572         // couldn't find constructor
 573 #ifndef PRODUCT
 574         if (PrintOptimizeStringConcat) {
 575           tty->print("giving up because couldn't find constructor ");
 576           alloc->jvms()->dump_spec(tty); tty->cr();
 577         }
 578 #endif
 579         break;
 580       }
 581 
 582       // Walked all the way back and found the constructor call so see
 583       // if this call converted into a direct string concatenation.
 584       sc->add_control(call);
 585       sc->add_control(constructor);
 586       sc->add_control(alloc);
 587       sc->set_allocation(alloc);
 588       sc->add_constructor(constructor);
 589       if (sc->validate_control_flow() && sc->validate_mem_flow()) {
 590         return sc;
 591       } else {
 592         return nullptr;
 593       }
 594     } else if (cnode->method() == nullptr) {
 595       break;
 596     } else if (!cnode->method()->is_static() &&
 597                cnode->method()->holder() == m->holder() &&
 598                cnode->method()->name() == ciSymbols::append_name() &&
 599                (cnode->method()->signature()->as_symbol() == string_sig ||
 600                 cnode->method()->signature()->as_symbol() == char_sig ||
 601                 cnode->method()->signature()->as_symbol() == int_sig)) {
 602       sc->add_control(cnode);
 603       Node* arg = cnode->in(TypeFunc::Parms + 1);
 604       if (arg == nullptr || arg->is_top()) {
 605 #ifndef PRODUCT
 606         if (PrintOptimizeStringConcat) {
 607           tty->print("giving up because the call is effectively dead");
 608           cnode->jvms()->dump_spec(tty); tty->cr();
 609         }
 610 #endif
 611         break;
 612       }
 613       if (cnode->method()->signature()->as_symbol() == int_sig) {
 614         sc->push_int(arg);
 615       } else if (cnode->method()->signature()->as_symbol() == char_sig) {
 616         sc->push_char(arg);
 617       } else {
 618         if (arg->is_Proj() && arg->in(0)->is_CallStaticJava()) {
 619           CallStaticJavaNode* csj = arg->in(0)->as_CallStaticJava();
 620           if (csj->method() != nullptr &&
 621               csj->method()->intrinsic_id() == vmIntrinsics::_Integer_toString &&
 622               arg->outcnt() == 1) {
 623             // _control is the list of StringBuilder calls nodes which
 624             // will be replaced by new String code after this optimization.
 625             // Integer::toString() call is not part of StringBuilder calls
 626             // chain. It could be eliminated only if its result is used
 627             // only by this SB calls chain.
 628             // Another limitation: it should be used only once because
 629             // it is unknown that it is used only by this SB calls chain
 630             // until all related SB calls nodes are collected.
 631             assert(arg->unique_out() == cnode, "sanity");
 632             sc->add_control(csj);
 633             sc->push_int(csj->in(TypeFunc::Parms));
 634             continue;
 635           }
 636         }
 637         sc->push_string(arg);
 638       }
 639       continue;
 640     } else {
 641       // some unhandled signature
 642 #ifndef PRODUCT
 643       if (PrintOptimizeStringConcat) {
 644         tty->print("giving up because encountered unexpected signature ");
 645         cnode->tf()->dump(); tty->cr();
 646         cnode->in(TypeFunc::Parms + 1)->dump();
 647       }
 648 #endif
 649       break;
 650     }
 651   }
 652   return nullptr;
 653 }
 654 
 655 
 656 PhaseStringOpts::PhaseStringOpts(PhaseGVN* gvn):
 657   Phase(StringOpts),
 658   _gvn(gvn) {
 659 
 660   assert(OptimizeStringConcat, "shouldn't be here");
 661 
 662   // Collect the types needed to talk about the various slices of memory
 663   byte_adr_idx = C->get_alias_index(TypeAryPtr::BYTES);
 664 
 665   // For each locally allocated StringBuffer see if the usages can be
 666   // collapsed into a single String construction.
 667 
 668   // Run through the list of allocation looking for SB.toString to see
 669   // if it's possible to fuse the usage of the SB into a single String
 670   // construction.
 671   GrowableArray<StringConcat*> concats;
 672   Node_List toStrings = collect_toString_calls();
 673   while (toStrings.size() > 0) {
 674     StringConcat* sc = build_candidate(toStrings.pop()->as_CallStaticJava());
 675     if (sc != nullptr) {
 676       concats.push(sc);
 677     }
 678   }
 679 
 680   // try to coalesce separate concats
 681  restart:
 682   for (int c = 0; c < concats.length(); c++) {
 683     StringConcat* sc = concats.at(c);
 684     for (int i = 0; i < sc->num_arguments(); i++) {
 685       Node* arg = sc->argument_uncast(i);
 686       if (arg->is_Proj() && StringConcat::is_SB_toString(arg->in(0))) {
 687         CallStaticJavaNode* csj = arg->in(0)->as_CallStaticJava();
 688         for (int o = 0; o < concats.length(); o++) {
 689           if (c == o) continue;
 690           StringConcat* other = concats.at(o);
 691           if (other->end() == csj) {
 692 #ifndef PRODUCT
 693             if (PrintOptimizeStringConcat) {
 694               tty->print_cr("considering stacked concats");
 695             }
 696 #endif
 697 
 698             StringConcat* merged = sc->merge(other, arg);
 699             if (merged != nullptr && merged->validate_control_flow() && merged->validate_mem_flow()) {
 700 #ifndef PRODUCT
 701               AtomicAccess::inc(&_stropts_merged);
 702               if (PrintOptimizeStringConcat) {
 703                 tty->print_cr("stacking would succeed");
 704               }
 705 #endif
 706               if (c < o) {
 707                 concats.remove_at(o);
 708                 concats.at_put(c, merged);
 709               } else {
 710                 concats.remove_at(c);
 711                 concats.at_put(o, merged);
 712               }
 713               goto restart;
 714             } else {
 715 #ifndef PRODUCT
 716               if (PrintOptimizeStringConcat) {
 717                 tty->print_cr("stacking would fail");
 718               }
 719 #endif
 720             }
 721           }
 722         }
 723       }
 724     }
 725   }
 726 
 727 
 728   for (int c = 0; c < concats.length(); c++) {
 729     StringConcat* sc = concats.at(c);
 730     replace_string_concat(sc);
 731   }
 732 
 733   remove_dead_nodes();
 734 }
 735 
 736 void PhaseStringOpts::record_dead_node(Node* dead) {
 737   dead_worklist.push(dead);
 738 }
 739 
 740 void PhaseStringOpts::remove_dead_nodes() {
 741   // Delete any dead nodes to make things clean enough that escape
 742   // analysis doesn't get unhappy.
 743   while (dead_worklist.size() > 0) {
 744     Node* use = dead_worklist.pop();
 745     int opc = use->Opcode();
 746     switch (opc) {
 747       case Op_Region: {
 748         uint i = 1;
 749         for (i = 1; i < use->req(); i++) {
 750           if (use->in(i) != C->top()) {
 751             break;
 752           }
 753         }
 754         if (i >= use->req()) {
 755           for (SimpleDUIterator i(use); i.has_next(); i.next()) {
 756             Node* m = i.get();
 757             if (m->is_Phi()) {
 758               dead_worklist.push(m);
 759             }
 760           }
 761           C->gvn_replace_by(use, C->top());
 762         }
 763         break;
 764       }
 765       case Op_AddP:
 766       case Op_CreateEx: {
 767         // Recursively clean up references to CreateEx so EA doesn't
 768         // get unhappy about the partially collapsed graph.
 769         for (SimpleDUIterator i(use); i.has_next(); i.next()) {
 770           Node* m = i.get();
 771           if (m->is_AddP()) {
 772             dead_worklist.push(m);
 773           }
 774         }
 775         C->gvn_replace_by(use, C->top());
 776         break;
 777       }
 778       case Op_Phi:
 779         if (use->in(0) == C->top()) {
 780           C->gvn_replace_by(use, C->top());
 781         }
 782         break;
 783     }
 784   }
 785 }
 786 
 787 
 788 bool StringConcat::validate_mem_flow() {
 789   Compile* C = _stringopts->C;
 790 
 791   for (uint i = 0; i < _control.size(); i++) {
 792 #ifndef PRODUCT
 793     Node_List path;
 794 #endif
 795     Node* curr = _control.at(i);
 796     if (curr->is_Call() && curr != _begin) { // For all calls except the first allocation
 797       // Now here's the main invariant in our case:
 798       // For memory between the constructor, and appends, and toString we should only see bottom memory,
 799       // produced by the previous call we know about.
 800       if (!_constructors.contains(curr)) {
 801         NOT_PRODUCT(path.push(curr);)
 802         Node* mem = curr->in(TypeFunc::Memory);
 803         assert(mem != nullptr, "calls should have memory edge");
 804         assert(!mem->is_Phi(), "should be handled by control flow validation");
 805         NOT_PRODUCT(path.push(mem);)
 806         while (mem->is_MergeMem()) {
 807           for (uint i = 1; i < mem->req(); i++) {
 808             if (i != Compile::AliasIdxBot && mem->in(i) != C->top()) {
 809 #ifndef PRODUCT
 810               if (PrintOptimizeStringConcat) {
 811                 tty->print("fusion has incorrect memory flow (side effects) for ");
 812                 _begin->jvms()->dump_spec(tty); tty->cr();
 813                 path.dump();
 814               }
 815 #endif
 816               return false;
 817             }
 818           }
 819           // skip through a potential MergeMem chain, linked through Bot
 820           mem = mem->in(Compile::AliasIdxBot);
 821           NOT_PRODUCT(path.push(mem);)
 822         }
 823         // now let it fall through, and see if we have a projection
 824         if (mem->is_Proj()) {
 825           // Should point to a previous known call
 826           Node *prev = mem->in(0);
 827           NOT_PRODUCT(path.push(prev);)
 828           if (!prev->is_Call() || !_control.contains(prev)) {
 829 #ifndef PRODUCT
 830             if (PrintOptimizeStringConcat) {
 831               tty->print("fusion has incorrect memory flow (unknown call) for ");
 832               _begin->jvms()->dump_spec(tty); tty->cr();
 833               path.dump();
 834             }
 835 #endif
 836             return false;
 837           }
 838         } else {
 839           assert(mem->is_Store() || mem->is_LoadStore(), "unexpected node type: %s", mem->Name());
 840 #ifndef PRODUCT
 841           if (PrintOptimizeStringConcat) {
 842             tty->print("fusion has incorrect memory flow (unexpected source) for ");
 843             _begin->jvms()->dump_spec(tty); tty->cr();
 844             path.dump();
 845           }
 846 #endif
 847           return false;
 848         }
 849       } else {
 850         // For memory that feeds into constructors it's more complicated.
 851         // However the advantage is that any side effect that happens between the Allocate/Initialize and
 852         // the constructor will have to be control-dependent on Initialize.
 853         // So we actually don't have to do anything, since it's going to be caught by the control flow
 854         // analysis.
 855 #ifdef ASSERT
 856         // Do a quick verification of the control pattern between the constructor and the initialize node
 857         assert(curr->is_Call(), "constructor should be a call");
 858         // Go up the control starting from the constructor call
 859         Node* ctrl = curr->in(0);
 860         IfNode* iff = nullptr;
 861         RegionNode* copy = nullptr;
 862 
 863         while (true) {
 864           // skip known check patterns
 865           if (ctrl->is_Region()) {
 866             if (ctrl->as_Region()->is_copy()) {
 867               copy = ctrl->as_Region();
 868               ctrl = copy->is_copy();
 869             } else { // a cast
 870               assert(ctrl->req() == 3 &&
 871                      ctrl->in(1) != nullptr && ctrl->in(1)->is_Proj() &&
 872                      ctrl->in(2) != nullptr && ctrl->in(2)->is_Proj() &&
 873                      ctrl->in(1)->in(0) == ctrl->in(2)->in(0) &&
 874                      ctrl->in(1)->in(0) != nullptr && ctrl->in(1)->in(0)->is_If(),
 875                      "must be a simple diamond");
 876               Node* true_proj = ctrl->in(1)->is_IfTrue() ? ctrl->in(1) : ctrl->in(2);
 877               for (SimpleDUIterator i(true_proj); i.has_next(); i.next()) {
 878                 Node* use = i.get();
 879                 assert(use == ctrl || use->is_ConstraintCast(),
 880                        "unexpected user: %s", use->Name());
 881               }
 882 
 883               iff = ctrl->in(1)->in(0)->as_If();
 884               ctrl = iff->in(0);
 885             }
 886           } else if (ctrl->is_IfTrue()) { // null checks, class checks
 887             iff = ctrl->in(0)->as_If();
 888             // Verify that the other arm is an uncommon trap
 889             Node* otherproj = iff->proj_out(1 - ctrl->as_Proj()->_con);
 890             CallStaticJavaNode* call = otherproj->unique_out()->isa_CallStaticJava();
 891             assert(strcmp(call->_name, "uncommon_trap") == 0, "must be uncommon trap");
 892             ctrl = iff->in(0);
 893           } else {
 894             break;
 895           }
 896         }
 897 
 898         assert(ctrl->is_Proj(), "must be a projection");
 899         assert(ctrl->in(0)->is_Initialize(), "should be initialize");
 900         for (SimpleDUIterator i(ctrl); i.has_next(); i.next()) {
 901           Node* use = i.get();
 902           assert(use == copy || use == iff || use == curr || use->is_CheckCastPP() || use->is_Load(),
 903                  "unexpected user: %s", use->Name());
 904         }
 905 #endif // ASSERT
 906       }
 907     }
 908   }
 909 
 910 #ifndef PRODUCT
 911   if (PrintOptimizeStringConcat) {
 912     tty->print("fusion has correct memory flow for ");
 913     _begin->jvms()->dump_spec(tty); tty->cr();
 914     tty->cr();
 915   }
 916 #endif
 917   return true;
 918 }
 919 
 920 bool StringConcat::validate_control_flow() {
 921   // We found all the calls and arguments now lets see if it's
 922   // safe to transform the graph as we would expect.
 923 
 924   // Check to see if this resulted in too many uncommon traps previously
 925   if (Compile::current()->too_many_traps(_begin->jvms()->method(), _begin->jvms()->bci(),
 926                         Deoptimization::Reason_intrinsic)) {
 927     return false;
 928   }
 929 
 930   // Walk backwards over the control flow from toString to the
 931   // allocation and make sure all the control flow is ok.  This
 932   // means it's either going to be eliminated once the calls are
 933   // removed or it can safely be transformed into an uncommon
 934   // trap.
 935 
 936   int null_check_count = 0;
 937   Unique_Node_List ctrl_path;
 938 
 939   assert(_control.contains(_begin), "missing");
 940   assert(_control.contains(_end), "missing");
 941 
 942   // Collect the nodes that we know about and will eliminate into ctrl_path
 943   for (uint i = 0; i < _control.size(); i++) {
 944     // Push the call and it's control projection
 945     Node* n = _control.at(i);
 946     if (n->is_Allocate()) {
 947       AllocateNode* an = n->as_Allocate();
 948       InitializeNode* init = an->initialization();
 949       ctrl_path.push(init);
 950       ctrl_path.push(init->as_Multi()->proj_out(0));
 951     }
 952     if (n->is_Call()) {
 953       CallNode* cn = n->as_Call();
 954       ctrl_path.push(cn);
 955       ctrl_path.push(cn->proj_out(0));
 956       ctrl_path.push(cn->proj_out(0)->unique_out());
 957       Node* catchproj = cn->proj_out(0)->unique_out()->as_Catch()->proj_out_or_null(0);
 958       if (catchproj != nullptr) {
 959         ctrl_path.push(catchproj);
 960       }
 961     } else {
 962       ShouldNotReachHere();
 963     }
 964   }
 965 
 966   // Skip backwards through the control checking for unexpected control flow
 967   Node* ptr = _end;
 968   bool fail = false;
 969   while (ptr != _begin) {
 970     if (ptr->is_Call() && ctrl_path.member(ptr)) {
 971       ptr = ptr->in(0);
 972     } else if (ptr->is_CatchProj() && ctrl_path.member(ptr)) {
 973       ptr = ptr->in(0)->in(0)->in(0);
 974       assert(ctrl_path.member(ptr), "should be a known piece of control");
 975     } else if (ptr->is_IfTrue()) {
 976       IfNode* iff = ptr->in(0)->as_If();
 977       BoolNode* b = iff->in(1)->isa_Bool();
 978 
 979       if (b == nullptr) {
 980 #ifndef PRODUCT
 981         if (PrintOptimizeStringConcat) {
 982           tty->print_cr("unexpected input to IfNode");
 983           iff->in(1)->dump();
 984           tty->cr();
 985         }
 986 #endif
 987         fail = true;
 988         break;
 989       }
 990 
 991       Node* cmp = b->in(1);
 992       Node* v1 = cmp->in(1);
 993       Node* v2 = cmp->in(2);
 994       Node* otherproj = iff->proj_out(1 - ptr->as_Proj()->_con);
 995 
 996       // Null check of the return of append which can simply be eliminated
 997       if (b->_test._test == BoolTest::ne &&
 998           v2->bottom_type() == TypePtr::NULL_PTR &&
 999           v1->is_Proj() && ctrl_path.member(v1->in(0))) {
1000         // null check of the return value of the append
1001         null_check_count++;
1002         if (otherproj->outcnt() == 1) {
1003           CallStaticJavaNode* call = otherproj->unique_out()->isa_CallStaticJava();
1004           if (call != nullptr && call->_name != nullptr && strcmp(call->_name, "uncommon_trap") == 0) {
1005             ctrl_path.push(call);
1006           }
1007         }
1008         _control.push(ptr);
1009         ptr = ptr->in(0)->in(0);
1010         continue;
1011       }
1012 
1013       // A test which leads to an uncommon trap. It is safe to convert the trap
1014       // into a trap that restarts at the beginning as long as its test does not
1015       // depend on intermediate results of the candidate chain.
1016       // at the beginning.
1017       if (otherproj->outcnt() == 1) {
1018         CallStaticJavaNode* call = otherproj->unique_out()->isa_CallStaticJava();
1019         if (call != nullptr && call->_name != nullptr && strcmp(call->_name, "uncommon_trap") == 0) {
1020           // First check for dependency on a toString that is going away during stacked concats.
1021           if (_multiple &&
1022               ((v1->is_Proj() && is_SB_toString(v1->in(0)) && ctrl_path.member(v1->in(0))) ||
1023                (v2->is_Proj() && is_SB_toString(v2->in(0)) && ctrl_path.member(v2->in(0))))) {
1024             // iftrue -> if -> bool -> cmpp -> resproj -> tostring
1025             fail = true;
1026             break;
1027           }
1028           // control flow leads to uct so should be ok
1029           _uncommon_traps.push(call);
1030           ctrl_path.push(call);
1031           ptr = ptr->in(0)->in(0);
1032           continue;
1033         }
1034       }
1035 
1036 #ifndef PRODUCT
1037       // Some unexpected control flow we don't know how to handle.
1038       if (PrintOptimizeStringConcat) {
1039         tty->print_cr("failing with unknown test");
1040         b->dump();
1041         cmp->dump();
1042         v1->dump();
1043         v2->dump();
1044         tty->cr();
1045       }
1046 #endif
1047       fail = true;
1048       break;
1049     } else if (ptr->is_Proj() && ptr->in(0)->is_Initialize()) {
1050       // Check for side effect between Initialize and the constructor
1051       for (SimpleDUIterator iter(ptr); iter.has_next(); iter.next()) {
1052         Node* use = iter.get();
1053         if (!use->is_CFG() && !use->is_CheckCastPP() && !use->is_Load()) {
1054 #ifndef PRODUCT
1055           if (PrintOptimizeStringConcat) {
1056             tty->print_cr("unexpected control use of Initialize");
1057             ptr->in(0)->dump(); // Initialize node
1058             use->dump(1);
1059           }
1060 #endif
1061           fail = true;
1062           break;
1063         }
1064       }
1065       ptr = ptr->in(0)->in(0);
1066     } else if (ptr->is_Region()) {
1067       Node* copy = ptr->as_Region()->is_copy();
1068       if (copy != nullptr) {
1069         ptr = copy;
1070         continue;
1071       }
1072       if (ptr->req() == 3 &&
1073           ptr->in(1) != nullptr && ptr->in(1)->is_Proj() &&
1074           ptr->in(2) != nullptr && ptr->in(2)->is_Proj() &&
1075           ptr->in(1)->in(0) == ptr->in(2)->in(0) &&
1076           ptr->in(1)->in(0) != nullptr && ptr->in(1)->in(0)->is_If()) {
1077         // Simple diamond.
1078         // XXX should check for possibly merging stores.  simple data merges are ok.
1079         // The IGVN will make this simple diamond go away when it
1080         // transforms the Region. Make sure it sees it.
1081         Compile::current()->record_for_igvn(ptr);
1082         _control.push(ptr);
1083         ptr = ptr->in(1)->in(0)->in(0);
1084         continue;
1085       }
1086 #ifndef PRODUCT
1087       if (PrintOptimizeStringConcat) {
1088         tty->print_cr("fusion would fail for region");
1089         _begin->dump();
1090         ptr->dump(2);
1091       }
1092 #endif
1093       fail = true;
1094       break;
1095     } else {
1096       // other unknown control
1097       if (!fail) {
1098 #ifndef PRODUCT
1099         if (PrintOptimizeStringConcat) {
1100           tty->print_cr("fusion would fail for");
1101           _begin->dump();
1102         }
1103 #endif
1104         fail = true;
1105       }
1106 #ifndef PRODUCT
1107       if (PrintOptimizeStringConcat) {
1108         ptr->dump();
1109       }
1110 #endif
1111       ptr = ptr->in(0);
1112     }
1113   }
1114 #ifndef PRODUCT
1115   if (PrintOptimizeStringConcat && fail) {
1116     tty->cr();
1117   }
1118 #endif
1119   if (fail) return !fail;
1120 
1121   // Validate that all these results produced are contained within
1122   // this cluster of objects.  First collect all the results produced
1123   // by calls in the region.
1124   _stringopts->_visited.clear();
1125   Node_List worklist;
1126   Node* final_result = _end->proj_out_or_null(TypeFunc::Parms);
1127   for (uint i = 0; i < _control.size(); i++) {
1128     CallNode* cnode = _control.at(i)->isa_Call();
1129     if (cnode != nullptr) {
1130       _stringopts->_visited.test_set(cnode->_idx);
1131     }
1132     Node* result = cnode != nullptr ? cnode->proj_out_or_null(TypeFunc::Parms) : nullptr;
1133     if (result != nullptr && result != final_result) {
1134       worklist.push(result);
1135     }
1136   }
1137 
1138   Node* last_result = nullptr;
1139   while (worklist.size() > 0) {
1140     Node* result = worklist.pop();
1141     if (_stringopts->_visited.test_set(result->_idx))
1142       continue;
1143     for (SimpleDUIterator i(result); i.has_next(); i.next()) {
1144       Node *use = i.get();
1145       if (ctrl_path.member(use)) {
1146         // already checked this
1147         continue;
1148       }
1149       int opc = use->Opcode();
1150       if (opc == Op_CmpP || opc == Op_Node) {
1151         ctrl_path.push(use);
1152         continue;
1153       }
1154       if (opc == Op_CastPP || opc == Op_CheckCastPP) {
1155         for (SimpleDUIterator j(use); j.has_next(); j.next()) {
1156           worklist.push(j.get());
1157         }
1158         worklist.push(use->in(1));
1159         ctrl_path.push(use);
1160         continue;
1161       }
1162 #ifndef PRODUCT
1163       if (PrintOptimizeStringConcat) {
1164         if (result != last_result) {
1165           last_result = result;
1166           tty->print_cr("extra uses for result:");
1167           last_result->dump();
1168         }
1169         use->dump();
1170       }
1171 #endif
1172       fail = true;
1173       break;
1174     }
1175   }
1176 
1177 #ifndef PRODUCT
1178   if (PrintOptimizeStringConcat && !fail) {
1179     ttyLocker ttyl;
1180     tty->cr();
1181     tty->print("fusion has correct control flow (%d %d) for ", null_check_count, _uncommon_traps.size());
1182     _begin->jvms()->dump_spec(tty); tty->cr();
1183     for (int i = 0; i < num_arguments(); i++) {
1184       argument(i)->dump();
1185     }
1186     _control.dump();
1187     tty->cr();
1188   }
1189 #endif
1190 
1191   return !fail;
1192 }
1193 
1194 // Mirror of Integer.stringSize() method, return the count of digits in integer,
1195 Node* PhaseStringOpts::int_stringSize(GraphKit& kit, Node* arg) {
1196   if (arg->is_Con()) {
1197     // Constant integer. Compute constant length
1198     jint arg_val = arg->get_int();
1199     jint d = 1;
1200     if (arg_val >= 0) {
1201       d = 0;
1202       arg_val = -arg_val;
1203     }
1204     jint p = -10;
1205     for (int i = 1; i < 10; i++) {
1206       if (arg_val > p) {
1207         return __ intcon(i + d);
1208       }
1209       p = java_multiply(10, p);
1210     }
1211     return __ intcon(10 + d);
1212   }
1213 
1214   // int d = 1;
1215   // if (x >= 0) {
1216   //     d = 0;
1217   //     x = -x;
1218   // }
1219   RegionNode* sign_merge = new RegionNode(3);
1220   kit.gvn().set_type(sign_merge, Type::CONTROL);
1221   Node* digit_cnt = new PhiNode(sign_merge, TypeInt::INT);
1222   kit.gvn().set_type(digit_cnt, TypeInt::INT);
1223   Node* val = new PhiNode(sign_merge, TypeInt::INT);
1224   kit.gvn().set_type(val, TypeInt::INT);
1225 
1226   IfNode* iff = kit.create_and_map_if(kit.control(),
1227                                       __ Bool(__ CmpI(arg, __ intcon(0)), BoolTest::ge),
1228                                       PROB_FAIR, COUNT_UNKNOWN);
1229   sign_merge->init_req(1, __ IfTrue(iff));
1230   sign_merge->init_req(2, __ IfFalse(iff));
1231   digit_cnt->init_req(1, __ intcon(0));
1232   digit_cnt->init_req(2, __ intcon(1));
1233   val->init_req(1, __ SubI(__ intcon(0), arg));
1234   val->init_req(2, arg);
1235   kit.set_control(sign_merge);
1236 
1237   // int p = -10;
1238   // for (int i = 1; i < 10; i++) {
1239   //     if (x > p)
1240   //         return i + d;
1241   //     p = 10 * p;
1242   // }
1243   RegionNode* final_merge = new RegionNode(3);
1244   kit.gvn().set_type(final_merge, Type::CONTROL);
1245   Node* final_size = new PhiNode(final_merge, TypeInt::INT);
1246   kit.gvn().set_type(final_size, TypeInt::INT);
1247 
1248   kit.add_parse_predicates();
1249   C->set_has_loops(true);
1250 
1251   RegionNode* loop = new RegionNode(3);
1252   kit.gvn().set_type(loop, Type::CONTROL);
1253   Node* index = new PhiNode(loop, TypeInt::INT);
1254   kit.gvn().set_type(index, TypeInt::INT);
1255   Node* temp = new PhiNode(loop, TypeInt::INT);
1256   kit.gvn().set_type(temp, TypeInt::INT);
1257 
1258   loop->init_req(1, kit.control());
1259   index->init_req(1, __ intcon(1));
1260   temp->init_req(1, __ intcon(-10));
1261   kit.set_control(loop);
1262 
1263   Node* limit = __ CmpI(index, __ intcon(10));
1264   Node* limitb = __ Bool(limit, BoolTest::lt);
1265   IfNode* iff2 = kit.create_and_map_if(kit.control(), limitb, PROB_MIN, COUNT_UNKNOWN);
1266   Node* limit_less = __ IfTrue(iff2);
1267   kit.set_control(limit_less);
1268 
1269   Node* cmp = __ CmpI(val, temp);
1270   Node* cmpb = __ Bool(cmp, BoolTest::gt);
1271   IfNode* iff3 = kit.create_and_map_if(kit.control(), cmpb, PROB_MIN, COUNT_UNKNOWN);
1272   Node* cmp_le = __ IfFalse(iff3);
1273   kit.set_control(cmp_le);
1274 
1275   loop->init_req(2, kit.control());
1276   index->init_req(2, __ AddI(index, __ intcon(1)));
1277   temp->init_req(2, __ MulI(temp, __ intcon(10)));
1278 
1279   final_merge->init_req(1, __ IfFalse(iff2));
1280   final_merge->init_req(2, __ IfTrue(iff3));
1281   final_size->init_req(1, __ AddI(digit_cnt, __ intcon(10)));
1282   final_size->init_req(2, __ AddI(digit_cnt, index));
1283   kit.set_control(final_merge);
1284 
1285   C->record_for_igvn(sign_merge);
1286   C->record_for_igvn(digit_cnt);
1287   C->record_for_igvn(val);
1288   C->record_for_igvn(final_merge);
1289   C->record_for_igvn(final_size);
1290   C->record_for_igvn(loop);
1291   C->record_for_igvn(index);
1292   C->record_for_igvn(temp);
1293   return final_size;
1294 }
1295 
1296 // Simplified version of Integer.getChars
1297 void PhaseStringOpts::getChars(GraphKit& kit, Node* arg, Node* dst_array, BasicType bt, Node* end, Node* final_merge, Node* final_mem, int merge_index) {
1298   // if (i < 0) {
1299   //     sign = '-';
1300   //     i = -i;
1301   // }
1302   IfNode* iff = kit.create_and_map_if(kit.control(), __ Bool(__ CmpI(arg, __ intcon(0)), BoolTest::lt),
1303                                       PROB_FAIR, COUNT_UNKNOWN);
1304 
1305   RegionNode* merge = new RegionNode(3);
1306   kit.gvn().set_type(merge, Type::CONTROL);
1307   Node* i = new PhiNode(merge, TypeInt::INT);
1308   kit.gvn().set_type(i, TypeInt::INT);
1309   Node* sign = new PhiNode(merge, TypeInt::INT);
1310   kit.gvn().set_type(sign, TypeInt::INT);
1311 
1312   merge->init_req(1, __ IfTrue(iff));
1313   i->init_req(1, __ SubI(__ intcon(0), arg));
1314   sign->init_req(1, __ intcon('-'));
1315   merge->init_req(2, __ IfFalse(iff));
1316   i->init_req(2, arg);
1317   sign->init_req(2, __ intcon(0));
1318 
1319   kit.set_control(merge);
1320 
1321   C->record_for_igvn(merge);
1322   C->record_for_igvn(i);
1323   C->record_for_igvn(sign);
1324 
1325   // for (;;) {
1326   //     q = i / 10;
1327   //     r = i - ((q << 3) + (q << 1));  // r = i-(q*10) ...
1328   //     buf [--charPos] = digits [r];
1329   //     i = q;
1330   //     if (i == 0) break;
1331   // }
1332 
1333   // Add Parse Predicates first.
1334   kit.add_parse_predicates();
1335 
1336   C->set_has_loops(true);
1337   RegionNode* head = new RegionNode(3);
1338   head->init_req(1, kit.control());
1339 
1340   kit.gvn().set_type(head, Type::CONTROL);
1341   Node* i_phi = new PhiNode(head, TypeInt::INT);
1342   i_phi->init_req(1, i);
1343   kit.gvn().set_type(i_phi, TypeInt::INT);
1344   Node* charPos = new PhiNode(head, TypeInt::INT);
1345   charPos->init_req(1, end);
1346   kit.gvn().set_type(charPos, TypeInt::INT);
1347   Node* mem = PhiNode::make(head, kit.memory(byte_adr_idx), Type::MEMORY, TypeAryPtr::BYTES);
1348   kit.gvn().set_type(mem, Type::MEMORY);
1349 
1350   kit.set_control(head);
1351   kit.set_memory(mem, byte_adr_idx);
1352 
1353   Node* q = __ DivI(kit.null(), i_phi, __ intcon(10));
1354   Node* r = __ SubI(i_phi, __ AddI(__ LShiftI(q, __ intcon(3)),
1355                                    __ LShiftI(q, __ intcon(1))));
1356   Node* index = __ SubI(charPos, __ intcon((bt == T_BYTE) ? 1 : 2));
1357   Node* ch = __ AddI(r, __ intcon('0'));
1358   Node* st = __ store_to_memory(kit.control(), kit.array_element_address(dst_array, index, T_BYTE),
1359                                 ch, bt, MemNode::unordered, false /* require_atomic_access */,
1360                                 false /* unaligned */, (bt != T_BYTE) /* mismatched */);
1361 
1362   iff = kit.create_and_map_if(head, __ Bool(__ CmpI(q, __ intcon(0)), BoolTest::ne),
1363                               PROB_FAIR, COUNT_UNKNOWN);
1364   Node* ne = __ IfTrue(iff);
1365   Node* eq = __ IfFalse(iff);
1366 
1367   head->init_req(2, ne);
1368   mem->init_req(2, st);
1369 
1370   i_phi->init_req(2, q);
1371   charPos->init_req(2, index);
1372   charPos = index;
1373 
1374   kit.set_control(eq);
1375   kit.set_memory(st, byte_adr_idx);
1376 
1377   C->record_for_igvn(head);
1378   C->record_for_igvn(mem);
1379   C->record_for_igvn(i_phi);
1380   C->record_for_igvn(charPos);
1381 
1382   // if (sign != 0) {
1383   //     buf [--charPos] = sign;
1384   // }
1385   iff = kit.create_and_map_if(kit.control(), __ Bool(__ CmpI(sign, __ intcon(0)), BoolTest::ne),
1386                               PROB_FAIR, COUNT_UNKNOWN);
1387 
1388   final_merge->init_req(merge_index + 2, __ IfFalse(iff));
1389   final_mem->init_req(merge_index + 2, kit.memory(byte_adr_idx));
1390 
1391   kit.set_control(__ IfTrue(iff));
1392   if (kit.stopped()) {
1393     final_merge->init_req(merge_index + 1, C->top());
1394     final_mem->init_req(merge_index + 1, C->top());
1395   } else {
1396     Node* index = __ SubI(charPos, __ intcon((bt == T_BYTE) ? 1 : 2));
1397     st = __ store_to_memory(kit.control(), kit.array_element_address(dst_array, index, T_BYTE),
1398                             sign, bt, MemNode::unordered, false /* require_atomic_access */, false /* unaligned */,
1399                             (bt != T_BYTE) /* mismatched */);
1400 
1401     final_merge->init_req(merge_index + 1, kit.control());
1402     final_mem->init_req(merge_index + 1, st);
1403   }
1404 }
1405 
1406 // Copy the characters representing arg into dst_array starting at start
1407 Node* PhaseStringOpts::int_getChars(GraphKit& kit, Node* arg, Node* dst_array, Node* dst_coder, Node* start, Node* size) {
1408   bool dcon = dst_coder->is_Con();
1409   bool dbyte = dcon ? (dst_coder->get_int() == java_lang_String::CODER_LATIN1) : false;
1410   Node* end = __ AddI(start, __ LShiftI(size, dst_coder));
1411 
1412   // The final_merge node has 4 entries in case the encoding is known:
1413   // (0) Control, (1) result w/ sign, (2) result w/o sign, (3) result for Integer.min_value
1414   // or 6 entries in case the encoding is not known:
1415   // (0) Control, (1) Latin1 w/ sign, (2) Latin1 w/o sign, (3) min_value, (4) UTF16 w/ sign, (5) UTF16 w/o sign
1416   RegionNode* final_merge = new RegionNode(dcon ? 4 : 6);
1417   kit.gvn().set_type(final_merge, Type::CONTROL);
1418 
1419   Node* final_mem = PhiNode::make(final_merge, kit.memory(byte_adr_idx), Type::MEMORY, TypeAryPtr::BYTES);
1420   kit.gvn().set_type(final_mem, Type::MEMORY);
1421 
1422   // need to handle arg == Integer.MIN_VALUE specially because negating doesn't make it positive
1423   IfNode* iff = kit.create_and_map_if(kit.control(), __ Bool(__ CmpI(arg, __ intcon(0x80000000)), BoolTest::ne),
1424                                       PROB_FAIR, COUNT_UNKNOWN);
1425 
1426   Node* old_mem = kit.memory(byte_adr_idx);
1427 
1428   kit.set_control(__ IfFalse(iff));
1429   if (kit.stopped()) {
1430     // Statically not equal to MIN_VALUE so this path is dead
1431     final_merge->init_req(3, kit.control());
1432   } else {
1433     copy_string(kit, __ makecon(TypeInstPtr::make(C->env()->the_min_jint_string())),
1434                 dst_array, dst_coder, start);
1435     final_merge->init_req(3, kit.control());
1436     final_mem->init_req(3, kit.memory(byte_adr_idx));
1437   }
1438 
1439   kit.set_control(__ IfTrue(iff));
1440   kit.set_memory(old_mem, byte_adr_idx);
1441 
1442   if (!dcon) {
1443     // Check encoding of destination
1444     iff = kit.create_and_map_if(kit.control(), __ Bool(__ CmpI(dst_coder, __ intcon(0)), BoolTest::eq),
1445                                 PROB_FAIR, COUNT_UNKNOWN);
1446     old_mem = kit.memory(byte_adr_idx);
1447   }
1448   if (!dcon || dbyte) {
1449     // Destination is Latin1,
1450     if (!dcon) {
1451       kit.set_control(__ IfTrue(iff));
1452     }
1453     getChars(kit, arg, dst_array, T_BYTE, end, final_merge, final_mem);
1454   }
1455   if (!dcon || !dbyte) {
1456     // Destination is UTF16
1457     int merge_index = 0;
1458     if (!dcon) {
1459       kit.set_control(__ IfFalse(iff));
1460       kit.set_memory(old_mem, byte_adr_idx);
1461       merge_index = 3; // Account for Latin1 case
1462     }
1463     getChars(kit, arg, dst_array, T_CHAR, end, final_merge, final_mem, merge_index);
1464   }
1465 
1466   // Final merge point for Latin1 and UTF16 case
1467   kit.set_control(final_merge);
1468   kit.set_memory(final_mem, byte_adr_idx);
1469 
1470   C->record_for_igvn(final_merge);
1471   C->record_for_igvn(final_mem);
1472   return end;
1473 }
1474 
1475 // Copy 'count' bytes/chars from src_array to dst_array starting at index start
1476 void PhaseStringOpts::arraycopy(GraphKit& kit, IdealKit& ideal, Node* src_array, Node* dst_array, BasicType elembt, Node* start, Node* count) {
1477   assert(elembt == T_BYTE || elembt == T_CHAR, "Invalid type for arraycopy");
1478 
1479   if (elembt == T_CHAR) {
1480     // Get number of chars
1481     count = __ RShiftI(count, __ intcon(1));
1482   }
1483 
1484   Node* extra = nullptr;
1485 #ifdef _LP64
1486   count = __ ConvI2L(count);
1487   extra = C->top();
1488 #endif
1489 
1490   Node* src_ptr = __ array_element_address(src_array, __ intcon(0), T_BYTE);
1491   Node* dst_ptr = __ array_element_address(dst_array, start, T_BYTE);
1492   // Check if src array address is aligned to HeapWordSize
1493   bool aligned = (arrayOopDesc::base_offset_in_bytes(T_BYTE) % HeapWordSize == 0);
1494   // If true, then check if dst array address is aligned to HeapWordSize
1495   if (aligned) {
1496     const TypeInt* tdst = __ gvn().type(start)->is_int();
1497     aligned = tdst->is_con() && ((arrayOopDesc::base_offset_in_bytes(T_BYTE) +
1498                                   tdst->get_con() * type2aelembytes(T_BYTE)) % HeapWordSize == 0);
1499   }
1500   // Figure out which arraycopy runtime method to call (disjoint, uninitialized).
1501   const char* copyfunc_name = "arraycopy";
1502   address     copyfunc_addr = StubRoutines::select_arraycopy_function(elembt, aligned, true, copyfunc_name, true);
1503   ideal.make_leaf_call_no_fp(OptoRuntime::fast_arraycopy_Type(), copyfunc_addr, copyfunc_name,
1504                              TypeAryPtr::BYTES, src_ptr, dst_ptr, count, extra);
1505 }
1506 
1507 #undef __
1508 #define __ ideal.
1509 
1510 // Copy contents of a Latin1 encoded string from src_array to dst_array
1511 void PhaseStringOpts::copy_latin1_string(GraphKit& kit, IdealKit& ideal, Node* src_array, IdealVariable& count,
1512                                          Node* dst_array, Node* dst_coder, Node* start) {
1513   bool dcon = dst_coder->is_Con();
1514   bool dbyte = dcon ? (dst_coder->get_int() == java_lang_String::CODER_LATIN1) : false;
1515 
1516   if (!dcon) {
1517     __ if_then(dst_coder, BoolTest::eq, __ ConI(java_lang_String::CODER_LATIN1));
1518   }
1519   if (!dcon || dbyte) {
1520     // Destination is Latin1. Simply emit a byte arraycopy.
1521     arraycopy(kit, ideal, src_array, dst_array, T_BYTE, start, __ value(count));
1522   }
1523   if (!dcon) {
1524     __ else_();
1525   }
1526   if (!dcon || !dbyte) {
1527     // Destination is UTF16. Inflate src_array into dst_array.
1528     kit.sync_kit(ideal);
1529     if (Matcher::match_rule_supported(Op_StrInflatedCopy)) {
1530       // Use fast intrinsic
1531       Node* src = kit.array_element_address(src_array, kit.intcon(0), T_BYTE);
1532       Node* dst = kit.array_element_address(dst_array, start, T_BYTE);
1533       kit.inflate_string(src, dst, TypeAryPtr::BYTES, __ value(count));
1534     } else {
1535       // No intrinsic available, use slow method
1536       kit.inflate_string_slow(src_array, dst_array, start, __ value(count));
1537     }
1538     ideal.sync_kit(&kit);
1539     // Multiply count by two since we now need two bytes per char
1540     __ set(count, __ LShiftI(__ value(count), __ ConI(1)));
1541   }
1542   if (!dcon) {
1543     __ end_if();
1544   }
1545 }
1546 
1547 // Read two bytes from index and index+1 and convert them to a char
1548 static jchar readChar(ciTypeArray* array, int index) {
1549   int shift_high, shift_low;
1550 #ifdef VM_LITTLE_ENDIAN
1551     shift_high = 0;
1552     shift_low = 8;
1553 #else
1554     shift_high = 8;
1555     shift_low = 0;
1556 #endif
1557 
1558   jchar b1 = ((jchar) array->byte_at(index)) & 0xff;
1559   jchar b2 = ((jchar) array->byte_at(index+1)) & 0xff;
1560   return (b1 << shift_high) | (b2 << shift_low);
1561 }
1562 
1563 // Copy contents of constant src_array to dst_array by emitting individual stores
1564 void PhaseStringOpts::copy_constant_string(GraphKit& kit, IdealKit& ideal, ciTypeArray* src_array, IdealVariable& count,
1565                                            bool src_is_byte, Node* dst_array, Node* dst_coder, Node* start) {
1566   bool dcon = dst_coder->is_Con();
1567   bool dbyte = dcon ? (dst_coder->get_int() == java_lang_String::CODER_LATIN1) : false;
1568   int length = src_array->length();
1569 
1570   if (!dcon) {
1571     __ if_then(dst_coder, BoolTest::eq, __ ConI(java_lang_String::CODER_LATIN1));
1572   }
1573   if (!dcon || dbyte) {
1574     // Destination is Latin1. Copy each byte of src_array into dst_array.
1575     Node* index = start;
1576     for (int i = 0; i < length; i++) {
1577       Node* adr = kit.array_element_address(dst_array, index, T_BYTE);
1578       Node* val = __ ConI(src_array->byte_at(i));
1579       __ store(__ ctrl(), adr, val, T_BYTE, byte_adr_idx, MemNode::unordered);
1580       index = __ AddI(index, __ ConI(1));
1581     }
1582   }
1583   if (!dcon) {
1584     __ else_();
1585   }
1586   if (!dcon || !dbyte) {
1587     // Destination is UTF16. Copy each char of src_array into dst_array.
1588     Node* index = start;
1589     for (int i = 0; i < length; i++) {
1590       Node* adr = kit.array_element_address(dst_array, index, T_BYTE);
1591       jchar val;
1592       if (src_is_byte) {
1593         val = src_array->byte_at(i) & 0xff;
1594       } else {
1595         val = readChar(src_array, i++);
1596       }
1597       __ store(__ ctrl(), adr, __ ConI(val), T_CHAR, byte_adr_idx, MemNode::unordered, false /* require_atomic_access */,
1598                true /* mismatched */);
1599       index = __ AddI(index, __ ConI(2));
1600     }
1601     if (src_is_byte) {
1602       // Multiply count by two since we now need two bytes per char
1603       __ set(count, __ ConI(2 * length));
1604     }
1605   }
1606   if (!dcon) {
1607     __ end_if();
1608   }
1609 }
1610 
1611 // Compress copy contents of the byte/char String str into dst_array starting at index start.
1612 Node* PhaseStringOpts::copy_string(GraphKit& kit, Node* str, Node* dst_array, Node* dst_coder, Node* start) {
1613   Node* src_array = kit.load_String_value(str, true);
1614 
1615   IdealKit ideal(&kit, true, true);
1616   IdealVariable count(ideal); __ declarations_done();
1617 
1618   if (str->is_Con()) {
1619     // Constant source string
1620     ciTypeArray* src_array_type = get_constant_value(kit, str);
1621 
1622     // Check encoding of constant string
1623     bool src_is_byte = (get_constant_coder(kit, str) == java_lang_String::CODER_LATIN1);
1624 
1625     // For small constant strings just emit individual stores.
1626     // A length of 6 seems like a good space/speed tradeof.
1627     __ set(count, __ ConI(src_array_type->length()));
1628     int src_len = src_array_type->length() / (src_is_byte ? 1 : 2);
1629     if (src_len < unroll_string_copy_length) {
1630       // Small constant string
1631       copy_constant_string(kit, ideal, src_array_type, count, src_is_byte, dst_array, dst_coder, start);
1632     } else if (src_is_byte) {
1633       // Source is Latin1
1634       copy_latin1_string(kit, ideal, src_array, count, dst_array, dst_coder, start);
1635     } else {
1636       // Source is UTF16 (destination too). Simply emit a char arraycopy.
1637       arraycopy(kit, ideal, src_array, dst_array, T_CHAR, start, __ value(count));
1638     }
1639   } else {
1640     Node* size = kit.load_array_length(src_array);
1641     __ set(count, size);
1642     // Non-constant source string
1643     if (CompactStrings) {
1644       // Emit runtime check for coder
1645       Node* coder = kit.load_String_coder(str, true);
1646       __ if_then(coder, BoolTest::eq, __ ConI(java_lang_String::CODER_LATIN1)); {
1647         // Source is Latin1
1648         copy_latin1_string(kit, ideal, src_array, count, dst_array, dst_coder, start);
1649       } __ else_();
1650     }
1651     // Source is UTF16 (destination too). Simply emit a char arraycopy.
1652     arraycopy(kit, ideal, src_array, dst_array, T_CHAR, start, __ value(count));
1653 
1654     if (CompactStrings) {
1655       __ end_if();
1656     }
1657   }
1658 
1659   // Finally sync IdealKit and GraphKit.
1660   kit.sync_kit(ideal);
1661   return __ AddI(start, __ value(count));
1662 }
1663 
1664 // Compress copy the char into dst_array at index start.
1665 Node* PhaseStringOpts::copy_char(GraphKit& kit, Node* val, Node* dst_array, Node* dst_coder, Node* start) {
1666   bool dcon = (dst_coder != nullptr) && dst_coder->is_Con();
1667   bool dbyte = dcon ? (dst_coder->get_int() == java_lang_String::CODER_LATIN1) : false;
1668 
1669   IdealKit ideal(&kit, true, true);
1670   IdealVariable end(ideal); __ declarations_done();
1671   Node* adr = kit.array_element_address(dst_array, start, T_BYTE);
1672   if (!dcon){
1673     __ if_then(dst_coder, BoolTest::eq, __ ConI(java_lang_String::CODER_LATIN1));
1674   }
1675   if (!dcon || dbyte) {
1676     // Destination is Latin1. Store a byte.
1677     __ store(__ ctrl(), adr, val, T_BYTE, byte_adr_idx, MemNode::unordered);
1678     __ set(end, __ AddI(start, __ ConI(1)));
1679   }
1680   if (!dcon) {
1681     __ else_();
1682   }
1683   if (!dcon || !dbyte) {
1684     // Destination is UTF16. Store a char.
1685     __ store(__ ctrl(), adr, val, T_CHAR, byte_adr_idx, MemNode::unordered, false /* require_atomic_access */,
1686              true /* mismatched */);
1687     __ set(end, __ AddI(start, __ ConI(2)));
1688   }
1689   if (!dcon) {
1690     __ end_if();
1691   }
1692   // Finally sync IdealKit and GraphKit.
1693   kit.sync_kit(ideal);
1694   return __ value(end);
1695 }
1696 
1697 #undef __
1698 #define __ kit.
1699 
1700 // Allocate a byte array of specified length.
1701 Node* PhaseStringOpts::allocate_byte_array(GraphKit& kit, IdealKit* ideal, Node* length) {
1702   if (ideal != nullptr) {
1703     // Sync IdealKit and graphKit.
1704     kit.sync_kit(*ideal);
1705   }
1706   Node* byte_array = nullptr;
1707   {
1708     PreserveReexecuteState preexecs(&kit);
1709     // The original jvms is for an allocation of either a String or
1710     // StringBuffer so no stack adjustment is necessary for proper
1711     // reexecution.  If we deoptimize in the slow path the bytecode
1712     // will be reexecuted and the char[] allocation will be thrown away.
1713     kit.jvms()->set_should_reexecute(true);
1714     byte_array = kit.new_array(__ makecon(TypeKlassPtr::make(ciTypeArrayKlass::make(T_BYTE))),
1715                                length, 1);
1716   }
1717 
1718   // Mark the allocation so that zeroing is skipped since the code
1719   // below will overwrite the entire array
1720   AllocateArrayNode* byte_alloc = AllocateArrayNode::Ideal_array_allocation(byte_array);
1721   byte_alloc->maybe_set_complete(_gvn);
1722 
1723   if (ideal != nullptr) {
1724     // Sync IdealKit and graphKit.
1725     ideal->sync_kit(&kit);
1726   }
1727   return byte_array;
1728 }
1729 
1730 jbyte PhaseStringOpts::get_constant_coder(GraphKit& kit, Node* str) {
1731   assert(str->is_Con(), "String must be constant");
1732   const TypeOopPtr* str_type = kit.gvn().type(str)->isa_oopptr();
1733   ciInstance* str_instance = str_type->const_oop()->as_instance();
1734   jbyte coder = str_instance->field_value_by_offset(java_lang_String::coder_offset()).as_byte();
1735   assert(CompactStrings || (coder == java_lang_String::CODER_UTF16), "Strings must be UTF16 encoded");
1736   return coder;
1737 }
1738 
1739 int PhaseStringOpts::get_constant_length(GraphKit& kit, Node* str) {
1740   assert(str->is_Con(), "String must be constant");
1741   return get_constant_value(kit, str)->length();
1742 }
1743 
1744 ciTypeArray* PhaseStringOpts::get_constant_value(GraphKit& kit, Node* str) {
1745   assert(str->is_Con(), "String must be constant");
1746   const TypeOopPtr* str_type = kit.gvn().type(str)->isa_oopptr();
1747   ciInstance* str_instance = str_type->const_oop()->as_instance();
1748   ciObject* src_array = str_instance->field_value_by_offset(java_lang_String::value_offset()).as_object();
1749   return src_array->as_type_array();
1750 }
1751 
1752 void PhaseStringOpts::replace_string_concat(StringConcat* sc) {
1753   // Log a little info about the transformation
1754   sc->maybe_log_transform();
1755 
1756   // pull the JVMState of the allocation into a SafePointNode to serve as
1757   // as a shim for the insertion of the new code.
1758   JVMState* jvms     = sc->begin()->jvms()->clone_shallow(C);
1759   uint size = sc->begin()->req();
1760   SafePointNode* map = new SafePointNode(size, jvms);
1761 
1762   // copy the control and memory state from the final call into our
1763   // new starting state.  This allows any preceding tests to feed
1764   // into the new section of code.
1765   for (uint i1 = 0; i1 < TypeFunc::Parms; i1++) {
1766     map->init_req(i1, sc->end()->in(i1));
1767   }
1768   // blow away old allocation arguments
1769   for (uint i1 = TypeFunc::Parms; i1 < jvms->debug_start(); i1++) {
1770     map->init_req(i1, C->top());
1771   }
1772   // Copy the rest of the inputs for the JVMState
1773   for (uint i1 = jvms->debug_start(); i1 < sc->begin()->req(); i1++) {
1774     map->init_req(i1, sc->begin()->in(i1));
1775   }
1776   // Make sure the memory state is a MergeMem for parsing.
1777   if (!map->in(TypeFunc::Memory)->is_MergeMem()) {
1778     map->set_req(TypeFunc::Memory, MergeMemNode::make(map->in(TypeFunc::Memory)));
1779   }
1780 
1781   jvms->set_map(map);
1782   map->ensure_stack(jvms, jvms->method()->max_stack());
1783 
1784   // disconnect all the old StringBuilder calls from the graph
1785   sc->eliminate_unneeded_control();
1786 
1787   // At this point all the old work has been completely removed from
1788   // the graph and the saved JVMState exists at the point where the
1789   // final toString call used to be.
1790   GraphKit kit(jvms);
1791 
1792   // There may be uncommon traps which are still using the
1793   // intermediate states and these need to be rewritten to point at
1794   // the JVMState at the beginning of the transformation.
1795   sc->convert_uncommon_traps(kit, jvms);
1796 
1797   // Now insert the logic to compute the size of the string followed
1798   // by all the logic to construct array and resulting string.
1799 
1800   Node* null_string = __ makecon(TypeInstPtr::make(C->env()->the_null_string()));
1801 
1802   // Create a region for the overflow checks to merge into.
1803   int args = MAX2(sc->num_arguments(), 1);
1804   RegionNode* overflow = new RegionNode(args);
1805   kit.gvn().set_type(overflow, Type::CONTROL);
1806 
1807   // Create a hook node to hold onto the individual sizes since they
1808   // are need for the copying phase.
1809   Node* string_sizes = new Node(args);
1810 
1811   Node* coder = __ intcon(0);
1812   Node* length = __ intcon(0);
1813   // If at least one argument is UTF16 encoded, we can fix the encoding.
1814   bool coder_fixed = false;
1815 
1816   if (!CompactStrings) {
1817     // Fix encoding of result string to UTF16
1818     coder_fixed = true;
1819     coder = __ intcon(java_lang_String::CODER_UTF16);
1820   }
1821 
1822   for (int argi = 0; argi < sc->num_arguments(); argi++) {
1823     Node* arg = sc->argument(argi);
1824     switch (sc->mode(argi)) {
1825       case StringConcat::NegativeIntCheckMode: {
1826         // Initial capacity argument might be negative in which case StringBuilder(int) throws
1827         // a NegativeArraySizeException. Insert a runtime check with an uncommon trap.
1828         const TypeInt* type = kit.gvn().type(arg)->is_int();
1829         assert(type->_hi >= 0 && type->_lo < 0, "no runtime int check needed");
1830         Node* p = __ Bool(__ CmpI(arg, kit.intcon(0)), BoolTest::ge);
1831         IfNode* iff = kit.create_and_map_if(kit.control(), p, PROB_MIN, COUNT_UNKNOWN);
1832         {
1833           // Negative int -> uncommon trap.
1834           PreserveJVMState pjvms(&kit);
1835           kit.set_control(__ IfFalse(iff));
1836           kit.uncommon_trap(Deoptimization::Reason_intrinsic,
1837                             Deoptimization::Action_maybe_recompile);
1838         }
1839         kit.set_control(__ IfTrue(iff));
1840         break;
1841       }
1842       case StringConcat::IntMode: {
1843         Node* string_size = int_stringSize(kit, arg);
1844 
1845         // accumulate total
1846         length = __ AddI(length, string_size);
1847 
1848         // Cache this value for the use by int_toString
1849         string_sizes->init_req(argi, string_size);
1850         break;
1851       }
1852       case StringConcat::StringNullCheckMode: {
1853         const Type* type = kit.gvn().type(arg);
1854         assert(type != TypePtr::NULL_PTR, "missing check");
1855         if (!type->higher_equal(TypeInstPtr::NOTNULL)) {
1856           // Null check with uncommon trap since
1857           // StringBuilder(null) throws exception.
1858           // Use special uncommon trap instead of
1859           // calling normal do_null_check().
1860           Node* p = __ Bool(__ CmpP(arg, kit.null()), BoolTest::ne);
1861           IfNode* iff = kit.create_and_map_if(kit.control(), p, PROB_MIN, COUNT_UNKNOWN);
1862           overflow->add_req(__ IfFalse(iff));
1863           Node* notnull = __ IfTrue(iff);
1864           kit.set_control(notnull); // set control for the cast_not_null
1865           arg = kit.cast_not_null(arg, false);
1866           sc->set_argument(argi, arg);
1867         }
1868         assert(kit.gvn().type(arg)->higher_equal(TypeInstPtr::NOTNULL), "sanity");
1869         // Fallthrough to add string length.
1870       }
1871       case StringConcat::StringMode: {
1872         const Type* type = kit.gvn().type(arg);
1873         Node* count = nullptr;
1874         Node* arg_coder = nullptr;
1875         if (type == TypePtr::NULL_PTR) {
1876           // replace the argument with the null checked version
1877           arg = null_string;
1878           sc->set_argument(argi, arg);
1879           count = kit.load_String_length(arg, true);
1880           arg_coder = kit.load_String_coder(arg, true);
1881         } else if (!type->higher_equal(TypeInstPtr::NOTNULL)) {
1882           // s = s != null ? s : "null";
1883           // length = length + (s.count - s.offset);
1884           RegionNode *r = new RegionNode(3);
1885           kit.gvn().set_type(r, Type::CONTROL);
1886           Node *phi = new PhiNode(r, type);
1887           kit.gvn().set_type(phi, phi->bottom_type());
1888           Node* p = __ Bool(__ CmpP(arg, kit.null()), BoolTest::ne);
1889           IfNode* iff = kit.create_and_map_if(kit.control(), p, PROB_MIN, COUNT_UNKNOWN);
1890           Node* notnull = __ IfTrue(iff);
1891           Node* isnull =  __ IfFalse(iff);
1892           kit.set_control(notnull); // set control for the cast_not_null
1893           r->init_req(1, notnull);
1894           phi->init_req(1, kit.cast_not_null(arg, false));
1895           r->init_req(2, isnull);
1896           phi->init_req(2, null_string);
1897           kit.set_control(r);
1898           C->record_for_igvn(r);
1899           C->record_for_igvn(phi);
1900           // replace the argument with the null checked version
1901           arg = phi;
1902           sc->set_argument(argi, arg);
1903           count = kit.load_String_length(arg, true);
1904           arg_coder = kit.load_String_coder(arg, true);
1905         } else {
1906           // A corresponding nullcheck will be connected during IGVN MemNode::Ideal_common_DU_postCCP
1907           // kit.control might be a different test, that can be hoisted above the actual nullcheck
1908           // in case, that the control input is not null, Ideal_common_DU_postCCP will not look for a nullcheck.
1909           count = kit.load_String_length(arg, false);
1910           arg_coder = kit.load_String_coder(arg, false);
1911         }
1912         if (arg->is_Con()) {
1913           // Constant string. Get constant coder and length.
1914           jbyte const_coder = get_constant_coder(kit, arg);
1915           int const_length = get_constant_length(kit, arg);
1916           if (const_coder == java_lang_String::CODER_LATIN1) {
1917             // Can be latin1 encoded
1918             arg_coder = __ intcon(const_coder);
1919             count = __ intcon(const_length);
1920           } else {
1921             // Found UTF16 encoded string. Fix result array encoding to UTF16.
1922             coder_fixed = true;
1923             coder = __ intcon(const_coder);
1924             count = __ intcon(const_length / 2);
1925           }
1926         }
1927 
1928         if (!coder_fixed) {
1929           coder = __ OrI(coder, arg_coder);
1930         }
1931         length = __ AddI(length, count);
1932         string_sizes->init_req(argi, nullptr);
1933         break;
1934       }
1935       case StringConcat::CharMode: {
1936         // one character only
1937         const TypeInt* t = kit.gvn().type(arg)->is_int();
1938         if (!coder_fixed && t->is_con()) {
1939           // Constant char
1940           if (t->get_con() <= 255) {
1941             // Can be latin1 encoded
1942             coder = __ OrI(coder, __ intcon(java_lang_String::CODER_LATIN1));
1943           } else {
1944             // Must be UTF16 encoded. Fix result array encoding to UTF16.
1945             coder_fixed = true;
1946             coder = __ intcon(java_lang_String::CODER_UTF16);
1947           }
1948         } else if (!coder_fixed) {
1949           // Not constant
1950 #undef __
1951 #define __ ideal.
1952           IdealKit ideal(&kit, true, true);
1953           IdealVariable char_coder(ideal); __ declarations_done();
1954           // Check if character can be latin1 encoded
1955           __ if_then(arg, BoolTest::le, __ ConI(0xFF));
1956             __ set(char_coder, __ ConI(java_lang_String::CODER_LATIN1));
1957           __ else_();
1958             __ set(char_coder, __ ConI(java_lang_String::CODER_UTF16));
1959           __ end_if();
1960           kit.sync_kit(ideal);
1961           coder = __ OrI(coder, __ value(char_coder));
1962 #undef __
1963 #define __ kit.
1964         }
1965         length = __ AddI(length, __ intcon(1));
1966         break;
1967       }
1968       default:
1969         ShouldNotReachHere();
1970     }
1971     if (argi > 0) {
1972       // Check that the sum hasn't overflowed
1973       IfNode* iff = kit.create_and_map_if(kit.control(),
1974                                           __ Bool(__ CmpI(length, __ intcon(0)), BoolTest::lt),
1975                                           PROB_MIN, COUNT_UNKNOWN);
1976       kit.set_control(__ IfFalse(iff));
1977       overflow->set_req(argi, __ IfTrue(iff));
1978     }
1979   }
1980 
1981   {
1982     // Hook
1983     PreserveJVMState pjvms(&kit);
1984     kit.set_control(overflow);
1985     C->record_for_igvn(overflow);
1986     kit.uncommon_trap(Deoptimization::Reason_intrinsic,
1987                       Deoptimization::Action_make_not_entrant);
1988   }
1989 
1990   Node* result;
1991   if (!kit.stopped()) {
1992     assert(CompactStrings || (coder->is_Con() && coder->get_int() == java_lang_String::CODER_UTF16),
1993            "Result string must be UTF16 encoded if CompactStrings is disabled");
1994 
1995     Node* dst_array = nullptr;
1996     if (sc->num_arguments() == 1 &&
1997         (sc->mode(0) == StringConcat::StringMode ||
1998          sc->mode(0) == StringConcat::StringNullCheckMode)) {
1999       // Handle the case when there is only a single String argument.
2000       // In this case, we can just pull the value from the String itself.
2001       dst_array = kit.load_String_value(sc->argument(0), true);
2002     } else {
2003       // Allocate destination byte array according to coder
2004       dst_array = allocate_byte_array(kit, nullptr, __ LShiftI(length, coder));
2005 
2006       // Now copy the string representations into the final byte[]
2007       Node* start = __ intcon(0);
2008       for (int argi = 0; argi < sc->num_arguments(); argi++) {
2009         Node* arg = sc->argument(argi);
2010         switch (sc->mode(argi)) {
2011           case StringConcat::NegativeIntCheckMode:
2012             break; // Nothing to do, was only needed to add a runtime check earlier.
2013           case StringConcat::IntMode: {
2014             start = int_getChars(kit, arg, dst_array, coder, start, string_sizes->in(argi));
2015             break;
2016           }
2017           case StringConcat::StringNullCheckMode:
2018           case StringConcat::StringMode: {
2019             start = copy_string(kit, arg, dst_array, coder, start);
2020             break;
2021           }
2022           case StringConcat::CharMode: {
2023             start = copy_char(kit, arg, dst_array, coder, start);
2024           break;
2025           }
2026           default:
2027             ShouldNotReachHere();
2028         }
2029       }
2030     }
2031 
2032     {
2033       PreserveReexecuteState preexecs(&kit);
2034       // The original jvms is for an allocation of either a String or
2035       // StringBuffer so no stack adjustment is necessary for proper
2036       // reexecution.
2037       kit.jvms()->set_should_reexecute(true);
2038       result = kit.new_instance(__ makecon(TypeKlassPtr::make(C->env()->String_klass())));
2039     }
2040 
2041     // Initialize the string
2042     kit.store_String_value(result, dst_array);
2043     kit.store_String_coder(result, coder);
2044 
2045     // The value field is final. Emit a barrier here to ensure that the effect
2046     // of the initialization is committed to memory before any code publishes
2047     // a reference to the newly constructed object (see Parse::do_exits()).
2048     assert(AllocateNode::Ideal_allocation(result) != nullptr, "should be newly allocated");
2049     kit.insert_mem_bar(UseStoreStoreForCtor ? Op_MemBarStoreStore : Op_MemBarRelease, result);
2050   } else {
2051     result = C->top();
2052   }
2053   // hook up the outgoing control and result
2054   kit.replace_call(sc->end(), result);
2055 
2056   // Unhook any hook nodes
2057   string_sizes->disconnect_inputs(C);
2058   sc->cleanup();
2059 #ifndef PRODUCT
2060   AtomicAccess::inc(&_stropts_replaced);
2061 #endif
2062 }
2063 
2064 #ifndef PRODUCT
2065 uint PhaseStringOpts::_stropts_replaced = 0;
2066 uint PhaseStringOpts::_stropts_merged = 0;
2067 uint PhaseStringOpts::_stropts_total = 0;
2068 
2069 void PhaseStringOpts::print_statistics() {
2070   tty->print_cr("StringConcat: %4d/%4d/%4d(replaced/merged/total)", _stropts_replaced, _stropts_merged, _stropts_total);
2071 }
2072 #endif