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 = call->extract_projections(false);
 345   if (projs->fallthrough_catchproj != nullptr) {
 346     C->gvn_replace_by(projs->fallthrough_catchproj, call->in(TypeFunc::Control));
 347   }
 348   if (projs->fallthrough_memproj != nullptr) {
 349     C->gvn_replace_by(projs->fallthrough_memproj, call->in(TypeFunc::Memory));
 350   }
 351   if (projs->catchall_memproj != nullptr) {
 352     C->gvn_replace_by(projs->catchall_memproj, C->top());
 353   }
 354   if (projs->fallthrough_ioproj != nullptr) {
 355     C->gvn_replace_by(projs->fallthrough_ioproj, call->in(TypeFunc::I_O));
 356   }
 357   if (projs->catchall_ioproj != nullptr) {
 358     C->gvn_replace_by(projs->catchall_ioproj, C->top());
 359   }
 360   if (projs->catchall_catchproj != nullptr) {
 361     // EA can't cope with the partially collapsed graph this
 362     // creates so put it on the worklist to be collapsed later.
 363     for (SimpleDUIterator i(projs->catchall_catchproj); i.has_next(); i.next()) {
 364       Node *use = i.get();
 365       int opc = use->Opcode();
 366       if (opc == Op_CreateEx || opc == Op_Region) {
 367         _stringopts->record_dead_node(use);
 368       }
 369     }
 370     C->gvn_replace_by(projs->catchall_catchproj, C->top());
 371   }
 372   if (projs->resproj[0] != nullptr) {
 373     assert(projs->nb_resproj == 1, "unexpected number of results");
 374     C->gvn_replace_by(projs->resproj[0], 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         if (opc == Op_CheckCastPP) {
1156           worklist.push(use);
1157         }
1158         for (SimpleDUIterator j(use); j.has_next(); j.next()) {
1159           worklist.push(j.get());
1160         }
1161         worklist.push(use->in(1));
1162         ctrl_path.push(use);
1163         continue;
1164       }
1165 #ifndef PRODUCT
1166       if (PrintOptimizeStringConcat) {
1167         if (result != last_result) {
1168           last_result = result;
1169           tty->print_cr("extra uses for result:");
1170           last_result->dump();
1171         }
1172         use->dump();
1173       }
1174 #endif
1175       fail = true;
1176       break;
1177     }
1178   }
1179 
1180 #ifndef PRODUCT
1181   if (PrintOptimizeStringConcat && !fail) {
1182     ttyLocker ttyl;
1183     tty->cr();
1184     tty->print("fusion has correct control flow (%d %d) for ", null_check_count, _uncommon_traps.size());
1185     _begin->jvms()->dump_spec(tty); tty->cr();
1186     for (int i = 0; i < num_arguments(); i++) {
1187       argument(i)->dump();
1188     }
1189     _control.dump();
1190     tty->cr();
1191   }
1192 #endif
1193 
1194   return !fail;
1195 }
1196 
1197 // Mirror of Integer.stringSize() method, return the count of digits in integer,
1198 Node* PhaseStringOpts::int_stringSize(GraphKit& kit, Node* arg) {
1199   if (arg->is_Con()) {
1200     // Constant integer. Compute constant length
1201     jint arg_val = arg->get_int();
1202     jint d = 1;
1203     if (arg_val >= 0) {
1204       d = 0;
1205       arg_val = -arg_val;
1206     }
1207     jint p = -10;
1208     for (int i = 1; i < 10; i++) {
1209       if (arg_val > p) {
1210         return __ intcon(i + d);
1211       }
1212       p = java_multiply(10, p);
1213     }
1214     return __ intcon(10 + d);
1215   }
1216 
1217   // int d = 1;
1218   // if (x >= 0) {
1219   //     d = 0;
1220   //     x = -x;
1221   // }
1222   RegionNode* sign_merge = new RegionNode(3);
1223   kit.gvn().set_type(sign_merge, Type::CONTROL);
1224   Node* digit_cnt = new PhiNode(sign_merge, TypeInt::INT);
1225   kit.gvn().set_type(digit_cnt, TypeInt::INT);
1226   Node* val = new PhiNode(sign_merge, TypeInt::INT);
1227   kit.gvn().set_type(val, TypeInt::INT);
1228 
1229   IfNode* iff = kit.create_and_map_if(kit.control(),
1230                                       __ Bool(__ CmpI(arg, __ intcon(0)), BoolTest::ge),
1231                                       PROB_FAIR, COUNT_UNKNOWN);
1232   sign_merge->init_req(1, __ IfTrue(iff));
1233   sign_merge->init_req(2, __ IfFalse(iff));
1234   digit_cnt->init_req(1, __ intcon(0));
1235   digit_cnt->init_req(2, __ intcon(1));
1236   val->init_req(1, __ SubI(__ intcon(0), arg));
1237   val->init_req(2, arg);
1238   kit.set_control(sign_merge);
1239 
1240   // int p = -10;
1241   // for (int i = 1; i < 10; i++) {
1242   //     if (x > p)
1243   //         return i + d;
1244   //     p = 10 * p;
1245   // }
1246   RegionNode* final_merge = new RegionNode(3);
1247   kit.gvn().set_type(final_merge, Type::CONTROL);
1248   Node* final_size = new PhiNode(final_merge, TypeInt::INT);
1249   kit.gvn().set_type(final_size, TypeInt::INT);
1250 
1251   kit.add_parse_predicates();
1252   C->set_has_loops(true);
1253 
1254   RegionNode* loop = new RegionNode(3);
1255   kit.gvn().set_type(loop, Type::CONTROL);
1256   Node* index = new PhiNode(loop, TypeInt::INT);
1257   kit.gvn().set_type(index, TypeInt::INT);
1258   Node* temp = new PhiNode(loop, TypeInt::INT);
1259   kit.gvn().set_type(temp, TypeInt::INT);
1260 
1261   loop->init_req(1, kit.control());
1262   index->init_req(1, __ intcon(1));
1263   temp->init_req(1, __ intcon(-10));
1264   kit.set_control(loop);
1265 
1266   Node* limit = __ CmpI(index, __ intcon(10));
1267   Node* limitb = __ Bool(limit, BoolTest::lt);
1268   IfNode* iff2 = kit.create_and_map_if(kit.control(), limitb, PROB_MIN, COUNT_UNKNOWN);
1269   Node* limit_less = __ IfTrue(iff2);
1270   kit.set_control(limit_less);
1271 
1272   Node* cmp = __ CmpI(val, temp);
1273   Node* cmpb = __ Bool(cmp, BoolTest::gt);
1274   IfNode* iff3 = kit.create_and_map_if(kit.control(), cmpb, PROB_MIN, COUNT_UNKNOWN);
1275   Node* cmp_le = __ IfFalse(iff3);
1276   kit.set_control(cmp_le);
1277 
1278   loop->init_req(2, kit.control());
1279   index->init_req(2, __ AddI(index, __ intcon(1)));
1280   temp->init_req(2, __ MulI(temp, __ intcon(10)));
1281 
1282   final_merge->init_req(1, __ IfFalse(iff2));
1283   final_merge->init_req(2, __ IfTrue(iff3));
1284   final_size->init_req(1, __ AddI(digit_cnt, __ intcon(10)));
1285   final_size->init_req(2, __ AddI(digit_cnt, index));
1286   kit.set_control(final_merge);
1287 
1288   C->record_for_igvn(sign_merge);
1289   C->record_for_igvn(digit_cnt);
1290   C->record_for_igvn(val);
1291   C->record_for_igvn(final_merge);
1292   C->record_for_igvn(final_size);
1293   C->record_for_igvn(loop);
1294   C->record_for_igvn(index);
1295   C->record_for_igvn(temp);
1296   return final_size;
1297 }
1298 
1299 // Simplified version of Integer.getChars
1300 void PhaseStringOpts::getChars(GraphKit& kit, Node* arg, Node* dst_array, BasicType bt, Node* end, Node* final_merge, Node* final_mem, int merge_index) {
1301   // if (i < 0) {
1302   //     sign = '-';
1303   //     i = -i;
1304   // }
1305   IfNode* iff = kit.create_and_map_if(kit.control(), __ Bool(__ CmpI(arg, __ intcon(0)), BoolTest::lt),
1306                                       PROB_FAIR, COUNT_UNKNOWN);
1307 
1308   RegionNode* merge = new RegionNode(3);
1309   kit.gvn().set_type(merge, Type::CONTROL);
1310   Node* i = new PhiNode(merge, TypeInt::INT);
1311   kit.gvn().set_type(i, TypeInt::INT);
1312   Node* sign = new PhiNode(merge, TypeInt::INT);
1313   kit.gvn().set_type(sign, TypeInt::INT);
1314 
1315   merge->init_req(1, __ IfTrue(iff));
1316   i->init_req(1, __ SubI(__ intcon(0), arg));
1317   sign->init_req(1, __ intcon('-'));
1318   merge->init_req(2, __ IfFalse(iff));
1319   i->init_req(2, arg);
1320   sign->init_req(2, __ intcon(0));
1321 
1322   kit.set_control(merge);
1323 
1324   C->record_for_igvn(merge);
1325   C->record_for_igvn(i);
1326   C->record_for_igvn(sign);
1327 
1328   // for (;;) {
1329   //     q = i / 10;
1330   //     r = i - ((q << 3) + (q << 1));  // r = i-(q*10) ...
1331   //     buf [--charPos] = digits [r];
1332   //     i = q;
1333   //     if (i == 0) break;
1334   // }
1335 
1336   // Add Parse Predicates first.
1337   kit.add_parse_predicates();
1338 
1339   C->set_has_loops(true);
1340   RegionNode* head = new RegionNode(3);
1341   head->init_req(1, kit.control());
1342 
1343   kit.gvn().set_type(head, Type::CONTROL);
1344   Node* i_phi = new PhiNode(head, TypeInt::INT);
1345   i_phi->init_req(1, i);
1346   kit.gvn().set_type(i_phi, TypeInt::INT);
1347   Node* charPos = new PhiNode(head, TypeInt::INT);
1348   charPos->init_req(1, end);
1349   kit.gvn().set_type(charPos, TypeInt::INT);
1350   Node* mem = PhiNode::make(head, kit.memory(byte_adr_idx), Type::MEMORY, TypeAryPtr::BYTES);
1351   kit.gvn().set_type(mem, Type::MEMORY);
1352 
1353   kit.set_control(head);
1354   kit.set_memory(mem, byte_adr_idx);
1355 
1356   Node* q = __ DivI(kit.null(), i_phi, __ intcon(10));
1357   Node* r = __ SubI(i_phi, __ AddI(__ LShiftI(q, __ intcon(3)),
1358                                    __ LShiftI(q, __ intcon(1))));
1359   Node* index = __ SubI(charPos, __ intcon((bt == T_BYTE) ? 1 : 2));
1360   Node* ch = __ AddI(r, __ intcon('0'));
1361   Node* st = __ store_to_memory(kit.control(), kit.array_element_address(dst_array, index, T_BYTE),
1362                                 ch, bt, MemNode::unordered, false /* require_atomic_access */,
1363                                 false /* unaligned */, (bt != T_BYTE) /* mismatched */);
1364 
1365   iff = kit.create_and_map_if(head, __ Bool(__ CmpI(q, __ intcon(0)), BoolTest::ne),
1366                               PROB_FAIR, COUNT_UNKNOWN);
1367   Node* ne = __ IfTrue(iff);
1368   Node* eq = __ IfFalse(iff);
1369 
1370   head->init_req(2, ne);
1371   mem->init_req(2, st);
1372 
1373   i_phi->init_req(2, q);
1374   charPos->init_req(2, index);
1375   charPos = index;
1376 
1377   kit.set_control(eq);
1378   kit.set_memory(st, byte_adr_idx);
1379 
1380   C->record_for_igvn(head);
1381   C->record_for_igvn(mem);
1382   C->record_for_igvn(i_phi);
1383   C->record_for_igvn(charPos);
1384 
1385   // if (sign != 0) {
1386   //     buf [--charPos] = sign;
1387   // }
1388   iff = kit.create_and_map_if(kit.control(), __ Bool(__ CmpI(sign, __ intcon(0)), BoolTest::ne),
1389                               PROB_FAIR, COUNT_UNKNOWN);
1390 
1391   final_merge->init_req(merge_index + 2, __ IfFalse(iff));
1392   final_mem->init_req(merge_index + 2, kit.memory(byte_adr_idx));
1393 
1394   kit.set_control(__ IfTrue(iff));
1395   if (kit.stopped()) {
1396     final_merge->init_req(merge_index + 1, C->top());
1397     final_mem->init_req(merge_index + 1, C->top());
1398   } else {
1399     Node* index = __ SubI(charPos, __ intcon((bt == T_BYTE) ? 1 : 2));
1400     st = __ store_to_memory(kit.control(), kit.array_element_address(dst_array, index, T_BYTE),
1401                             sign, bt, MemNode::unordered, false /* require_atomic_access */, false /* unaligned */,
1402                             (bt != T_BYTE) /* mismatched */);
1403 
1404     final_merge->init_req(merge_index + 1, kit.control());
1405     final_mem->init_req(merge_index + 1, st);
1406   }
1407 }
1408 
1409 // Copy the characters representing arg into dst_array starting at start
1410 Node* PhaseStringOpts::int_getChars(GraphKit& kit, Node* arg, Node* dst_array, Node* dst_coder, Node* start, Node* size) {
1411   bool dcon = dst_coder->is_Con();
1412   bool dbyte = dcon ? (dst_coder->get_int() == java_lang_String::CODER_LATIN1) : false;
1413   Node* end = __ AddI(start, __ LShiftI(size, dst_coder));
1414 
1415   // The final_merge node has 4 entries in case the encoding is known:
1416   // (0) Control, (1) result w/ sign, (2) result w/o sign, (3) result for Integer.min_value
1417   // or 6 entries in case the encoding is not known:
1418   // (0) Control, (1) Latin1 w/ sign, (2) Latin1 w/o sign, (3) min_value, (4) UTF16 w/ sign, (5) UTF16 w/o sign
1419   RegionNode* final_merge = new RegionNode(dcon ? 4 : 6);
1420   kit.gvn().set_type(final_merge, Type::CONTROL);
1421 
1422   Node* final_mem = PhiNode::make(final_merge, kit.memory(byte_adr_idx), Type::MEMORY, TypeAryPtr::BYTES);
1423   kit.gvn().set_type(final_mem, Type::MEMORY);
1424 
1425   // need to handle arg == Integer.MIN_VALUE specially because negating doesn't make it positive
1426   IfNode* iff = kit.create_and_map_if(kit.control(), __ Bool(__ CmpI(arg, __ intcon(0x80000000)), BoolTest::ne),
1427                                       PROB_FAIR, COUNT_UNKNOWN);
1428 
1429   Node* old_mem = kit.memory(byte_adr_idx);
1430 
1431   kit.set_control(__ IfFalse(iff));
1432   if (kit.stopped()) {
1433     // Statically not equal to MIN_VALUE so this path is dead
1434     final_merge->init_req(3, kit.control());
1435   } else {
1436     copy_string(kit, __ makecon(TypeInstPtr::make(C->env()->the_min_jint_string())),
1437                 dst_array, dst_coder, start);
1438     final_merge->init_req(3, kit.control());
1439     final_mem->init_req(3, kit.memory(byte_adr_idx));
1440   }
1441 
1442   kit.set_control(__ IfTrue(iff));
1443   kit.set_memory(old_mem, byte_adr_idx);
1444 
1445   if (!dcon) {
1446     // Check encoding of destination
1447     iff = kit.create_and_map_if(kit.control(), __ Bool(__ CmpI(dst_coder, __ intcon(0)), BoolTest::eq),
1448                                 PROB_FAIR, COUNT_UNKNOWN);
1449     old_mem = kit.memory(byte_adr_idx);
1450   }
1451   if (!dcon || dbyte) {
1452     // Destination is Latin1,
1453     if (!dcon) {
1454       kit.set_control(__ IfTrue(iff));
1455     }
1456     getChars(kit, arg, dst_array, T_BYTE, end, final_merge, final_mem);
1457   }
1458   if (!dcon || !dbyte) {
1459     // Destination is UTF16
1460     int merge_index = 0;
1461     if (!dcon) {
1462       kit.set_control(__ IfFalse(iff));
1463       kit.set_memory(old_mem, byte_adr_idx);
1464       merge_index = 3; // Account for Latin1 case
1465     }
1466     getChars(kit, arg, dst_array, T_CHAR, end, final_merge, final_mem, merge_index);
1467   }
1468 
1469   // Final merge point for Latin1 and UTF16 case
1470   kit.set_control(final_merge);
1471   kit.set_memory(final_mem, byte_adr_idx);
1472 
1473   C->record_for_igvn(final_merge);
1474   C->record_for_igvn(final_mem);
1475   return end;
1476 }
1477 
1478 // Copy 'count' bytes/chars from src_array to dst_array starting at index start
1479 void PhaseStringOpts::arraycopy(GraphKit& kit, IdealKit& ideal, Node* src_array, Node* dst_array, BasicType elembt, Node* start, Node* count) {
1480   assert(elembt == T_BYTE || elembt == T_CHAR, "Invalid type for arraycopy");
1481 
1482   if (elembt == T_CHAR) {
1483     // Get number of chars
1484     count = __ RShiftI(count, __ intcon(1));
1485   }
1486 
1487   Node* extra = nullptr;
1488 #ifdef _LP64
1489   count = __ ConvI2L(count);
1490   extra = C->top();
1491 #endif
1492 
1493   Node* src_ptr = __ array_element_address(src_array, __ intcon(0), T_BYTE);
1494   Node* dst_ptr = __ array_element_address(dst_array, start, T_BYTE);
1495   // Check if src array address is aligned to HeapWordSize
1496   bool aligned = (arrayOopDesc::base_offset_in_bytes(T_BYTE) % HeapWordSize == 0);
1497   // If true, then check if dst array address is aligned to HeapWordSize
1498   if (aligned) {
1499     const TypeInt* tdst = __ gvn().type(start)->is_int();
1500     aligned = tdst->is_con() && ((arrayOopDesc::base_offset_in_bytes(T_BYTE) +
1501                                   tdst->get_con() * type2aelembytes(T_BYTE)) % HeapWordSize == 0);
1502   }
1503   // Figure out which arraycopy runtime method to call (disjoint, uninitialized).
1504   const char* copyfunc_name = "arraycopy";
1505   address     copyfunc_addr = StubRoutines::select_arraycopy_function(elembt, aligned, true, copyfunc_name, true);
1506   ideal.make_leaf_call_no_fp(OptoRuntime::fast_arraycopy_Type(), copyfunc_addr, copyfunc_name,
1507                              TypeAryPtr::BYTES, src_ptr, dst_ptr, count, extra);
1508 }
1509 
1510 #undef __
1511 #define __ ideal.
1512 
1513 // Copy contents of a Latin1 encoded string from src_array to dst_array
1514 void PhaseStringOpts::copy_latin1_string(GraphKit& kit, IdealKit& ideal, Node* src_array, IdealVariable& count,
1515                                          Node* dst_array, Node* dst_coder, Node* start) {
1516   bool dcon = dst_coder->is_Con();
1517   bool dbyte = dcon ? (dst_coder->get_int() == java_lang_String::CODER_LATIN1) : false;
1518 
1519   if (!dcon) {
1520     __ if_then(dst_coder, BoolTest::eq, __ ConI(java_lang_String::CODER_LATIN1));
1521   }
1522   if (!dcon || dbyte) {
1523     // Destination is Latin1. Simply emit a byte arraycopy.
1524     arraycopy(kit, ideal, src_array, dst_array, T_BYTE, start, __ value(count));
1525   }
1526   if (!dcon) {
1527     __ else_();
1528   }
1529   if (!dcon || !dbyte) {
1530     // Destination is UTF16. Inflate src_array into dst_array.
1531     kit.sync_kit(ideal);
1532     if (Matcher::match_rule_supported(Op_StrInflatedCopy)) {
1533       // Use fast intrinsic
1534       Node* src = kit.array_element_address(src_array, kit.intcon(0), T_BYTE);
1535       Node* dst = kit.array_element_address(dst_array, start, T_BYTE);
1536       kit.inflate_string(src, dst, TypeAryPtr::BYTES, __ value(count));
1537     } else {
1538       // No intrinsic available, use slow method
1539       kit.inflate_string_slow(src_array, dst_array, start, __ value(count));
1540     }
1541     ideal.sync_kit(&kit);
1542     // Multiply count by two since we now need two bytes per char
1543     __ set(count, __ LShiftI(__ value(count), __ ConI(1)));
1544   }
1545   if (!dcon) {
1546     __ end_if();
1547   }
1548 }
1549 
1550 // Read two bytes from index and index+1 and convert them to a char
1551 static jchar readChar(ciTypeArray* array, int index) {
1552   int shift_high, shift_low;
1553 #ifdef VM_LITTLE_ENDIAN
1554     shift_high = 0;
1555     shift_low = 8;
1556 #else
1557     shift_high = 8;
1558     shift_low = 0;
1559 #endif
1560 
1561   jchar b1 = ((jchar) array->byte_at(index)) & 0xff;
1562   jchar b2 = ((jchar) array->byte_at(index+1)) & 0xff;
1563   return (b1 << shift_high) | (b2 << shift_low);
1564 }
1565 
1566 // Copy contents of constant src_array to dst_array by emitting individual stores
1567 void PhaseStringOpts::copy_constant_string(GraphKit& kit, IdealKit& ideal, ciTypeArray* src_array, IdealVariable& count,
1568                                            bool src_is_byte, Node* dst_array, Node* dst_coder, Node* start) {
1569   bool dcon = dst_coder->is_Con();
1570   bool dbyte = dcon ? (dst_coder->get_int() == java_lang_String::CODER_LATIN1) : false;
1571   int length = src_array->length();
1572 
1573   if (!dcon) {
1574     __ if_then(dst_coder, BoolTest::eq, __ ConI(java_lang_String::CODER_LATIN1));
1575   }
1576   if (!dcon || dbyte) {
1577     // Destination is Latin1. Copy each byte of src_array into dst_array.
1578     Node* index = start;
1579     for (int i = 0; i < length; i++) {
1580       Node* adr = kit.array_element_address(dst_array, index, T_BYTE);
1581       Node* val = __ ConI(src_array->byte_at(i));
1582       __ store(__ ctrl(), adr, val, T_BYTE, byte_adr_idx, MemNode::unordered);
1583       index = __ AddI(index, __ ConI(1));
1584     }
1585   }
1586   if (!dcon) {
1587     __ else_();
1588   }
1589   if (!dcon || !dbyte) {
1590     // Destination is UTF16. Copy each char of src_array into dst_array.
1591     Node* index = start;
1592     for (int i = 0; i < length; i++) {
1593       Node* adr = kit.array_element_address(dst_array, index, T_BYTE);
1594       jchar val;
1595       if (src_is_byte) {
1596         val = src_array->byte_at(i) & 0xff;
1597       } else {
1598         val = readChar(src_array, i++);
1599       }
1600       __ store(__ ctrl(), adr, __ ConI(val), T_CHAR, byte_adr_idx, MemNode::unordered, false /* require_atomic_access */,
1601                true /* mismatched */);
1602       index = __ AddI(index, __ ConI(2));
1603     }
1604     if (src_is_byte) {
1605       // Multiply count by two since we now need two bytes per char
1606       __ set(count, __ ConI(2 * length));
1607     }
1608   }
1609   if (!dcon) {
1610     __ end_if();
1611   }
1612 }
1613 
1614 // Compress copy contents of the byte/char String str into dst_array starting at index start.
1615 Node* PhaseStringOpts::copy_string(GraphKit& kit, Node* str, Node* dst_array, Node* dst_coder, Node* start) {
1616   Node* src_array = kit.load_String_value(str, true);
1617 
1618   IdealKit ideal(&kit, true, true);
1619   IdealVariable count(ideal); __ declarations_done();
1620 
1621   if (str->is_Con()) {
1622     // Constant source string
1623     ciTypeArray* src_array_type = get_constant_value(kit, str);
1624 
1625     // Check encoding of constant string
1626     bool src_is_byte = (get_constant_coder(kit, str) == java_lang_String::CODER_LATIN1);
1627 
1628     // For small constant strings just emit individual stores.
1629     // A length of 6 seems like a good space/speed tradeof.
1630     __ set(count, __ ConI(src_array_type->length()));
1631     int src_len = src_array_type->length() / (src_is_byte ? 1 : 2);
1632     if (src_len < unroll_string_copy_length) {
1633       // Small constant string
1634       copy_constant_string(kit, ideal, src_array_type, count, src_is_byte, dst_array, dst_coder, start);
1635     } else if (src_is_byte) {
1636       // Source is Latin1
1637       copy_latin1_string(kit, ideal, src_array, count, dst_array, dst_coder, start);
1638     } else {
1639       // Source is UTF16 (destination too). Simply emit a char arraycopy.
1640       arraycopy(kit, ideal, src_array, dst_array, T_CHAR, start, __ value(count));
1641     }
1642   } else {
1643     Node* size = kit.load_array_length(src_array);
1644     __ set(count, size);
1645     // Non-constant source string
1646     if (CompactStrings) {
1647       // Emit runtime check for coder
1648       Node* coder = kit.load_String_coder(str, true);
1649       __ if_then(coder, BoolTest::eq, __ ConI(java_lang_String::CODER_LATIN1)); {
1650         // Source is Latin1
1651         copy_latin1_string(kit, ideal, src_array, count, dst_array, dst_coder, start);
1652       } __ else_();
1653     }
1654     // Source is UTF16 (destination too). Simply emit a char arraycopy.
1655     arraycopy(kit, ideal, src_array, dst_array, T_CHAR, start, __ value(count));
1656 
1657     if (CompactStrings) {
1658       __ end_if();
1659     }
1660   }
1661 
1662   // Finally sync IdealKit and GraphKit.
1663   kit.sync_kit(ideal);
1664   return __ AddI(start, __ value(count));
1665 }
1666 
1667 // Compress copy the char into dst_array at index start.
1668 Node* PhaseStringOpts::copy_char(GraphKit& kit, Node* val, Node* dst_array, Node* dst_coder, Node* start) {
1669   bool dcon = (dst_coder != nullptr) && dst_coder->is_Con();
1670   bool dbyte = dcon ? (dst_coder->get_int() == java_lang_String::CODER_LATIN1) : false;
1671 
1672   IdealKit ideal(&kit, true, true);
1673   IdealVariable end(ideal); __ declarations_done();
1674   Node* adr = kit.array_element_address(dst_array, start, T_BYTE);
1675   if (!dcon){
1676     __ if_then(dst_coder, BoolTest::eq, __ ConI(java_lang_String::CODER_LATIN1));
1677   }
1678   if (!dcon || dbyte) {
1679     // Destination is Latin1. Store a byte.
1680     __ store(__ ctrl(), adr, val, T_BYTE, byte_adr_idx, MemNode::unordered);
1681     __ set(end, __ AddI(start, __ ConI(1)));
1682   }
1683   if (!dcon) {
1684     __ else_();
1685   }
1686   if (!dcon || !dbyte) {
1687     // Destination is UTF16. Store a char.
1688     __ store(__ ctrl(), adr, val, T_CHAR, byte_adr_idx, MemNode::unordered, false /* require_atomic_access */,
1689              true /* mismatched */);
1690     __ set(end, __ AddI(start, __ ConI(2)));
1691   }
1692   if (!dcon) {
1693     __ end_if();
1694   }
1695   // Finally sync IdealKit and GraphKit.
1696   kit.sync_kit(ideal);
1697   return __ value(end);
1698 }
1699 
1700 #undef __
1701 #define __ kit.
1702 
1703 // Allocate a byte array of specified length.
1704 Node* PhaseStringOpts::allocate_byte_array(GraphKit& kit, IdealKit* ideal, Node* length) {
1705   if (ideal != nullptr) {
1706     // Sync IdealKit and graphKit.
1707     kit.sync_kit(*ideal);
1708   }
1709   Node* byte_array = nullptr;
1710   {
1711     PreserveReexecuteState preexecs(&kit);
1712     // The original jvms is for an allocation of either a String or
1713     // StringBuffer so no stack adjustment is necessary for proper
1714     // reexecution.  If we deoptimize in the slow path the bytecode
1715     // will be reexecuted and the char[] allocation will be thrown away.
1716     kit.jvms()->set_should_reexecute(true);
1717     byte_array = kit.new_array(__ makecon(TypeKlassPtr::make(ciTypeArrayKlass::make(T_BYTE))),
1718                                length, 1);
1719   }
1720 
1721   // Mark the allocation so that zeroing is skipped since the code
1722   // below will overwrite the entire array
1723   AllocateArrayNode* byte_alloc = AllocateArrayNode::Ideal_array_allocation(byte_array);
1724   byte_alloc->maybe_set_complete(_gvn);
1725 
1726   if (ideal != nullptr) {
1727     // Sync IdealKit and graphKit.
1728     ideal->sync_kit(&kit);
1729   }
1730   return byte_array;
1731 }
1732 
1733 jbyte PhaseStringOpts::get_constant_coder(GraphKit& kit, Node* str) {
1734   assert(str->is_Con(), "String must be constant");
1735   const TypeOopPtr* str_type = kit.gvn().type(str)->isa_oopptr();
1736   ciInstance* str_instance = str_type->const_oop()->as_instance();
1737   jbyte coder = str_instance->field_value_by_offset(java_lang_String::coder_offset()).as_byte();
1738   assert(CompactStrings || (coder == java_lang_String::CODER_UTF16), "Strings must be UTF16 encoded");
1739   return coder;
1740 }
1741 
1742 int PhaseStringOpts::get_constant_length(GraphKit& kit, Node* str) {
1743   assert(str->is_Con(), "String must be constant");
1744   return get_constant_value(kit, str)->length();
1745 }
1746 
1747 ciTypeArray* PhaseStringOpts::get_constant_value(GraphKit& kit, Node* str) {
1748   assert(str->is_Con(), "String must be constant");
1749   const TypeOopPtr* str_type = kit.gvn().type(str)->isa_oopptr();
1750   ciInstance* str_instance = str_type->const_oop()->as_instance();
1751   ciObject* src_array = str_instance->field_value_by_offset(java_lang_String::value_offset()).as_object();
1752   return src_array->as_type_array();
1753 }
1754 
1755 void PhaseStringOpts::replace_string_concat(StringConcat* sc) {
1756   // Log a little info about the transformation
1757   sc->maybe_log_transform();
1758 
1759   // pull the JVMState of the allocation into a SafePointNode to serve as
1760   // as a shim for the insertion of the new code.
1761   JVMState* jvms     = sc->begin()->jvms()->clone_shallow(C);
1762   uint size = sc->begin()->req();
1763   SafePointNode* map = new SafePointNode(size, jvms);
1764 
1765   // copy the control and memory state from the final call into our
1766   // new starting state.  This allows any preceding tests to feed
1767   // into the new section of code.
1768   for (uint i1 = 0; i1 < TypeFunc::Parms; i1++) {
1769     map->init_req(i1, sc->end()->in(i1));
1770   }
1771   // blow away old allocation arguments
1772   for (uint i1 = TypeFunc::Parms; i1 < jvms->debug_start(); i1++) {
1773     map->init_req(i1, C->top());
1774   }
1775   // Copy the rest of the inputs for the JVMState
1776   for (uint i1 = jvms->debug_start(); i1 < sc->begin()->req(); i1++) {
1777     map->init_req(i1, sc->begin()->in(i1));
1778   }
1779   // Make sure the memory state is a MergeMem for parsing.
1780   if (!map->in(TypeFunc::Memory)->is_MergeMem()) {
1781     map->set_req(TypeFunc::Memory, MergeMemNode::make(map->in(TypeFunc::Memory)));
1782   }
1783 
1784   jvms->set_map(map);
1785   map->ensure_stack(jvms, jvms->method()->max_stack());
1786 
1787   // disconnect all the old StringBuilder calls from the graph
1788   sc->eliminate_unneeded_control();
1789 
1790   // At this point all the old work has been completely removed from
1791   // the graph and the saved JVMState exists at the point where the
1792   // final toString call used to be.
1793   GraphKit kit(jvms);
1794 
1795   // There may be uncommon traps which are still using the
1796   // intermediate states and these need to be rewritten to point at
1797   // the JVMState at the beginning of the transformation.
1798   sc->convert_uncommon_traps(kit, jvms);
1799 
1800   // Now insert the logic to compute the size of the string followed
1801   // by all the logic to construct array and resulting string.
1802 
1803   Node* null_string = __ makecon(TypeInstPtr::make(C->env()->the_null_string()));
1804 
1805   // Create a region for the overflow checks to merge into.
1806   int args = MAX2(sc->num_arguments(), 1);
1807   RegionNode* overflow = new RegionNode(args);
1808   kit.gvn().set_type(overflow, Type::CONTROL);
1809 
1810   // Create a hook node to hold onto the individual sizes since they
1811   // are need for the copying phase.
1812   Node* string_sizes = new Node(args);
1813 
1814   Node* coder = __ intcon(0);
1815   Node* length = __ intcon(0);
1816   // If at least one argument is UTF16 encoded, we can fix the encoding.
1817   bool coder_fixed = false;
1818 
1819   if (!CompactStrings) {
1820     // Fix encoding of result string to UTF16
1821     coder_fixed = true;
1822     coder = __ intcon(java_lang_String::CODER_UTF16);
1823   }
1824 
1825   for (int argi = 0; argi < sc->num_arguments(); argi++) {
1826     Node* arg = sc->argument(argi);
1827     switch (sc->mode(argi)) {
1828       case StringConcat::NegativeIntCheckMode: {
1829         // Initial capacity argument might be negative in which case StringBuilder(int) throws
1830         // a NegativeArraySizeException. Insert a runtime check with an uncommon trap.
1831         const TypeInt* type = kit.gvn().type(arg)->is_int();
1832         assert(type->_hi >= 0 && type->_lo < 0, "no runtime int check needed");
1833         Node* p = __ Bool(__ CmpI(arg, kit.intcon(0)), BoolTest::ge);
1834         IfNode* iff = kit.create_and_map_if(kit.control(), p, PROB_MIN, COUNT_UNKNOWN);
1835         {
1836           // Negative int -> uncommon trap.
1837           PreserveJVMState pjvms(&kit);
1838           kit.set_control(__ IfFalse(iff));
1839           kit.uncommon_trap(Deoptimization::Reason_intrinsic,
1840                             Deoptimization::Action_maybe_recompile);
1841         }
1842         kit.set_control(__ IfTrue(iff));
1843         break;
1844       }
1845       case StringConcat::IntMode: {
1846         Node* string_size = int_stringSize(kit, arg);
1847 
1848         // accumulate total
1849         length = __ AddI(length, string_size);
1850 
1851         // Cache this value for the use by int_toString
1852         string_sizes->init_req(argi, string_size);
1853         break;
1854       }
1855       case StringConcat::StringNullCheckMode: {
1856         const Type* type = kit.gvn().type(arg);
1857         assert(type != TypePtr::NULL_PTR, "missing check");
1858         if (!type->higher_equal(TypeInstPtr::NOTNULL)) {
1859           // Null check with uncommon trap since
1860           // StringBuilder(null) throws exception.
1861           // Use special uncommon trap instead of
1862           // calling normal do_null_check().
1863           Node* p = __ Bool(__ CmpP(arg, kit.null()), BoolTest::ne);
1864           IfNode* iff = kit.create_and_map_if(kit.control(), p, PROB_MIN, COUNT_UNKNOWN);
1865           overflow->add_req(__ IfFalse(iff));
1866           Node* notnull = __ IfTrue(iff);
1867           kit.set_control(notnull); // set control for the cast_not_null
1868           arg = kit.cast_not_null(arg, false);
1869           sc->set_argument(argi, arg);
1870         }
1871         assert(kit.gvn().type(arg)->higher_equal(TypeInstPtr::NOTNULL), "sanity");
1872         // Fallthrough to add string length.
1873       }
1874       case StringConcat::StringMode: {
1875         const Type* type = kit.gvn().type(arg);
1876         Node* count = nullptr;
1877         Node* arg_coder = nullptr;
1878         if (type == TypePtr::NULL_PTR) {
1879           // replace the argument with the null checked version
1880           arg = null_string;
1881           sc->set_argument(argi, arg);
1882           count = kit.load_String_length(arg, true);
1883           arg_coder = kit.load_String_coder(arg, true);
1884         } else if (!type->higher_equal(TypeInstPtr::NOTNULL)) {
1885           // s = s != null ? s : "null";
1886           // length = length + (s.count - s.offset);
1887           RegionNode *r = new RegionNode(3);
1888           kit.gvn().set_type(r, Type::CONTROL);
1889           Node *phi = new PhiNode(r, type);
1890           kit.gvn().set_type(phi, phi->bottom_type());
1891           Node* p = __ Bool(__ CmpP(arg, kit.null()), BoolTest::ne);
1892           IfNode* iff = kit.create_and_map_if(kit.control(), p, PROB_MIN, COUNT_UNKNOWN);
1893           Node* notnull = __ IfTrue(iff);
1894           Node* isnull =  __ IfFalse(iff);
1895           kit.set_control(notnull); // set control for the cast_not_null
1896           r->init_req(1, notnull);
1897           phi->init_req(1, kit.cast_not_null(arg, false));
1898           r->init_req(2, isnull);
1899           phi->init_req(2, null_string);
1900           kit.set_control(r);
1901           C->record_for_igvn(r);
1902           C->record_for_igvn(phi);
1903           // replace the argument with the null checked version
1904           arg = phi;
1905           sc->set_argument(argi, arg);
1906           count = kit.load_String_length(arg, true);
1907           arg_coder = kit.load_String_coder(arg, true);
1908         } else {
1909           // A corresponding nullcheck will be connected during IGVN MemNode::Ideal_common_DU_postCCP
1910           // kit.control might be a different test, that can be hoisted above the actual nullcheck
1911           // in case, that the control input is not null, Ideal_common_DU_postCCP will not look for a nullcheck.
1912           count = kit.load_String_length(arg, false);
1913           arg_coder = kit.load_String_coder(arg, false);
1914         }
1915         if (arg->is_Con()) {
1916           // Constant string. Get constant coder and length.
1917           jbyte const_coder = get_constant_coder(kit, arg);
1918           int const_length = get_constant_length(kit, arg);
1919           if (const_coder == java_lang_String::CODER_LATIN1) {
1920             // Can be latin1 encoded
1921             arg_coder = __ intcon(const_coder);
1922             count = __ intcon(const_length);
1923           } else {
1924             // Found UTF16 encoded string. Fix result array encoding to UTF16.
1925             coder_fixed = true;
1926             coder = __ intcon(const_coder);
1927             count = __ intcon(const_length / 2);
1928           }
1929         }
1930 
1931         if (!coder_fixed) {
1932           coder = __ OrI(coder, arg_coder);
1933         }
1934         length = __ AddI(length, count);
1935         string_sizes->init_req(argi, nullptr);
1936         break;
1937       }
1938       case StringConcat::CharMode: {
1939         // one character only
1940         const TypeInt* t = kit.gvn().type(arg)->is_int();
1941         if (!coder_fixed && t->is_con()) {
1942           // Constant char
1943           if (t->get_con() <= 255) {
1944             // Can be latin1 encoded
1945             coder = __ OrI(coder, __ intcon(java_lang_String::CODER_LATIN1));
1946           } else {
1947             // Must be UTF16 encoded. Fix result array encoding to UTF16.
1948             coder_fixed = true;
1949             coder = __ intcon(java_lang_String::CODER_UTF16);
1950           }
1951         } else if (!coder_fixed) {
1952           // Not constant
1953 #undef __
1954 #define __ ideal.
1955           IdealKit ideal(&kit, true, true);
1956           IdealVariable char_coder(ideal); __ declarations_done();
1957           // Check if character can be latin1 encoded
1958           __ if_then(arg, BoolTest::le, __ ConI(0xFF));
1959             __ set(char_coder, __ ConI(java_lang_String::CODER_LATIN1));
1960           __ else_();
1961             __ set(char_coder, __ ConI(java_lang_String::CODER_UTF16));
1962           __ end_if();
1963           kit.sync_kit(ideal);
1964           coder = __ OrI(coder, __ value(char_coder));
1965 #undef __
1966 #define __ kit.
1967         }
1968         length = __ AddI(length, __ intcon(1));
1969         break;
1970       }
1971       default:
1972         ShouldNotReachHere();
1973     }
1974     if (argi > 0) {
1975       // Check that the sum hasn't overflowed
1976       IfNode* iff = kit.create_and_map_if(kit.control(),
1977                                           __ Bool(__ CmpI(length, __ intcon(0)), BoolTest::lt),
1978                                           PROB_MIN, COUNT_UNKNOWN);
1979       kit.set_control(__ IfFalse(iff));
1980       overflow->set_req(argi, __ IfTrue(iff));
1981     }
1982   }
1983 
1984   {
1985     // Hook
1986     PreserveJVMState pjvms(&kit);
1987     kit.set_control(overflow);
1988     C->record_for_igvn(overflow);
1989     kit.uncommon_trap(Deoptimization::Reason_intrinsic,
1990                       Deoptimization::Action_make_not_entrant);
1991   }
1992 
1993   Node* result;
1994   if (!kit.stopped()) {
1995     assert(CompactStrings || (coder->is_Con() && coder->get_int() == java_lang_String::CODER_UTF16),
1996            "Result string must be UTF16 encoded if CompactStrings is disabled");
1997 
1998     Node* dst_array = nullptr;
1999     if (sc->num_arguments() == 1 &&
2000         (sc->mode(0) == StringConcat::StringMode ||
2001          sc->mode(0) == StringConcat::StringNullCheckMode)) {
2002       // Handle the case when there is only a single String argument.
2003       // In this case, we can just pull the value from the String itself.
2004       dst_array = kit.load_String_value(sc->argument(0), true);
2005     } else {
2006       // Allocate destination byte array according to coder
2007       dst_array = allocate_byte_array(kit, nullptr, __ LShiftI(length, coder));
2008 
2009       // Now copy the string representations into the final byte[]
2010       Node* start = __ intcon(0);
2011       for (int argi = 0; argi < sc->num_arguments(); argi++) {
2012         Node* arg = sc->argument(argi);
2013         switch (sc->mode(argi)) {
2014           case StringConcat::NegativeIntCheckMode:
2015             break; // Nothing to do, was only needed to add a runtime check earlier.
2016           case StringConcat::IntMode: {
2017             start = int_getChars(kit, arg, dst_array, coder, start, string_sizes->in(argi));
2018             break;
2019           }
2020           case StringConcat::StringNullCheckMode:
2021           case StringConcat::StringMode: {
2022             start = copy_string(kit, arg, dst_array, coder, start);
2023             break;
2024           }
2025           case StringConcat::CharMode: {
2026             start = copy_char(kit, arg, dst_array, coder, start);
2027           break;
2028           }
2029           default:
2030             ShouldNotReachHere();
2031         }
2032       }
2033     }
2034 
2035     {
2036       PreserveReexecuteState preexecs(&kit);
2037       // The original jvms is for an allocation of either a String or
2038       // StringBuffer so no stack adjustment is necessary for proper
2039       // reexecution.
2040       kit.jvms()->set_should_reexecute(true);
2041       result = kit.new_instance(__ makecon(TypeKlassPtr::make(C->env()->String_klass())));
2042     }
2043 
2044     // Initialize the string
2045     kit.store_String_value(result, dst_array);
2046     kit.store_String_coder(result, coder);
2047 
2048     // The value field is final. Emit a barrier here to ensure that the effect
2049     // of the initialization is committed to memory before any code publishes
2050     // a reference to the newly constructed object (see Parse::do_exits()).
2051     assert(AllocateNode::Ideal_allocation(result) != nullptr, "should be newly allocated");
2052     kit.insert_mem_bar(UseStoreStoreForCtor ? Op_MemBarStoreStore : Op_MemBarRelease, result);
2053   } else {
2054     result = C->top();
2055   }
2056   // hook up the outgoing control and result
2057   kit.replace_call(sc->end(), result);
2058 
2059   // Unhook any hook nodes
2060   string_sizes->disconnect_inputs(C);
2061   sc->cleanup();
2062 #ifndef PRODUCT
2063   AtomicAccess::inc(&_stropts_replaced);
2064 #endif
2065 }
2066 
2067 #ifndef PRODUCT
2068 uint PhaseStringOpts::_stropts_replaced = 0;
2069 uint PhaseStringOpts::_stropts_merged = 0;
2070 uint PhaseStringOpts::_stropts_total = 0;
2071 
2072 void PhaseStringOpts::print_statistics() {
2073   tty->print_cr("StringConcat: %4d/%4d/%4d(replaced/merged/total)", _stropts_replaced, _stropts_merged, _stropts_total);
2074 }
2075 #endif