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