Wed, 14 Oct 2020 17:44:48 +0800
Merge
1 /*
2 * Copyright (c) 1997, 2018, 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 /*
26 * This file has been modified by Loongson Technology in 2015. These
27 * modifications are Copyright (c) 2015 Loongson Technology, and are made
28 * available on the same license terms set forth above.
29 */
31 #include "precompiled.hpp"
32 #include "asm/macroAssembler.hpp"
33 #include "asm/macroAssembler.inline.hpp"
34 #include "ci/ciReplay.hpp"
35 #include "classfile/systemDictionary.hpp"
36 #include "code/exceptionHandlerTable.hpp"
37 #include "code/nmethod.hpp"
38 #include "compiler/compileLog.hpp"
39 #include "compiler/disassembler.hpp"
40 #include "compiler/oopMap.hpp"
41 #include "jfr/jfrEvents.hpp"
42 #include "opto/addnode.hpp"
43 #include "opto/block.hpp"
44 #include "opto/c2compiler.hpp"
45 #include "opto/callGenerator.hpp"
46 #include "opto/callnode.hpp"
47 #include "opto/cfgnode.hpp"
48 #include "opto/chaitin.hpp"
49 #include "opto/compile.hpp"
50 #include "opto/connode.hpp"
51 #include "opto/divnode.hpp"
52 #include "opto/escape.hpp"
53 #include "opto/idealGraphPrinter.hpp"
54 #include "opto/loopnode.hpp"
55 #include "opto/machnode.hpp"
56 #include "opto/macro.hpp"
57 #include "opto/matcher.hpp"
58 #include "opto/mathexactnode.hpp"
59 #include "opto/memnode.hpp"
60 #include "opto/mulnode.hpp"
61 #include "opto/node.hpp"
62 #include "opto/opcodes.hpp"
63 #include "opto/output.hpp"
64 #include "opto/parse.hpp"
65 #include "opto/phaseX.hpp"
66 #include "opto/rootnode.hpp"
67 #include "opto/runtime.hpp"
68 #include "opto/stringopts.hpp"
69 #include "opto/type.hpp"
70 #include "opto/vectornode.hpp"
71 #include "runtime/arguments.hpp"
72 #include "runtime/signature.hpp"
73 #include "runtime/stubRoutines.hpp"
74 #include "runtime/timer.hpp"
75 #include "utilities/copy.hpp"
76 #if defined AD_MD_HPP
77 # include AD_MD_HPP
78 #elif defined TARGET_ARCH_MODEL_x86_32
79 # include "adfiles/ad_x86_32.hpp"
80 #elif defined TARGET_ARCH_MODEL_x86_64
81 # include "adfiles/ad_x86_64.hpp"
82 #elif defined TARGET_ARCH_MODEL_sparc
83 # include "adfiles/ad_sparc.hpp"
84 #elif defined TARGET_ARCH_MODEL_zero
85 # include "adfiles/ad_zero.hpp"
86 #elif defined TARGET_ARCH_MODEL_ppc_64
87 # include "adfiles/ad_ppc_64.hpp"
88 #elif defined TARGET_ARCH_MODEL_mips_64
89 # include "adfiles/ad_mips_64.hpp"
90 #endif
92 // -------------------- Compile::mach_constant_base_node -----------------------
93 // Constant table base node singleton.
94 MachConstantBaseNode* Compile::mach_constant_base_node() {
95 if (_mach_constant_base_node == NULL) {
96 _mach_constant_base_node = new (C) MachConstantBaseNode();
97 _mach_constant_base_node->add_req(C->root());
98 }
99 return _mach_constant_base_node;
100 }
103 /// Support for intrinsics.
105 // Return the index at which m must be inserted (or already exists).
106 // The sort order is by the address of the ciMethod, with is_virtual as minor key.
107 int Compile::intrinsic_insertion_index(ciMethod* m, bool is_virtual) {
108 #ifdef ASSERT
109 for (int i = 1; i < _intrinsics->length(); i++) {
110 CallGenerator* cg1 = _intrinsics->at(i-1);
111 CallGenerator* cg2 = _intrinsics->at(i);
112 assert(cg1->method() != cg2->method()
113 ? cg1->method() < cg2->method()
114 : cg1->is_virtual() < cg2->is_virtual(),
115 "compiler intrinsics list must stay sorted");
116 }
117 #endif
118 // Binary search sorted list, in decreasing intervals [lo, hi].
119 int lo = 0, hi = _intrinsics->length()-1;
120 while (lo <= hi) {
121 int mid = (uint)(hi + lo) / 2;
122 ciMethod* mid_m = _intrinsics->at(mid)->method();
123 if (m < mid_m) {
124 hi = mid-1;
125 } else if (m > mid_m) {
126 lo = mid+1;
127 } else {
128 // look at minor sort key
129 bool mid_virt = _intrinsics->at(mid)->is_virtual();
130 if (is_virtual < mid_virt) {
131 hi = mid-1;
132 } else if (is_virtual > mid_virt) {
133 lo = mid+1;
134 } else {
135 return mid; // exact match
136 }
137 }
138 }
139 return lo; // inexact match
140 }
142 void Compile::register_intrinsic(CallGenerator* cg) {
143 if (_intrinsics == NULL) {
144 _intrinsics = new (comp_arena())GrowableArray<CallGenerator*>(comp_arena(), 60, 0, NULL);
145 }
146 // This code is stolen from ciObjectFactory::insert.
147 // Really, GrowableArray should have methods for
148 // insert_at, remove_at, and binary_search.
149 int len = _intrinsics->length();
150 int index = intrinsic_insertion_index(cg->method(), cg->is_virtual());
151 if (index == len) {
152 _intrinsics->append(cg);
153 } else {
154 #ifdef ASSERT
155 CallGenerator* oldcg = _intrinsics->at(index);
156 assert(oldcg->method() != cg->method() || oldcg->is_virtual() != cg->is_virtual(), "don't register twice");
157 #endif
158 _intrinsics->append(_intrinsics->at(len-1));
159 int pos;
160 for (pos = len-2; pos >= index; pos--) {
161 _intrinsics->at_put(pos+1,_intrinsics->at(pos));
162 }
163 _intrinsics->at_put(index, cg);
164 }
165 assert(find_intrinsic(cg->method(), cg->is_virtual()) == cg, "registration worked");
166 }
168 CallGenerator* Compile::find_intrinsic(ciMethod* m, bool is_virtual) {
169 assert(m->is_loaded(), "don't try this on unloaded methods");
170 if (_intrinsics != NULL) {
171 int index = intrinsic_insertion_index(m, is_virtual);
172 if (index < _intrinsics->length()
173 && _intrinsics->at(index)->method() == m
174 && _intrinsics->at(index)->is_virtual() == is_virtual) {
175 return _intrinsics->at(index);
176 }
177 }
178 // Lazily create intrinsics for intrinsic IDs well-known in the runtime.
179 if (m->intrinsic_id() != vmIntrinsics::_none &&
180 m->intrinsic_id() <= vmIntrinsics::LAST_COMPILER_INLINE) {
181 CallGenerator* cg = make_vm_intrinsic(m, is_virtual);
182 if (cg != NULL) {
183 // Save it for next time:
184 register_intrinsic(cg);
185 return cg;
186 } else {
187 gather_intrinsic_statistics(m->intrinsic_id(), is_virtual, _intrinsic_disabled);
188 }
189 }
190 return NULL;
191 }
193 // Compile:: register_library_intrinsics and make_vm_intrinsic are defined
194 // in library_call.cpp.
197 #ifndef PRODUCT
198 // statistics gathering...
200 juint Compile::_intrinsic_hist_count[vmIntrinsics::ID_LIMIT] = {0};
201 jubyte Compile::_intrinsic_hist_flags[vmIntrinsics::ID_LIMIT] = {0};
203 bool Compile::gather_intrinsic_statistics(vmIntrinsics::ID id, bool is_virtual, int flags) {
204 assert(id > vmIntrinsics::_none && id < vmIntrinsics::ID_LIMIT, "oob");
205 int oflags = _intrinsic_hist_flags[id];
206 assert(flags != 0, "what happened?");
207 if (is_virtual) {
208 flags |= _intrinsic_virtual;
209 }
210 bool changed = (flags != oflags);
211 if ((flags & _intrinsic_worked) != 0) {
212 juint count = (_intrinsic_hist_count[id] += 1);
213 if (count == 1) {
214 changed = true; // first time
215 }
216 // increment the overall count also:
217 _intrinsic_hist_count[vmIntrinsics::_none] += 1;
218 }
219 if (changed) {
220 if (((oflags ^ flags) & _intrinsic_virtual) != 0) {
221 // Something changed about the intrinsic's virtuality.
222 if ((flags & _intrinsic_virtual) != 0) {
223 // This is the first use of this intrinsic as a virtual call.
224 if (oflags != 0) {
225 // We already saw it as a non-virtual, so note both cases.
226 flags |= _intrinsic_both;
227 }
228 } else if ((oflags & _intrinsic_both) == 0) {
229 // This is the first use of this intrinsic as a non-virtual
230 flags |= _intrinsic_both;
231 }
232 }
233 _intrinsic_hist_flags[id] = (jubyte) (oflags | flags);
234 }
235 // update the overall flags also:
236 _intrinsic_hist_flags[vmIntrinsics::_none] |= (jubyte) flags;
237 return changed;
238 }
240 static char* format_flags(int flags, char* buf) {
241 buf[0] = 0;
242 if ((flags & Compile::_intrinsic_worked) != 0) strcat(buf, ",worked");
243 if ((flags & Compile::_intrinsic_failed) != 0) strcat(buf, ",failed");
244 if ((flags & Compile::_intrinsic_disabled) != 0) strcat(buf, ",disabled");
245 if ((flags & Compile::_intrinsic_virtual) != 0) strcat(buf, ",virtual");
246 if ((flags & Compile::_intrinsic_both) != 0) strcat(buf, ",nonvirtual");
247 if (buf[0] == 0) strcat(buf, ",");
248 assert(buf[0] == ',', "must be");
249 return &buf[1];
250 }
252 void Compile::print_intrinsic_statistics() {
253 char flagsbuf[100];
254 ttyLocker ttyl;
255 if (xtty != NULL) xtty->head("statistics type='intrinsic'");
256 tty->print_cr("Compiler intrinsic usage:");
257 juint total = _intrinsic_hist_count[vmIntrinsics::_none];
258 if (total == 0) total = 1; // avoid div0 in case of no successes
259 #define PRINT_STAT_LINE(name, c, f) \
260 tty->print_cr(" %4d (%4.1f%%) %s (%s)", (int)(c), ((c) * 100.0) / total, name, f);
261 for (int index = 1 + (int)vmIntrinsics::_none; index < (int)vmIntrinsics::ID_LIMIT; index++) {
262 vmIntrinsics::ID id = (vmIntrinsics::ID) index;
263 int flags = _intrinsic_hist_flags[id];
264 juint count = _intrinsic_hist_count[id];
265 if ((flags | count) != 0) {
266 PRINT_STAT_LINE(vmIntrinsics::name_at(id), count, format_flags(flags, flagsbuf));
267 }
268 }
269 PRINT_STAT_LINE("total", total, format_flags(_intrinsic_hist_flags[vmIntrinsics::_none], flagsbuf));
270 if (xtty != NULL) xtty->tail("statistics");
271 }
273 void Compile::print_statistics() {
274 { ttyLocker ttyl;
275 if (xtty != NULL) xtty->head("statistics type='opto'");
276 Parse::print_statistics();
277 PhaseCCP::print_statistics();
278 PhaseRegAlloc::print_statistics();
279 Scheduling::print_statistics();
280 PhasePeephole::print_statistics();
281 PhaseIdealLoop::print_statistics();
282 if (xtty != NULL) xtty->tail("statistics");
283 }
284 if (_intrinsic_hist_flags[vmIntrinsics::_none] != 0) {
285 // put this under its own <statistics> element.
286 print_intrinsic_statistics();
287 }
288 }
289 #endif //PRODUCT
291 // Support for bundling info
292 Bundle* Compile::node_bundling(const Node *n) {
293 assert(valid_bundle_info(n), "oob");
294 return &_node_bundling_base[n->_idx];
295 }
297 bool Compile::valid_bundle_info(const Node *n) {
298 return (_node_bundling_limit > n->_idx);
299 }
302 void Compile::gvn_replace_by(Node* n, Node* nn) {
303 for (DUIterator_Last imin, i = n->last_outs(imin); i >= imin; ) {
304 Node* use = n->last_out(i);
305 bool is_in_table = initial_gvn()->hash_delete(use);
306 uint uses_found = 0;
307 for (uint j = 0; j < use->len(); j++) {
308 if (use->in(j) == n) {
309 if (j < use->req())
310 use->set_req(j, nn);
311 else
312 use->set_prec(j, nn);
313 uses_found++;
314 }
315 }
316 if (is_in_table) {
317 // reinsert into table
318 initial_gvn()->hash_find_insert(use);
319 }
320 record_for_igvn(use);
321 i -= uses_found; // we deleted 1 or more copies of this edge
322 }
323 }
326 static inline bool not_a_node(const Node* n) {
327 if (n == NULL) return true;
328 if (((intptr_t)n & 1) != 0) return true; // uninitialized, etc.
329 if (*(address*)n == badAddress) return true; // kill by Node::destruct
330 return false;
331 }
333 // Identify all nodes that are reachable from below, useful.
334 // Use breadth-first pass that records state in a Unique_Node_List,
335 // recursive traversal is slower.
336 void Compile::identify_useful_nodes(Unique_Node_List &useful) {
337 int estimated_worklist_size = live_nodes();
338 useful.map( estimated_worklist_size, NULL ); // preallocate space
340 // Initialize worklist
341 if (root() != NULL) { useful.push(root()); }
342 // If 'top' is cached, declare it useful to preserve cached node
343 if( cached_top_node() ) { useful.push(cached_top_node()); }
345 // Push all useful nodes onto the list, breadthfirst
346 for( uint next = 0; next < useful.size(); ++next ) {
347 assert( next < unique(), "Unique useful nodes < total nodes");
348 Node *n = useful.at(next);
349 uint max = n->len();
350 for( uint i = 0; i < max; ++i ) {
351 Node *m = n->in(i);
352 if (not_a_node(m)) continue;
353 useful.push(m);
354 }
355 }
356 }
358 // Update dead_node_list with any missing dead nodes using useful
359 // list. Consider all non-useful nodes to be useless i.e., dead nodes.
360 void Compile::update_dead_node_list(Unique_Node_List &useful) {
361 uint max_idx = unique();
362 VectorSet& useful_node_set = useful.member_set();
364 for (uint node_idx = 0; node_idx < max_idx; node_idx++) {
365 // If node with index node_idx is not in useful set,
366 // mark it as dead in dead node list.
367 if (! useful_node_set.test(node_idx) ) {
368 record_dead_node(node_idx);
369 }
370 }
371 }
373 void Compile::remove_useless_late_inlines(GrowableArray<CallGenerator*>* inlines, Unique_Node_List &useful) {
374 int shift = 0;
375 for (int i = 0; i < inlines->length(); i++) {
376 CallGenerator* cg = inlines->at(i);
377 CallNode* call = cg->call_node();
378 if (shift > 0) {
379 inlines->at_put(i-shift, cg);
380 }
381 if (!useful.member(call)) {
382 shift++;
383 }
384 }
385 inlines->trunc_to(inlines->length()-shift);
386 }
388 // Disconnect all useless nodes by disconnecting those at the boundary.
389 void Compile::remove_useless_nodes(Unique_Node_List &useful) {
390 uint next = 0;
391 while (next < useful.size()) {
392 Node *n = useful.at(next++);
393 if (n->is_SafePoint()) {
394 // We're done with a parsing phase. Replaced nodes are not valid
395 // beyond that point.
396 n->as_SafePoint()->delete_replaced_nodes();
397 }
398 // Use raw traversal of out edges since this code removes out edges
399 int max = n->outcnt();
400 for (int j = 0; j < max; ++j) {
401 Node* child = n->raw_out(j);
402 if (! useful.member(child)) {
403 assert(!child->is_top() || child != top(),
404 "If top is cached in Compile object it is in useful list");
405 // Only need to remove this out-edge to the useless node
406 n->raw_del_out(j);
407 --j;
408 --max;
409 }
410 }
411 if (n->outcnt() == 1 && n->has_special_unique_user()) {
412 record_for_igvn(n->unique_out());
413 }
414 }
415 // Remove useless macro and predicate opaq nodes
416 for (int i = C->macro_count()-1; i >= 0; i--) {
417 Node* n = C->macro_node(i);
418 if (!useful.member(n)) {
419 remove_macro_node(n);
420 }
421 }
422 // Remove useless CastII nodes with range check dependency
423 for (int i = range_check_cast_count() - 1; i >= 0; i--) {
424 Node* cast = range_check_cast_node(i);
425 if (!useful.member(cast)) {
426 remove_range_check_cast(cast);
427 }
428 }
429 // Remove useless expensive node
430 for (int i = C->expensive_count()-1; i >= 0; i--) {
431 Node* n = C->expensive_node(i);
432 if (!useful.member(n)) {
433 remove_expensive_node(n);
434 }
435 }
436 // clean up the late inline lists
437 remove_useless_late_inlines(&_string_late_inlines, useful);
438 remove_useless_late_inlines(&_boxing_late_inlines, useful);
439 remove_useless_late_inlines(&_late_inlines, useful);
440 debug_only(verify_graph_edges(true/*check for no_dead_code*/);)
441 }
443 //------------------------------frame_size_in_words-----------------------------
444 // frame_slots in units of words
445 int Compile::frame_size_in_words() const {
446 // shift is 0 in LP32 and 1 in LP64
447 const int shift = (LogBytesPerWord - LogBytesPerInt);
448 int words = _frame_slots >> shift;
449 assert( words << shift == _frame_slots, "frame size must be properly aligned in LP64" );
450 return words;
451 }
453 // To bang the stack of this compiled method we use the stack size
454 // that the interpreter would need in case of a deoptimization. This
455 // removes the need to bang the stack in the deoptimization blob which
456 // in turn simplifies stack overflow handling.
457 int Compile::bang_size_in_bytes() const {
458 return MAX2(_interpreter_frame_size, frame_size_in_bytes());
459 }
461 // ============================================================================
462 //------------------------------CompileWrapper---------------------------------
463 class CompileWrapper : public StackObj {
464 Compile *const _compile;
465 public:
466 CompileWrapper(Compile* compile);
468 ~CompileWrapper();
469 };
471 CompileWrapper::CompileWrapper(Compile* compile) : _compile(compile) {
472 // the Compile* pointer is stored in the current ciEnv:
473 ciEnv* env = compile->env();
474 assert(env == ciEnv::current(), "must already be a ciEnv active");
475 assert(env->compiler_data() == NULL, "compile already active?");
476 env->set_compiler_data(compile);
477 assert(compile == Compile::current(), "sanity");
479 compile->set_type_dict(NULL);
480 compile->set_type_hwm(NULL);
481 compile->set_type_last_size(0);
482 compile->set_last_tf(NULL, NULL);
483 compile->set_indexSet_arena(NULL);
484 compile->set_indexSet_free_block_list(NULL);
485 compile->init_type_arena();
486 Type::Initialize(compile);
487 _compile->set_scratch_buffer_blob(NULL);
488 _compile->begin_method();
489 }
490 CompileWrapper::~CompileWrapper() {
491 _compile->end_method();
492 if (_compile->scratch_buffer_blob() != NULL)
493 BufferBlob::free(_compile->scratch_buffer_blob());
494 _compile->env()->set_compiler_data(NULL);
495 }
498 //----------------------------print_compile_messages---------------------------
499 void Compile::print_compile_messages() {
500 #ifndef PRODUCT
501 // Check if recompiling
502 if (_subsume_loads == false && PrintOpto) {
503 // Recompiling without allowing machine instructions to subsume loads
504 tty->print_cr("*********************************************************");
505 tty->print_cr("** Bailout: Recompile without subsuming loads **");
506 tty->print_cr("*********************************************************");
507 }
508 if (_do_escape_analysis != DoEscapeAnalysis && PrintOpto) {
509 // Recompiling without escape analysis
510 tty->print_cr("*********************************************************");
511 tty->print_cr("** Bailout: Recompile without escape analysis **");
512 tty->print_cr("*********************************************************");
513 }
514 if (_eliminate_boxing != EliminateAutoBox && PrintOpto) {
515 // Recompiling without boxing elimination
516 tty->print_cr("*********************************************************");
517 tty->print_cr("** Bailout: Recompile without boxing elimination **");
518 tty->print_cr("*********************************************************");
519 }
520 if (env()->break_at_compile()) {
521 // Open the debugger when compiling this method.
522 tty->print("### Breaking when compiling: ");
523 method()->print_short_name();
524 tty->cr();
525 BREAKPOINT;
526 }
528 if( PrintOpto ) {
529 if (is_osr_compilation()) {
530 tty->print("[OSR]%3d", _compile_id);
531 } else {
532 tty->print("%3d", _compile_id);
533 }
534 }
535 #endif
536 }
539 //-----------------------init_scratch_buffer_blob------------------------------
540 // Construct a temporary BufferBlob and cache it for this compile.
541 void Compile::init_scratch_buffer_blob(int const_size) {
542 // If there is already a scratch buffer blob allocated and the
543 // constant section is big enough, use it. Otherwise free the
544 // current and allocate a new one.
545 BufferBlob* blob = scratch_buffer_blob();
546 if ((blob != NULL) && (const_size <= _scratch_const_size)) {
547 // Use the current blob.
548 } else {
549 if (blob != NULL) {
550 BufferBlob::free(blob);
551 }
553 ResourceMark rm;
554 _scratch_const_size = const_size;
555 int size = (MAX_inst_size + MAX_stubs_size + _scratch_const_size);
556 blob = BufferBlob::create("Compile::scratch_buffer", size);
557 // Record the buffer blob for next time.
558 set_scratch_buffer_blob(blob);
559 // Have we run out of code space?
560 if (scratch_buffer_blob() == NULL) {
561 // Let CompilerBroker disable further compilations.
562 record_failure("Not enough space for scratch buffer in CodeCache");
563 return;
564 }
565 }
567 // Initialize the relocation buffers
568 relocInfo* locs_buf = (relocInfo*) blob->content_end() - MAX_locs_size;
569 set_scratch_locs_memory(locs_buf);
570 }
573 //-----------------------scratch_emit_size-------------------------------------
574 // Helper function that computes size by emitting code
575 uint Compile::scratch_emit_size(const Node* n) {
576 // Start scratch_emit_size section.
577 set_in_scratch_emit_size(true);
579 // Emit into a trash buffer and count bytes emitted.
580 // This is a pretty expensive way to compute a size,
581 // but it works well enough if seldom used.
582 // All common fixed-size instructions are given a size
583 // method by the AD file.
584 // Note that the scratch buffer blob and locs memory are
585 // allocated at the beginning of the compile task, and
586 // may be shared by several calls to scratch_emit_size.
587 // The allocation of the scratch buffer blob is particularly
588 // expensive, since it has to grab the code cache lock.
589 BufferBlob* blob = this->scratch_buffer_blob();
590 assert(blob != NULL, "Initialize BufferBlob at start");
591 assert(blob->size() > MAX_inst_size, "sanity");
592 relocInfo* locs_buf = scratch_locs_memory();
593 address blob_begin = blob->content_begin();
594 address blob_end = (address)locs_buf;
595 assert(blob->content_contains(blob_end), "sanity");
596 CodeBuffer buf(blob_begin, blob_end - blob_begin);
597 buf.initialize_consts_size(_scratch_const_size);
598 buf.initialize_stubs_size(MAX_stubs_size);
599 assert(locs_buf != NULL, "sanity");
600 int lsize = MAX_locs_size / 3;
601 buf.consts()->initialize_shared_locs(&locs_buf[lsize * 0], lsize);
602 buf.insts()->initialize_shared_locs( &locs_buf[lsize * 1], lsize);
603 buf.stubs()->initialize_shared_locs( &locs_buf[lsize * 2], lsize);
605 // Do the emission.
607 Label fakeL; // Fake label for branch instructions.
608 Label* saveL = NULL;
609 uint save_bnum = 0;
610 bool is_branch = n->is_MachBranch();
611 if (is_branch) {
612 MacroAssembler masm(&buf);
613 masm.bind(fakeL);
614 n->as_MachBranch()->save_label(&saveL, &save_bnum);
615 n->as_MachBranch()->label_set(&fakeL, 0);
616 }
617 n->emit(buf, this->regalloc());
619 // Emitting into the scratch buffer should not fail
620 assert (!failing(), err_msg_res("Must not have pending failure. Reason is: %s", failure_reason()));
622 if (is_branch) // Restore label.
623 n->as_MachBranch()->label_set(saveL, save_bnum);
625 // End scratch_emit_size section.
626 set_in_scratch_emit_size(false);
628 return buf.insts_size();
629 }
632 // ============================================================================
633 //------------------------------Compile standard-------------------------------
634 debug_only( int Compile::_debug_idx = 100000; )
636 // Compile a method. entry_bci is -1 for normal compilations and indicates
637 // the continuation bci for on stack replacement.
640 Compile::Compile( ciEnv* ci_env, C2Compiler* compiler, ciMethod* target, int osr_bci,
641 bool subsume_loads, bool do_escape_analysis, bool eliminate_boxing )
642 : Phase(Compiler),
643 _env(ci_env),
644 _log(ci_env->log()),
645 _compile_id(ci_env->compile_id()),
646 _save_argument_registers(false),
647 _stub_name(NULL),
648 _stub_function(NULL),
649 _stub_entry_point(NULL),
650 _method(target),
651 _entry_bci(osr_bci),
652 _initial_gvn(NULL),
653 _for_igvn(NULL),
654 _warm_calls(NULL),
655 _subsume_loads(subsume_loads),
656 _do_escape_analysis(do_escape_analysis),
657 _eliminate_boxing(eliminate_boxing),
658 _failure_reason(NULL),
659 _code_buffer("Compile::Fill_buffer"),
660 _orig_pc_slot(0),
661 _orig_pc_slot_offset_in_bytes(0),
662 _has_method_handle_invokes(false),
663 _mach_constant_base_node(NULL),
664 _node_bundling_limit(0),
665 _node_bundling_base(NULL),
666 _java_calls(0),
667 _inner_loops(0),
668 _scratch_const_size(-1),
669 _in_scratch_emit_size(false),
670 _dead_node_list(comp_arena()),
671 _dead_node_count(0),
672 #ifndef PRODUCT
673 _trace_opto_output(TraceOptoOutput || method()->has_option("TraceOptoOutput")),
674 _in_dump_cnt(0),
675 _printer(IdealGraphPrinter::printer()),
676 #endif
677 _congraph(NULL),
678 _comp_arena(mtCompiler),
679 _node_arena(mtCompiler),
680 _old_arena(mtCompiler),
681 _Compile_types(mtCompiler),
682 _replay_inline_data(NULL),
683 _late_inlines(comp_arena(), 2, 0, NULL),
684 _string_late_inlines(comp_arena(), 2, 0, NULL),
685 _boxing_late_inlines(comp_arena(), 2, 0, NULL),
686 _late_inlines_pos(0),
687 _number_of_mh_late_inlines(0),
688 _inlining_progress(false),
689 _inlining_incrementally(false),
690 _print_inlining_list(NULL),
691 _print_inlining_idx(0),
692 _interpreter_frame_size(0),
693 _max_node_limit(MaxNodeLimit) {
694 C = this;
696 CompileWrapper cw(this);
697 #ifndef PRODUCT
698 if (TimeCompiler2) {
699 tty->print(" ");
700 target->holder()->name()->print();
701 tty->print(".");
702 target->print_short_name();
703 tty->print(" ");
704 }
705 TraceTime t1("Total compilation time", &_t_totalCompilation, TimeCompiler, TimeCompiler2);
706 TraceTime t2(NULL, &_t_methodCompilation, TimeCompiler, false);
707 bool print_opto_assembly = PrintOptoAssembly || _method->has_option("PrintOptoAssembly");
708 if (!print_opto_assembly) {
709 bool print_assembly = (PrintAssembly || _method->should_print_assembly());
710 if (print_assembly && !Disassembler::can_decode()) {
711 tty->print_cr("PrintAssembly request changed to PrintOptoAssembly");
712 print_opto_assembly = true;
713 }
714 }
715 set_print_assembly(print_opto_assembly);
716 set_parsed_irreducible_loop(false);
718 if (method()->has_option("ReplayInline")) {
719 _replay_inline_data = ciReplay::load_inline_data(method(), entry_bci(), ci_env->comp_level());
720 }
721 #endif
722 set_print_inlining(PrintInlining || method()->has_option("PrintInlining") NOT_PRODUCT( || PrintOptoInlining));
723 set_print_intrinsics(PrintIntrinsics || method()->has_option("PrintIntrinsics"));
724 set_has_irreducible_loop(true); // conservative until build_loop_tree() reset it
726 if (ProfileTraps RTM_OPT_ONLY( || UseRTMLocking )) {
727 // Make sure the method being compiled gets its own MDO,
728 // so we can at least track the decompile_count().
729 // Need MDO to record RTM code generation state.
730 method()->ensure_method_data();
731 }
733 Init(::AliasLevel);
736 print_compile_messages();
738 _ilt = InlineTree::build_inline_tree_root();
740 // Even if NO memory addresses are used, MergeMem nodes must have at least 1 slice
741 assert(num_alias_types() >= AliasIdxRaw, "");
743 #define MINIMUM_NODE_HASH 1023
744 // Node list that Iterative GVN will start with
745 Unique_Node_List for_igvn(comp_arena());
746 set_for_igvn(&for_igvn);
748 // GVN that will be run immediately on new nodes
749 uint estimated_size = method()->code_size()*4+64;
750 estimated_size = (estimated_size < MINIMUM_NODE_HASH ? MINIMUM_NODE_HASH : estimated_size);
751 PhaseGVN gvn(node_arena(), estimated_size);
752 set_initial_gvn(&gvn);
754 if (print_inlining() || print_intrinsics()) {
755 _print_inlining_list = new (comp_arena())GrowableArray<PrintInliningBuffer>(comp_arena(), 1, 1, PrintInliningBuffer());
756 }
757 { // Scope for timing the parser
758 TracePhase t3("parse", &_t_parser, true);
760 // Put top into the hash table ASAP.
761 initial_gvn()->transform_no_reclaim(top());
763 // Set up tf(), start(), and find a CallGenerator.
764 CallGenerator* cg = NULL;
765 if (is_osr_compilation()) {
766 const TypeTuple *domain = StartOSRNode::osr_domain();
767 const TypeTuple *range = TypeTuple::make_range(method()->signature());
768 init_tf(TypeFunc::make(domain, range));
769 StartNode* s = new (this) StartOSRNode(root(), domain);
770 initial_gvn()->set_type_bottom(s);
771 init_start(s);
772 cg = CallGenerator::for_osr(method(), entry_bci());
773 } else {
774 // Normal case.
775 init_tf(TypeFunc::make(method()));
776 StartNode* s = new (this) StartNode(root(), tf()->domain());
777 initial_gvn()->set_type_bottom(s);
778 init_start(s);
779 if (method()->intrinsic_id() == vmIntrinsics::_Reference_get && UseG1GC) {
780 // With java.lang.ref.reference.get() we must go through the
781 // intrinsic when G1 is enabled - even when get() is the root
782 // method of the compile - so that, if necessary, the value in
783 // the referent field of the reference object gets recorded by
784 // the pre-barrier code.
785 // Specifically, if G1 is enabled, the value in the referent
786 // field is recorded by the G1 SATB pre barrier. This will
787 // result in the referent being marked live and the reference
788 // object removed from the list of discovered references during
789 // reference processing.
790 cg = find_intrinsic(method(), false);
791 }
792 if (cg == NULL) {
793 float past_uses = method()->interpreter_invocation_count();
794 float expected_uses = past_uses;
795 cg = CallGenerator::for_inline(method(), expected_uses);
796 }
797 }
798 if (failing()) return;
799 if (cg == NULL) {
800 record_method_not_compilable_all_tiers("cannot parse method");
801 return;
802 }
803 JVMState* jvms = build_start_state(start(), tf());
804 if ((jvms = cg->generate(jvms)) == NULL) {
805 if (!failure_reason_is(C2Compiler::retry_class_loading_during_parsing())) {
806 record_method_not_compilable("method parse failed");
807 }
808 return;
809 }
810 GraphKit kit(jvms);
812 if (!kit.stopped()) {
813 // Accept return values, and transfer control we know not where.
814 // This is done by a special, unique ReturnNode bound to root.
815 return_values(kit.jvms());
816 }
818 if (kit.has_exceptions()) {
819 // Any exceptions that escape from this call must be rethrown
820 // to whatever caller is dynamically above us on the stack.
821 // This is done by a special, unique RethrowNode bound to root.
822 rethrow_exceptions(kit.transfer_exceptions_into_jvms());
823 }
825 assert(IncrementalInline || (_late_inlines.length() == 0 && !has_mh_late_inlines()), "incremental inlining is off");
827 if (_late_inlines.length() == 0 && !has_mh_late_inlines() && !failing() && has_stringbuilder()) {
828 inline_string_calls(true);
829 }
831 if (failing()) return;
833 print_method(PHASE_BEFORE_REMOVEUSELESS, 3);
835 // Remove clutter produced by parsing.
836 if (!failing()) {
837 ResourceMark rm;
838 PhaseRemoveUseless pru(initial_gvn(), &for_igvn);
839 }
840 }
842 // Note: Large methods are capped off in do_one_bytecode().
843 if (failing()) return;
845 // After parsing, node notes are no longer automagic.
846 // They must be propagated by register_new_node_with_optimizer(),
847 // clone(), or the like.
848 set_default_node_notes(NULL);
850 for (;;) {
851 int successes = Inline_Warm();
852 if (failing()) return;
853 if (successes == 0) break;
854 }
856 // Drain the list.
857 Finish_Warm();
858 #ifndef PRODUCT
859 if (_printer) {
860 _printer->print_inlining(this);
861 }
862 #endif
864 if (failing()) return;
865 NOT_PRODUCT( verify_graph_edges(); )
867 // Now optimize
868 Optimize();
869 if (failing()) return;
870 NOT_PRODUCT( verify_graph_edges(); )
872 #ifndef PRODUCT
873 if (PrintIdeal) {
874 ttyLocker ttyl; // keep the following output all in one block
875 // This output goes directly to the tty, not the compiler log.
876 // To enable tools to match it up with the compilation activity,
877 // be sure to tag this tty output with the compile ID.
878 if (xtty != NULL) {
879 xtty->head("ideal compile_id='%d'%s", compile_id(),
880 is_osr_compilation() ? " compile_kind='osr'" :
881 "");
882 }
883 root()->dump(9999);
884 if (xtty != NULL) {
885 xtty->tail("ideal");
886 }
887 }
888 #endif
890 NOT_PRODUCT( verify_barriers(); )
892 // Dump compilation data to replay it.
893 if (method()->has_option("DumpReplay")) {
894 env()->dump_replay_data(_compile_id);
895 }
896 if (method()->has_option("DumpInline") && (ilt() != NULL)) {
897 env()->dump_inline_data(_compile_id);
898 }
900 // Now that we know the size of all the monitors we can add a fixed slot
901 // for the original deopt pc.
903 _orig_pc_slot = fixed_slots();
904 int next_slot = _orig_pc_slot + (sizeof(address) / VMRegImpl::stack_slot_size);
905 set_fixed_slots(next_slot);
907 // Compute when to use implicit null checks. Used by matching trap based
908 // nodes and NullCheck optimization.
909 set_allowed_deopt_reasons();
911 // Now generate code
912 Code_Gen();
913 if (failing()) return;
915 // Check if we want to skip execution of all compiled code.
916 {
917 #ifndef PRODUCT
918 if (OptoNoExecute) {
919 record_method_not_compilable("+OptoNoExecute"); // Flag as failed
920 return;
921 }
922 TracePhase t2("install_code", &_t_registerMethod, TimeCompiler);
923 #endif
925 if (is_osr_compilation()) {
926 _code_offsets.set_value(CodeOffsets::Verified_Entry, 0);
927 _code_offsets.set_value(CodeOffsets::OSR_Entry, _first_block_size);
928 } else {
929 _code_offsets.set_value(CodeOffsets::Verified_Entry, _first_block_size);
930 _code_offsets.set_value(CodeOffsets::OSR_Entry, 0);
931 }
933 env()->register_method(_method, _entry_bci,
934 &_code_offsets,
935 _orig_pc_slot_offset_in_bytes,
936 code_buffer(),
937 frame_size_in_words(), _oop_map_set,
938 &_handler_table, &_inc_table,
939 compiler,
940 env()->comp_level(),
941 has_unsafe_access(),
942 SharedRuntime::is_wide_vector(max_vector_size()),
943 rtm_state()
944 );
946 if (log() != NULL) // Print code cache state into compiler log
947 log()->code_cache_state();
948 }
949 }
951 //------------------------------Compile----------------------------------------
952 // Compile a runtime stub
953 Compile::Compile( ciEnv* ci_env,
954 TypeFunc_generator generator,
955 address stub_function,
956 const char *stub_name,
957 int is_fancy_jump,
958 bool pass_tls,
959 bool save_arg_registers,
960 bool return_pc )
961 : Phase(Compiler),
962 _env(ci_env),
963 _log(ci_env->log()),
964 _compile_id(0),
965 _save_argument_registers(save_arg_registers),
966 _method(NULL),
967 _stub_name(stub_name),
968 _stub_function(stub_function),
969 _stub_entry_point(NULL),
970 _entry_bci(InvocationEntryBci),
971 _initial_gvn(NULL),
972 _for_igvn(NULL),
973 _warm_calls(NULL),
974 _orig_pc_slot(0),
975 _orig_pc_slot_offset_in_bytes(0),
976 _subsume_loads(true),
977 _do_escape_analysis(false),
978 _eliminate_boxing(false),
979 _failure_reason(NULL),
980 _code_buffer("Compile::Fill_buffer"),
981 _has_method_handle_invokes(false),
982 _mach_constant_base_node(NULL),
983 _node_bundling_limit(0),
984 _node_bundling_base(NULL),
985 _java_calls(0),
986 _inner_loops(0),
987 #ifndef PRODUCT
988 _trace_opto_output(TraceOptoOutput),
989 _in_dump_cnt(0),
990 _printer(NULL),
991 #endif
992 _comp_arena(mtCompiler),
993 _node_arena(mtCompiler),
994 _old_arena(mtCompiler),
995 _Compile_types(mtCompiler),
996 _dead_node_list(comp_arena()),
997 _dead_node_count(0),
998 _congraph(NULL),
999 _replay_inline_data(NULL),
1000 _number_of_mh_late_inlines(0),
1001 _inlining_progress(false),
1002 _inlining_incrementally(false),
1003 _print_inlining_list(NULL),
1004 _print_inlining_idx(0),
1005 _allowed_reasons(0),
1006 _interpreter_frame_size(0),
1007 _max_node_limit(MaxNodeLimit) {
1008 C = this;
1010 #ifndef PRODUCT
1011 TraceTime t1(NULL, &_t_totalCompilation, TimeCompiler, false);
1012 TraceTime t2(NULL, &_t_stubCompilation, TimeCompiler, false);
1013 set_print_assembly(PrintFrameConverterAssembly);
1014 set_parsed_irreducible_loop(false);
1015 #endif
1016 set_has_irreducible_loop(false); // no loops
1018 CompileWrapper cw(this);
1019 Init(/*AliasLevel=*/ 0);
1020 init_tf((*generator)());
1022 {
1023 // The following is a dummy for the sake of GraphKit::gen_stub
1024 Unique_Node_List for_igvn(comp_arena());
1025 set_for_igvn(&for_igvn); // not used, but some GraphKit guys push on this
1026 PhaseGVN gvn(Thread::current()->resource_area(),255);
1027 set_initial_gvn(&gvn); // not significant, but GraphKit guys use it pervasively
1028 gvn.transform_no_reclaim(top());
1030 GraphKit kit;
1031 kit.gen_stub(stub_function, stub_name, is_fancy_jump, pass_tls, return_pc);
1032 }
1034 NOT_PRODUCT( verify_graph_edges(); )
1035 Code_Gen();
1036 if (failing()) return;
1039 // Entry point will be accessed using compile->stub_entry_point();
1040 if (code_buffer() == NULL) {
1041 Matcher::soft_match_failure();
1042 } else {
1043 if (PrintAssembly && (WizardMode || Verbose))
1044 tty->print_cr("### Stub::%s", stub_name);
1046 if (!failing()) {
1047 assert(_fixed_slots == 0, "no fixed slots used for runtime stubs");
1049 // Make the NMethod
1050 // For now we mark the frame as never safe for profile stackwalking
1051 RuntimeStub *rs = RuntimeStub::new_runtime_stub(stub_name,
1052 code_buffer(),
1053 CodeOffsets::frame_never_safe,
1054 // _code_offsets.value(CodeOffsets::Frame_Complete),
1055 frame_size_in_words(),
1056 _oop_map_set,
1057 save_arg_registers);
1058 assert(rs != NULL && rs->is_runtime_stub(), "sanity check");
1060 _stub_entry_point = rs->entry_point();
1061 }
1062 }
1063 }
1065 //------------------------------Init-------------------------------------------
1066 // Prepare for a single compilation
1067 void Compile::Init(int aliaslevel) {
1068 _unique = 0;
1069 _regalloc = NULL;
1071 _tf = NULL; // filled in later
1072 _top = NULL; // cached later
1073 _matcher = NULL; // filled in later
1074 _cfg = NULL; // filled in later
1076 set_24_bit_selection_and_mode(Use24BitFP, false);
1078 _node_note_array = NULL;
1079 _default_node_notes = NULL;
1081 _immutable_memory = NULL; // filled in at first inquiry
1083 // Globally visible Nodes
1084 // First set TOP to NULL to give safe behavior during creation of RootNode
1085 set_cached_top_node(NULL);
1086 set_root(new (this) RootNode());
1087 // Now that you have a Root to point to, create the real TOP
1088 set_cached_top_node( new (this) ConNode(Type::TOP) );
1089 set_recent_alloc(NULL, NULL);
1091 // Create Debug Information Recorder to record scopes, oopmaps, etc.
1092 env()->set_oop_recorder(new OopRecorder(env()->arena()));
1093 env()->set_debug_info(new DebugInformationRecorder(env()->oop_recorder()));
1094 env()->set_dependencies(new Dependencies(env()));
1096 _fixed_slots = 0;
1097 set_has_split_ifs(false);
1098 set_has_loops(has_method() && method()->has_loops()); // first approximation
1099 set_has_stringbuilder(false);
1100 set_has_boxed_value(false);
1101 _trap_can_recompile = false; // no traps emitted yet
1102 _major_progress = true; // start out assuming good things will happen
1103 set_has_unsafe_access(false);
1104 set_max_vector_size(0);
1105 Copy::zero_to_bytes(_trap_hist, sizeof(_trap_hist));
1106 set_decompile_count(0);
1108 set_do_freq_based_layout(BlockLayoutByFrequency || method_has_option("BlockLayoutByFrequency"));
1109 set_num_loop_opts(LoopOptsCount);
1110 set_do_inlining(Inline);
1111 set_max_inline_size(MaxInlineSize);
1112 set_freq_inline_size(FreqInlineSize);
1113 set_do_scheduling(OptoScheduling);
1114 set_do_count_invocations(false);
1115 set_do_method_data_update(false);
1116 set_rtm_state(NoRTM); // No RTM lock eliding by default
1117 method_has_option_value("MaxNodeLimit", _max_node_limit);
1118 #if INCLUDE_RTM_OPT
1119 if (UseRTMLocking && has_method() && (method()->method_data_or_null() != NULL)) {
1120 int rtm_state = method()->method_data()->rtm_state();
1121 if (method_has_option("NoRTMLockEliding") || ((rtm_state & NoRTM) != 0)) {
1122 // Don't generate RTM lock eliding code.
1123 set_rtm_state(NoRTM);
1124 } else if (method_has_option("UseRTMLockEliding") || ((rtm_state & UseRTM) != 0) || !UseRTMDeopt) {
1125 // Generate RTM lock eliding code without abort ratio calculation code.
1126 set_rtm_state(UseRTM);
1127 } else if (UseRTMDeopt) {
1128 // Generate RTM lock eliding code and include abort ratio calculation
1129 // code if UseRTMDeopt is on.
1130 set_rtm_state(ProfileRTM);
1131 }
1132 }
1133 #endif
1134 if (debug_info()->recording_non_safepoints()) {
1135 set_node_note_array(new(comp_arena()) GrowableArray<Node_Notes*>
1136 (comp_arena(), 8, 0, NULL));
1137 set_default_node_notes(Node_Notes::make(this));
1138 }
1140 // // -- Initialize types before each compile --
1141 // // Update cached type information
1142 // if( _method && _method->constants() )
1143 // Type::update_loaded_types(_method, _method->constants());
1145 // Init alias_type map.
1146 if (!_do_escape_analysis && aliaslevel == 3)
1147 aliaslevel = 2; // No unique types without escape analysis
1148 _AliasLevel = aliaslevel;
1149 const int grow_ats = 16;
1150 _max_alias_types = grow_ats;
1151 _alias_types = NEW_ARENA_ARRAY(comp_arena(), AliasType*, grow_ats);
1152 AliasType* ats = NEW_ARENA_ARRAY(comp_arena(), AliasType, grow_ats);
1153 Copy::zero_to_bytes(ats, sizeof(AliasType)*grow_ats);
1154 {
1155 for (int i = 0; i < grow_ats; i++) _alias_types[i] = &ats[i];
1156 }
1157 // Initialize the first few types.
1158 _alias_types[AliasIdxTop]->Init(AliasIdxTop, NULL);
1159 _alias_types[AliasIdxBot]->Init(AliasIdxBot, TypePtr::BOTTOM);
1160 _alias_types[AliasIdxRaw]->Init(AliasIdxRaw, TypeRawPtr::BOTTOM);
1161 _num_alias_types = AliasIdxRaw+1;
1162 // Zero out the alias type cache.
1163 Copy::zero_to_bytes(_alias_cache, sizeof(_alias_cache));
1164 // A NULL adr_type hits in the cache right away. Preload the right answer.
1165 probe_alias_cache(NULL)->_index = AliasIdxTop;
1167 _intrinsics = NULL;
1168 _macro_nodes = new(comp_arena()) GrowableArray<Node*>(comp_arena(), 8, 0, NULL);
1169 _predicate_opaqs = new(comp_arena()) GrowableArray<Node*>(comp_arena(), 8, 0, NULL);
1170 _expensive_nodes = new(comp_arena()) GrowableArray<Node*>(comp_arena(), 8, 0, NULL);
1171 _range_check_casts = new(comp_arena()) GrowableArray<Node*>(comp_arena(), 8, 0, NULL);
1172 register_library_intrinsics();
1173 }
1175 //---------------------------init_start----------------------------------------
1176 // Install the StartNode on this compile object.
1177 void Compile::init_start(StartNode* s) {
1178 if (failing())
1179 return; // already failing
1180 assert(s == start(), "");
1181 }
1183 StartNode* Compile::start() const {
1184 assert(!failing(), "");
1185 for (DUIterator_Fast imax, i = root()->fast_outs(imax); i < imax; i++) {
1186 Node* start = root()->fast_out(i);
1187 if( start->is_Start() )
1188 return start->as_Start();
1189 }
1190 fatal("Did not find Start node!");
1191 return NULL;
1192 }
1194 //-------------------------------immutable_memory-------------------------------------
1195 // Access immutable memory
1196 Node* Compile::immutable_memory() {
1197 if (_immutable_memory != NULL) {
1198 return _immutable_memory;
1199 }
1200 StartNode* s = start();
1201 for (DUIterator_Fast imax, i = s->fast_outs(imax); true; i++) {
1202 Node *p = s->fast_out(i);
1203 if (p != s && p->as_Proj()->_con == TypeFunc::Memory) {
1204 _immutable_memory = p;
1205 return _immutable_memory;
1206 }
1207 }
1208 ShouldNotReachHere();
1209 return NULL;
1210 }
1212 //----------------------set_cached_top_node------------------------------------
1213 // Install the cached top node, and make sure Node::is_top works correctly.
1214 void Compile::set_cached_top_node(Node* tn) {
1215 if (tn != NULL) verify_top(tn);
1216 Node* old_top = _top;
1217 _top = tn;
1218 // Calling Node::setup_is_top allows the nodes the chance to adjust
1219 // their _out arrays.
1220 if (_top != NULL) _top->setup_is_top();
1221 if (old_top != NULL) old_top->setup_is_top();
1222 assert(_top == NULL || top()->is_top(), "");
1223 }
1225 #ifdef ASSERT
1226 uint Compile::count_live_nodes_by_graph_walk() {
1227 Unique_Node_List useful(comp_arena());
1228 // Get useful node list by walking the graph.
1229 identify_useful_nodes(useful);
1230 return useful.size();
1231 }
1233 void Compile::print_missing_nodes() {
1235 // Return if CompileLog is NULL and PrintIdealNodeCount is false.
1236 if ((_log == NULL) && (! PrintIdealNodeCount)) {
1237 return;
1238 }
1240 // This is an expensive function. It is executed only when the user
1241 // specifies VerifyIdealNodeCount option or otherwise knows the
1242 // additional work that needs to be done to identify reachable nodes
1243 // by walking the flow graph and find the missing ones using
1244 // _dead_node_list.
1246 Unique_Node_List useful(comp_arena());
1247 // Get useful node list by walking the graph.
1248 identify_useful_nodes(useful);
1250 uint l_nodes = C->live_nodes();
1251 uint l_nodes_by_walk = useful.size();
1253 if (l_nodes != l_nodes_by_walk) {
1254 if (_log != NULL) {
1255 _log->begin_head("mismatched_nodes count='%d'", abs((int) (l_nodes - l_nodes_by_walk)));
1256 _log->stamp();
1257 _log->end_head();
1258 }
1259 VectorSet& useful_member_set = useful.member_set();
1260 int last_idx = l_nodes_by_walk;
1261 for (int i = 0; i < last_idx; i++) {
1262 if (useful_member_set.test(i)) {
1263 if (_dead_node_list.test(i)) {
1264 if (_log != NULL) {
1265 _log->elem("mismatched_node_info node_idx='%d' type='both live and dead'", i);
1266 }
1267 if (PrintIdealNodeCount) {
1268 // Print the log message to tty
1269 tty->print_cr("mismatched_node idx='%d' both live and dead'", i);
1270 useful.at(i)->dump();
1271 }
1272 }
1273 }
1274 else if (! _dead_node_list.test(i)) {
1275 if (_log != NULL) {
1276 _log->elem("mismatched_node_info node_idx='%d' type='neither live nor dead'", i);
1277 }
1278 if (PrintIdealNodeCount) {
1279 // Print the log message to tty
1280 tty->print_cr("mismatched_node idx='%d' type='neither live nor dead'", i);
1281 }
1282 }
1283 }
1284 if (_log != NULL) {
1285 _log->tail("mismatched_nodes");
1286 }
1287 }
1288 }
1289 #endif
1291 #ifndef PRODUCT
1292 void Compile::verify_top(Node* tn) const {
1293 if (tn != NULL) {
1294 assert(tn->is_Con(), "top node must be a constant");
1295 assert(((ConNode*)tn)->type() == Type::TOP, "top node must have correct type");
1296 assert(tn->in(0) != NULL, "must have live top node");
1297 }
1298 }
1299 #endif
1302 ///-------------------Managing Per-Node Debug & Profile Info-------------------
1304 void Compile::grow_node_notes(GrowableArray<Node_Notes*>* arr, int grow_by) {
1305 guarantee(arr != NULL, "");
1306 int num_blocks = arr->length();
1307 if (grow_by < num_blocks) grow_by = num_blocks;
1308 int num_notes = grow_by * _node_notes_block_size;
1309 Node_Notes* notes = NEW_ARENA_ARRAY(node_arena(), Node_Notes, num_notes);
1310 Copy::zero_to_bytes(notes, num_notes * sizeof(Node_Notes));
1311 while (num_notes > 0) {
1312 arr->append(notes);
1313 notes += _node_notes_block_size;
1314 num_notes -= _node_notes_block_size;
1315 }
1316 assert(num_notes == 0, "exact multiple, please");
1317 }
1319 bool Compile::copy_node_notes_to(Node* dest, Node* source) {
1320 if (source == NULL || dest == NULL) return false;
1322 if (dest->is_Con())
1323 return false; // Do not push debug info onto constants.
1325 #ifdef ASSERT
1326 // Leave a bread crumb trail pointing to the original node:
1327 if (dest != NULL && dest != source && dest->debug_orig() == NULL) {
1328 dest->set_debug_orig(source);
1329 }
1330 #endif
1332 if (node_note_array() == NULL)
1333 return false; // Not collecting any notes now.
1335 // This is a copy onto a pre-existing node, which may already have notes.
1336 // If both nodes have notes, do not overwrite any pre-existing notes.
1337 Node_Notes* source_notes = node_notes_at(source->_idx);
1338 if (source_notes == NULL || source_notes->is_clear()) return false;
1339 Node_Notes* dest_notes = node_notes_at(dest->_idx);
1340 if (dest_notes == NULL || dest_notes->is_clear()) {
1341 return set_node_notes_at(dest->_idx, source_notes);
1342 }
1344 Node_Notes merged_notes = (*source_notes);
1345 // The order of operations here ensures that dest notes will win...
1346 merged_notes.update_from(dest_notes);
1347 return set_node_notes_at(dest->_idx, &merged_notes);
1348 }
1351 //--------------------------allow_range_check_smearing-------------------------
1352 // Gating condition for coalescing similar range checks.
1353 // Sometimes we try 'speculatively' replacing a series of a range checks by a
1354 // single covering check that is at least as strong as any of them.
1355 // If the optimization succeeds, the simplified (strengthened) range check
1356 // will always succeed. If it fails, we will deopt, and then give up
1357 // on the optimization.
1358 bool Compile::allow_range_check_smearing() const {
1359 // If this method has already thrown a range-check,
1360 // assume it was because we already tried range smearing
1361 // and it failed.
1362 uint already_trapped = trap_count(Deoptimization::Reason_range_check);
1363 return !already_trapped;
1364 }
1367 //------------------------------flatten_alias_type-----------------------------
1368 const TypePtr *Compile::flatten_alias_type( const TypePtr *tj ) const {
1369 int offset = tj->offset();
1370 TypePtr::PTR ptr = tj->ptr();
1372 // Known instance (scalarizable allocation) alias only with itself.
1373 bool is_known_inst = tj->isa_oopptr() != NULL &&
1374 tj->is_oopptr()->is_known_instance();
1376 // Process weird unsafe references.
1377 if (offset == Type::OffsetBot && (tj->isa_instptr() /*|| tj->isa_klassptr()*/)) {
1378 assert(InlineUnsafeOps, "indeterminate pointers come only from unsafe ops");
1379 assert(!is_known_inst, "scalarizable allocation should not have unsafe references");
1380 tj = TypeOopPtr::BOTTOM;
1381 ptr = tj->ptr();
1382 offset = tj->offset();
1383 }
1385 // Array pointers need some flattening
1386 const TypeAryPtr *ta = tj->isa_aryptr();
1387 if (ta && ta->is_stable()) {
1388 // Erase stability property for alias analysis.
1389 tj = ta = ta->cast_to_stable(false);
1390 }
1391 if( ta && is_known_inst ) {
1392 if ( offset != Type::OffsetBot &&
1393 offset > arrayOopDesc::length_offset_in_bytes() ) {
1394 offset = Type::OffsetBot; // Flatten constant access into array body only
1395 tj = ta = TypeAryPtr::make(ptr, ta->ary(), ta->klass(), true, offset, ta->instance_id());
1396 }
1397 } else if( ta && _AliasLevel >= 2 ) {
1398 // For arrays indexed by constant indices, we flatten the alias
1399 // space to include all of the array body. Only the header, klass
1400 // and array length can be accessed un-aliased.
1401 if( offset != Type::OffsetBot ) {
1402 if( ta->const_oop() ) { // MethodData* or Method*
1403 offset = Type::OffsetBot; // Flatten constant access into array body
1404 tj = ta = TypeAryPtr::make(ptr,ta->const_oop(),ta->ary(),ta->klass(),false,offset);
1405 } else if( offset == arrayOopDesc::length_offset_in_bytes() ) {
1406 // range is OK as-is.
1407 tj = ta = TypeAryPtr::RANGE;
1408 } else if( offset == oopDesc::klass_offset_in_bytes() ) {
1409 tj = TypeInstPtr::KLASS; // all klass loads look alike
1410 ta = TypeAryPtr::RANGE; // generic ignored junk
1411 ptr = TypePtr::BotPTR;
1412 } else if( offset == oopDesc::mark_offset_in_bytes() ) {
1413 tj = TypeInstPtr::MARK;
1414 ta = TypeAryPtr::RANGE; // generic ignored junk
1415 ptr = TypePtr::BotPTR;
1416 } else { // Random constant offset into array body
1417 offset = Type::OffsetBot; // Flatten constant access into array body
1418 tj = ta = TypeAryPtr::make(ptr,ta->ary(),ta->klass(),false,offset);
1419 }
1420 }
1421 // Arrays of fixed size alias with arrays of unknown size.
1422 if (ta->size() != TypeInt::POS) {
1423 const TypeAry *tary = TypeAry::make(ta->elem(), TypeInt::POS);
1424 tj = ta = TypeAryPtr::make(ptr,ta->const_oop(),tary,ta->klass(),false,offset);
1425 }
1426 // Arrays of known objects become arrays of unknown objects.
1427 if (ta->elem()->isa_narrowoop() && ta->elem() != TypeNarrowOop::BOTTOM) {
1428 const TypeAry *tary = TypeAry::make(TypeNarrowOop::BOTTOM, ta->size());
1429 tj = ta = TypeAryPtr::make(ptr,ta->const_oop(),tary,NULL,false,offset);
1430 }
1431 if (ta->elem()->isa_oopptr() && ta->elem() != TypeInstPtr::BOTTOM) {
1432 const TypeAry *tary = TypeAry::make(TypeInstPtr::BOTTOM, ta->size());
1433 tj = ta = TypeAryPtr::make(ptr,ta->const_oop(),tary,NULL,false,offset);
1434 }
1435 // Arrays of bytes and of booleans both use 'bastore' and 'baload' so
1436 // cannot be distinguished by bytecode alone.
1437 if (ta->elem() == TypeInt::BOOL) {
1438 const TypeAry *tary = TypeAry::make(TypeInt::BYTE, ta->size());
1439 ciKlass* aklass = ciTypeArrayKlass::make(T_BYTE);
1440 tj = ta = TypeAryPtr::make(ptr,ta->const_oop(),tary,aklass,false,offset);
1441 }
1442 // During the 2nd round of IterGVN, NotNull castings are removed.
1443 // Make sure the Bottom and NotNull variants alias the same.
1444 // Also, make sure exact and non-exact variants alias the same.
1445 if (ptr == TypePtr::NotNull || ta->klass_is_exact() || ta->speculative() != NULL) {
1446 tj = ta = TypeAryPtr::make(TypePtr::BotPTR,ta->ary(),ta->klass(),false,offset);
1447 }
1448 }
1450 // Oop pointers need some flattening
1451 const TypeInstPtr *to = tj->isa_instptr();
1452 if( to && _AliasLevel >= 2 && to != TypeOopPtr::BOTTOM ) {
1453 ciInstanceKlass *k = to->klass()->as_instance_klass();
1454 if( ptr == TypePtr::Constant ) {
1455 if (to->klass() != ciEnv::current()->Class_klass() ||
1456 offset < k->size_helper() * wordSize) {
1457 // No constant oop pointers (such as Strings); they alias with
1458 // unknown strings.
1459 assert(!is_known_inst, "not scalarizable allocation");
1460 tj = to = TypeInstPtr::make(TypePtr::BotPTR,to->klass(),false,0,offset);
1461 }
1462 } else if( is_known_inst ) {
1463 tj = to; // Keep NotNull and klass_is_exact for instance type
1464 } else if( ptr == TypePtr::NotNull || to->klass_is_exact() ) {
1465 // During the 2nd round of IterGVN, NotNull castings are removed.
1466 // Make sure the Bottom and NotNull variants alias the same.
1467 // Also, make sure exact and non-exact variants alias the same.
1468 tj = to = TypeInstPtr::make(TypePtr::BotPTR,to->klass(),false,0,offset);
1469 }
1470 if (to->speculative() != NULL) {
1471 tj = to = TypeInstPtr::make(to->ptr(),to->klass(),to->klass_is_exact(),to->const_oop(),to->offset(), to->instance_id());
1472 }
1473 // Canonicalize the holder of this field
1474 if (offset >= 0 && offset < instanceOopDesc::base_offset_in_bytes()) {
1475 // First handle header references such as a LoadKlassNode, even if the
1476 // object's klass is unloaded at compile time (4965979).
1477 if (!is_known_inst) { // Do it only for non-instance types
1478 tj = to = TypeInstPtr::make(TypePtr::BotPTR, env()->Object_klass(), false, NULL, offset);
1479 }
1480 } else if (offset < 0 || offset >= k->size_helper() * wordSize) {
1481 // Static fields are in the space above the normal instance
1482 // fields in the java.lang.Class instance.
1483 if (to->klass() != ciEnv::current()->Class_klass()) {
1484 to = NULL;
1485 tj = TypeOopPtr::BOTTOM;
1486 offset = tj->offset();
1487 }
1488 } else {
1489 ciInstanceKlass *canonical_holder = k->get_canonical_holder(offset);
1490 if (!k->equals(canonical_holder) || tj->offset() != offset) {
1491 if( is_known_inst ) {
1492 tj = to = TypeInstPtr::make(to->ptr(), canonical_holder, true, NULL, offset, to->instance_id());
1493 } else {
1494 tj = to = TypeInstPtr::make(to->ptr(), canonical_holder, false, NULL, offset);
1495 }
1496 }
1497 }
1498 }
1500 // Klass pointers to object array klasses need some flattening
1501 const TypeKlassPtr *tk = tj->isa_klassptr();
1502 if( tk ) {
1503 // If we are referencing a field within a Klass, we need
1504 // to assume the worst case of an Object. Both exact and
1505 // inexact types must flatten to the same alias class so
1506 // use NotNull as the PTR.
1507 if ( offset == Type::OffsetBot || (offset >= 0 && (size_t)offset < sizeof(Klass)) ) {
1509 tj = tk = TypeKlassPtr::make(TypePtr::NotNull,
1510 TypeKlassPtr::OBJECT->klass(),
1511 offset);
1512 }
1514 ciKlass* klass = tk->klass();
1515 if( klass->is_obj_array_klass() ) {
1516 ciKlass* k = TypeAryPtr::OOPS->klass();
1517 if( !k || !k->is_loaded() ) // Only fails for some -Xcomp runs
1518 k = TypeInstPtr::BOTTOM->klass();
1519 tj = tk = TypeKlassPtr::make( TypePtr::NotNull, k, offset );
1520 }
1522 // Check for precise loads from the primary supertype array and force them
1523 // to the supertype cache alias index. Check for generic array loads from
1524 // the primary supertype array and also force them to the supertype cache
1525 // alias index. Since the same load can reach both, we need to merge
1526 // these 2 disparate memories into the same alias class. Since the
1527 // primary supertype array is read-only, there's no chance of confusion
1528 // where we bypass an array load and an array store.
1529 int primary_supers_offset = in_bytes(Klass::primary_supers_offset());
1530 if (offset == Type::OffsetBot ||
1531 (offset >= primary_supers_offset &&
1532 offset < (int)(primary_supers_offset + Klass::primary_super_limit() * wordSize)) ||
1533 offset == (int)in_bytes(Klass::secondary_super_cache_offset())) {
1534 offset = in_bytes(Klass::secondary_super_cache_offset());
1535 tj = tk = TypeKlassPtr::make( TypePtr::NotNull, tk->klass(), offset );
1536 }
1537 }
1539 // Flatten all Raw pointers together.
1540 if (tj->base() == Type::RawPtr)
1541 tj = TypeRawPtr::BOTTOM;
1543 if (tj->base() == Type::AnyPtr)
1544 tj = TypePtr::BOTTOM; // An error, which the caller must check for.
1546 // Flatten all to bottom for now
1547 switch( _AliasLevel ) {
1548 case 0:
1549 tj = TypePtr::BOTTOM;
1550 break;
1551 case 1: // Flatten to: oop, static, field or array
1552 switch (tj->base()) {
1553 //case Type::AryPtr: tj = TypeAryPtr::RANGE; break;
1554 case Type::RawPtr: tj = TypeRawPtr::BOTTOM; break;
1555 case Type::AryPtr: // do not distinguish arrays at all
1556 case Type::InstPtr: tj = TypeInstPtr::BOTTOM; break;
1557 case Type::KlassPtr: tj = TypeKlassPtr::OBJECT; break;
1558 case Type::AnyPtr: tj = TypePtr::BOTTOM; break; // caller checks it
1559 default: ShouldNotReachHere();
1560 }
1561 break;
1562 case 2: // No collapsing at level 2; keep all splits
1563 case 3: // No collapsing at level 3; keep all splits
1564 break;
1565 default:
1566 Unimplemented();
1567 }
1569 offset = tj->offset();
1570 assert( offset != Type::OffsetTop, "Offset has fallen from constant" );
1572 assert( (offset != Type::OffsetBot && tj->base() != Type::AryPtr) ||
1573 (offset == Type::OffsetBot && tj->base() == Type::AryPtr) ||
1574 (offset == Type::OffsetBot && tj == TypeOopPtr::BOTTOM) ||
1575 (offset == Type::OffsetBot && tj == TypePtr::BOTTOM) ||
1576 (offset == oopDesc::mark_offset_in_bytes() && tj->base() == Type::AryPtr) ||
1577 (offset == oopDesc::klass_offset_in_bytes() && tj->base() == Type::AryPtr) ||
1578 (offset == arrayOopDesc::length_offset_in_bytes() && tj->base() == Type::AryPtr) ,
1579 "For oops, klasses, raw offset must be constant; for arrays the offset is never known" );
1580 assert( tj->ptr() != TypePtr::TopPTR &&
1581 tj->ptr() != TypePtr::AnyNull &&
1582 tj->ptr() != TypePtr::Null, "No imprecise addresses" );
1583 // assert( tj->ptr() != TypePtr::Constant ||
1584 // tj->base() == Type::RawPtr ||
1585 // tj->base() == Type::KlassPtr, "No constant oop addresses" );
1587 return tj;
1588 }
1590 void Compile::AliasType::Init(int i, const TypePtr* at) {
1591 _index = i;
1592 _adr_type = at;
1593 _field = NULL;
1594 _element = NULL;
1595 _is_rewritable = true; // default
1596 const TypeOopPtr *atoop = (at != NULL) ? at->isa_oopptr() : NULL;
1597 if (atoop != NULL && atoop->is_known_instance()) {
1598 const TypeOopPtr *gt = atoop->cast_to_instance_id(TypeOopPtr::InstanceBot);
1599 _general_index = Compile::current()->get_alias_index(gt);
1600 } else {
1601 _general_index = 0;
1602 }
1603 }
1605 BasicType Compile::AliasType::basic_type() const {
1606 if (element() != NULL) {
1607 const Type* element = adr_type()->is_aryptr()->elem();
1608 return element->isa_narrowoop() ? T_OBJECT : element->array_element_basic_type();
1609 } if (field() != NULL) {
1610 return field()->layout_type();
1611 } else {
1612 return T_ILLEGAL; // unknown
1613 }
1614 }
1616 //---------------------------------print_on------------------------------------
1617 #ifndef PRODUCT
1618 void Compile::AliasType::print_on(outputStream* st) {
1619 if (index() < 10)
1620 st->print("@ <%d> ", index());
1621 else st->print("@ <%d>", index());
1622 st->print(is_rewritable() ? " " : " RO");
1623 int offset = adr_type()->offset();
1624 if (offset == Type::OffsetBot)
1625 st->print(" +any");
1626 else st->print(" +%-3d", offset);
1627 st->print(" in ");
1628 adr_type()->dump_on(st);
1629 const TypeOopPtr* tjp = adr_type()->isa_oopptr();
1630 if (field() != NULL && tjp) {
1631 if (tjp->klass() != field()->holder() ||
1632 tjp->offset() != field()->offset_in_bytes()) {
1633 st->print(" != ");
1634 field()->print();
1635 st->print(" ***");
1636 }
1637 }
1638 }
1640 void print_alias_types() {
1641 Compile* C = Compile::current();
1642 tty->print_cr("--- Alias types, AliasIdxBot .. %d", C->num_alias_types()-1);
1643 for (int idx = Compile::AliasIdxBot; idx < C->num_alias_types(); idx++) {
1644 C->alias_type(idx)->print_on(tty);
1645 tty->cr();
1646 }
1647 }
1648 #endif
1651 //----------------------------probe_alias_cache--------------------------------
1652 Compile::AliasCacheEntry* Compile::probe_alias_cache(const TypePtr* adr_type) {
1653 intptr_t key = (intptr_t) adr_type;
1654 key ^= key >> logAliasCacheSize;
1655 return &_alias_cache[key & right_n_bits(logAliasCacheSize)];
1656 }
1659 //-----------------------------grow_alias_types--------------------------------
1660 void Compile::grow_alias_types() {
1661 const int old_ats = _max_alias_types; // how many before?
1662 const int new_ats = old_ats; // how many more?
1663 const int grow_ats = old_ats+new_ats; // how many now?
1664 _max_alias_types = grow_ats;
1665 _alias_types = REALLOC_ARENA_ARRAY(comp_arena(), AliasType*, _alias_types, old_ats, grow_ats);
1666 AliasType* ats = NEW_ARENA_ARRAY(comp_arena(), AliasType, new_ats);
1667 Copy::zero_to_bytes(ats, sizeof(AliasType)*new_ats);
1668 for (int i = 0; i < new_ats; i++) _alias_types[old_ats+i] = &ats[i];
1669 }
1672 //--------------------------------find_alias_type------------------------------
1673 Compile::AliasType* Compile::find_alias_type(const TypePtr* adr_type, bool no_create, ciField* original_field) {
1674 if (_AliasLevel == 0)
1675 return alias_type(AliasIdxBot);
1677 AliasCacheEntry* ace = probe_alias_cache(adr_type);
1678 if (ace->_adr_type == adr_type) {
1679 return alias_type(ace->_index);
1680 }
1682 // Handle special cases.
1683 if (adr_type == NULL) return alias_type(AliasIdxTop);
1684 if (adr_type == TypePtr::BOTTOM) return alias_type(AliasIdxBot);
1686 // Do it the slow way.
1687 const TypePtr* flat = flatten_alias_type(adr_type);
1689 #ifdef ASSERT
1690 {
1691 ResourceMark rm;
1692 assert(flat == flatten_alias_type(flat),
1693 err_msg("not idempotent: adr_type = %s; flat = %s => %s", Type::str(adr_type),
1694 Type::str(flat), Type::str(flatten_alias_type(flat))));
1695 assert(flat != TypePtr::BOTTOM,
1696 err_msg("cannot alias-analyze an untyped ptr: adr_type = %s", Type::str(adr_type)));
1697 if (flat->isa_oopptr() && !flat->isa_klassptr()) {
1698 const TypeOopPtr* foop = flat->is_oopptr();
1699 // Scalarizable allocations have exact klass always.
1700 bool exact = !foop->klass_is_exact() || foop->is_known_instance();
1701 const TypePtr* xoop = foop->cast_to_exactness(exact)->is_ptr();
1702 assert(foop == flatten_alias_type(xoop),
1703 err_msg("exactness must not affect alias type: foop = %s; xoop = %s",
1704 Type::str(foop), Type::str(xoop)));
1705 }
1706 }
1707 #endif
1709 int idx = AliasIdxTop;
1710 for (int i = 0; i < num_alias_types(); i++) {
1711 if (alias_type(i)->adr_type() == flat) {
1712 idx = i;
1713 break;
1714 }
1715 }
1717 if (idx == AliasIdxTop) {
1718 if (no_create) return NULL;
1719 // Grow the array if necessary.
1720 if (_num_alias_types == _max_alias_types) grow_alias_types();
1721 // Add a new alias type.
1722 idx = _num_alias_types++;
1723 _alias_types[idx]->Init(idx, flat);
1724 if (flat == TypeInstPtr::KLASS) alias_type(idx)->set_rewritable(false);
1725 if (flat == TypeAryPtr::RANGE) alias_type(idx)->set_rewritable(false);
1726 if (flat->isa_instptr()) {
1727 if (flat->offset() == java_lang_Class::klass_offset_in_bytes()
1728 && flat->is_instptr()->klass() == env()->Class_klass())
1729 alias_type(idx)->set_rewritable(false);
1730 }
1731 if (flat->isa_aryptr()) {
1732 #ifdef ASSERT
1733 const int header_size_min = arrayOopDesc::base_offset_in_bytes(T_BYTE);
1734 // (T_BYTE has the weakest alignment and size restrictions...)
1735 assert(flat->offset() < header_size_min, "array body reference must be OffsetBot");
1736 #endif
1737 if (flat->offset() == TypePtr::OffsetBot) {
1738 alias_type(idx)->set_element(flat->is_aryptr()->elem());
1739 }
1740 }
1741 if (flat->isa_klassptr()) {
1742 if (flat->offset() == in_bytes(Klass::super_check_offset_offset()))
1743 alias_type(idx)->set_rewritable(false);
1744 if (flat->offset() == in_bytes(Klass::modifier_flags_offset()))
1745 alias_type(idx)->set_rewritable(false);
1746 if (flat->offset() == in_bytes(Klass::access_flags_offset()))
1747 alias_type(idx)->set_rewritable(false);
1748 if (flat->offset() == in_bytes(Klass::java_mirror_offset()))
1749 alias_type(idx)->set_rewritable(false);
1750 }
1751 // %%% (We would like to finalize JavaThread::threadObj_offset(),
1752 // but the base pointer type is not distinctive enough to identify
1753 // references into JavaThread.)
1755 // Check for final fields.
1756 const TypeInstPtr* tinst = flat->isa_instptr();
1757 if (tinst && tinst->offset() >= instanceOopDesc::base_offset_in_bytes()) {
1758 ciField* field;
1759 if (tinst->const_oop() != NULL &&
1760 tinst->klass() == ciEnv::current()->Class_klass() &&
1761 tinst->offset() >= (tinst->klass()->as_instance_klass()->size_helper() * wordSize)) {
1762 // static field
1763 ciInstanceKlass* k = tinst->const_oop()->as_instance()->java_lang_Class_klass()->as_instance_klass();
1764 field = k->get_field_by_offset(tinst->offset(), true);
1765 } else {
1766 ciInstanceKlass *k = tinst->klass()->as_instance_klass();
1767 field = k->get_field_by_offset(tinst->offset(), false);
1768 }
1769 assert(field == NULL ||
1770 original_field == NULL ||
1771 (field->holder() == original_field->holder() &&
1772 field->offset() == original_field->offset() &&
1773 field->is_static() == original_field->is_static()), "wrong field?");
1774 // Set field() and is_rewritable() attributes.
1775 if (field != NULL) alias_type(idx)->set_field(field);
1776 }
1777 }
1779 // Fill the cache for next time.
1780 ace->_adr_type = adr_type;
1781 ace->_index = idx;
1782 assert(alias_type(adr_type) == alias_type(idx), "type must be installed");
1784 // Might as well try to fill the cache for the flattened version, too.
1785 AliasCacheEntry* face = probe_alias_cache(flat);
1786 if (face->_adr_type == NULL) {
1787 face->_adr_type = flat;
1788 face->_index = idx;
1789 assert(alias_type(flat) == alias_type(idx), "flat type must work too");
1790 }
1792 return alias_type(idx);
1793 }
1796 Compile::AliasType* Compile::alias_type(ciField* field) {
1797 const TypeOopPtr* t;
1798 if (field->is_static())
1799 t = TypeInstPtr::make(field->holder()->java_mirror());
1800 else
1801 t = TypeOopPtr::make_from_klass_raw(field->holder());
1802 AliasType* atp = alias_type(t->add_offset(field->offset_in_bytes()), field);
1803 assert((field->is_final() || field->is_stable()) == !atp->is_rewritable(), "must get the rewritable bits correct");
1804 return atp;
1805 }
1808 //------------------------------have_alias_type--------------------------------
1809 bool Compile::have_alias_type(const TypePtr* adr_type) {
1810 AliasCacheEntry* ace = probe_alias_cache(adr_type);
1811 if (ace->_adr_type == adr_type) {
1812 return true;
1813 }
1815 // Handle special cases.
1816 if (adr_type == NULL) return true;
1817 if (adr_type == TypePtr::BOTTOM) return true;
1819 return find_alias_type(adr_type, true, NULL) != NULL;
1820 }
1822 //-----------------------------must_alias--------------------------------------
1823 // True if all values of the given address type are in the given alias category.
1824 bool Compile::must_alias(const TypePtr* adr_type, int alias_idx) {
1825 if (alias_idx == AliasIdxBot) return true; // the universal category
1826 if (adr_type == NULL) return true; // NULL serves as TypePtr::TOP
1827 if (alias_idx == AliasIdxTop) return false; // the empty category
1828 if (adr_type->base() == Type::AnyPtr) return false; // TypePtr::BOTTOM or its twins
1830 // the only remaining possible overlap is identity
1831 int adr_idx = get_alias_index(adr_type);
1832 assert(adr_idx != AliasIdxBot && adr_idx != AliasIdxTop, "");
1833 assert(adr_idx == alias_idx ||
1834 (alias_type(alias_idx)->adr_type() != TypeOopPtr::BOTTOM
1835 && adr_type != TypeOopPtr::BOTTOM),
1836 "should not be testing for overlap with an unsafe pointer");
1837 return adr_idx == alias_idx;
1838 }
1840 //------------------------------can_alias--------------------------------------
1841 // True if any values of the given address type are in the given alias category.
1842 bool Compile::can_alias(const TypePtr* adr_type, int alias_idx) {
1843 if (alias_idx == AliasIdxTop) return false; // the empty category
1844 if (adr_type == NULL) return false; // NULL serves as TypePtr::TOP
1845 if (alias_idx == AliasIdxBot) return true; // the universal category
1846 if (adr_type->base() == Type::AnyPtr) return true; // TypePtr::BOTTOM or its twins
1848 // the only remaining possible overlap is identity
1849 int adr_idx = get_alias_index(adr_type);
1850 assert(adr_idx != AliasIdxBot && adr_idx != AliasIdxTop, "");
1851 return adr_idx == alias_idx;
1852 }
1856 //---------------------------pop_warm_call-------------------------------------
1857 WarmCallInfo* Compile::pop_warm_call() {
1858 WarmCallInfo* wci = _warm_calls;
1859 if (wci != NULL) _warm_calls = wci->remove_from(wci);
1860 return wci;
1861 }
1863 //----------------------------Inline_Warm--------------------------------------
1864 int Compile::Inline_Warm() {
1865 // If there is room, try to inline some more warm call sites.
1866 // %%% Do a graph index compaction pass when we think we're out of space?
1867 if (!InlineWarmCalls) return 0;
1869 int calls_made_hot = 0;
1870 int room_to_grow = NodeCountInliningCutoff - unique();
1871 int amount_to_grow = MIN2(room_to_grow, (int)NodeCountInliningStep);
1872 int amount_grown = 0;
1873 WarmCallInfo* call;
1874 while (amount_to_grow > 0 && (call = pop_warm_call()) != NULL) {
1875 int est_size = (int)call->size();
1876 if (est_size > (room_to_grow - amount_grown)) {
1877 // This one won't fit anyway. Get rid of it.
1878 call->make_cold();
1879 continue;
1880 }
1881 call->make_hot();
1882 calls_made_hot++;
1883 amount_grown += est_size;
1884 amount_to_grow -= est_size;
1885 }
1887 if (calls_made_hot > 0) set_major_progress();
1888 return calls_made_hot;
1889 }
1892 //----------------------------Finish_Warm--------------------------------------
1893 void Compile::Finish_Warm() {
1894 if (!InlineWarmCalls) return;
1895 if (failing()) return;
1896 if (warm_calls() == NULL) return;
1898 // Clean up loose ends, if we are out of space for inlining.
1899 WarmCallInfo* call;
1900 while ((call = pop_warm_call()) != NULL) {
1901 call->make_cold();
1902 }
1903 }
1905 //---------------------cleanup_loop_predicates-----------------------
1906 // Remove the opaque nodes that protect the predicates so that all unused
1907 // checks and uncommon_traps will be eliminated from the ideal graph
1908 void Compile::cleanup_loop_predicates(PhaseIterGVN &igvn) {
1909 if (predicate_count()==0) return;
1910 for (int i = predicate_count(); i > 0; i--) {
1911 Node * n = predicate_opaque1_node(i-1);
1912 assert(n->Opcode() == Op_Opaque1, "must be");
1913 igvn.replace_node(n, n->in(1));
1914 }
1915 assert(predicate_count()==0, "should be clean!");
1916 }
1918 void Compile::add_range_check_cast(Node* n) {
1919 assert(n->isa_CastII()->has_range_check(), "CastII should have range check dependency");
1920 assert(!_range_check_casts->contains(n), "duplicate entry in range check casts");
1921 _range_check_casts->append(n);
1922 }
1924 // Remove all range check dependent CastIINodes.
1925 void Compile::remove_range_check_casts(PhaseIterGVN &igvn) {
1926 for (int i = range_check_cast_count(); i > 0; i--) {
1927 Node* cast = range_check_cast_node(i-1);
1928 assert(cast->isa_CastII()->has_range_check(), "CastII should have range check dependency");
1929 igvn.replace_node(cast, cast->in(1));
1930 }
1931 assert(range_check_cast_count() == 0, "should be empty");
1932 }
1934 // StringOpts and late inlining of string methods
1935 void Compile::inline_string_calls(bool parse_time) {
1936 {
1937 // remove useless nodes to make the usage analysis simpler
1938 ResourceMark rm;
1939 PhaseRemoveUseless pru(initial_gvn(), for_igvn());
1940 }
1942 {
1943 ResourceMark rm;
1944 print_method(PHASE_BEFORE_STRINGOPTS, 3);
1945 PhaseStringOpts pso(initial_gvn(), for_igvn());
1946 print_method(PHASE_AFTER_STRINGOPTS, 3);
1947 }
1949 // now inline anything that we skipped the first time around
1950 if (!parse_time) {
1951 _late_inlines_pos = _late_inlines.length();
1952 }
1954 while (_string_late_inlines.length() > 0) {
1955 CallGenerator* cg = _string_late_inlines.pop();
1956 cg->do_late_inline();
1957 if (failing()) return;
1958 }
1959 _string_late_inlines.trunc_to(0);
1960 }
1962 // Late inlining of boxing methods
1963 void Compile::inline_boxing_calls(PhaseIterGVN& igvn) {
1964 if (_boxing_late_inlines.length() > 0) {
1965 assert(has_boxed_value(), "inconsistent");
1967 PhaseGVN* gvn = initial_gvn();
1968 set_inlining_incrementally(true);
1970 assert( igvn._worklist.size() == 0, "should be done with igvn" );
1971 for_igvn()->clear();
1972 gvn->replace_with(&igvn);
1974 _late_inlines_pos = _late_inlines.length();
1976 while (_boxing_late_inlines.length() > 0) {
1977 CallGenerator* cg = _boxing_late_inlines.pop();
1978 cg->do_late_inline();
1979 if (failing()) return;
1980 }
1981 _boxing_late_inlines.trunc_to(0);
1983 {
1984 ResourceMark rm;
1985 PhaseRemoveUseless pru(gvn, for_igvn());
1986 }
1988 igvn = PhaseIterGVN(gvn);
1989 igvn.optimize();
1991 set_inlining_progress(false);
1992 set_inlining_incrementally(false);
1993 }
1994 }
1996 void Compile::inline_incrementally_one(PhaseIterGVN& igvn) {
1997 assert(IncrementalInline, "incremental inlining should be on");
1998 PhaseGVN* gvn = initial_gvn();
2000 set_inlining_progress(false);
2001 for_igvn()->clear();
2002 gvn->replace_with(&igvn);
2004 int i = 0;
2006 for (; i <_late_inlines.length() && !inlining_progress(); i++) {
2007 CallGenerator* cg = _late_inlines.at(i);
2008 _late_inlines_pos = i+1;
2009 cg->do_late_inline();
2010 if (failing()) return;
2011 }
2012 int j = 0;
2013 for (; i < _late_inlines.length(); i++, j++) {
2014 _late_inlines.at_put(j, _late_inlines.at(i));
2015 }
2016 _late_inlines.trunc_to(j);
2018 {
2019 ResourceMark rm;
2020 PhaseRemoveUseless pru(gvn, for_igvn());
2021 }
2023 igvn = PhaseIterGVN(gvn);
2024 }
2026 // Perform incremental inlining until bound on number of live nodes is reached
2027 void Compile::inline_incrementally(PhaseIterGVN& igvn) {
2028 PhaseGVN* gvn = initial_gvn();
2030 set_inlining_incrementally(true);
2031 set_inlining_progress(true);
2032 uint low_live_nodes = 0;
2034 while(inlining_progress() && _late_inlines.length() > 0) {
2036 if (live_nodes() > (uint)LiveNodeCountInliningCutoff) {
2037 if (low_live_nodes < (uint)LiveNodeCountInliningCutoff * 8 / 10) {
2038 // PhaseIdealLoop is expensive so we only try it once we are
2039 // out of live nodes and we only try it again if the previous
2040 // helped got the number of nodes down significantly
2041 PhaseIdealLoop ideal_loop( igvn, false, true );
2042 if (failing()) return;
2043 low_live_nodes = live_nodes();
2044 _major_progress = true;
2045 }
2047 if (live_nodes() > (uint)LiveNodeCountInliningCutoff) {
2048 break;
2049 }
2050 }
2052 inline_incrementally_one(igvn);
2054 if (failing()) return;
2056 igvn.optimize();
2058 if (failing()) return;
2059 }
2061 assert( igvn._worklist.size() == 0, "should be done with igvn" );
2063 if (_string_late_inlines.length() > 0) {
2064 assert(has_stringbuilder(), "inconsistent");
2065 for_igvn()->clear();
2066 initial_gvn()->replace_with(&igvn);
2068 inline_string_calls(false);
2070 if (failing()) return;
2072 {
2073 ResourceMark rm;
2074 PhaseRemoveUseless pru(initial_gvn(), for_igvn());
2075 }
2077 igvn = PhaseIterGVN(gvn);
2079 igvn.optimize();
2080 }
2082 set_inlining_incrementally(false);
2083 }
2086 //------------------------------Optimize---------------------------------------
2087 // Given a graph, optimize it.
2088 void Compile::Optimize() {
2089 TracePhase t1("optimizer", &_t_optimizer, true);
2091 #ifndef PRODUCT
2092 if (env()->break_at_compile()) {
2093 BREAKPOINT;
2094 }
2096 #endif
2098 ResourceMark rm;
2099 int loop_opts_cnt;
2101 NOT_PRODUCT( verify_graph_edges(); )
2103 print_method(PHASE_AFTER_PARSING);
2105 {
2106 // Iterative Global Value Numbering, including ideal transforms
2107 // Initialize IterGVN with types and values from parse-time GVN
2108 PhaseIterGVN igvn(initial_gvn());
2109 {
2110 NOT_PRODUCT( TracePhase t2("iterGVN", &_t_iterGVN, TimeCompiler); )
2111 igvn.optimize();
2112 }
2114 print_method(PHASE_ITER_GVN1, 2);
2116 if (failing()) return;
2118 {
2119 NOT_PRODUCT( TracePhase t2("incrementalInline", &_t_incrInline, TimeCompiler); )
2120 inline_incrementally(igvn);
2121 }
2123 print_method(PHASE_INCREMENTAL_INLINE, 2);
2125 if (failing()) return;
2127 if (eliminate_boxing()) {
2128 NOT_PRODUCT( TracePhase t2("incrementalInline", &_t_incrInline, TimeCompiler); )
2129 // Inline valueOf() methods now.
2130 inline_boxing_calls(igvn);
2132 if (AlwaysIncrementalInline) {
2133 inline_incrementally(igvn);
2134 }
2136 print_method(PHASE_INCREMENTAL_BOXING_INLINE, 2);
2138 if (failing()) return;
2139 }
2141 // Remove the speculative part of types and clean up the graph from
2142 // the extra CastPP nodes whose only purpose is to carry them. Do
2143 // that early so that optimizations are not disrupted by the extra
2144 // CastPP nodes.
2145 remove_speculative_types(igvn);
2147 // No more new expensive nodes will be added to the list from here
2148 // so keep only the actual candidates for optimizations.
2149 cleanup_expensive_nodes(igvn);
2151 if (!failing() && RenumberLiveNodes && live_nodes() + NodeLimitFudgeFactor < unique()) {
2152 NOT_PRODUCT(Compile::TracePhase t2("", &_t_renumberLive, TimeCompiler);)
2153 initial_gvn()->replace_with(&igvn);
2154 for_igvn()->clear();
2155 Unique_Node_List new_worklist(C->comp_arena());
2156 {
2157 ResourceMark rm;
2158 PhaseRenumberLive prl = PhaseRenumberLive(initial_gvn(), for_igvn(), &new_worklist);
2159 }
2160 set_for_igvn(&new_worklist);
2161 igvn = PhaseIterGVN(initial_gvn());
2162 igvn.optimize();
2163 }
2165 // Perform escape analysis
2166 if (_do_escape_analysis && ConnectionGraph::has_candidates(this)) {
2167 if (has_loops()) {
2168 // Cleanup graph (remove dead nodes).
2169 TracePhase t2("idealLoop", &_t_idealLoop, true);
2170 PhaseIdealLoop ideal_loop( igvn, false, true );
2171 if (major_progress()) print_method(PHASE_PHASEIDEAL_BEFORE_EA, 2);
2172 if (failing()) return;
2173 }
2174 ConnectionGraph::do_analysis(this, &igvn);
2176 if (failing()) return;
2178 // Optimize out fields loads from scalar replaceable allocations.
2179 igvn.optimize();
2180 print_method(PHASE_ITER_GVN_AFTER_EA, 2);
2182 if (failing()) return;
2184 if (congraph() != NULL && macro_count() > 0) {
2185 NOT_PRODUCT( TracePhase t2("macroEliminate", &_t_macroEliminate, TimeCompiler); )
2186 PhaseMacroExpand mexp(igvn);
2187 mexp.eliminate_macro_nodes();
2188 igvn.set_delay_transform(false);
2190 igvn.optimize();
2191 print_method(PHASE_ITER_GVN_AFTER_ELIMINATION, 2);
2193 if (failing()) return;
2194 }
2195 }
2197 // Loop transforms on the ideal graph. Range Check Elimination,
2198 // peeling, unrolling, etc.
2200 // Set loop opts counter
2201 loop_opts_cnt = num_loop_opts();
2202 if((loop_opts_cnt > 0) && (has_loops() || has_split_ifs())) {
2203 {
2204 TracePhase t2("idealLoop", &_t_idealLoop, true);
2205 PhaseIdealLoop ideal_loop( igvn, true );
2206 loop_opts_cnt--;
2207 if (major_progress()) print_method(PHASE_PHASEIDEALLOOP1, 2);
2208 if (failing()) return;
2209 }
2210 // Loop opts pass if partial peeling occurred in previous pass
2211 if(PartialPeelLoop && major_progress() && (loop_opts_cnt > 0)) {
2212 TracePhase t3("idealLoop", &_t_idealLoop, true);
2213 PhaseIdealLoop ideal_loop( igvn, false );
2214 loop_opts_cnt--;
2215 if (major_progress()) print_method(PHASE_PHASEIDEALLOOP2, 2);
2216 if (failing()) return;
2217 }
2218 // Loop opts pass for loop-unrolling before CCP
2219 if(major_progress() && (loop_opts_cnt > 0)) {
2220 TracePhase t4("idealLoop", &_t_idealLoop, true);
2221 PhaseIdealLoop ideal_loop( igvn, false );
2222 loop_opts_cnt--;
2223 if (major_progress()) print_method(PHASE_PHASEIDEALLOOP3, 2);
2224 }
2225 if (!failing()) {
2226 // Verify that last round of loop opts produced a valid graph
2227 NOT_PRODUCT( TracePhase t2("idealLoopVerify", &_t_idealLoopVerify, TimeCompiler); )
2228 PhaseIdealLoop::verify(igvn);
2229 }
2230 }
2231 if (failing()) return;
2233 // Conditional Constant Propagation;
2234 PhaseCCP ccp( &igvn );
2235 assert( true, "Break here to ccp.dump_nodes_and_types(_root,999,1)");
2236 {
2237 TracePhase t2("ccp", &_t_ccp, true);
2238 ccp.do_transform();
2239 }
2240 print_method(PHASE_CPP1, 2);
2242 assert( true, "Break here to ccp.dump_old2new_map()");
2244 // Iterative Global Value Numbering, including ideal transforms
2245 {
2246 NOT_PRODUCT( TracePhase t2("iterGVN2", &_t_iterGVN2, TimeCompiler); )
2247 igvn = ccp;
2248 igvn.optimize();
2249 }
2251 print_method(PHASE_ITER_GVN2, 2);
2253 if (failing()) return;
2255 // Loop transforms on the ideal graph. Range Check Elimination,
2256 // peeling, unrolling, etc.
2257 if(loop_opts_cnt > 0) {
2258 debug_only( int cnt = 0; );
2259 while(major_progress() && (loop_opts_cnt > 0)) {
2260 TracePhase t2("idealLoop", &_t_idealLoop, true);
2261 assert( cnt++ < 40, "infinite cycle in loop optimization" );
2262 PhaseIdealLoop ideal_loop( igvn, true);
2263 loop_opts_cnt--;
2264 if (major_progress()) print_method(PHASE_PHASEIDEALLOOP_ITERATIONS, 2);
2265 if (failing()) return;
2266 }
2267 }
2269 {
2270 // Verify that all previous optimizations produced a valid graph
2271 // at least to this point, even if no loop optimizations were done.
2272 NOT_PRODUCT( TracePhase t2("idealLoopVerify", &_t_idealLoopVerify, TimeCompiler); )
2273 PhaseIdealLoop::verify(igvn);
2274 }
2276 if (range_check_cast_count() > 0) {
2277 // No more loop optimizations. Remove all range check dependent CastIINodes.
2278 C->remove_range_check_casts(igvn);
2279 igvn.optimize();
2280 }
2282 {
2283 NOT_PRODUCT( TracePhase t2("macroExpand", &_t_macroExpand, TimeCompiler); )
2284 PhaseMacroExpand mex(igvn);
2285 if (mex.expand_macro_nodes()) {
2286 assert(failing(), "must bail out w/ explicit message");
2287 return;
2288 }
2289 }
2291 } // (End scope of igvn; run destructor if necessary for asserts.)
2293 dump_inlining();
2294 // A method with only infinite loops has no edges entering loops from root
2295 {
2296 NOT_PRODUCT( TracePhase t2("graphReshape", &_t_graphReshaping, TimeCompiler); )
2297 if (final_graph_reshaping()) {
2298 assert(failing(), "must bail out w/ explicit message");
2299 return;
2300 }
2301 }
2303 print_method(PHASE_OPTIMIZE_FINISHED, 2);
2304 }
2307 //------------------------------Code_Gen---------------------------------------
2308 // Given a graph, generate code for it
2309 void Compile::Code_Gen() {
2310 if (failing()) {
2311 return;
2312 }
2314 // Perform instruction selection. You might think we could reclaim Matcher
2315 // memory PDQ, but actually the Matcher is used in generating spill code.
2316 // Internals of the Matcher (including some VectorSets) must remain live
2317 // for awhile - thus I cannot reclaim Matcher memory lest a VectorSet usage
2318 // set a bit in reclaimed memory.
2320 // In debug mode can dump m._nodes.dump() for mapping of ideal to machine
2321 // nodes. Mapping is only valid at the root of each matched subtree.
2322 NOT_PRODUCT( verify_graph_edges(); )
2324 Matcher matcher;
2325 _matcher = &matcher;
2326 {
2327 TracePhase t2("matcher", &_t_matcher, true);
2328 matcher.match();
2329 }
2330 // In debug mode can dump m._nodes.dump() for mapping of ideal to machine
2331 // nodes. Mapping is only valid at the root of each matched subtree.
2332 NOT_PRODUCT( verify_graph_edges(); )
2334 // If you have too many nodes, or if matching has failed, bail out
2335 check_node_count(0, "out of nodes matching instructions");
2336 if (failing()) {
2337 return;
2338 }
2340 // Build a proper-looking CFG
2341 PhaseCFG cfg(node_arena(), root(), matcher);
2342 _cfg = &cfg;
2343 {
2344 NOT_PRODUCT( TracePhase t2("scheduler", &_t_scheduler, TimeCompiler); )
2345 bool success = cfg.do_global_code_motion();
2346 if (!success) {
2347 return;
2348 }
2350 print_method(PHASE_GLOBAL_CODE_MOTION, 2);
2351 NOT_PRODUCT( verify_graph_edges(); )
2352 debug_only( cfg.verify(); )
2353 }
2355 PhaseChaitin regalloc(unique(), cfg, matcher);
2356 _regalloc = ®alloc;
2357 {
2358 TracePhase t2("regalloc", &_t_registerAllocation, true);
2359 // Perform register allocation. After Chaitin, use-def chains are
2360 // no longer accurate (at spill code) and so must be ignored.
2361 // Node->LRG->reg mappings are still accurate.
2362 _regalloc->Register_Allocate();
2364 // Bail out if the allocator builds too many nodes
2365 if (failing()) {
2366 return;
2367 }
2368 }
2370 // Prior to register allocation we kept empty basic blocks in case the
2371 // the allocator needed a place to spill. After register allocation we
2372 // are not adding any new instructions. If any basic block is empty, we
2373 // can now safely remove it.
2374 {
2375 NOT_PRODUCT( TracePhase t2("blockOrdering", &_t_blockOrdering, TimeCompiler); )
2376 cfg.remove_empty_blocks();
2377 if (do_freq_based_layout()) {
2378 PhaseBlockLayout layout(cfg);
2379 } else {
2380 cfg.set_loop_alignment();
2381 }
2382 cfg.fixup_flow();
2383 }
2385 // Apply peephole optimizations
2386 if( OptoPeephole ) {
2387 NOT_PRODUCT( TracePhase t2("peephole", &_t_peephole, TimeCompiler); )
2388 PhasePeephole peep( _regalloc, cfg);
2389 peep.do_transform();
2390 }
2392 // Do late expand if CPU requires this.
2393 if (Matcher::require_postalloc_expand) {
2394 NOT_PRODUCT(TracePhase t2c("postalloc_expand", &_t_postalloc_expand, true));
2395 cfg.postalloc_expand(_regalloc);
2396 }
2398 // Convert Nodes to instruction bits in a buffer
2399 {
2400 // %%%% workspace merge brought two timers together for one job
2401 TracePhase t2a("output", &_t_output, true);
2402 NOT_PRODUCT( TraceTime t2b(NULL, &_t_codeGeneration, TimeCompiler, false); )
2403 Output();
2404 }
2406 print_method(PHASE_FINAL_CODE);
2408 // He's dead, Jim.
2409 _cfg = (PhaseCFG*)((intptr_t)0xdeadbeef);
2410 _regalloc = (PhaseChaitin*)((intptr_t)0xdeadbeef);
2411 }
2414 //------------------------------dump_asm---------------------------------------
2415 // Dump formatted assembly
2416 #ifndef PRODUCT
2417 void Compile::dump_asm(int *pcs, uint pc_limit) {
2418 bool cut_short = false;
2419 tty->print_cr("#");
2420 tty->print("# "); _tf->dump(); tty->cr();
2421 tty->print_cr("#");
2423 // For all blocks
2424 int pc = 0x0; // Program counter
2425 char starts_bundle = ' ';
2426 _regalloc->dump_frame();
2428 Node *n = NULL;
2429 for (uint i = 0; i < _cfg->number_of_blocks(); i++) {
2430 if (VMThread::should_terminate()) {
2431 cut_short = true;
2432 break;
2433 }
2434 Block* block = _cfg->get_block(i);
2435 if (block->is_connector() && !Verbose) {
2436 continue;
2437 }
2438 n = block->head();
2439 if (pcs && n->_idx < pc_limit) {
2440 tty->print("%3.3x ", pcs[n->_idx]);
2441 } else {
2442 tty->print(" ");
2443 }
2444 block->dump_head(_cfg);
2445 if (block->is_connector()) {
2446 tty->print_cr(" # Empty connector block");
2447 } else if (block->num_preds() == 2 && block->pred(1)->is_CatchProj() && block->pred(1)->as_CatchProj()->_con == CatchProjNode::fall_through_index) {
2448 tty->print_cr(" # Block is sole successor of call");
2449 }
2451 // For all instructions
2452 Node *delay = NULL;
2453 for (uint j = 0; j < block->number_of_nodes(); j++) {
2454 if (VMThread::should_terminate()) {
2455 cut_short = true;
2456 break;
2457 }
2458 n = block->get_node(j);
2459 if (valid_bundle_info(n)) {
2460 Bundle* bundle = node_bundling(n);
2461 if (bundle->used_in_unconditional_delay()) {
2462 delay = n;
2463 continue;
2464 }
2465 if (bundle->starts_bundle()) {
2466 starts_bundle = '+';
2467 }
2468 }
2470 if (WizardMode) {
2471 n->dump();
2472 }
2474 if( !n->is_Region() && // Dont print in the Assembly
2475 !n->is_Phi() && // a few noisely useless nodes
2476 !n->is_Proj() &&
2477 !n->is_MachTemp() &&
2478 !n->is_SafePointScalarObject() &&
2479 !n->is_Catch() && // Would be nice to print exception table targets
2480 !n->is_MergeMem() && // Not very interesting
2481 !n->is_top() && // Debug info table constants
2482 !(n->is_Con() && !n->is_Mach())// Debug info table constants
2483 ) {
2484 if (pcs && n->_idx < pc_limit)
2485 tty->print("%3.3x", pcs[n->_idx]);
2486 else
2487 tty->print(" ");
2488 tty->print(" %c ", starts_bundle);
2489 starts_bundle = ' ';
2490 tty->print("\t");
2491 n->format(_regalloc, tty);
2492 tty->cr();
2493 }
2495 // If we have an instruction with a delay slot, and have seen a delay,
2496 // then back up and print it
2497 if (valid_bundle_info(n) && node_bundling(n)->use_unconditional_delay()) {
2498 assert(delay != NULL, "no unconditional delay instruction");
2499 if (WizardMode) delay->dump();
2501 if (node_bundling(delay)->starts_bundle())
2502 starts_bundle = '+';
2503 if (pcs && n->_idx < pc_limit)
2504 tty->print("%3.3x", pcs[n->_idx]);
2505 else
2506 tty->print(" ");
2507 tty->print(" %c ", starts_bundle);
2508 starts_bundle = ' ';
2509 tty->print("\t");
2510 delay->format(_regalloc, tty);
2511 tty->cr();
2512 delay = NULL;
2513 }
2515 // Dump the exception table as well
2516 if( n->is_Catch() && (Verbose || WizardMode) ) {
2517 // Print the exception table for this offset
2518 _handler_table.print_subtable_for(pc);
2519 }
2520 }
2522 if (pcs && n->_idx < pc_limit)
2523 tty->print_cr("%3.3x", pcs[n->_idx]);
2524 else
2525 tty->cr();
2527 assert(cut_short || delay == NULL, "no unconditional delay branch");
2529 } // End of per-block dump
2530 tty->cr();
2532 if (cut_short) tty->print_cr("*** disassembly is cut short ***");
2533 }
2534 #endif
2536 //------------------------------Final_Reshape_Counts---------------------------
2537 // This class defines counters to help identify when a method
2538 // may/must be executed using hardware with only 24-bit precision.
2539 struct Final_Reshape_Counts : public StackObj {
2540 int _call_count; // count non-inlined 'common' calls
2541 int _float_count; // count float ops requiring 24-bit precision
2542 int _double_count; // count double ops requiring more precision
2543 int _java_call_count; // count non-inlined 'java' calls
2544 int _inner_loop_count; // count loops which need alignment
2545 VectorSet _visited; // Visitation flags
2546 Node_List _tests; // Set of IfNodes & PCTableNodes
2548 Final_Reshape_Counts() :
2549 _call_count(0), _float_count(0), _double_count(0),
2550 _java_call_count(0), _inner_loop_count(0),
2551 _visited( Thread::current()->resource_area() ) { }
2553 void inc_call_count () { _call_count ++; }
2554 void inc_float_count () { _float_count ++; }
2555 void inc_double_count() { _double_count++; }
2556 void inc_java_call_count() { _java_call_count++; }
2557 void inc_inner_loop_count() { _inner_loop_count++; }
2559 int get_call_count () const { return _call_count ; }
2560 int get_float_count () const { return _float_count ; }
2561 int get_double_count() const { return _double_count; }
2562 int get_java_call_count() const { return _java_call_count; }
2563 int get_inner_loop_count() const { return _inner_loop_count; }
2564 };
2566 #ifdef ASSERT
2567 static bool oop_offset_is_sane(const TypeInstPtr* tp) {
2568 ciInstanceKlass *k = tp->klass()->as_instance_klass();
2569 // Make sure the offset goes inside the instance layout.
2570 return k->contains_field_offset(tp->offset());
2571 // Note that OffsetBot and OffsetTop are very negative.
2572 }
2573 #endif
2575 // Eliminate trivially redundant StoreCMs and accumulate their
2576 // precedence edges.
2577 void Compile::eliminate_redundant_card_marks(Node* n) {
2578 assert(n->Opcode() == Op_StoreCM, "expected StoreCM");
2579 if (n->in(MemNode::Address)->outcnt() > 1) {
2580 // There are multiple users of the same address so it might be
2581 // possible to eliminate some of the StoreCMs
2582 Node* mem = n->in(MemNode::Memory);
2583 Node* adr = n->in(MemNode::Address);
2584 Node* val = n->in(MemNode::ValueIn);
2585 Node* prev = n;
2586 bool done = false;
2587 // Walk the chain of StoreCMs eliminating ones that match. As
2588 // long as it's a chain of single users then the optimization is
2589 // safe. Eliminating partially redundant StoreCMs would require
2590 // cloning copies down the other paths.
2591 while (mem->Opcode() == Op_StoreCM && mem->outcnt() == 1 && !done) {
2592 if (adr == mem->in(MemNode::Address) &&
2593 val == mem->in(MemNode::ValueIn)) {
2594 // redundant StoreCM
2595 if (mem->req() > MemNode::OopStore) {
2596 // Hasn't been processed by this code yet.
2597 n->add_prec(mem->in(MemNode::OopStore));
2598 } else {
2599 // Already converted to precedence edge
2600 for (uint i = mem->req(); i < mem->len(); i++) {
2601 // Accumulate any precedence edges
2602 if (mem->in(i) != NULL) {
2603 n->add_prec(mem->in(i));
2604 }
2605 }
2606 // Everything above this point has been processed.
2607 done = true;
2608 }
2609 // Eliminate the previous StoreCM
2610 prev->set_req(MemNode::Memory, mem->in(MemNode::Memory));
2611 assert(mem->outcnt() == 0, "should be dead");
2612 mem->disconnect_inputs(NULL, this);
2613 } else {
2614 prev = mem;
2615 }
2616 mem = prev->in(MemNode::Memory);
2617 }
2618 }
2619 }
2621 //------------------------------final_graph_reshaping_impl----------------------
2622 // Implement items 1-5 from final_graph_reshaping below.
2623 void Compile::final_graph_reshaping_impl( Node *n, Final_Reshape_Counts &frc) {
2625 if ( n->outcnt() == 0 ) return; // dead node
2626 uint nop = n->Opcode();
2628 // Check for 2-input instruction with "last use" on right input.
2629 // Swap to left input. Implements item (2).
2630 if( n->req() == 3 && // two-input instruction
2631 n->in(1)->outcnt() > 1 && // left use is NOT a last use
2632 (!n->in(1)->is_Phi() || n->in(1)->in(2) != n) && // it is not data loop
2633 n->in(2)->outcnt() == 1 &&// right use IS a last use
2634 !n->in(2)->is_Con() ) { // right use is not a constant
2635 // Check for commutative opcode
2636 switch( nop ) {
2637 case Op_AddI: case Op_AddF: case Op_AddD: case Op_AddL:
2638 case Op_MaxI: case Op_MinI:
2639 case Op_MulI: case Op_MulF: case Op_MulD: case Op_MulL:
2640 case Op_AndL: case Op_XorL: case Op_OrL:
2641 case Op_AndI: case Op_XorI: case Op_OrI: {
2642 // Move "last use" input to left by swapping inputs
2643 n->swap_edges(1, 2);
2644 break;
2645 }
2646 default:
2647 break;
2648 }
2649 }
2651 #ifdef ASSERT
2652 if( n->is_Mem() ) {
2653 int alias_idx = get_alias_index(n->as_Mem()->adr_type());
2654 assert( n->in(0) != NULL || alias_idx != Compile::AliasIdxRaw ||
2655 // oop will be recorded in oop map if load crosses safepoint
2656 n->is_Load() && (n->as_Load()->bottom_type()->isa_oopptr() ||
2657 LoadNode::is_immutable_value(n->in(MemNode::Address))),
2658 "raw memory operations should have control edge");
2659 }
2660 #endif
2661 // Count FPU ops and common calls, implements item (3)
2662 switch( nop ) {
2663 // Count all float operations that may use FPU
2664 case Op_AddF:
2665 case Op_SubF:
2666 case Op_MulF:
2667 case Op_DivF:
2668 case Op_NegF:
2669 case Op_ModF:
2670 case Op_ConvI2F:
2671 case Op_ConF:
2672 case Op_CmpF:
2673 case Op_CmpF3:
2674 // case Op_ConvL2F: // longs are split into 32-bit halves
2675 frc.inc_float_count();
2676 break;
2678 case Op_ConvF2D:
2679 case Op_ConvD2F:
2680 frc.inc_float_count();
2681 frc.inc_double_count();
2682 break;
2684 // Count all double operations that may use FPU
2685 case Op_AddD:
2686 case Op_SubD:
2687 case Op_MulD:
2688 case Op_DivD:
2689 case Op_NegD:
2690 case Op_ModD:
2691 case Op_ConvI2D:
2692 case Op_ConvD2I:
2693 // case Op_ConvL2D: // handled by leaf call
2694 // case Op_ConvD2L: // handled by leaf call
2695 case Op_ConD:
2696 case Op_CmpD:
2697 case Op_CmpD3:
2698 frc.inc_double_count();
2699 break;
2700 case Op_Opaque1: // Remove Opaque Nodes before matching
2701 case Op_Opaque2: // Remove Opaque Nodes before matching
2702 case Op_Opaque3:
2703 n->subsume_by(n->in(1), this);
2704 break;
2705 case Op_CallStaticJava:
2706 case Op_CallJava:
2707 case Op_CallDynamicJava:
2708 frc.inc_java_call_count(); // Count java call site;
2709 case Op_CallRuntime:
2710 case Op_CallLeaf:
2711 case Op_CallLeafNoFP: {
2712 assert( n->is_Call(), "" );
2713 CallNode *call = n->as_Call();
2714 // Count call sites where the FP mode bit would have to be flipped.
2715 // Do not count uncommon runtime calls:
2716 // uncommon_trap, _complete_monitor_locking, _complete_monitor_unlocking,
2717 // _new_Java, _new_typeArray, _new_objArray, _rethrow_Java, ...
2718 if( !call->is_CallStaticJava() || !call->as_CallStaticJava()->_name ) {
2719 frc.inc_call_count(); // Count the call site
2720 } else { // See if uncommon argument is shared
2721 Node *n = call->in(TypeFunc::Parms);
2722 int nop = n->Opcode();
2723 // Clone shared simple arguments to uncommon calls, item (1).
2724 if( n->outcnt() > 1 &&
2725 !n->is_Proj() &&
2726 nop != Op_CreateEx &&
2727 nop != Op_CheckCastPP &&
2728 nop != Op_DecodeN &&
2729 nop != Op_DecodeNKlass &&
2730 !n->is_Mem() ) {
2731 Node *x = n->clone();
2732 call->set_req( TypeFunc::Parms, x );
2733 }
2734 }
2735 break;
2736 }
2738 case Op_StoreD:
2739 case Op_LoadD:
2740 case Op_LoadD_unaligned:
2741 frc.inc_double_count();
2742 goto handle_mem;
2743 case Op_StoreF:
2744 case Op_LoadF:
2745 frc.inc_float_count();
2746 goto handle_mem;
2748 case Op_StoreCM:
2749 {
2750 // Convert OopStore dependence into precedence edge
2751 Node* prec = n->in(MemNode::OopStore);
2752 n->del_req(MemNode::OopStore);
2753 n->add_prec(prec);
2754 eliminate_redundant_card_marks(n);
2755 }
2757 // fall through
2759 case Op_StoreB:
2760 case Op_StoreC:
2761 case Op_StorePConditional:
2762 case Op_StoreI:
2763 case Op_StoreL:
2764 case Op_StoreIConditional:
2765 case Op_StoreLConditional:
2766 case Op_CompareAndSwapI:
2767 case Op_CompareAndSwapL:
2768 case Op_CompareAndSwapP:
2769 case Op_CompareAndSwapN:
2770 case Op_GetAndAddI:
2771 case Op_GetAndAddL:
2772 case Op_GetAndSetI:
2773 case Op_GetAndSetL:
2774 case Op_GetAndSetP:
2775 case Op_GetAndSetN:
2776 case Op_StoreP:
2777 case Op_StoreN:
2778 case Op_StoreNKlass:
2779 case Op_LoadB:
2780 case Op_LoadUB:
2781 case Op_LoadUS:
2782 case Op_LoadI:
2783 case Op_LoadKlass:
2784 case Op_LoadNKlass:
2785 case Op_LoadL:
2786 case Op_LoadL_unaligned:
2787 case Op_LoadPLocked:
2788 case Op_LoadP:
2789 case Op_LoadN:
2790 case Op_LoadRange:
2791 case Op_LoadS: {
2792 handle_mem:
2793 #ifdef ASSERT
2794 if( VerifyOptoOopOffsets ) {
2795 assert( n->is_Mem(), "" );
2796 MemNode *mem = (MemNode*)n;
2797 // Check to see if address types have grounded out somehow.
2798 const TypeInstPtr *tp = mem->in(MemNode::Address)->bottom_type()->isa_instptr();
2799 assert( !tp || oop_offset_is_sane(tp), "" );
2800 }
2801 #endif
2802 break;
2803 }
2805 case Op_AddP: { // Assert sane base pointers
2806 Node *addp = n->in(AddPNode::Address);
2807 assert( !addp->is_AddP() ||
2808 addp->in(AddPNode::Base)->is_top() || // Top OK for allocation
2809 addp->in(AddPNode::Base) == n->in(AddPNode::Base),
2810 "Base pointers must match" );
2811 #ifdef _LP64
2812 if ((UseCompressedOops || UseCompressedClassPointers) &&
2813 addp->Opcode() == Op_ConP &&
2814 addp == n->in(AddPNode::Base) &&
2815 n->in(AddPNode::Offset)->is_Con()) {
2816 // Use addressing with narrow klass to load with offset on x86.
2817 // On sparc loading 32-bits constant and decoding it have less
2818 // instructions (4) then load 64-bits constant (7).
2819 // Do this transformation here since IGVN will convert ConN back to ConP.
2820 const Type* t = addp->bottom_type();
2821 if (t->isa_oopptr() || t->isa_klassptr()) {
2822 Node* nn = NULL;
2824 int op = t->isa_oopptr() ? Op_ConN : Op_ConNKlass;
2826 // Look for existing ConN node of the same exact type.
2827 Node* r = root();
2828 uint cnt = r->outcnt();
2829 for (uint i = 0; i < cnt; i++) {
2830 Node* m = r->raw_out(i);
2831 if (m!= NULL && m->Opcode() == op &&
2832 m->bottom_type()->make_ptr() == t) {
2833 nn = m;
2834 break;
2835 }
2836 }
2837 if (nn != NULL) {
2838 // Decode a narrow oop to match address
2839 // [R12 + narrow_oop_reg<<3 + offset]
2840 if (t->isa_oopptr()) {
2841 nn = new (this) DecodeNNode(nn, t);
2842 } else {
2843 nn = new (this) DecodeNKlassNode(nn, t);
2844 }
2845 n->set_req(AddPNode::Base, nn);
2846 n->set_req(AddPNode::Address, nn);
2847 if (addp->outcnt() == 0) {
2848 addp->disconnect_inputs(NULL, this);
2849 }
2850 }
2851 }
2852 }
2853 #endif
2854 break;
2855 }
2857 #ifdef _LP64
2858 case Op_CastPP:
2859 if (n->in(1)->is_DecodeN() && Matcher::gen_narrow_oop_implicit_null_checks()) {
2860 Node* in1 = n->in(1);
2861 const Type* t = n->bottom_type();
2862 Node* new_in1 = in1->clone();
2863 new_in1->as_DecodeN()->set_type(t);
2865 if (!Matcher::narrow_oop_use_complex_address()) {
2866 //
2867 // x86, ARM and friends can handle 2 adds in addressing mode
2868 // and Matcher can fold a DecodeN node into address by using
2869 // a narrow oop directly and do implicit NULL check in address:
2870 //
2871 // [R12 + narrow_oop_reg<<3 + offset]
2872 // NullCheck narrow_oop_reg
2873 //
2874 // On other platforms (Sparc) we have to keep new DecodeN node and
2875 // use it to do implicit NULL check in address:
2876 //
2877 // decode_not_null narrow_oop_reg, base_reg
2878 // [base_reg + offset]
2879 // NullCheck base_reg
2880 //
2881 // Pin the new DecodeN node to non-null path on these platform (Sparc)
2882 // to keep the information to which NULL check the new DecodeN node
2883 // corresponds to use it as value in implicit_null_check().
2884 //
2885 new_in1->set_req(0, n->in(0));
2886 }
2888 n->subsume_by(new_in1, this);
2889 if (in1->outcnt() == 0) {
2890 in1->disconnect_inputs(NULL, this);
2891 }
2892 }
2893 break;
2895 case Op_CmpP:
2896 // Do this transformation here to preserve CmpPNode::sub() and
2897 // other TypePtr related Ideal optimizations (for example, ptr nullness).
2898 if (n->in(1)->is_DecodeNarrowPtr() || n->in(2)->is_DecodeNarrowPtr()) {
2899 Node* in1 = n->in(1);
2900 Node* in2 = n->in(2);
2901 if (!in1->is_DecodeNarrowPtr()) {
2902 in2 = in1;
2903 in1 = n->in(2);
2904 }
2905 assert(in1->is_DecodeNarrowPtr(), "sanity");
2907 Node* new_in2 = NULL;
2908 if (in2->is_DecodeNarrowPtr()) {
2909 assert(in2->Opcode() == in1->Opcode(), "must be same node type");
2910 new_in2 = in2->in(1);
2911 } else if (in2->Opcode() == Op_ConP) {
2912 const Type* t = in2->bottom_type();
2913 if (t == TypePtr::NULL_PTR) {
2914 assert(in1->is_DecodeN(), "compare klass to null?");
2915 // Don't convert CmpP null check into CmpN if compressed
2916 // oops implicit null check is not generated.
2917 // This will allow to generate normal oop implicit null check.
2918 if (Matcher::gen_narrow_oop_implicit_null_checks())
2919 new_in2 = ConNode::make(this, TypeNarrowOop::NULL_PTR);
2920 //
2921 // This transformation together with CastPP transformation above
2922 // will generated code for implicit NULL checks for compressed oops.
2923 //
2924 // The original code after Optimize()
2925 //
2926 // LoadN memory, narrow_oop_reg
2927 // decode narrow_oop_reg, base_reg
2928 // CmpP base_reg, NULL
2929 // CastPP base_reg // NotNull
2930 // Load [base_reg + offset], val_reg
2931 //
2932 // after these transformations will be
2933 //
2934 // LoadN memory, narrow_oop_reg
2935 // CmpN narrow_oop_reg, NULL
2936 // decode_not_null narrow_oop_reg, base_reg
2937 // Load [base_reg + offset], val_reg
2938 //
2939 // and the uncommon path (== NULL) will use narrow_oop_reg directly
2940 // since narrow oops can be used in debug info now (see the code in
2941 // final_graph_reshaping_walk()).
2942 //
2943 // At the end the code will be matched to
2944 // on x86:
2945 //
2946 // Load_narrow_oop memory, narrow_oop_reg
2947 // Load [R12 + narrow_oop_reg<<3 + offset], val_reg
2948 // NullCheck narrow_oop_reg
2949 //
2950 // and on sparc:
2951 //
2952 // Load_narrow_oop memory, narrow_oop_reg
2953 // decode_not_null narrow_oop_reg, base_reg
2954 // Load [base_reg + offset], val_reg
2955 // NullCheck base_reg
2956 //
2957 } else if (t->isa_oopptr()) {
2958 new_in2 = ConNode::make(this, t->make_narrowoop());
2959 } else if (t->isa_klassptr()) {
2960 new_in2 = ConNode::make(this, t->make_narrowklass());
2961 }
2962 }
2963 if (new_in2 != NULL) {
2964 Node* cmpN = new (this) CmpNNode(in1->in(1), new_in2);
2965 n->subsume_by(cmpN, this);
2966 if (in1->outcnt() == 0) {
2967 in1->disconnect_inputs(NULL, this);
2968 }
2969 if (in2->outcnt() == 0) {
2970 in2->disconnect_inputs(NULL, this);
2971 }
2972 }
2973 }
2974 break;
2976 case Op_DecodeN:
2977 case Op_DecodeNKlass:
2978 assert(!n->in(1)->is_EncodeNarrowPtr(), "should be optimized out");
2979 // DecodeN could be pinned when it can't be fold into
2980 // an address expression, see the code for Op_CastPP above.
2981 assert(n->in(0) == NULL || (UseCompressedOops && !Matcher::narrow_oop_use_complex_address()), "no control");
2982 break;
2984 case Op_EncodeP:
2985 case Op_EncodePKlass: {
2986 Node* in1 = n->in(1);
2987 if (in1->is_DecodeNarrowPtr()) {
2988 n->subsume_by(in1->in(1), this);
2989 } else if (in1->Opcode() == Op_ConP) {
2990 const Type* t = in1->bottom_type();
2991 if (t == TypePtr::NULL_PTR) {
2992 assert(t->isa_oopptr(), "null klass?");
2993 n->subsume_by(ConNode::make(this, TypeNarrowOop::NULL_PTR), this);
2994 } else if (t->isa_oopptr()) {
2995 n->subsume_by(ConNode::make(this, t->make_narrowoop()), this);
2996 } else if (t->isa_klassptr()) {
2997 n->subsume_by(ConNode::make(this, t->make_narrowklass()), this);
2998 }
2999 }
3000 if (in1->outcnt() == 0) {
3001 in1->disconnect_inputs(NULL, this);
3002 }
3003 break;
3004 }
3006 case Op_Proj: {
3007 if (OptimizeStringConcat) {
3008 ProjNode* p = n->as_Proj();
3009 if (p->_is_io_use) {
3010 // Separate projections were used for the exception path which
3011 // are normally removed by a late inline. If it wasn't inlined
3012 // then they will hang around and should just be replaced with
3013 // the original one.
3014 Node* proj = NULL;
3015 // Replace with just one
3016 for (SimpleDUIterator i(p->in(0)); i.has_next(); i.next()) {
3017 Node *use = i.get();
3018 if (use->is_Proj() && p != use && use->as_Proj()->_con == p->_con) {
3019 proj = use;
3020 break;
3021 }
3022 }
3023 assert(proj != NULL, "must be found");
3024 p->subsume_by(proj, this);
3025 }
3026 }
3027 break;
3028 }
3030 case Op_Phi:
3031 if (n->as_Phi()->bottom_type()->isa_narrowoop() || n->as_Phi()->bottom_type()->isa_narrowklass()) {
3032 // The EncodeP optimization may create Phi with the same edges
3033 // for all paths. It is not handled well by Register Allocator.
3034 Node* unique_in = n->in(1);
3035 assert(unique_in != NULL, "");
3036 uint cnt = n->req();
3037 for (uint i = 2; i < cnt; i++) {
3038 Node* m = n->in(i);
3039 assert(m != NULL, "");
3040 if (unique_in != m)
3041 unique_in = NULL;
3042 }
3043 if (unique_in != NULL) {
3044 n->subsume_by(unique_in, this);
3045 }
3046 }
3047 break;
3049 #endif
3051 #ifdef ASSERT
3052 case Op_CastII:
3053 // Verify that all range check dependent CastII nodes were removed.
3054 if (n->isa_CastII()->has_range_check()) {
3055 n->dump(3);
3056 assert(false, "Range check dependent CastII node was not removed");
3057 }
3058 break;
3059 #endif
3061 case Op_ModI:
3062 if (UseDivMod) {
3063 // Check if a%b and a/b both exist
3064 Node* d = n->find_similar(Op_DivI);
3065 if (d) {
3066 // Replace them with a fused divmod if supported
3067 if (Matcher::has_match_rule(Op_DivModI)) {
3068 DivModINode* divmod = DivModINode::make(this, n);
3069 d->subsume_by(divmod->div_proj(), this);
3070 n->subsume_by(divmod->mod_proj(), this);
3071 } else {
3072 // replace a%b with a-((a/b)*b)
3073 Node* mult = new (this) MulINode(d, d->in(2));
3074 Node* sub = new (this) SubINode(d->in(1), mult);
3075 n->subsume_by(sub, this);
3076 }
3077 }
3078 }
3079 break;
3081 case Op_ModL:
3082 if (UseDivMod) {
3083 // Check if a%b and a/b both exist
3084 Node* d = n->find_similar(Op_DivL);
3085 if (d) {
3086 // Replace them with a fused divmod if supported
3087 if (Matcher::has_match_rule(Op_DivModL)) {
3088 DivModLNode* divmod = DivModLNode::make(this, n);
3089 d->subsume_by(divmod->div_proj(), this);
3090 n->subsume_by(divmod->mod_proj(), this);
3091 } else {
3092 // replace a%b with a-((a/b)*b)
3093 Node* mult = new (this) MulLNode(d, d->in(2));
3094 Node* sub = new (this) SubLNode(d->in(1), mult);
3095 n->subsume_by(sub, this);
3096 }
3097 }
3098 }
3099 break;
3101 case Op_LoadVector:
3102 case Op_StoreVector:
3103 break;
3105 case Op_PackB:
3106 case Op_PackS:
3107 case Op_PackI:
3108 case Op_PackF:
3109 case Op_PackL:
3110 case Op_PackD:
3111 if (n->req()-1 > 2) {
3112 // Replace many operand PackNodes with a binary tree for matching
3113 PackNode* p = (PackNode*) n;
3114 Node* btp = p->binary_tree_pack(this, 1, n->req());
3115 n->subsume_by(btp, this);
3116 }
3117 break;
3118 case Op_Loop:
3119 case Op_CountedLoop:
3120 if (n->as_Loop()->is_inner_loop()) {
3121 frc.inc_inner_loop_count();
3122 }
3123 break;
3124 case Op_LShiftI:
3125 case Op_RShiftI:
3126 case Op_URShiftI:
3127 case Op_LShiftL:
3128 case Op_RShiftL:
3129 case Op_URShiftL:
3130 if (Matcher::need_masked_shift_count) {
3131 // The cpu's shift instructions don't restrict the count to the
3132 // lower 5/6 bits. We need to do the masking ourselves.
3133 Node* in2 = n->in(2);
3134 juint mask = (n->bottom_type() == TypeInt::INT) ? (BitsPerInt - 1) : (BitsPerLong - 1);
3135 const TypeInt* t = in2->find_int_type();
3136 if (t != NULL && t->is_con()) {
3137 juint shift = t->get_con();
3138 if (shift > mask) { // Unsigned cmp
3139 n->set_req(2, ConNode::make(this, TypeInt::make(shift & mask)));
3140 }
3141 } else {
3142 if (t == NULL || t->_lo < 0 || t->_hi > (int)mask) {
3143 Node* shift = new (this) AndINode(in2, ConNode::make(this, TypeInt::make(mask)));
3144 n->set_req(2, shift);
3145 }
3146 }
3147 if (in2->outcnt() == 0) { // Remove dead node
3148 in2->disconnect_inputs(NULL, this);
3149 }
3150 }
3151 break;
3152 case Op_MemBarStoreStore:
3153 case Op_MemBarRelease:
3154 // Break the link with AllocateNode: it is no longer useful and
3155 // confuses register allocation.
3156 if (n->req() > MemBarNode::Precedent) {
3157 n->set_req(MemBarNode::Precedent, top());
3158 }
3159 break;
3160 default:
3161 assert( !n->is_Call(), "" );
3162 assert( !n->is_Mem(), "" );
3163 assert( nop != Op_ProfileBoolean, "should be eliminated during IGVN");
3164 break;
3165 }
3167 // Collect CFG split points
3168 if (n->is_MultiBranch())
3169 frc._tests.push(n);
3170 }
3172 //------------------------------final_graph_reshaping_walk---------------------
3173 // Replacing Opaque nodes with their input in final_graph_reshaping_impl(),
3174 // requires that the walk visits a node's inputs before visiting the node.
3175 void Compile::final_graph_reshaping_walk( Node_Stack &nstack, Node *root, Final_Reshape_Counts &frc ) {
3176 ResourceArea *area = Thread::current()->resource_area();
3177 Unique_Node_List sfpt(area);
3179 frc._visited.set(root->_idx); // first, mark node as visited
3180 uint cnt = root->req();
3181 Node *n = root;
3182 uint i = 0;
3183 while (true) {
3184 if (i < cnt) {
3185 // Place all non-visited non-null inputs onto stack
3186 Node* m = n->in(i);
3187 ++i;
3188 if (m != NULL && !frc._visited.test_set(m->_idx)) {
3189 if (m->is_SafePoint() && m->as_SafePoint()->jvms() != NULL) {
3190 // compute worst case interpreter size in case of a deoptimization
3191 update_interpreter_frame_size(m->as_SafePoint()->jvms()->interpreter_frame_size());
3193 sfpt.push(m);
3194 }
3195 cnt = m->req();
3196 nstack.push(n, i); // put on stack parent and next input's index
3197 n = m;
3198 i = 0;
3199 }
3200 } else {
3201 // Now do post-visit work
3202 final_graph_reshaping_impl( n, frc );
3203 if (nstack.is_empty())
3204 break; // finished
3205 n = nstack.node(); // Get node from stack
3206 cnt = n->req();
3207 i = nstack.index();
3208 nstack.pop(); // Shift to the next node on stack
3209 }
3210 }
3212 // Skip next transformation if compressed oops are not used.
3213 if ((UseCompressedOops && !Matcher::gen_narrow_oop_implicit_null_checks()) ||
3214 (!UseCompressedOops && !UseCompressedClassPointers))
3215 return;
3217 // Go over safepoints nodes to skip DecodeN/DecodeNKlass nodes for debug edges.
3218 // It could be done for an uncommon traps or any safepoints/calls
3219 // if the DecodeN/DecodeNKlass node is referenced only in a debug info.
3220 while (sfpt.size() > 0) {
3221 n = sfpt.pop();
3222 JVMState *jvms = n->as_SafePoint()->jvms();
3223 assert(jvms != NULL, "sanity");
3224 int start = jvms->debug_start();
3225 int end = n->req();
3226 bool is_uncommon = (n->is_CallStaticJava() &&
3227 n->as_CallStaticJava()->uncommon_trap_request() != 0);
3228 for (int j = start; j < end; j++) {
3229 Node* in = n->in(j);
3230 if (in->is_DecodeNarrowPtr()) {
3231 bool safe_to_skip = true;
3232 if (!is_uncommon ) {
3233 // Is it safe to skip?
3234 for (uint i = 0; i < in->outcnt(); i++) {
3235 Node* u = in->raw_out(i);
3236 if (!u->is_SafePoint() ||
3237 u->is_Call() && u->as_Call()->has_non_debug_use(n)) {
3238 safe_to_skip = false;
3239 }
3240 }
3241 }
3242 if (safe_to_skip) {
3243 n->set_req(j, in->in(1));
3244 }
3245 if (in->outcnt() == 0) {
3246 in->disconnect_inputs(NULL, this);
3247 }
3248 }
3249 }
3250 }
3251 }
3253 //------------------------------final_graph_reshaping--------------------------
3254 // Final Graph Reshaping.
3255 //
3256 // (1) Clone simple inputs to uncommon calls, so they can be scheduled late
3257 // and not commoned up and forced early. Must come after regular
3258 // optimizations to avoid GVN undoing the cloning. Clone constant
3259 // inputs to Loop Phis; these will be split by the allocator anyways.
3260 // Remove Opaque nodes.
3261 // (2) Move last-uses by commutative operations to the left input to encourage
3262 // Intel update-in-place two-address operations and better register usage
3263 // on RISCs. Must come after regular optimizations to avoid GVN Ideal
3264 // calls canonicalizing them back.
3265 // (3) Count the number of double-precision FP ops, single-precision FP ops
3266 // and call sites. On Intel, we can get correct rounding either by
3267 // forcing singles to memory (requires extra stores and loads after each
3268 // FP bytecode) or we can set a rounding mode bit (requires setting and
3269 // clearing the mode bit around call sites). The mode bit is only used
3270 // if the relative frequency of single FP ops to calls is low enough.
3271 // This is a key transform for SPEC mpeg_audio.
3272 // (4) Detect infinite loops; blobs of code reachable from above but not
3273 // below. Several of the Code_Gen algorithms fail on such code shapes,
3274 // so we simply bail out. Happens a lot in ZKM.jar, but also happens
3275 // from time to time in other codes (such as -Xcomp finalizer loops, etc).
3276 // Detection is by looking for IfNodes where only 1 projection is
3277 // reachable from below or CatchNodes missing some targets.
3278 // (5) Assert for insane oop offsets in debug mode.
3280 bool Compile::final_graph_reshaping() {
3281 // an infinite loop may have been eliminated by the optimizer,
3282 // in which case the graph will be empty.
3283 if (root()->req() == 1) {
3284 record_method_not_compilable("trivial infinite loop");
3285 return true;
3286 }
3288 // Expensive nodes have their control input set to prevent the GVN
3289 // from freely commoning them. There's no GVN beyond this point so
3290 // no need to keep the control input. We want the expensive nodes to
3291 // be freely moved to the least frequent code path by gcm.
3292 assert(OptimizeExpensiveOps || expensive_count() == 0, "optimization off but list non empty?");
3293 for (int i = 0; i < expensive_count(); i++) {
3294 _expensive_nodes->at(i)->set_req(0, NULL);
3295 }
3297 Final_Reshape_Counts frc;
3299 // Visit everybody reachable!
3300 // Allocate stack of size C->live_nodes()/2 to avoid frequent realloc
3301 Node_Stack nstack(live_nodes() >> 1);
3302 final_graph_reshaping_walk(nstack, root(), frc);
3304 // Check for unreachable (from below) code (i.e., infinite loops).
3305 for( uint i = 0; i < frc._tests.size(); i++ ) {
3306 MultiBranchNode *n = frc._tests[i]->as_MultiBranch();
3307 // Get number of CFG targets.
3308 // Note that PCTables include exception targets after calls.
3309 uint required_outcnt = n->required_outcnt();
3310 if (n->outcnt() != required_outcnt) {
3311 // Check for a few special cases. Rethrow Nodes never take the
3312 // 'fall-thru' path, so expected kids is 1 less.
3313 if (n->is_PCTable() && n->in(0) && n->in(0)->in(0)) {
3314 if (n->in(0)->in(0)->is_Call()) {
3315 CallNode *call = n->in(0)->in(0)->as_Call();
3316 if (call->entry_point() == OptoRuntime::rethrow_stub()) {
3317 required_outcnt--; // Rethrow always has 1 less kid
3318 } else if (call->req() > TypeFunc::Parms &&
3319 call->is_CallDynamicJava()) {
3320 // Check for null receiver. In such case, the optimizer has
3321 // detected that the virtual call will always result in a null
3322 // pointer exception. The fall-through projection of this CatchNode
3323 // will not be populated.
3324 Node *arg0 = call->in(TypeFunc::Parms);
3325 if (arg0->is_Type() &&
3326 arg0->as_Type()->type()->higher_equal(TypePtr::NULL_PTR)) {
3327 required_outcnt--;
3328 }
3329 } else if (call->entry_point() == OptoRuntime::new_array_Java() &&
3330 call->req() > TypeFunc::Parms+1 &&
3331 call->is_CallStaticJava()) {
3332 // Check for negative array length. In such case, the optimizer has
3333 // detected that the allocation attempt will always result in an
3334 // exception. There is no fall-through projection of this CatchNode .
3335 Node *arg1 = call->in(TypeFunc::Parms+1);
3336 if (arg1->is_Type() &&
3337 arg1->as_Type()->type()->join(TypeInt::POS)->empty()) {
3338 required_outcnt--;
3339 }
3340 }
3341 }
3342 }
3343 // Recheck with a better notion of 'required_outcnt'
3344 if (n->outcnt() != required_outcnt) {
3345 record_method_not_compilable("malformed control flow");
3346 return true; // Not all targets reachable!
3347 }
3348 }
3349 // Check that I actually visited all kids. Unreached kids
3350 // must be infinite loops.
3351 for (DUIterator_Fast jmax, j = n->fast_outs(jmax); j < jmax; j++)
3352 if (!frc._visited.test(n->fast_out(j)->_idx)) {
3353 record_method_not_compilable("infinite loop");
3354 return true; // Found unvisited kid; must be unreach
3355 }
3356 }
3358 // If original bytecodes contained a mixture of floats and doubles
3359 // check if the optimizer has made it homogenous, item (3).
3360 if( Use24BitFPMode && Use24BitFP && UseSSE == 0 &&
3361 frc.get_float_count() > 32 &&
3362 frc.get_double_count() == 0 &&
3363 (10 * frc.get_call_count() < frc.get_float_count()) ) {
3364 set_24_bit_selection_and_mode( false, true );
3365 }
3367 set_java_calls(frc.get_java_call_count());
3368 set_inner_loops(frc.get_inner_loop_count());
3370 // No infinite loops, no reason to bail out.
3371 return false;
3372 }
3374 //-----------------------------too_many_traps----------------------------------
3375 // Report if there are too many traps at the current method and bci.
3376 // Return true if there was a trap, and/or PerMethodTrapLimit is exceeded.
3377 bool Compile::too_many_traps(ciMethod* method,
3378 int bci,
3379 Deoptimization::DeoptReason reason) {
3380 ciMethodData* md = method->method_data();
3381 if (md->is_empty()) {
3382 // Assume the trap has not occurred, or that it occurred only
3383 // because of a transient condition during start-up in the interpreter.
3384 return false;
3385 }
3386 ciMethod* m = Deoptimization::reason_is_speculate(reason) ? this->method() : NULL;
3387 if (md->has_trap_at(bci, m, reason) != 0) {
3388 // Assume PerBytecodeTrapLimit==0, for a more conservative heuristic.
3389 // Also, if there are multiple reasons, or if there is no per-BCI record,
3390 // assume the worst.
3391 if (log())
3392 log()->elem("observe trap='%s' count='%d'",
3393 Deoptimization::trap_reason_name(reason),
3394 md->trap_count(reason));
3395 return true;
3396 } else {
3397 // Ignore method/bci and see if there have been too many globally.
3398 return too_many_traps(reason, md);
3399 }
3400 }
3402 // Less-accurate variant which does not require a method and bci.
3403 bool Compile::too_many_traps(Deoptimization::DeoptReason reason,
3404 ciMethodData* logmd) {
3405 if (trap_count(reason) >= Deoptimization::per_method_trap_limit(reason)) {
3406 // Too many traps globally.
3407 // Note that we use cumulative trap_count, not just md->trap_count.
3408 if (log()) {
3409 int mcount = (logmd == NULL)? -1: (int)logmd->trap_count(reason);
3410 log()->elem("observe trap='%s' count='0' mcount='%d' ccount='%d'",
3411 Deoptimization::trap_reason_name(reason),
3412 mcount, trap_count(reason));
3413 }
3414 return true;
3415 } else {
3416 // The coast is clear.
3417 return false;
3418 }
3419 }
3421 //--------------------------too_many_recompiles--------------------------------
3422 // Report if there are too many recompiles at the current method and bci.
3423 // Consults PerBytecodeRecompilationCutoff and PerMethodRecompilationCutoff.
3424 // Is not eager to return true, since this will cause the compiler to use
3425 // Action_none for a trap point, to avoid too many recompilations.
3426 bool Compile::too_many_recompiles(ciMethod* method,
3427 int bci,
3428 Deoptimization::DeoptReason reason) {
3429 ciMethodData* md = method->method_data();
3430 if (md->is_empty()) {
3431 // Assume the trap has not occurred, or that it occurred only
3432 // because of a transient condition during start-up in the interpreter.
3433 return false;
3434 }
3435 // Pick a cutoff point well within PerBytecodeRecompilationCutoff.
3436 uint bc_cutoff = (uint) PerBytecodeRecompilationCutoff / 8;
3437 uint m_cutoff = (uint) PerMethodRecompilationCutoff / 2 + 1; // not zero
3438 Deoptimization::DeoptReason per_bc_reason
3439 = Deoptimization::reason_recorded_per_bytecode_if_any(reason);
3440 ciMethod* m = Deoptimization::reason_is_speculate(reason) ? this->method() : NULL;
3441 if ((per_bc_reason == Deoptimization::Reason_none
3442 || md->has_trap_at(bci, m, reason) != 0)
3443 // The trap frequency measure we care about is the recompile count:
3444 && md->trap_recompiled_at(bci, m)
3445 && md->overflow_recompile_count() >= bc_cutoff) {
3446 // Do not emit a trap here if it has already caused recompilations.
3447 // Also, if there are multiple reasons, or if there is no per-BCI record,
3448 // assume the worst.
3449 if (log())
3450 log()->elem("observe trap='%s recompiled' count='%d' recompiles2='%d'",
3451 Deoptimization::trap_reason_name(reason),
3452 md->trap_count(reason),
3453 md->overflow_recompile_count());
3454 return true;
3455 } else if (trap_count(reason) != 0
3456 && decompile_count() >= m_cutoff) {
3457 // Too many recompiles globally, and we have seen this sort of trap.
3458 // Use cumulative decompile_count, not just md->decompile_count.
3459 if (log())
3460 log()->elem("observe trap='%s' count='%d' mcount='%d' decompiles='%d' mdecompiles='%d'",
3461 Deoptimization::trap_reason_name(reason),
3462 md->trap_count(reason), trap_count(reason),
3463 md->decompile_count(), decompile_count());
3464 return true;
3465 } else {
3466 // The coast is clear.
3467 return false;
3468 }
3469 }
3471 // Compute when not to trap. Used by matching trap based nodes and
3472 // NullCheck optimization.
3473 void Compile::set_allowed_deopt_reasons() {
3474 _allowed_reasons = 0;
3475 if (is_method_compilation()) {
3476 for (int rs = (int)Deoptimization::Reason_none+1; rs < Compile::trapHistLength; rs++) {
3477 assert(rs < BitsPerInt, "recode bit map");
3478 if (!too_many_traps((Deoptimization::DeoptReason) rs)) {
3479 _allowed_reasons |= nth_bit(rs);
3480 }
3481 }
3482 }
3483 }
3485 #ifndef PRODUCT
3486 //------------------------------verify_graph_edges---------------------------
3487 // Walk the Graph and verify that there is a one-to-one correspondence
3488 // between Use-Def edges and Def-Use edges in the graph.
3489 void Compile::verify_graph_edges(bool no_dead_code) {
3490 if (VerifyGraphEdges) {
3491 ResourceArea *area = Thread::current()->resource_area();
3492 Unique_Node_List visited(area);
3493 // Call recursive graph walk to check edges
3494 _root->verify_edges(visited);
3495 if (no_dead_code) {
3496 // Now make sure that no visited node is used by an unvisited node.
3497 bool dead_nodes = false;
3498 Unique_Node_List checked(area);
3499 while (visited.size() > 0) {
3500 Node* n = visited.pop();
3501 checked.push(n);
3502 for (uint i = 0; i < n->outcnt(); i++) {
3503 Node* use = n->raw_out(i);
3504 if (checked.member(use)) continue; // already checked
3505 if (visited.member(use)) continue; // already in the graph
3506 if (use->is_Con()) continue; // a dead ConNode is OK
3507 // At this point, we have found a dead node which is DU-reachable.
3508 if (!dead_nodes) {
3509 tty->print_cr("*** Dead nodes reachable via DU edges:");
3510 dead_nodes = true;
3511 }
3512 use->dump(2);
3513 tty->print_cr("---");
3514 checked.push(use); // No repeats; pretend it is now checked.
3515 }
3516 }
3517 assert(!dead_nodes, "using nodes must be reachable from root");
3518 }
3519 }
3520 }
3522 // Verify GC barriers consistency
3523 // Currently supported:
3524 // - G1 pre-barriers (see GraphKit::g1_write_barrier_pre())
3525 void Compile::verify_barriers() {
3526 if (UseG1GC) {
3527 // Verify G1 pre-barriers
3528 const int marking_offset = in_bytes(JavaThread::satb_mark_queue_offset() + PtrQueue::byte_offset_of_active());
3530 ResourceArea *area = Thread::current()->resource_area();
3531 Unique_Node_List visited(area);
3532 Node_List worklist(area);
3533 // We're going to walk control flow backwards starting from the Root
3534 worklist.push(_root);
3535 while (worklist.size() > 0) {
3536 Node* x = worklist.pop();
3537 if (x == NULL || x == top()) continue;
3538 if (visited.member(x)) {
3539 continue;
3540 } else {
3541 visited.push(x);
3542 }
3544 if (x->is_Region()) {
3545 for (uint i = 1; i < x->req(); i++) {
3546 worklist.push(x->in(i));
3547 }
3548 } else {
3549 worklist.push(x->in(0));
3550 // We are looking for the pattern:
3551 // /->ThreadLocal
3552 // If->Bool->CmpI->LoadB->AddP->ConL(marking_offset)
3553 // \->ConI(0)
3554 // We want to verify that the If and the LoadB have the same control
3555 // See GraphKit::g1_write_barrier_pre()
3556 if (x->is_If()) {
3557 IfNode *iff = x->as_If();
3558 if (iff->in(1)->is_Bool() && iff->in(1)->in(1)->is_Cmp()) {
3559 CmpNode *cmp = iff->in(1)->in(1)->as_Cmp();
3560 if (cmp->Opcode() == Op_CmpI && cmp->in(2)->is_Con() && cmp->in(2)->bottom_type()->is_int()->get_con() == 0
3561 && cmp->in(1)->is_Load()) {
3562 LoadNode* load = cmp->in(1)->as_Load();
3563 if (load->Opcode() == Op_LoadB && load->in(2)->is_AddP() && load->in(2)->in(2)->Opcode() == Op_ThreadLocal
3564 && load->in(2)->in(3)->is_Con()
3565 && load->in(2)->in(3)->bottom_type()->is_intptr_t()->get_con() == marking_offset) {
3567 Node* if_ctrl = iff->in(0);
3568 Node* load_ctrl = load->in(0);
3570 if (if_ctrl != load_ctrl) {
3571 // Skip possible CProj->NeverBranch in infinite loops
3572 if ((if_ctrl->is_Proj() && if_ctrl->Opcode() == Op_CProj)
3573 && (if_ctrl->in(0)->is_MultiBranch() && if_ctrl->in(0)->Opcode() == Op_NeverBranch)) {
3574 if_ctrl = if_ctrl->in(0)->in(0);
3575 }
3576 }
3577 assert(load_ctrl != NULL && if_ctrl == load_ctrl, "controls must match");
3578 }
3579 }
3580 }
3581 }
3582 }
3583 }
3584 }
3585 }
3587 #endif
3589 // The Compile object keeps track of failure reasons separately from the ciEnv.
3590 // This is required because there is not quite a 1-1 relation between the
3591 // ciEnv and its compilation task and the Compile object. Note that one
3592 // ciEnv might use two Compile objects, if C2Compiler::compile_method decides
3593 // to backtrack and retry without subsuming loads. Other than this backtracking
3594 // behavior, the Compile's failure reason is quietly copied up to the ciEnv
3595 // by the logic in C2Compiler.
3596 void Compile::record_failure(const char* reason) {
3597 if (log() != NULL) {
3598 log()->elem("failure reason='%s' phase='compile'", reason);
3599 }
3600 if (_failure_reason == NULL) {
3601 // Record the first failure reason.
3602 _failure_reason = reason;
3603 }
3605 if (!C->failure_reason_is(C2Compiler::retry_no_subsuming_loads())) {
3606 C->print_method(PHASE_FAILURE);
3607 }
3608 _root = NULL; // flush the graph, too
3609 }
3611 Compile::TracePhase::TracePhase(const char* name, elapsedTimer* accumulator, bool dolog)
3612 : TraceTime(NULL, accumulator, false NOT_PRODUCT( || TimeCompiler ), false),
3613 _phase_name(name), _dolog(dolog)
3614 {
3615 if (dolog) {
3616 C = Compile::current();
3617 _log = C->log();
3618 } else {
3619 C = NULL;
3620 _log = NULL;
3621 }
3622 if (_log != NULL) {
3623 _log->begin_head("phase name='%s' nodes='%d' live='%d'", _phase_name, C->unique(), C->live_nodes());
3624 _log->stamp();
3625 _log->end_head();
3626 }
3627 }
3629 Compile::TracePhase::~TracePhase() {
3631 C = Compile::current();
3632 if (_dolog) {
3633 _log = C->log();
3634 } else {
3635 _log = NULL;
3636 }
3638 #ifdef ASSERT
3639 if (PrintIdealNodeCount) {
3640 tty->print_cr("phase name='%s' nodes='%d' live='%d' live_graph_walk='%d'",
3641 _phase_name, C->unique(), C->live_nodes(), C->count_live_nodes_by_graph_walk());
3642 }
3644 if (VerifyIdealNodeCount) {
3645 Compile::current()->print_missing_nodes();
3646 }
3647 #endif
3649 if (_log != NULL) {
3650 _log->done("phase name='%s' nodes='%d' live='%d'", _phase_name, C->unique(), C->live_nodes());
3651 }
3652 }
3654 //=============================================================================
3655 // Two Constant's are equal when the type and the value are equal.
3656 bool Compile::Constant::operator==(const Constant& other) {
3657 if (type() != other.type() ) return false;
3658 if (can_be_reused() != other.can_be_reused()) return false;
3659 // For floating point values we compare the bit pattern.
3660 switch (type()) {
3661 case T_FLOAT: return (_v._value.i == other._v._value.i);
3662 case T_LONG:
3663 case T_DOUBLE: return (_v._value.j == other._v._value.j);
3664 case T_OBJECT:
3665 case T_ADDRESS: return (_v._value.l == other._v._value.l);
3666 case T_VOID: return (_v._value.l == other._v._value.l); // jump-table entries
3667 case T_METADATA: return (_v._metadata == other._v._metadata);
3668 default: ShouldNotReachHere();
3669 }
3670 return false;
3671 }
3673 static int type_to_size_in_bytes(BasicType t) {
3674 switch (t) {
3675 case T_LONG: return sizeof(jlong );
3676 case T_FLOAT: return sizeof(jfloat );
3677 case T_DOUBLE: return sizeof(jdouble);
3678 case T_METADATA: return sizeof(Metadata*);
3679 // We use T_VOID as marker for jump-table entries (labels) which
3680 // need an internal word relocation.
3681 case T_VOID:
3682 case T_ADDRESS:
3683 case T_OBJECT: return sizeof(jobject);
3684 }
3686 ShouldNotReachHere();
3687 return -1;
3688 }
3690 int Compile::ConstantTable::qsort_comparator(Constant* a, Constant* b) {
3691 // sort descending
3692 if (a->freq() > b->freq()) return -1;
3693 if (a->freq() < b->freq()) return 1;
3694 return 0;
3695 }
3697 void Compile::ConstantTable::calculate_offsets_and_size() {
3698 // First, sort the array by frequencies.
3699 _constants.sort(qsort_comparator);
3701 #ifdef ASSERT
3702 // Make sure all jump-table entries were sorted to the end of the
3703 // array (they have a negative frequency).
3704 bool found_void = false;
3705 for (int i = 0; i < _constants.length(); i++) {
3706 Constant con = _constants.at(i);
3707 if (con.type() == T_VOID)
3708 found_void = true; // jump-tables
3709 else
3710 assert(!found_void, "wrong sorting");
3711 }
3712 #endif
3714 int offset = 0;
3715 for (int i = 0; i < _constants.length(); i++) {
3716 Constant* con = _constants.adr_at(i);
3718 // Align offset for type.
3719 int typesize = type_to_size_in_bytes(con->type());
3720 offset = align_size_up(offset, typesize);
3721 con->set_offset(offset); // set constant's offset
3723 if (con->type() == T_VOID) {
3724 MachConstantNode* n = (MachConstantNode*) con->get_jobject();
3725 offset = offset + typesize * n->outcnt(); // expand jump-table
3726 } else {
3727 offset = offset + typesize;
3728 }
3729 }
3731 // Align size up to the next section start (which is insts; see
3732 // CodeBuffer::align_at_start).
3733 assert(_size == -1, "already set?");
3734 _size = align_size_up(offset, CodeEntryAlignment);
3735 }
3737 void Compile::ConstantTable::emit(CodeBuffer& cb) {
3738 MacroAssembler _masm(&cb);
3739 for (int i = 0; i < _constants.length(); i++) {
3740 Constant con = _constants.at(i);
3741 address constant_addr = NULL;
3742 switch (con.type()) {
3743 case T_LONG: constant_addr = _masm.long_constant( con.get_jlong() ); break;
3744 case T_FLOAT: constant_addr = _masm.float_constant( con.get_jfloat() ); break;
3745 case T_DOUBLE: constant_addr = _masm.double_constant(con.get_jdouble()); break;
3746 case T_OBJECT: {
3747 jobject obj = con.get_jobject();
3748 int oop_index = _masm.oop_recorder()->find_index(obj);
3749 constant_addr = _masm.address_constant((address) obj, oop_Relocation::spec(oop_index));
3750 break;
3751 }
3752 case T_ADDRESS: {
3753 address addr = (address) con.get_jobject();
3754 constant_addr = _masm.address_constant(addr);
3755 break;
3756 }
3757 // We use T_VOID as marker for jump-table entries (labels) which
3758 // need an internal word relocation.
3759 case T_VOID: {
3760 MachConstantNode* n = (MachConstantNode*) con.get_jobject();
3761 // Fill the jump-table with a dummy word. The real value is
3762 // filled in later in fill_jump_table.
3763 address dummy = (address) n;
3764 constant_addr = _masm.address_constant(dummy);
3765 // Expand jump-table
3766 for (uint i = 1; i < n->outcnt(); i++) {
3767 address temp_addr = _masm.address_constant(dummy + i);
3768 assert(temp_addr, "consts section too small");
3769 }
3770 break;
3771 }
3772 case T_METADATA: {
3773 Metadata* obj = con.get_metadata();
3774 int metadata_index = _masm.oop_recorder()->find_index(obj);
3775 constant_addr = _masm.address_constant((address) obj, metadata_Relocation::spec(metadata_index));
3776 break;
3777 }
3778 default: ShouldNotReachHere();
3779 }
3780 assert(constant_addr, "consts section too small");
3781 assert((constant_addr - _masm.code()->consts()->start()) == con.offset(),
3782 err_msg_res("must be: %d == %d", (int) (constant_addr - _masm.code()->consts()->start()), (int)(con.offset())));
3783 }
3784 }
3786 int Compile::ConstantTable::find_offset(Constant& con) const {
3787 int idx = _constants.find(con);
3788 assert(idx != -1, "constant must be in constant table");
3789 int offset = _constants.at(idx).offset();
3790 assert(offset != -1, "constant table not emitted yet?");
3791 return offset;
3792 }
3794 void Compile::ConstantTable::add(Constant& con) {
3795 if (con.can_be_reused()) {
3796 int idx = _constants.find(con);
3797 if (idx != -1 && _constants.at(idx).can_be_reused()) {
3798 _constants.adr_at(idx)->inc_freq(con.freq()); // increase the frequency by the current value
3799 return;
3800 }
3801 }
3802 (void) _constants.append(con);
3803 }
3805 Compile::Constant Compile::ConstantTable::add(MachConstantNode* n, BasicType type, jvalue value) {
3806 Block* b = Compile::current()->cfg()->get_block_for_node(n);
3807 Constant con(type, value, b->_freq);
3808 add(con);
3809 return con;
3810 }
3812 Compile::Constant Compile::ConstantTable::add(Metadata* metadata) {
3813 Constant con(metadata);
3814 add(con);
3815 return con;
3816 }
3818 Compile::Constant Compile::ConstantTable::add(MachConstantNode* n, MachOper* oper) {
3819 jvalue value;
3820 BasicType type = oper->type()->basic_type();
3821 switch (type) {
3822 case T_LONG: value.j = oper->constantL(); break;
3823 case T_FLOAT: value.f = oper->constantF(); break;
3824 case T_DOUBLE: value.d = oper->constantD(); break;
3825 case T_OBJECT:
3826 case T_ADDRESS: value.l = (jobject) oper->constant(); break;
3827 case T_METADATA: return add((Metadata*)oper->constant()); break;
3828 default: guarantee(false, err_msg_res("unhandled type: %s", type2name(type)));
3829 }
3830 return add(n, type, value);
3831 }
3833 Compile::Constant Compile::ConstantTable::add_jump_table(MachConstantNode* n) {
3834 jvalue value;
3835 // We can use the node pointer here to identify the right jump-table
3836 // as this method is called from Compile::Fill_buffer right before
3837 // the MachNodes are emitted and the jump-table is filled (means the
3838 // MachNode pointers do not change anymore).
3839 value.l = (jobject) n;
3840 Constant con(T_VOID, value, next_jump_table_freq(), false); // Labels of a jump-table cannot be reused.
3841 add(con);
3842 return con;
3843 }
3845 void Compile::ConstantTable::fill_jump_table(CodeBuffer& cb, MachConstantNode* n, GrowableArray<Label*> labels) const {
3846 // If called from Compile::scratch_emit_size do nothing.
3847 if (Compile::current()->in_scratch_emit_size()) return;
3849 assert(labels.is_nonempty(), "must be");
3850 assert((uint) labels.length() == n->outcnt(), err_msg_res("must be equal: %d == %d", labels.length(), n->outcnt()));
3852 // Since MachConstantNode::constant_offset() also contains
3853 // table_base_offset() we need to subtract the table_base_offset()
3854 // to get the plain offset into the constant table.
3855 int offset = n->constant_offset() - table_base_offset();
3857 MacroAssembler _masm(&cb);
3858 address* jump_table_base = (address*) (_masm.code()->consts()->start() + offset);
3860 for (uint i = 0; i < n->outcnt(); i++) {
3861 address* constant_addr = &jump_table_base[i];
3862 assert(*constant_addr == (((address) n) + i), err_msg_res("all jump-table entries must contain adjusted node pointer: " INTPTR_FORMAT " == " INTPTR_FORMAT, p2i(*constant_addr), p2i(((address) n) + i)));
3863 *constant_addr = cb.consts()->target(*labels.at(i), (address) constant_addr);
3864 cb.consts()->relocate((address) constant_addr, relocInfo::internal_word_type);
3865 }
3866 }
3868 void Compile::dump_inlining() {
3869 if (print_inlining() || print_intrinsics()) {
3870 // Print inlining message for candidates that we couldn't inline
3871 // for lack of space or non constant receiver
3872 for (int i = 0; i < _late_inlines.length(); i++) {
3873 CallGenerator* cg = _late_inlines.at(i);
3874 cg->print_inlining_late("live nodes > LiveNodeCountInliningCutoff");
3875 }
3876 Unique_Node_List useful;
3877 useful.push(root());
3878 for (uint next = 0; next < useful.size(); ++next) {
3879 Node* n = useful.at(next);
3880 if (n->is_Call() && n->as_Call()->generator() != NULL && n->as_Call()->generator()->call_node() == n) {
3881 CallNode* call = n->as_Call();
3882 CallGenerator* cg = call->generator();
3883 cg->print_inlining_late("receiver not constant");
3884 }
3885 uint max = n->len();
3886 for ( uint i = 0; i < max; ++i ) {
3887 Node *m = n->in(i);
3888 if ( m == NULL ) continue;
3889 useful.push(m);
3890 }
3891 }
3892 for (int i = 0; i < _print_inlining_list->length(); i++) {
3893 tty->print("%s", _print_inlining_list->adr_at(i)->ss()->as_string());
3894 }
3895 }
3896 }
3898 // Dump inlining replay data to the stream.
3899 // Don't change thread state and acquire any locks.
3900 void Compile::dump_inline_data(outputStream* out) {
3901 InlineTree* inl_tree = ilt();
3902 if (inl_tree != NULL) {
3903 out->print(" inline %d", inl_tree->count());
3904 inl_tree->dump_replay_data(out);
3905 }
3906 }
3908 int Compile::cmp_expensive_nodes(Node* n1, Node* n2) {
3909 if (n1->Opcode() < n2->Opcode()) return -1;
3910 else if (n1->Opcode() > n2->Opcode()) return 1;
3912 assert(n1->req() == n2->req(), err_msg_res("can't compare %s nodes: n1->req() = %d, n2->req() = %d", NodeClassNames[n1->Opcode()], n1->req(), n2->req()));
3913 for (uint i = 1; i < n1->req(); i++) {
3914 if (n1->in(i) < n2->in(i)) return -1;
3915 else if (n1->in(i) > n2->in(i)) return 1;
3916 }
3918 return 0;
3919 }
3921 int Compile::cmp_expensive_nodes(Node** n1p, Node** n2p) {
3922 Node* n1 = *n1p;
3923 Node* n2 = *n2p;
3925 return cmp_expensive_nodes(n1, n2);
3926 }
3928 void Compile::sort_expensive_nodes() {
3929 if (!expensive_nodes_sorted()) {
3930 _expensive_nodes->sort(cmp_expensive_nodes);
3931 }
3932 }
3934 bool Compile::expensive_nodes_sorted() const {
3935 for (int i = 1; i < _expensive_nodes->length(); i++) {
3936 if (cmp_expensive_nodes(_expensive_nodes->adr_at(i), _expensive_nodes->adr_at(i-1)) < 0) {
3937 return false;
3938 }
3939 }
3940 return true;
3941 }
3943 bool Compile::should_optimize_expensive_nodes(PhaseIterGVN &igvn) {
3944 if (_expensive_nodes->length() == 0) {
3945 return false;
3946 }
3948 assert(OptimizeExpensiveOps, "optimization off?");
3950 // Take this opportunity to remove dead nodes from the list
3951 int j = 0;
3952 for (int i = 0; i < _expensive_nodes->length(); i++) {
3953 Node* n = _expensive_nodes->at(i);
3954 if (!n->is_unreachable(igvn)) {
3955 assert(n->is_expensive(), "should be expensive");
3956 _expensive_nodes->at_put(j, n);
3957 j++;
3958 }
3959 }
3960 _expensive_nodes->trunc_to(j);
3962 // Then sort the list so that similar nodes are next to each other
3963 // and check for at least two nodes of identical kind with same data
3964 // inputs.
3965 sort_expensive_nodes();
3967 for (int i = 0; i < _expensive_nodes->length()-1; i++) {
3968 if (cmp_expensive_nodes(_expensive_nodes->adr_at(i), _expensive_nodes->adr_at(i+1)) == 0) {
3969 return true;
3970 }
3971 }
3973 return false;
3974 }
3976 void Compile::cleanup_expensive_nodes(PhaseIterGVN &igvn) {
3977 if (_expensive_nodes->length() == 0) {
3978 return;
3979 }
3981 assert(OptimizeExpensiveOps, "optimization off?");
3983 // Sort to bring similar nodes next to each other and clear the
3984 // control input of nodes for which there's only a single copy.
3985 sort_expensive_nodes();
3987 int j = 0;
3988 int identical = 0;
3989 int i = 0;
3990 for (; i < _expensive_nodes->length()-1; i++) {
3991 assert(j <= i, "can't write beyond current index");
3992 if (_expensive_nodes->at(i)->Opcode() == _expensive_nodes->at(i+1)->Opcode()) {
3993 identical++;
3994 _expensive_nodes->at_put(j++, _expensive_nodes->at(i));
3995 continue;
3996 }
3997 if (identical > 0) {
3998 _expensive_nodes->at_put(j++, _expensive_nodes->at(i));
3999 identical = 0;
4000 } else {
4001 Node* n = _expensive_nodes->at(i);
4002 igvn.hash_delete(n);
4003 n->set_req(0, NULL);
4004 igvn.hash_insert(n);
4005 }
4006 }
4007 if (identical > 0) {
4008 _expensive_nodes->at_put(j++, _expensive_nodes->at(i));
4009 } else if (_expensive_nodes->length() >= 1) {
4010 Node* n = _expensive_nodes->at(i);
4011 igvn.hash_delete(n);
4012 n->set_req(0, NULL);
4013 igvn.hash_insert(n);
4014 }
4015 _expensive_nodes->trunc_to(j);
4016 }
4018 void Compile::add_expensive_node(Node * n) {
4019 assert(!_expensive_nodes->contains(n), "duplicate entry in expensive list");
4020 assert(n->is_expensive(), "expensive nodes with non-null control here only");
4021 assert(!n->is_CFG() && !n->is_Mem(), "no cfg or memory nodes here");
4022 if (OptimizeExpensiveOps) {
4023 _expensive_nodes->append(n);
4024 } else {
4025 // Clear control input and let IGVN optimize expensive nodes if
4026 // OptimizeExpensiveOps is off.
4027 n->set_req(0, NULL);
4028 }
4029 }
4031 /**
4032 * Remove the speculative part of types and clean up the graph
4033 */
4034 void Compile::remove_speculative_types(PhaseIterGVN &igvn) {
4035 if (UseTypeSpeculation) {
4036 Unique_Node_List worklist;
4037 worklist.push(root());
4038 int modified = 0;
4039 // Go over all type nodes that carry a speculative type, drop the
4040 // speculative part of the type and enqueue the node for an igvn
4041 // which may optimize it out.
4042 for (uint next = 0; next < worklist.size(); ++next) {
4043 Node *n = worklist.at(next);
4044 if (n->is_Type()) {
4045 TypeNode* tn = n->as_Type();
4046 const Type* t = tn->type();
4047 const Type* t_no_spec = t->remove_speculative();
4048 if (t_no_spec != t) {
4049 bool in_hash = igvn.hash_delete(n);
4050 assert(in_hash, "node should be in igvn hash table");
4051 tn->set_type(t_no_spec);
4052 igvn.hash_insert(n);
4053 igvn._worklist.push(n); // give it a chance to go away
4054 modified++;
4055 }
4056 }
4057 uint max = n->len();
4058 for( uint i = 0; i < max; ++i ) {
4059 Node *m = n->in(i);
4060 if (not_a_node(m)) continue;
4061 worklist.push(m);
4062 }
4063 }
4064 // Drop the speculative part of all types in the igvn's type table
4065 igvn.remove_speculative_types();
4066 if (modified > 0) {
4067 igvn.optimize();
4068 }
4069 #ifdef ASSERT
4070 // Verify that after the IGVN is over no speculative type has resurfaced
4071 worklist.clear();
4072 worklist.push(root());
4073 for (uint next = 0; next < worklist.size(); ++next) {
4074 Node *n = worklist.at(next);
4075 const Type* t = igvn.type_or_null(n);
4076 assert((t == NULL) || (t == t->remove_speculative()), "no more speculative types");
4077 if (n->is_Type()) {
4078 t = n->as_Type()->type();
4079 assert(t == t->remove_speculative(), "no more speculative types");
4080 }
4081 uint max = n->len();
4082 for( uint i = 0; i < max; ++i ) {
4083 Node *m = n->in(i);
4084 if (not_a_node(m)) continue;
4085 worklist.push(m);
4086 }
4087 }
4088 igvn.check_no_speculative_types();
4089 #endif
4090 }
4091 }
4093 // Convert integer value to a narrowed long type dependent on ctrl (for example, a range check)
4094 Node* Compile::constrained_convI2L(PhaseGVN* phase, Node* value, const TypeInt* itype, Node* ctrl) {
4095 if (ctrl != NULL) {
4096 // Express control dependency by a CastII node with a narrow type.
4097 value = new (phase->C) CastIINode(value, itype, false, true /* range check dependency */);
4098 // Make the CastII node dependent on the control input to prevent the narrowed ConvI2L
4099 // node from floating above the range check during loop optimizations. Otherwise, the
4100 // ConvI2L node may be eliminated independently of the range check, causing the data path
4101 // to become TOP while the control path is still there (although it's unreachable).
4102 value->set_req(0, ctrl);
4103 // Save CastII node to remove it after loop optimizations.
4104 phase->C->add_range_check_cast(value);
4105 value = phase->transform(value);
4106 }
4107 const TypeLong* ltype = TypeLong::make(itype->_lo, itype->_hi, itype->_widen);
4108 return phase->transform(new (phase->C) ConvI2LNode(value, ltype));
4109 }
4111 // Auxiliary method to support randomized stressing/fuzzing.
4112 //
4113 // This method can be called the arbitrary number of times, with current count
4114 // as the argument. The logic allows selecting a single candidate from the
4115 // running list of candidates as follows:
4116 // int count = 0;
4117 // Cand* selected = null;
4118 // while(cand = cand->next()) {
4119 // if (randomized_select(++count)) {
4120 // selected = cand;
4121 // }
4122 // }
4123 //
4124 // Including count equalizes the chances any candidate is "selected".
4125 // This is useful when we don't have the complete list of candidates to choose
4126 // from uniformly. In this case, we need to adjust the randomicity of the
4127 // selection, or else we will end up biasing the selection towards the latter
4128 // candidates.
4129 //
4130 // Quick back-envelope calculation shows that for the list of n candidates
4131 // the equal probability for the candidate to persist as "best" can be
4132 // achieved by replacing it with "next" k-th candidate with the probability
4133 // of 1/k. It can be easily shown that by the end of the run, the
4134 // probability for any candidate is converged to 1/n, thus giving the
4135 // uniform distribution among all the candidates.
4136 //
4137 // We don't care about the domain size as long as (RANDOMIZED_DOMAIN / count) is large.
4138 #define RANDOMIZED_DOMAIN_POW 29
4139 #define RANDOMIZED_DOMAIN (1 << RANDOMIZED_DOMAIN_POW)
4140 #define RANDOMIZED_DOMAIN_MASK ((1 << (RANDOMIZED_DOMAIN_POW + 1)) - 1)
4141 bool Compile::randomized_select(int count) {
4142 assert(count > 0, "only positive");
4143 return (os::random() & RANDOMIZED_DOMAIN_MASK) < (RANDOMIZED_DOMAIN / count);
4144 }