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