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