1 #ifdef USE_PRAGMA_IDENT_SRC
2 #pragma ident "@(#)macro.cpp 1.33 07/10/04 14:36:00 JVM"
3 #endif
4 /*
5 * Copyright 2005-2007 Sun Microsystems, Inc. All Rights Reserved.
6 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
7 *
8 * This code is free software; you can redistribute it and/or modify it
9 * under the terms of the GNU General Public License version 2 only, as
10 * published by the Free Software Foundation.
11 *
12 * This code is distributed in the hope that it will be useful, but WITHOUT
13 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
15 * version 2 for more details (a copy is included in the LICENSE file that
16 * accompanied this code).
17 *
18 * You should have received a copy of the GNU General Public License version
19 * 2 along with this work; if not, write to the Free Software Foundation,
20 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
21 *
22 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
23 * CA 95054 USA or visit www.sun.com if you need additional information or
24 * have any questions.
25 *
40 Node *uin = use->in(j);
41 if (uin == oldref) {
42 if (j < req)
43 use->set_req(j, newref);
44 else
45 use->set_prec(j, newref);
46 nreplacements++;
47 } else if (j >= req && uin == NULL) {
48 break;
49 }
50 }
51 return nreplacements;
52 }
53
54 void PhaseMacroExpand::copy_call_debug_info(CallNode *oldcall, CallNode * newcall) {
55 // Copy debug information and adjust JVMState information
56 uint old_dbg_start = oldcall->tf()->domain()->cnt();
57 uint new_dbg_start = newcall->tf()->domain()->cnt();
58 int jvms_adj = new_dbg_start - old_dbg_start;
59 assert (new_dbg_start == newcall->req(), "argument count mismatch");
60 for (uint i = old_dbg_start; i < oldcall->req(); i++) {
61 newcall->add_req(oldcall->in(i));
62 }
63 newcall->set_jvms(oldcall->jvms());
64 for (JVMState *jvms = newcall->jvms(); jvms != NULL; jvms = jvms->caller()) {
65 jvms->set_map(newcall);
66 jvms->set_locoff(jvms->locoff()+jvms_adj);
67 jvms->set_stkoff(jvms->stkoff()+jvms_adj);
68 jvms->set_monoff(jvms->monoff()+jvms_adj);
69 jvms->set_endoff(jvms->endoff()+jvms_adj);
70 }
71 }
72
73 Node* PhaseMacroExpand::opt_iff(Node* region, Node* iff) {
74 IfNode *opt_iff = transform_later(iff)->as_If();
75
76 // Fast path taken; set region slot 2
77 Node *fast_taken = transform_later( new (C, 1) IfFalseNode(opt_iff) );
78 region->init_req(2,fast_taken); // Capture fast-control
79
80 // Fast path not-taken, i.e. slow path
81 Node *slow_taken = transform_later( new (C, 1) IfTrueNode(opt_iff) );
82 return slow_taken;
83 }
84
85 //--------------------copy_predefined_input_for_runtime_call--------------------
86 void PhaseMacroExpand::copy_predefined_input_for_runtime_call(Node * ctrl, CallNode* oldcall, CallNode* call) {
87 // Set fixed predefined input arguments
88 call->init_req( TypeFunc::Control, ctrl );
89 call->init_req( TypeFunc::I_O , oldcall->in( TypeFunc::I_O) );
90 call->init_req( TypeFunc::Memory , oldcall->in( TypeFunc::Memory ) ); // ?????
91 call->init_req( TypeFunc::ReturnAdr, oldcall->in( TypeFunc::ReturnAdr ) );
92 call->init_req( TypeFunc::FramePtr, oldcall->in( TypeFunc::FramePtr ) );
93 }
94
95 //------------------------------make_slow_call---------------------------------
96 CallNode* PhaseMacroExpand::make_slow_call(CallNode *oldcall, const TypeFunc* slow_call_type, address slow_call, const char* leaf_name, Node* slow_path, Node* parm0, Node* parm1) {
97
98 // Slow-path call
99 int size = slow_call_type->domain()->cnt();
100 CallNode *call = leaf_name
101 ? (CallNode*)new (C, size) CallLeafNode ( slow_call_type, slow_call, leaf_name, TypeRawPtr::BOTTOM )
102 : (CallNode*)new (C, size) CallStaticJavaNode( slow_call_type, slow_call, OptoRuntime::stub_name(slow_call), oldcall->jvms()->bci(), TypeRawPtr::BOTTOM );
152 _ioproj_catchall = pn;
153 else
154 _ioproj_fallthrough = pn;
155 break;
156 case TypeFunc::Memory:
157 if (pn->_is_io_use)
158 _memproj_catchall = pn;
159 else
160 _memproj_fallthrough = pn;
161 break;
162 case TypeFunc::Parms:
163 _resproj = pn;
164 break;
165 default:
166 assert(false, "unexpected projection from allocation node.");
167 }
168 }
169
170 }
171
172
173 //---------------------------set_eden_pointers-------------------------
174 void PhaseMacroExpand::set_eden_pointers(Node* &eden_top_adr, Node* &eden_end_adr) {
175 if (UseTLAB) { // Private allocation: load from TLS
176 Node* thread = transform_later(new (C, 1) ThreadLocalNode());
177 int tlab_top_offset = in_bytes(JavaThread::tlab_top_offset());
178 int tlab_end_offset = in_bytes(JavaThread::tlab_end_offset());
179 eden_top_adr = basic_plus_adr(top()/*not oop*/, thread, tlab_top_offset);
180 eden_end_adr = basic_plus_adr(top()/*not oop*/, thread, tlab_end_offset);
181 } else { // Shared allocation: load from globals
182 CollectedHeap* ch = Universe::heap();
183 address top_adr = (address)ch->top_addr();
184 address end_adr = (address)ch->end_addr();
185 eden_top_adr = makecon(TypeRawPtr::make(top_adr));
186 eden_end_adr = basic_plus_adr(eden_top_adr, end_adr - top_adr);
187 }
188 }
189
190
191 Node* PhaseMacroExpand::make_load(Node* ctl, Node* mem, Node* base, int offset, const Type* value_type, BasicType bt) {
192 Node* adr = basic_plus_adr(base, offset);
193 const TypePtr* adr_type = TypeRawPtr::BOTTOM;
194 Node* value = LoadNode::make(C, ctl, mem, adr, adr_type, value_type, bt);
195 transform_later(value);
196 return value;
197 }
198
199
200 Node* PhaseMacroExpand::make_store(Node* ctl, Node* mem, Node* base, int offset, Node* value, BasicType bt) {
201 Node* adr = basic_plus_adr(base, offset);
202 mem = StoreNode::make(C, ctl, mem, adr, NULL, value, bt);
203 transform_later(mem);
204 return mem;
205 }
206
207 //=============================================================================
208 //
209 // A L L O C A T I O N
210 //
211 // Allocation attempts to be fast in the case of frequent small objects.
212 // It breaks down like this:
213 //
214 // 1) Size in doublewords is computed. This is a constant for objects and
215 // variable for most arrays. Doubleword units are used to avoid size
216 // overflow of huge doubleword arrays. We need doublewords in the end for
217 // rounding.
218 //
219 // 2) Size is checked for being 'too large'. Too-large allocations will go
220 // the slow path into the VM. The slow path can throw any required
221 // exceptions, and does all the special checks for very large arrays. The
222 // size test can constant-fold away for objects. For objects with
256 // code shape produced here, so if you are changing this code shape
257 // make sure the GC info for the heap-top is correct in and around the
258 // slow-path call.
259 //
260
261 void PhaseMacroExpand::expand_allocate_common(
262 AllocateNode* alloc, // allocation node to be expanded
263 Node* length, // array length for an array allocation
264 const TypeFunc* slow_call_type, // Type of slow call
265 address slow_call_address // Address of slow call
266 )
267 {
268
269 Node* ctrl = alloc->in(TypeFunc::Control);
270 Node* mem = alloc->in(TypeFunc::Memory);
271 Node* i_o = alloc->in(TypeFunc::I_O);
272 Node* size_in_bytes = alloc->in(AllocateNode::AllocSize);
273 Node* klass_node = alloc->in(AllocateNode::KlassNode);
274 Node* initial_slow_test = alloc->in(AllocateNode::InitialTest);
275
276 Node* eden_top_adr;
277 Node* eden_end_adr;
278 set_eden_pointers(eden_top_adr, eden_end_adr);
279
280 uint raw_idx = C->get_alias_index(TypeRawPtr::BOTTOM);
281 assert(ctrl != NULL, "must have control");
282
283 // Load Eden::end. Loop invariant and hoisted.
284 //
285 // Note: We set the control input on "eden_end" and "old_eden_top" when using
286 // a TLAB to work around a bug where these values were being moved across
287 // a safepoint. These are not oops, so they cannot be include in the oop
288 // map, but the can be changed by a GC. The proper way to fix this would
289 // be to set the raw memory state when generating a SafepointNode. However
290 // this will require extensive changes to the loop optimization in order to
291 // prevent a degradation of the optimization.
292 // See comment in memnode.hpp, around line 227 in class LoadPNode.
293 Node* eden_end = make_load(ctrl, mem, eden_end_adr, 0, TypeRawPtr::BOTTOM, T_ADDRESS);
294
295 // We need a Region and corresponding Phi's to merge the slow-path and fast-path results.
296 // they will not be used if "always_slow" is set
297 enum { slow_result_path = 1, fast_result_path = 2 };
298 Node *result_region;
299 Node *result_phi_rawmem;
300 Node *result_phi_rawoop;
301 Node *result_phi_i_o;
302
303 // The initial slow comparison is a size check, the comparison
304 // we want to do is a BoolTest::gt
305 bool always_slow = false;
306 int tv = _igvn.find_int_con(initial_slow_test, -1);
307 if (tv >= 0) {
308 always_slow = (tv == 1);
309 initial_slow_test = NULL;
310 } else {
311 initial_slow_test = BoolNode::make_predicate(initial_slow_test, &_igvn);
312 }
313
314 if (DTraceAllocProbes) {
315 // Force slow-path allocation
316 always_slow = true;
317 initial_slow_test = NULL;
318 }
319
320 enum { too_big_or_final_path = 1, need_gc_path = 2 };
321 Node *slow_region = NULL;
322 Node *toobig_false = ctrl;
323
324 assert (initial_slow_test == NULL || !always_slow, "arguments must be consistent");
325 // generate the initial test if necessary
326 if (initial_slow_test != NULL ) {
327 slow_region = new (C, 3) RegionNode(3);
328
329 // Now make the initial failure test. Usually a too-big test but
330 // might be a TRUE for finalizers or a fancy class check for
331 // newInstance0.
332 IfNode *toobig_iff = new (C, 2) IfNode(ctrl, initial_slow_test, PROB_MIN, COUNT_UNKNOWN);
333 transform_later(toobig_iff);
334 // Plug the failing-too-big test into the slow-path region
335 Node *toobig_true = new (C, 1) IfTrueNode( toobig_iff );
336 transform_later(toobig_true);
337 slow_region ->init_req( too_big_or_final_path, toobig_true );
338 toobig_false = new (C, 1) IfFalseNode( toobig_iff );
339 transform_later(toobig_false);
340 } else { // No initial test, just fall into next case
341 toobig_false = ctrl;
342 debug_only(slow_region = NodeSentinel);
343 }
344
345 Node *slow_mem = mem; // save the current memory state for slow path
346 // generate the fast allocation code unless we know that the initial test will always go slow
347 if (!always_slow) {
348 // allocate the Region and Phi nodes for the result
349 result_region = new (C, 3) RegionNode(3);
350 result_phi_rawmem = new (C, 3) PhiNode( result_region, Type::MEMORY, TypeRawPtr::BOTTOM );
351 result_phi_rawoop = new (C, 3) PhiNode( result_region, TypeRawPtr::BOTTOM );
352 result_phi_i_o = new (C, 3) PhiNode( result_region, Type::ABIO ); // I/O is used for Prefetch
353
354 // We need a Region for the loop-back contended case.
355 enum { fall_in_path = 1, contended_loopback_path = 2 };
356 Node *contended_region;
357 Node *contended_phi_rawmem;
358 if( UseTLAB ) {
359 contended_region = toobig_false;
360 contended_phi_rawmem = mem;
361 } else {
362 contended_region = new (C, 3) RegionNode(3);
363 contended_phi_rawmem = new (C, 3) PhiNode( contended_region, Type::MEMORY, TypeRawPtr::BOTTOM);
364 // Now handle the passing-too-big test. We fall into the contended
365 // loop-back merge point.
366 contended_region ->init_req( fall_in_path, toobig_false );
367 contended_phi_rawmem->init_req( fall_in_path, mem );
618 }
619
620
621 // Helper for PhaseMacroExpand::expand_allocate_common.
622 // Initializes the newly-allocated storage.
623 Node*
624 PhaseMacroExpand::initialize_object(AllocateNode* alloc,
625 Node* control, Node* rawmem, Node* object,
626 Node* klass_node, Node* length,
627 Node* size_in_bytes) {
628 InitializeNode* init = alloc->initialization();
629 // Store the klass & mark bits
630 Node* mark_node = NULL;
631 // For now only enable fast locking for non-array types
632 if (UseBiasedLocking && (length == NULL)) {
633 mark_node = make_load(NULL, rawmem, klass_node, Klass::prototype_header_offset_in_bytes() + sizeof(oopDesc), TypeRawPtr::BOTTOM, T_ADDRESS);
634 } else {
635 mark_node = makecon(TypeRawPtr::make((address)markOopDesc::prototype()));
636 }
637 rawmem = make_store(control, rawmem, object, oopDesc::mark_offset_in_bytes(), mark_node, T_ADDRESS);
638 rawmem = make_store(control, rawmem, object, oopDesc::klass_offset_in_bytes(), klass_node, T_OBJECT);
639 int header_size = alloc->minimum_header_size(); // conservatively small
640
641 // Array length
642 if (length != NULL) { // Arrays need length field
643 rawmem = make_store(control, rawmem, object, arrayOopDesc::length_offset_in_bytes(), length, T_INT);
644 // conservatively small header size:
645 header_size = sizeof(arrayOopDesc);
646 ciKlass* k = _igvn.type(klass_node)->is_klassptr()->klass();
647 if (k->is_array_klass()) // we know the exact header size in most cases:
648 header_size = Klass::layout_helper_header_size(k->layout_helper());
649 }
650
651 // Clear the object body, if necessary.
652 if (init == NULL) {
653 // The init has somehow disappeared; be cautious and clear everything.
654 //
655 // This can happen if a node is allocated but an uncommon trap occurs
656 // immediately. In this case, the Initialize gets associated with the
657 // trap, and may be placed in a different (outer) loop, if the Allocate
658 // is in a loop. If (this is rare) the inner loop gets unrolled, then
659 // there can be two Allocates to one Initialize. The answer in all these
660 // edge cases is safety first. It is always safe to clear immediately
661 // within an Allocate, and then (maybe or maybe not) clear some more later.
662 if (!ZeroTLAB)
663 rawmem = ClearArrayNode::clear_memory(control, rawmem, object,
664 header_size, size_in_bytes,
665 &_igvn);
666 } else {
667 if (!init->is_complete()) {
668 // Try to win by zeroing only what the init does not store.
669 // We can also try to do some peephole optimizations,
670 // such as combining some adjacent subword stores.
671 rawmem = init->complete_stores(control, rawmem, object,
672 header_size, size_in_bytes, &_igvn);
673 }
674
675 // We have no more use for this link, since the AllocateNode goes away:
676 init->set_req(InitializeNode::RawAddress, top());
677 // (If we keep the link, it just confuses the register allocator,
678 // who thinks he sees a real use of the address by the membar.)
679 }
680
681 return rawmem;
682 }
683
684 // Generate prefetch instructions for next allocations.
685 Node* PhaseMacroExpand::prefetch_allocation(Node* i_o, Node*& needgc_false,
686 Node*& contended_phi_rawmem,
687 Node* old_eden_top, Node* new_eden_top,
688 Node* length) {
689 if( UseTLAB && AllocatePrefetchStyle == 2 ) {
690 // Generate prefetch allocation with watermark check.
691 // As an allocation hits the watermark, we will prefetch starting
692 // at a "distance" away from watermark.
693 enum { fall_in_path = 1, pf_path = 2 };
694
799 void PhaseMacroExpand::expand_allocate(AllocateNode *alloc) {
800 expand_allocate_common(alloc, NULL,
801 OptoRuntime::new_instance_Type(),
802 OptoRuntime::new_instance_Java());
803 }
804
805 void PhaseMacroExpand::expand_allocate_array(AllocateArrayNode *alloc) {
806 Node* length = alloc->in(AllocateNode::ALength);
807 expand_allocate_common(alloc, length,
808 OptoRuntime::new_array_Type(),
809 OptoRuntime::new_array_Java());
810 }
811
812
813 // we have determined that this lock/unlock can be eliminated, we simply
814 // eliminate the node without expanding it.
815 //
816 // Note: The membar's associated with the lock/unlock are currently not
817 // eliminated. This should be investigated as a future enhancement.
818 //
819 void PhaseMacroExpand::eliminate_locking_node(AbstractLockNode *alock) {
820 Node* mem = alock->in(TypeFunc::Memory);
821
822 // The memory projection from a lock/unlock is RawMem
823 // The input to a Lock is merged memory, so extract its RawMem input
824 // (unless the MergeMem has been optimized away.)
825 if (alock->is_Lock()) {
826 if (mem->is_MergeMem())
827 mem = mem->as_MergeMem()->in(Compile::AliasIdxRaw);
828 }
829
830 extract_call_projections(alock);
831 // There are 2 projections from the lock. The lock node will
832 // be deleted when its last use is subsumed below.
833 assert(alock->outcnt() == 2 && _fallthroughproj != NULL &&
834 _memproj_fallthrough != NULL, "Unexpected projections from Lock/Unlock");
835 _igvn.hash_delete(_fallthroughproj);
836 _igvn.subsume_node(_fallthroughproj, alock->in(TypeFunc::Control));
837 _igvn.hash_delete(_memproj_fallthrough);
838 _igvn.subsume_node(_memproj_fallthrough, mem);
839 return;
840 }
841
842
843 //------------------------------expand_lock_node----------------------
844 void PhaseMacroExpand::expand_lock_node(LockNode *lock) {
845
846 Node* ctrl = lock->in(TypeFunc::Control);
847 Node* mem = lock->in(TypeFunc::Memory);
848 Node* obj = lock->obj_node();
849 Node* box = lock->box_node();
850 Node *flock = lock->fastlock_node();
851
852 if (lock->is_eliminated()) {
853 eliminate_locking_node(lock);
854 return;
855 }
856
857 // Make the merge point
858 Node *region = new (C, 3) RegionNode(3);
859
860 Node *bol = transform_later(new (C, 2) BoolNode(flock,BoolTest::ne));
861 Node *iff = new (C, 2) IfNode( ctrl, bol, PROB_MIN, COUNT_UNKNOWN );
862 // Optimize test; set region slot 2
863 Node *slow_path = opt_iff(region,iff);
864
865 // Make slow path call
866 CallNode *call = make_slow_call( (CallNode *) lock, OptoRuntime::complete_monitor_enter_Type(), OptoRuntime::complete_monitor_locking_Java(), NULL, slow_path, obj, box );
867
868 extract_call_projections(call);
869
870 // Slow path can only throw asynchronous exceptions, which are always
871 // de-opted. So the compiler thinks the slow-call can never throw an
872 // exception. If it DOES throw an exception we would need the debug
873 // info removed first (since if it throws there is no monitor).
874 assert ( _ioproj_fallthrough == NULL && _ioproj_catchall == NULL &&
875 _memproj_catchall == NULL && _catchallcatchproj == NULL, "Unexpected projection from Lock");
876
877 // Capture slow path
878 // disconnect fall-through projection from call and create a new one
879 // hook up users of fall-through projection to region
880 Node *slow_ctrl = _fallthroughproj->clone();
881 transform_later(slow_ctrl);
882 _igvn.hash_delete(_fallthroughproj);
883 _fallthroughproj->disconnect_inputs(NULL);
884 region->init_req(1, slow_ctrl);
885 // region inputs are now complete
886 transform_later(region);
887 _igvn.subsume_node(_fallthroughproj, region);
888
889 // create a Phi for the memory state
890 Node *mem_phi = new (C, 3) PhiNode( region, Type::MEMORY, TypeRawPtr::BOTTOM);
891 Node *memproj = transform_later( new (C, 1) ProjNode(call, TypeFunc::Memory) );
892 mem_phi->init_req(1, memproj );
893 mem_phi->init_req(2, mem);
894 transform_later(mem_phi);
895 _igvn.hash_delete(_memproj_fallthrough);
896 _igvn.subsume_node(_memproj_fallthrough, mem_phi);
897
898
899 }
900
901 //------------------------------expand_unlock_node----------------------
902 void PhaseMacroExpand::expand_unlock_node(UnlockNode *unlock) {
903
904 Node *ctrl = unlock->in(TypeFunc::Control);
905 Node* mem = unlock->in(TypeFunc::Memory);
906 Node* obj = unlock->obj_node();
907 Node* box = unlock->box_node();
908
909
910 if (unlock->is_eliminated()) {
911 eliminate_locking_node(unlock);
912 return;
913 }
914
915 // No need for a null check on unlock
916
917 // Make the merge point
918 RegionNode *region = new (C, 3) RegionNode(3);
919
920 FastUnlockNode *funlock = new (C, 3) FastUnlockNode( ctrl, obj, box );
921 funlock = transform_later( funlock )->as_FastUnlock();
922 Node *bol = transform_later(new (C, 2) BoolNode(funlock,BoolTest::ne));
923 Node *iff = new (C, 2) IfNode( ctrl, bol, PROB_MIN, COUNT_UNKNOWN );
924 // Optimize test; set region slot 2
925 Node *slow_path = opt_iff(region,iff);
926
927 CallNode *call = make_slow_call( (CallNode *) unlock, OptoRuntime::complete_monitor_exit_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::complete_monitor_unlocking_C), "complete_monitor_unlocking_C", slow_path, obj, box );
928
929 extract_call_projections(call);
930
931 assert ( _ioproj_fallthrough == NULL && _ioproj_catchall == NULL &&
932 _memproj_catchall == NULL && _catchallcatchproj == NULL, "Unexpected projection from Lock");
933
934 // No exceptions for unlocking
935 // Capture slow path
936 // disconnect fall-through projection from call and create a new one
937 // hook up users of fall-through projection to region
938 Node *slow_ctrl = _fallthroughproj->clone();
939 transform_later(slow_ctrl);
940 _igvn.hash_delete(_fallthroughproj);
941 _fallthroughproj->disconnect_inputs(NULL);
942 region->init_req(1, slow_ctrl);
943 // region inputs are now complete
944 transform_later(region);
945 _igvn.subsume_node(_fallthroughproj, region);
946
947 // create a Phi for the memory state
948 Node *mem_phi = new (C, 3) PhiNode( region, Type::MEMORY, TypeRawPtr::BOTTOM);
949 Node *memproj = transform_later( new(C, 1) ProjNode(call, TypeFunc::Memory) );
950 mem_phi->init_req(1, memproj );
951 mem_phi->init_req(2, mem);
952 transform_later(mem_phi);
953 _igvn.hash_delete(_memproj_fallthrough);
954 _igvn.subsume_node(_memproj_fallthrough, mem_phi);
955
956
957 }
958
959 //------------------------------expand_macro_nodes----------------------
960 // Returns true if a failure occurred.
961 bool PhaseMacroExpand::expand_macro_nodes() {
962 if (C->macro_count() == 0)
963 return false;
964 // Make sure expansion will not cause node limit to be exceeded. Worst case is a
965 // macro node gets expanded into about 50 nodes. Allow 50% more for optimization
966 if (C->check_node_count(C->macro_count() * 75, "out of nodes before macro expansion" ) )
967 return true;
968 // expand "macro" nodes
969 // nodes are removed from the macro list as they are processed
970 while (C->macro_count() > 0) {
971 Node * n = C->macro_node(0);
972 assert(n->is_macro(), "only macro nodes expected here");
973 if (_igvn.type(n) == Type::TOP || n->in(0)->is_top() ) {
974 // node is unreachable, so don't try to expand it
975 C->remove_macro_node(n);
976 continue;
977 }
978 switch (n->class_id()) {
979 case Node::Class_Allocate:
980 expand_allocate(n->as_Allocate());
981 break;
982 case Node::Class_AllocateArray:
983 expand_allocate_array(n->as_AllocateArray());
984 break;
985 case Node::Class_Lock:
986 expand_lock_node(n->as_Lock());
987 break;
988 case Node::Class_Unlock:
989 expand_unlock_node(n->as_Unlock());
990 break;
991 default:
992 assert(false, "unknown node type in macro list");
993 }
994 if (C->failing()) return true;
995 }
996 _igvn.optimize();
997 return false;
998 }
999
|
1 #ifdef USE_PRAGMA_IDENT_SRC
2 #pragma ident "@(#)macro.cpp 1.33 07/10/04 14:36:00 JVM"
3 #endif
4 /*
5 * Copyright 2005-2008 Sun Microsystems, Inc. All Rights Reserved.
6 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
7 *
8 * This code is free software; you can redistribute it and/or modify it
9 * under the terms of the GNU General Public License version 2 only, as
10 * published by the Free Software Foundation.
11 *
12 * This code is distributed in the hope that it will be useful, but WITHOUT
13 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
15 * version 2 for more details (a copy is included in the LICENSE file that
16 * accompanied this code).
17 *
18 * You should have received a copy of the GNU General Public License version
19 * 2 along with this work; if not, write to the Free Software Foundation,
20 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
21 *
22 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
23 * CA 95054 USA or visit www.sun.com if you need additional information or
24 * have any questions.
25 *
40 Node *uin = use->in(j);
41 if (uin == oldref) {
42 if (j < req)
43 use->set_req(j, newref);
44 else
45 use->set_prec(j, newref);
46 nreplacements++;
47 } else if (j >= req && uin == NULL) {
48 break;
49 }
50 }
51 return nreplacements;
52 }
53
54 void PhaseMacroExpand::copy_call_debug_info(CallNode *oldcall, CallNode * newcall) {
55 // Copy debug information and adjust JVMState information
56 uint old_dbg_start = oldcall->tf()->domain()->cnt();
57 uint new_dbg_start = newcall->tf()->domain()->cnt();
58 int jvms_adj = new_dbg_start - old_dbg_start;
59 assert (new_dbg_start == newcall->req(), "argument count mismatch");
60
61 Dict* sosn_map = new Dict(cmpkey,hashkey);
62 for (uint i = old_dbg_start; i < oldcall->req(); i++) {
63 Node* old_in = oldcall->in(i);
64 // Clone old SafePointScalarObjectNodes, adjusting their field contents.
65 if (old_in != NULL && old_in->is_SafePointScalarObject()) {
66 SafePointScalarObjectNode* old_sosn = old_in->as_SafePointScalarObject();
67 uint old_unique = C->unique();
68 Node* new_in = old_sosn->clone(jvms_adj, sosn_map);
69 if (old_unique != C->unique()) {
70 new_in = transform_later(new_in); // Register new node.
71 }
72 old_in = new_in;
73 }
74 newcall->add_req(old_in);
75 }
76
77 newcall->set_jvms(oldcall->jvms());
78 for (JVMState *jvms = newcall->jvms(); jvms != NULL; jvms = jvms->caller()) {
79 jvms->set_map(newcall);
80 jvms->set_locoff(jvms->locoff()+jvms_adj);
81 jvms->set_stkoff(jvms->stkoff()+jvms_adj);
82 jvms->set_monoff(jvms->monoff()+jvms_adj);
83 jvms->set_scloff(jvms->scloff()+jvms_adj);
84 jvms->set_endoff(jvms->endoff()+jvms_adj);
85 }
86 }
87
88 Node* PhaseMacroExpand::opt_bits_test(Node* ctrl, Node* region, int edge, Node* word, int mask, int bits, bool return_fast_path) {
89 Node* cmp;
90 if (mask != 0) {
91 Node* and_node = transform_later(new (C, 3) AndXNode(word, MakeConX(mask)));
92 cmp = transform_later(new (C, 3) CmpXNode(and_node, MakeConX(bits)));
93 } else {
94 cmp = word;
95 }
96 Node* bol = transform_later(new (C, 2) BoolNode(cmp, BoolTest::ne));
97 IfNode* iff = new (C, 2) IfNode( ctrl, bol, PROB_MIN, COUNT_UNKNOWN );
98 transform_later(iff);
99
100 // Fast path taken.
101 Node *fast_taken = transform_later( new (C, 1) IfFalseNode(iff) );
102
103 // Fast path not-taken, i.e. slow path
104 Node *slow_taken = transform_later( new (C, 1) IfTrueNode(iff) );
105
106 if (return_fast_path) {
107 region->init_req(edge, slow_taken); // Capture slow-control
108 return fast_taken;
109 } else {
110 region->init_req(edge, fast_taken); // Capture fast-control
111 return slow_taken;
112 }
113 }
114
115 //--------------------copy_predefined_input_for_runtime_call--------------------
116 void PhaseMacroExpand::copy_predefined_input_for_runtime_call(Node * ctrl, CallNode* oldcall, CallNode* call) {
117 // Set fixed predefined input arguments
118 call->init_req( TypeFunc::Control, ctrl );
119 call->init_req( TypeFunc::I_O , oldcall->in( TypeFunc::I_O) );
120 call->init_req( TypeFunc::Memory , oldcall->in( TypeFunc::Memory ) ); // ?????
121 call->init_req( TypeFunc::ReturnAdr, oldcall->in( TypeFunc::ReturnAdr ) );
122 call->init_req( TypeFunc::FramePtr, oldcall->in( TypeFunc::FramePtr ) );
123 }
124
125 //------------------------------make_slow_call---------------------------------
126 CallNode* PhaseMacroExpand::make_slow_call(CallNode *oldcall, const TypeFunc* slow_call_type, address slow_call, const char* leaf_name, Node* slow_path, Node* parm0, Node* parm1) {
127
128 // Slow-path call
129 int size = slow_call_type->domain()->cnt();
130 CallNode *call = leaf_name
131 ? (CallNode*)new (C, size) CallLeafNode ( slow_call_type, slow_call, leaf_name, TypeRawPtr::BOTTOM )
132 : (CallNode*)new (C, size) CallStaticJavaNode( slow_call_type, slow_call, OptoRuntime::stub_name(slow_call), oldcall->jvms()->bci(), TypeRawPtr::BOTTOM );
182 _ioproj_catchall = pn;
183 else
184 _ioproj_fallthrough = pn;
185 break;
186 case TypeFunc::Memory:
187 if (pn->_is_io_use)
188 _memproj_catchall = pn;
189 else
190 _memproj_fallthrough = pn;
191 break;
192 case TypeFunc::Parms:
193 _resproj = pn;
194 break;
195 default:
196 assert(false, "unexpected projection from allocation node.");
197 }
198 }
199
200 }
201
202 // Eliminate a card mark sequence. p2x is a ConvP2XNode
203 void PhaseMacroExpand::eliminate_card_mark(Node *p2x) {
204 assert(p2x->Opcode() == Op_CastP2X, "ConvP2XNode required");
205 Node *shift = p2x->unique_out();
206 Node *addp = shift->unique_out();
207 for (DUIterator_Last jmin, j = addp->last_outs(jmin); j >= jmin; --j) {
208 Node *st = addp->last_out(j);
209 assert(st->is_Store(), "store required");
210 _igvn.replace_node(st, st->in(MemNode::Memory));
211 }
212 }
213
214 // Search for a memory operation for the specified memory slice.
215 static Node *scan_mem_chain(Node *mem, int alias_idx, int offset, Node *start_mem, Node *alloc, PhaseGVN *phase) {
216 Node *orig_mem = mem;
217 Node *alloc_mem = alloc->in(TypeFunc::Memory);
218 const TypeOopPtr *tinst = phase->C->get_adr_type(alias_idx)->isa_oopptr();
219 while (true) {
220 if (mem == alloc_mem || mem == start_mem ) {
221 return mem; // hit one of our sentinals
222 } else if (mem->is_MergeMem()) {
223 mem = mem->as_MergeMem()->memory_at(alias_idx);
224 } else if (mem->is_Proj() && mem->as_Proj()->_con == TypeFunc::Memory) {
225 Node *in = mem->in(0);
226 // we can safely skip over safepoints, calls, locks and membars because we
227 // already know that the object is safe to eliminate.
228 if (in->is_Initialize() && in->as_Initialize()->allocation() == alloc) {
229 return in;
230 } else if (in->is_Call()) {
231 CallNode *call = in->as_Call();
232 if (!call->may_modify(tinst, phase)) {
233 mem = call->in(TypeFunc::Memory);
234 }
235 mem = in->in(TypeFunc::Memory);
236 } else if (in->is_MemBar()) {
237 mem = in->in(TypeFunc::Memory);
238 } else {
239 assert(false, "unexpected projection");
240 }
241 } else if (mem->is_Store()) {
242 const TypePtr* atype = mem->as_Store()->adr_type();
243 int adr_idx = Compile::current()->get_alias_index(atype);
244 if (adr_idx == alias_idx) {
245 assert(atype->isa_oopptr(), "address type must be oopptr");
246 int adr_offset = atype->offset();
247 uint adr_iid = atype->is_oopptr()->instance_id();
248 // Array elements references have the same alias_idx
249 // but different offset and different instance_id.
250 if (adr_offset == offset && adr_iid == alloc->_idx)
251 return mem;
252 } else {
253 assert(adr_idx == Compile::AliasIdxRaw, "address must match or be raw");
254 }
255 mem = mem->in(MemNode::Memory);
256 } else {
257 return mem;
258 }
259 assert(mem != orig_mem, "dead memory loop");
260 }
261 }
262
263 //
264 // Given a Memory Phi, compute a value Phi containing the values from stores
265 // on the input paths.
266 // Note: this function is recursive, its depth is limied by the "level" argument
267 // Returns the computed Phi, or NULL if it cannot compute it.
268 Node *PhaseMacroExpand::value_from_mem_phi(Node *mem, BasicType ft, const Type *phi_type, const TypeOopPtr *adr_t, Node *alloc, Node_Stack *value_phis, int level) {
269 assert(mem->is_Phi(), "sanity");
270 int alias_idx = C->get_alias_index(adr_t);
271 int offset = adr_t->offset();
272 int instance_id = adr_t->instance_id();
273
274 // Check if an appropriate value phi already exists.
275 Node* region = mem->in(0);
276 for (DUIterator_Fast kmax, k = region->fast_outs(kmax); k < kmax; k++) {
277 Node* phi = region->fast_out(k);
278 if (phi->is_Phi() && phi != mem &&
279 phi->as_Phi()->is_same_inst_field(phi_type, instance_id, alias_idx, offset)) {
280 return phi;
281 }
282 }
283 // Check if an appropriate new value phi already exists.
284 Node* new_phi = NULL;
285 uint size = value_phis->size();
286 for (uint i=0; i < size; i++) {
287 if ( mem->_idx == value_phis->index_at(i) ) {
288 return value_phis->node_at(i);
289 }
290 }
291
292 if (level <= 0) {
293 return NULL; // Give up: phi tree too deep
294 }
295 Node *start_mem = C->start()->proj_out(TypeFunc::Memory);
296 Node *alloc_mem = alloc->in(TypeFunc::Memory);
297
298 uint length = mem->req();
299 GrowableArray <Node *> values(length, length, NULL);
300
301 // create a new Phi for the value
302 PhiNode *phi = new (C, length) PhiNode(mem->in(0), phi_type, NULL, instance_id, alias_idx, offset);
303 transform_later(phi);
304 value_phis->push(phi, mem->_idx);
305
306 for (uint j = 1; j < length; j++) {
307 Node *in = mem->in(j);
308 if (in == NULL || in->is_top()) {
309 values.at_put(j, in);
310 } else {
311 Node *val = scan_mem_chain(in, alias_idx, offset, start_mem, alloc, &_igvn);
312 if (val == start_mem || val == alloc_mem) {
313 // hit a sentinel, return appropriate 0 value
314 values.at_put(j, _igvn.zerocon(ft));
315 continue;
316 }
317 if (val->is_Initialize()) {
318 val = val->as_Initialize()->find_captured_store(offset, type2aelembytes(ft), &_igvn);
319 }
320 if (val == NULL) {
321 return NULL; // can't find a value on this path
322 }
323 if (val == mem) {
324 values.at_put(j, mem);
325 } else if (val->is_Store()) {
326 values.at_put(j, val->in(MemNode::ValueIn));
327 } else if(val->is_Proj() && val->in(0) == alloc) {
328 values.at_put(j, _igvn.zerocon(ft));
329 } else if (val->is_Phi()) {
330 val = value_from_mem_phi(val, ft, phi_type, adr_t, alloc, value_phis, level-1);
331 if (val == NULL) {
332 return NULL;
333 }
334 values.at_put(j, val);
335 } else {
336 assert(false, "unknown node on this path");
337 return NULL; // unknown node on this path
338 }
339 }
340 }
341 // Set Phi's inputs
342 for (uint j = 1; j < length; j++) {
343 if (values.at(j) == mem) {
344 phi->init_req(j, phi);
345 } else {
346 phi->init_req(j, values.at(j));
347 }
348 }
349 return phi;
350 }
351
352 // Search the last value stored into the object's field.
353 Node *PhaseMacroExpand::value_from_mem(Node *sfpt_mem, BasicType ft, const Type *ftype, const TypeOopPtr *adr_t, Node *alloc) {
354 assert(adr_t->is_known_instance_field(), "instance required");
355 int instance_id = adr_t->instance_id();
356 assert((uint)instance_id == alloc->_idx, "wrong allocation");
357
358 int alias_idx = C->get_alias_index(adr_t);
359 int offset = adr_t->offset();
360 Node *start_mem = C->start()->proj_out(TypeFunc::Memory);
361 Node *alloc_ctrl = alloc->in(TypeFunc::Control);
362 Node *alloc_mem = alloc->in(TypeFunc::Memory);
363 Arena *a = Thread::current()->resource_area();
364 VectorSet visited(a);
365
366
367 bool done = sfpt_mem == alloc_mem;
368 Node *mem = sfpt_mem;
369 while (!done) {
370 if (visited.test_set(mem->_idx)) {
371 return NULL; // found a loop, give up
372 }
373 mem = scan_mem_chain(mem, alias_idx, offset, start_mem, alloc, &_igvn);
374 if (mem == start_mem || mem == alloc_mem) {
375 done = true; // hit a sentinel, return appropriate 0 value
376 } else if (mem->is_Initialize()) {
377 mem = mem->as_Initialize()->find_captured_store(offset, type2aelembytes(ft), &_igvn);
378 if (mem == NULL) {
379 done = true; // Something go wrong.
380 } else if (mem->is_Store()) {
381 const TypePtr* atype = mem->as_Store()->adr_type();
382 assert(C->get_alias_index(atype) == Compile::AliasIdxRaw, "store is correct memory slice");
383 done = true;
384 }
385 } else if (mem->is_Store()) {
386 const TypeOopPtr* atype = mem->as_Store()->adr_type()->isa_oopptr();
387 assert(atype != NULL, "address type must be oopptr");
388 assert(C->get_alias_index(atype) == alias_idx &&
389 atype->is_known_instance_field() && atype->offset() == offset &&
390 atype->instance_id() == instance_id, "store is correct memory slice");
391 done = true;
392 } else if (mem->is_Phi()) {
393 // try to find a phi's unique input
394 Node *unique_input = NULL;
395 Node *top = C->top();
396 for (uint i = 1; i < mem->req(); i++) {
397 Node *n = scan_mem_chain(mem->in(i), alias_idx, offset, start_mem, alloc, &_igvn);
398 if (n == NULL || n == top || n == mem) {
399 continue;
400 } else if (unique_input == NULL) {
401 unique_input = n;
402 } else if (unique_input != n) {
403 unique_input = top;
404 break;
405 }
406 }
407 if (unique_input != NULL && unique_input != top) {
408 mem = unique_input;
409 } else {
410 done = true;
411 }
412 } else {
413 assert(false, "unexpected node");
414 }
415 }
416 if (mem != NULL) {
417 if (mem == start_mem || mem == alloc_mem) {
418 // hit a sentinel, return appropriate 0 value
419 return _igvn.zerocon(ft);
420 } else if (mem->is_Store()) {
421 return mem->in(MemNode::ValueIn);
422 } else if (mem->is_Phi()) {
423 // attempt to produce a Phi reflecting the values on the input paths of the Phi
424 Node_Stack value_phis(a, 8);
425 Node * phi = value_from_mem_phi(mem, ft, ftype, adr_t, alloc, &value_phis, ValueSearchLimit);
426 if (phi != NULL) {
427 return phi;
428 } else {
429 // Kill all new Phis
430 while(value_phis.is_nonempty()) {
431 Node* n = value_phis.node();
432 _igvn.hash_delete(n);
433 _igvn.subsume_node(n, C->top());
434 value_phis.pop();
435 }
436 }
437 }
438 }
439 // Something go wrong.
440 return NULL;
441 }
442
443 // Check the possibility of scalar replacement.
444 bool PhaseMacroExpand::can_eliminate_allocation(AllocateNode *alloc, GrowableArray <SafePointNode *>& safepoints) {
445 // Scan the uses of the allocation to check for anything that would
446 // prevent us from eliminating it.
447 NOT_PRODUCT( const char* fail_eliminate = NULL; )
448 DEBUG_ONLY( Node* disq_node = NULL; )
449 bool can_eliminate = true;
450
451 Node* res = alloc->result_cast();
452 const TypeOopPtr* res_type = NULL;
453 if (res == NULL) {
454 // All users were eliminated.
455 } else if (!res->is_CheckCastPP()) {
456 alloc->_is_scalar_replaceable = false; // don't try again
457 NOT_PRODUCT(fail_eliminate = "Allocation does not have unique CheckCastPP";)
458 can_eliminate = false;
459 } else {
460 res_type = _igvn.type(res)->isa_oopptr();
461 if (res_type == NULL) {
462 NOT_PRODUCT(fail_eliminate = "Neither instance or array allocation";)
463 can_eliminate = false;
464 } else if (res_type->isa_aryptr()) {
465 int length = alloc->in(AllocateNode::ALength)->find_int_con(-1);
466 if (length < 0) {
467 NOT_PRODUCT(fail_eliminate = "Array's size is not constant";)
468 can_eliminate = false;
469 }
470 }
471 }
472
473 if (can_eliminate && res != NULL) {
474 for (DUIterator_Fast jmax, j = res->fast_outs(jmax);
475 j < jmax && can_eliminate; j++) {
476 Node* use = res->fast_out(j);
477
478 if (use->is_AddP()) {
479 const TypePtr* addp_type = _igvn.type(use)->is_ptr();
480 int offset = addp_type->offset();
481
482 if (offset == Type::OffsetTop || offset == Type::OffsetBot) {
483 NOT_PRODUCT(fail_eliminate = "Undefined field referrence";)
484 can_eliminate = false;
485 break;
486 }
487 for (DUIterator_Fast kmax, k = use->fast_outs(kmax);
488 k < kmax && can_eliminate; k++) {
489 Node* n = use->fast_out(k);
490 if (!n->is_Store() && n->Opcode() != Op_CastP2X) {
491 DEBUG_ONLY(disq_node = n;)
492 if (n->is_Load() || n->is_LoadStore()) {
493 NOT_PRODUCT(fail_eliminate = "Field load";)
494 } else {
495 NOT_PRODUCT(fail_eliminate = "Not store field referrence";)
496 }
497 can_eliminate = false;
498 }
499 }
500 } else if (use->is_SafePoint()) {
501 SafePointNode* sfpt = use->as_SafePoint();
502 if (sfpt->is_Call() && sfpt->as_Call()->has_non_debug_use(res)) {
503 // Object is passed as argument.
504 DEBUG_ONLY(disq_node = use;)
505 NOT_PRODUCT(fail_eliminate = "Object is passed as argument";)
506 can_eliminate = false;
507 }
508 Node* sfptMem = sfpt->memory();
509 if (sfptMem == NULL || sfptMem->is_top()) {
510 DEBUG_ONLY(disq_node = use;)
511 NOT_PRODUCT(fail_eliminate = "NULL or TOP memory";)
512 can_eliminate = false;
513 } else {
514 safepoints.append_if_missing(sfpt);
515 }
516 } else if (use->Opcode() != Op_CastP2X) { // CastP2X is used by card mark
517 if (use->is_Phi()) {
518 if (use->outcnt() == 1 && use->unique_out()->Opcode() == Op_Return) {
519 NOT_PRODUCT(fail_eliminate = "Object is return value";)
520 } else {
521 NOT_PRODUCT(fail_eliminate = "Object is referenced by Phi";)
522 }
523 DEBUG_ONLY(disq_node = use;)
524 } else {
525 if (use->Opcode() == Op_Return) {
526 NOT_PRODUCT(fail_eliminate = "Object is return value";)
527 }else {
528 NOT_PRODUCT(fail_eliminate = "Object is referenced by node";)
529 }
530 DEBUG_ONLY(disq_node = use;)
531 }
532 can_eliminate = false;
533 }
534 }
535 }
536
537 #ifndef PRODUCT
538 if (PrintEliminateAllocations) {
539 if (can_eliminate) {
540 tty->print("Scalar ");
541 if (res == NULL)
542 alloc->dump();
543 else
544 res->dump();
545 } else {
546 tty->print("NotScalar (%s)", fail_eliminate);
547 if (res == NULL)
548 alloc->dump();
549 else
550 res->dump();
551 #ifdef ASSERT
552 if (disq_node != NULL) {
553 tty->print(" >>>> ");
554 disq_node->dump();
555 }
556 #endif /*ASSERT*/
557 }
558 }
559 #endif
560 return can_eliminate;
561 }
562
563 // Do scalar replacement.
564 bool PhaseMacroExpand::scalar_replacement(AllocateNode *alloc, GrowableArray <SafePointNode *>& safepoints) {
565 GrowableArray <SafePointNode *> safepoints_done;
566
567 ciKlass* klass = NULL;
568 ciInstanceKlass* iklass = NULL;
569 int nfields = 0;
570 int array_base;
571 int element_size;
572 BasicType basic_elem_type;
573 ciType* elem_type;
574
575 Node* res = alloc->result_cast();
576 const TypeOopPtr* res_type = NULL;
577 if (res != NULL) { // Could be NULL when there are no users
578 res_type = _igvn.type(res)->isa_oopptr();
579 }
580
581 if (res != NULL) {
582 klass = res_type->klass();
583 if (res_type->isa_instptr()) {
584 // find the fields of the class which will be needed for safepoint debug information
585 assert(klass->is_instance_klass(), "must be an instance klass.");
586 iklass = klass->as_instance_klass();
587 nfields = iklass->nof_nonstatic_fields();
588 } else {
589 // find the array's elements which will be needed for safepoint debug information
590 nfields = alloc->in(AllocateNode::ALength)->find_int_con(-1);
591 assert(klass->is_array_klass() && nfields >= 0, "must be an array klass.");
592 elem_type = klass->as_array_klass()->element_type();
593 basic_elem_type = elem_type->basic_type();
594 array_base = arrayOopDesc::base_offset_in_bytes(basic_elem_type);
595 element_size = type2aelembytes(basic_elem_type);
596 }
597 }
598 //
599 // Process the safepoint uses
600 //
601 while (safepoints.length() > 0) {
602 SafePointNode* sfpt = safepoints.pop();
603 Node* mem = sfpt->memory();
604 uint first_ind = sfpt->req();
605 SafePointScalarObjectNode* sobj = new (C, 1) SafePointScalarObjectNode(res_type,
606 #ifdef ASSERT
607 alloc,
608 #endif
609 first_ind, nfields);
610 sobj->init_req(0, sfpt->in(TypeFunc::Control));
611 transform_later(sobj);
612
613 // Scan object's fields adding an input to the safepoint for each field.
614 for (int j = 0; j < nfields; j++) {
615 intptr_t offset;
616 ciField* field = NULL;
617 if (iklass != NULL) {
618 field = iklass->nonstatic_field_at(j);
619 offset = field->offset();
620 elem_type = field->type();
621 basic_elem_type = field->layout_type();
622 } else {
623 offset = array_base + j * (intptr_t)element_size;
624 }
625
626 const Type *field_type;
627 // The next code is taken from Parse::do_get_xxx().
628 if (basic_elem_type == T_OBJECT || basic_elem_type == T_ARRAY) {
629 if (!elem_type->is_loaded()) {
630 field_type = TypeInstPtr::BOTTOM;
631 } else if (field != NULL && field->is_constant()) {
632 // This can happen if the constant oop is non-perm.
633 ciObject* con = field->constant_value().as_object();
634 // Do not "join" in the previous type; it doesn't add value,
635 // and may yield a vacuous result if the field is of interface type.
636 field_type = TypeOopPtr::make_from_constant(con)->isa_oopptr();
637 assert(field_type != NULL, "field singleton type must be consistent");
638 } else {
639 field_type = TypeOopPtr::make_from_klass(elem_type->as_klass());
640 }
641 if (UseCompressedOops) {
642 field_type = field_type->make_narrowoop();
643 basic_elem_type = T_NARROWOOP;
644 }
645 } else {
646 field_type = Type::get_const_basic_type(basic_elem_type);
647 }
648
649 const TypeOopPtr *field_addr_type = res_type->add_offset(offset)->isa_oopptr();
650
651 Node *field_val = value_from_mem(mem, basic_elem_type, field_type, field_addr_type, alloc);
652 if (field_val == NULL) {
653 // we weren't able to find a value for this field,
654 // give up on eliminating this allocation
655 alloc->_is_scalar_replaceable = false; // don't try again
656 // remove any extra entries we added to the safepoint
657 uint last = sfpt->req() - 1;
658 for (int k = 0; k < j; k++) {
659 sfpt->del_req(last--);
660 }
661 // rollback processed safepoints
662 while (safepoints_done.length() > 0) {
663 SafePointNode* sfpt_done = safepoints_done.pop();
664 // remove any extra entries we added to the safepoint
665 last = sfpt_done->req() - 1;
666 for (int k = 0; k < nfields; k++) {
667 sfpt_done->del_req(last--);
668 }
669 JVMState *jvms = sfpt_done->jvms();
670 jvms->set_endoff(sfpt_done->req());
671 // Now make a pass over the debug information replacing any references
672 // to SafePointScalarObjectNode with the allocated object.
673 int start = jvms->debug_start();
674 int end = jvms->debug_end();
675 for (int i = start; i < end; i++) {
676 if (sfpt_done->in(i)->is_SafePointScalarObject()) {
677 SafePointScalarObjectNode* scobj = sfpt_done->in(i)->as_SafePointScalarObject();
678 if (scobj->first_index() == sfpt_done->req() &&
679 scobj->n_fields() == (uint)nfields) {
680 assert(scobj->alloc() == alloc, "sanity");
681 sfpt_done->set_req(i, res);
682 }
683 }
684 }
685 }
686 #ifndef PRODUCT
687 if (PrintEliminateAllocations) {
688 if (field != NULL) {
689 tty->print("=== At SafePoint node %d can't find value of Field: ",
690 sfpt->_idx);
691 field->print();
692 int field_idx = C->get_alias_index(field_addr_type);
693 tty->print(" (alias_idx=%d)", field_idx);
694 } else { // Array's element
695 tty->print("=== At SafePoint node %d can't find value of array element [%d]",
696 sfpt->_idx, j);
697 }
698 tty->print(", which prevents elimination of: ");
699 if (res == NULL)
700 alloc->dump();
701 else
702 res->dump();
703 }
704 #endif
705 return false;
706 }
707 if (UseCompressedOops && field_type->isa_narrowoop()) {
708 // Enable "DecodeN(EncodeP(Allocate)) --> Allocate" transformation
709 // to be able scalar replace the allocation.
710 if (field_val->is_EncodeP()) {
711 field_val = field_val->in(1);
712 } else {
713 field_val = transform_later(new (C, 2) DecodeNNode(field_val, field_val->bottom_type()->make_ptr()));
714 }
715 }
716 sfpt->add_req(field_val);
717 }
718 JVMState *jvms = sfpt->jvms();
719 jvms->set_endoff(sfpt->req());
720 // Now make a pass over the debug information replacing any references
721 // to the allocated object with "sobj"
722 int start = jvms->debug_start();
723 int end = jvms->debug_end();
724 for (int i = start; i < end; i++) {
725 if (sfpt->in(i) == res) {
726 sfpt->set_req(i, sobj);
727 }
728 }
729 safepoints_done.append_if_missing(sfpt); // keep it for rollback
730 }
731 return true;
732 }
733
734 // Process users of eliminated allocation.
735 void PhaseMacroExpand::process_users_of_allocation(AllocateNode *alloc) {
736 Node* res = alloc->result_cast();
737 if (res != NULL) {
738 for (DUIterator_Last jmin, j = res->last_outs(jmin); j >= jmin; ) {
739 Node *use = res->last_out(j);
740 uint oc1 = res->outcnt();
741
742 if (use->is_AddP()) {
743 for (DUIterator_Last kmin, k = use->last_outs(kmin); k >= kmin; ) {
744 Node *n = use->last_out(k);
745 uint oc2 = use->outcnt();
746 if (n->is_Store()) {
747 _igvn.replace_node(n, n->in(MemNode::Memory));
748 } else {
749 assert( n->Opcode() == Op_CastP2X, "CastP2X required");
750 eliminate_card_mark(n);
751 }
752 k -= (oc2 - use->outcnt());
753 }
754 } else {
755 assert( !use->is_SafePoint(), "safepoint uses must have been already elimiated");
756 assert( use->Opcode() == Op_CastP2X, "CastP2X required");
757 eliminate_card_mark(use);
758 }
759 j -= (oc1 - res->outcnt());
760 }
761 assert(res->outcnt() == 0, "all uses of allocated objects must be deleted");
762 _igvn.remove_dead_node(res);
763 }
764
765 //
766 // Process other users of allocation's projections
767 //
768 if (_resproj != NULL && _resproj->outcnt() != 0) {
769 for (DUIterator_Last jmin, j = _resproj->last_outs(jmin); j >= jmin; ) {
770 Node *use = _resproj->last_out(j);
771 uint oc1 = _resproj->outcnt();
772 if (use->is_Initialize()) {
773 // Eliminate Initialize node.
774 InitializeNode *init = use->as_Initialize();
775 assert(init->outcnt() <= 2, "only a control and memory projection expected");
776 Node *ctrl_proj = init->proj_out(TypeFunc::Control);
777 if (ctrl_proj != NULL) {
778 assert(init->in(TypeFunc::Control) == _fallthroughcatchproj, "allocation control projection");
779 _igvn.replace_node(ctrl_proj, _fallthroughcatchproj);
780 }
781 Node *mem_proj = init->proj_out(TypeFunc::Memory);
782 if (mem_proj != NULL) {
783 Node *mem = init->in(TypeFunc::Memory);
784 #ifdef ASSERT
785 if (mem->is_MergeMem()) {
786 assert(mem->in(TypeFunc::Memory) == _memproj_fallthrough, "allocation memory projection");
787 } else {
788 assert(mem == _memproj_fallthrough, "allocation memory projection");
789 }
790 #endif
791 _igvn.replace_node(mem_proj, mem);
792 }
793 } else if (use->is_AddP()) {
794 // raw memory addresses used only by the initialization
795 _igvn.hash_delete(use);
796 _igvn.subsume_node(use, C->top());
797 } else {
798 assert(false, "only Initialize or AddP expected");
799 }
800 j -= (oc1 - _resproj->outcnt());
801 }
802 }
803 if (_fallthroughcatchproj != NULL) {
804 _igvn.replace_node(_fallthroughcatchproj, alloc->in(TypeFunc::Control));
805 }
806 if (_memproj_fallthrough != NULL) {
807 _igvn.replace_node(_memproj_fallthrough, alloc->in(TypeFunc::Memory));
808 }
809 if (_memproj_catchall != NULL) {
810 _igvn.replace_node(_memproj_catchall, C->top());
811 }
812 if (_ioproj_fallthrough != NULL) {
813 _igvn.replace_node(_ioproj_fallthrough, alloc->in(TypeFunc::I_O));
814 }
815 if (_ioproj_catchall != NULL) {
816 _igvn.replace_node(_ioproj_catchall, C->top());
817 }
818 if (_catchallcatchproj != NULL) {
819 _igvn.replace_node(_catchallcatchproj, C->top());
820 }
821 }
822
823 bool PhaseMacroExpand::eliminate_allocate_node(AllocateNode *alloc) {
824
825 if (!EliminateAllocations || !alloc->_is_scalar_replaceable) {
826 return false;
827 }
828
829 extract_call_projections(alloc);
830
831 GrowableArray <SafePointNode *> safepoints;
832 if (!can_eliminate_allocation(alloc, safepoints)) {
833 return false;
834 }
835
836 if (!scalar_replacement(alloc, safepoints)) {
837 return false;
838 }
839
840 process_users_of_allocation(alloc);
841
842 #ifndef PRODUCT
843 if (PrintEliminateAllocations) {
844 if (alloc->is_AllocateArray())
845 tty->print_cr("++++ Eliminated: %d AllocateArray", alloc->_idx);
846 else
847 tty->print_cr("++++ Eliminated: %d Allocate", alloc->_idx);
848 }
849 #endif
850
851 return true;
852 }
853
854
855 //---------------------------set_eden_pointers-------------------------
856 void PhaseMacroExpand::set_eden_pointers(Node* &eden_top_adr, Node* &eden_end_adr) {
857 if (UseTLAB) { // Private allocation: load from TLS
858 Node* thread = transform_later(new (C, 1) ThreadLocalNode());
859 int tlab_top_offset = in_bytes(JavaThread::tlab_top_offset());
860 int tlab_end_offset = in_bytes(JavaThread::tlab_end_offset());
861 eden_top_adr = basic_plus_adr(top()/*not oop*/, thread, tlab_top_offset);
862 eden_end_adr = basic_plus_adr(top()/*not oop*/, thread, tlab_end_offset);
863 } else { // Shared allocation: load from globals
864 CollectedHeap* ch = Universe::heap();
865 address top_adr = (address)ch->top_addr();
866 address end_adr = (address)ch->end_addr();
867 eden_top_adr = makecon(TypeRawPtr::make(top_adr));
868 eden_end_adr = basic_plus_adr(eden_top_adr, end_adr - top_adr);
869 }
870 }
871
872
873 Node* PhaseMacroExpand::make_load(Node* ctl, Node* mem, Node* base, int offset, const Type* value_type, BasicType bt) {
874 Node* adr = basic_plus_adr(base, offset);
875 const TypePtr* adr_type = adr->bottom_type()->is_ptr();
876 Node* value = LoadNode::make(_igvn, ctl, mem, adr, adr_type, value_type, bt);
877 transform_later(value);
878 return value;
879 }
880
881
882 Node* PhaseMacroExpand::make_store(Node* ctl, Node* mem, Node* base, int offset, Node* value, BasicType bt) {
883 Node* adr = basic_plus_adr(base, offset);
884 mem = StoreNode::make(_igvn, ctl, mem, adr, NULL, value, bt);
885 transform_later(mem);
886 return mem;
887 }
888
889 //=============================================================================
890 //
891 // A L L O C A T I O N
892 //
893 // Allocation attempts to be fast in the case of frequent small objects.
894 // It breaks down like this:
895 //
896 // 1) Size in doublewords is computed. This is a constant for objects and
897 // variable for most arrays. Doubleword units are used to avoid size
898 // overflow of huge doubleword arrays. We need doublewords in the end for
899 // rounding.
900 //
901 // 2) Size is checked for being 'too large'. Too-large allocations will go
902 // the slow path into the VM. The slow path can throw any required
903 // exceptions, and does all the special checks for very large arrays. The
904 // size test can constant-fold away for objects. For objects with
938 // code shape produced here, so if you are changing this code shape
939 // make sure the GC info for the heap-top is correct in and around the
940 // slow-path call.
941 //
942
943 void PhaseMacroExpand::expand_allocate_common(
944 AllocateNode* alloc, // allocation node to be expanded
945 Node* length, // array length for an array allocation
946 const TypeFunc* slow_call_type, // Type of slow call
947 address slow_call_address // Address of slow call
948 )
949 {
950
951 Node* ctrl = alloc->in(TypeFunc::Control);
952 Node* mem = alloc->in(TypeFunc::Memory);
953 Node* i_o = alloc->in(TypeFunc::I_O);
954 Node* size_in_bytes = alloc->in(AllocateNode::AllocSize);
955 Node* klass_node = alloc->in(AllocateNode::KlassNode);
956 Node* initial_slow_test = alloc->in(AllocateNode::InitialTest);
957
958 // With escape analysis, the entire memory state was needed to be able to
959 // eliminate the allocation. Since the allocations cannot be eliminated,
960 // optimize it to the raw slice.
961 if (mem->is_MergeMem()) {
962 mem = mem->as_MergeMem()->memory_at(Compile::AliasIdxRaw);
963 }
964
965 assert(ctrl != NULL, "must have control");
966 // We need a Region and corresponding Phi's to merge the slow-path and fast-path results.
967 // they will not be used if "always_slow" is set
968 enum { slow_result_path = 1, fast_result_path = 2 };
969 Node *result_region;
970 Node *result_phi_rawmem;
971 Node *result_phi_rawoop;
972 Node *result_phi_i_o;
973
974 // The initial slow comparison is a size check, the comparison
975 // we want to do is a BoolTest::gt
976 bool always_slow = false;
977 int tv = _igvn.find_int_con(initial_slow_test, -1);
978 if (tv >= 0) {
979 always_slow = (tv == 1);
980 initial_slow_test = NULL;
981 } else {
982 initial_slow_test = BoolNode::make_predicate(initial_slow_test, &_igvn);
983 }
984
985 if (DTraceAllocProbes ||
986 !UseTLAB && (!Universe::heap()->supports_inline_contig_alloc() ||
987 (UseConcMarkSweepGC && CMSIncrementalMode))) {
988 // Force slow-path allocation
989 always_slow = true;
990 initial_slow_test = NULL;
991 }
992
993
994 enum { too_big_or_final_path = 1, need_gc_path = 2 };
995 Node *slow_region = NULL;
996 Node *toobig_false = ctrl;
997
998 assert (initial_slow_test == NULL || !always_slow, "arguments must be consistent");
999 // generate the initial test if necessary
1000 if (initial_slow_test != NULL ) {
1001 slow_region = new (C, 3) RegionNode(3);
1002
1003 // Now make the initial failure test. Usually a too-big test but
1004 // might be a TRUE for finalizers or a fancy class check for
1005 // newInstance0.
1006 IfNode *toobig_iff = new (C, 2) IfNode(ctrl, initial_slow_test, PROB_MIN, COUNT_UNKNOWN);
1007 transform_later(toobig_iff);
1008 // Plug the failing-too-big test into the slow-path region
1009 Node *toobig_true = new (C, 1) IfTrueNode( toobig_iff );
1010 transform_later(toobig_true);
1011 slow_region ->init_req( too_big_or_final_path, toobig_true );
1012 toobig_false = new (C, 1) IfFalseNode( toobig_iff );
1013 transform_later(toobig_false);
1014 } else { // No initial test, just fall into next case
1015 toobig_false = ctrl;
1016 debug_only(slow_region = NodeSentinel);
1017 }
1018
1019 Node *slow_mem = mem; // save the current memory state for slow path
1020 // generate the fast allocation code unless we know that the initial test will always go slow
1021 if (!always_slow) {
1022 Node* eden_top_adr;
1023 Node* eden_end_adr;
1024
1025 set_eden_pointers(eden_top_adr, eden_end_adr);
1026
1027 // Load Eden::end. Loop invariant and hoisted.
1028 //
1029 // Note: We set the control input on "eden_end" and "old_eden_top" when using
1030 // a TLAB to work around a bug where these values were being moved across
1031 // a safepoint. These are not oops, so they cannot be include in the oop
1032 // map, but the can be changed by a GC. The proper way to fix this would
1033 // be to set the raw memory state when generating a SafepointNode. However
1034 // this will require extensive changes to the loop optimization in order to
1035 // prevent a degradation of the optimization.
1036 // See comment in memnode.hpp, around line 227 in class LoadPNode.
1037 Node *eden_end = make_load(ctrl, mem, eden_end_adr, 0, TypeRawPtr::BOTTOM, T_ADDRESS);
1038
1039 // allocate the Region and Phi nodes for the result
1040 result_region = new (C, 3) RegionNode(3);
1041 result_phi_rawmem = new (C, 3) PhiNode( result_region, Type::MEMORY, TypeRawPtr::BOTTOM );
1042 result_phi_rawoop = new (C, 3) PhiNode( result_region, TypeRawPtr::BOTTOM );
1043 result_phi_i_o = new (C, 3) PhiNode( result_region, Type::ABIO ); // I/O is used for Prefetch
1044
1045 // We need a Region for the loop-back contended case.
1046 enum { fall_in_path = 1, contended_loopback_path = 2 };
1047 Node *contended_region;
1048 Node *contended_phi_rawmem;
1049 if( UseTLAB ) {
1050 contended_region = toobig_false;
1051 contended_phi_rawmem = mem;
1052 } else {
1053 contended_region = new (C, 3) RegionNode(3);
1054 contended_phi_rawmem = new (C, 3) PhiNode( contended_region, Type::MEMORY, TypeRawPtr::BOTTOM);
1055 // Now handle the passing-too-big test. We fall into the contended
1056 // loop-back merge point.
1057 contended_region ->init_req( fall_in_path, toobig_false );
1058 contended_phi_rawmem->init_req( fall_in_path, mem );
1309 }
1310
1311
1312 // Helper for PhaseMacroExpand::expand_allocate_common.
1313 // Initializes the newly-allocated storage.
1314 Node*
1315 PhaseMacroExpand::initialize_object(AllocateNode* alloc,
1316 Node* control, Node* rawmem, Node* object,
1317 Node* klass_node, Node* length,
1318 Node* size_in_bytes) {
1319 InitializeNode* init = alloc->initialization();
1320 // Store the klass & mark bits
1321 Node* mark_node = NULL;
1322 // For now only enable fast locking for non-array types
1323 if (UseBiasedLocking && (length == NULL)) {
1324 mark_node = make_load(NULL, rawmem, klass_node, Klass::prototype_header_offset_in_bytes() + sizeof(oopDesc), TypeRawPtr::BOTTOM, T_ADDRESS);
1325 } else {
1326 mark_node = makecon(TypeRawPtr::make((address)markOopDesc::prototype()));
1327 }
1328 rawmem = make_store(control, rawmem, object, oopDesc::mark_offset_in_bytes(), mark_node, T_ADDRESS);
1329
1330 rawmem = make_store(control, rawmem, object, oopDesc::klass_offset_in_bytes(), klass_node, T_OBJECT);
1331 int header_size = alloc->minimum_header_size(); // conservatively small
1332
1333 // Array length
1334 if (length != NULL) { // Arrays need length field
1335 rawmem = make_store(control, rawmem, object, arrayOopDesc::length_offset_in_bytes(), length, T_INT);
1336 // conservatively small header size:
1337 header_size = arrayOopDesc::base_offset_in_bytes(T_BYTE);
1338 ciKlass* k = _igvn.type(klass_node)->is_klassptr()->klass();
1339 if (k->is_array_klass()) // we know the exact header size in most cases:
1340 header_size = Klass::layout_helper_header_size(k->layout_helper());
1341 }
1342
1343 // Clear the object body, if necessary.
1344 if (init == NULL) {
1345 // The init has somehow disappeared; be cautious and clear everything.
1346 //
1347 // This can happen if a node is allocated but an uncommon trap occurs
1348 // immediately. In this case, the Initialize gets associated with the
1349 // trap, and may be placed in a different (outer) loop, if the Allocate
1350 // is in a loop. If (this is rare) the inner loop gets unrolled, then
1351 // there can be two Allocates to one Initialize. The answer in all these
1352 // edge cases is safety first. It is always safe to clear immediately
1353 // within an Allocate, and then (maybe or maybe not) clear some more later.
1354 if (!ZeroTLAB)
1355 rawmem = ClearArrayNode::clear_memory(control, rawmem, object,
1356 header_size, size_in_bytes,
1357 &_igvn);
1358 } else {
1359 if (!init->is_complete()) {
1360 // Try to win by zeroing only what the init does not store.
1361 // We can also try to do some peephole optimizations,
1362 // such as combining some adjacent subword stores.
1363 rawmem = init->complete_stores(control, rawmem, object,
1364 header_size, size_in_bytes, &_igvn);
1365 }
1366 // We have no more use for this link, since the AllocateNode goes away:
1367 init->set_req(InitializeNode::RawAddress, top());
1368 // (If we keep the link, it just confuses the register allocator,
1369 // who thinks he sees a real use of the address by the membar.)
1370 }
1371
1372 return rawmem;
1373 }
1374
1375 // Generate prefetch instructions for next allocations.
1376 Node* PhaseMacroExpand::prefetch_allocation(Node* i_o, Node*& needgc_false,
1377 Node*& contended_phi_rawmem,
1378 Node* old_eden_top, Node* new_eden_top,
1379 Node* length) {
1380 if( UseTLAB && AllocatePrefetchStyle == 2 ) {
1381 // Generate prefetch allocation with watermark check.
1382 // As an allocation hits the watermark, we will prefetch starting
1383 // at a "distance" away from watermark.
1384 enum { fall_in_path = 1, pf_path = 2 };
1385
1490 void PhaseMacroExpand::expand_allocate(AllocateNode *alloc) {
1491 expand_allocate_common(alloc, NULL,
1492 OptoRuntime::new_instance_Type(),
1493 OptoRuntime::new_instance_Java());
1494 }
1495
1496 void PhaseMacroExpand::expand_allocate_array(AllocateArrayNode *alloc) {
1497 Node* length = alloc->in(AllocateNode::ALength);
1498 expand_allocate_common(alloc, length,
1499 OptoRuntime::new_array_Type(),
1500 OptoRuntime::new_array_Java());
1501 }
1502
1503
1504 // we have determined that this lock/unlock can be eliminated, we simply
1505 // eliminate the node without expanding it.
1506 //
1507 // Note: The membar's associated with the lock/unlock are currently not
1508 // eliminated. This should be investigated as a future enhancement.
1509 //
1510 bool PhaseMacroExpand::eliminate_locking_node(AbstractLockNode *alock) {
1511
1512 if (!alock->is_eliminated()) {
1513 return false;
1514 }
1515 if (alock->is_Lock() && !alock->is_coarsened()) {
1516 // Create new "eliminated" BoxLock node and use it
1517 // in monitor debug info for the same object.
1518 BoxLockNode* oldbox = alock->box_node()->as_BoxLock();
1519 Node* obj = alock->obj_node();
1520 if (!oldbox->is_eliminated()) {
1521 BoxLockNode* newbox = oldbox->clone()->as_BoxLock();
1522 newbox->set_eliminated();
1523 transform_later(newbox);
1524 // Replace old box node with new box for all users
1525 // of the same object.
1526 for (uint i = 0; i < oldbox->outcnt();) {
1527
1528 bool next_edge = true;
1529 Node* u = oldbox->raw_out(i);
1530 if (u == alock) {
1531 i++;
1532 continue; // It will be removed below
1533 }
1534 if (u->is_Lock() &&
1535 u->as_Lock()->obj_node() == obj &&
1536 // oldbox could be referenced in debug info also
1537 u->as_Lock()->box_node() == oldbox) {
1538 assert(u->as_Lock()->is_eliminated(), "sanity");
1539 _igvn.hash_delete(u);
1540 u->set_req(TypeFunc::Parms + 1, newbox);
1541 next_edge = false;
1542 #ifdef ASSERT
1543 } else if (u->is_Unlock() && u->as_Unlock()->obj_node() == obj) {
1544 assert(u->as_Unlock()->is_eliminated(), "sanity");
1545 #endif
1546 }
1547 // Replace old box in monitor debug info.
1548 if (u->is_SafePoint() && u->as_SafePoint()->jvms()) {
1549 SafePointNode* sfn = u->as_SafePoint();
1550 JVMState* youngest_jvms = sfn->jvms();
1551 int max_depth = youngest_jvms->depth();
1552 for (int depth = 1; depth <= max_depth; depth++) {
1553 JVMState* jvms = youngest_jvms->of_depth(depth);
1554 int num_mon = jvms->nof_monitors();
1555 // Loop over monitors
1556 for (int idx = 0; idx < num_mon; idx++) {
1557 Node* obj_node = sfn->monitor_obj(jvms, idx);
1558 Node* box_node = sfn->monitor_box(jvms, idx);
1559 if (box_node == oldbox && obj_node == obj) {
1560 int j = jvms->monitor_box_offset(idx);
1561 _igvn.hash_delete(u);
1562 u->set_req(j, newbox);
1563 next_edge = false;
1564 }
1565 } // for (int idx = 0;
1566 } // for (int depth = 1;
1567 } // if (u->is_SafePoint()
1568 if (next_edge) i++;
1569 } // for (uint i = 0; i < oldbox->outcnt();)
1570 } // if (!oldbox->is_eliminated())
1571 } // if (alock->is_Lock() && !lock->is_coarsened())
1572
1573 #ifndef PRODUCT
1574 if (PrintEliminateLocks) {
1575 if (alock->is_Lock()) {
1576 tty->print_cr("++++ Eliminating: %d Lock", alock->_idx);
1577 } else {
1578 tty->print_cr("++++ Eliminating: %d Unlock", alock->_idx);
1579 }
1580 }
1581 #endif
1582
1583 Node* mem = alock->in(TypeFunc::Memory);
1584 Node* ctrl = alock->in(TypeFunc::Control);
1585
1586 extract_call_projections(alock);
1587 // There are 2 projections from the lock. The lock node will
1588 // be deleted when its last use is subsumed below.
1589 assert(alock->outcnt() == 2 &&
1590 _fallthroughproj != NULL &&
1591 _memproj_fallthrough != NULL,
1592 "Unexpected projections from Lock/Unlock");
1593
1594 Node* fallthroughproj = _fallthroughproj;
1595 Node* memproj_fallthrough = _memproj_fallthrough;
1596
1597 // The memory projection from a lock/unlock is RawMem
1598 // The input to a Lock is merged memory, so extract its RawMem input
1599 // (unless the MergeMem has been optimized away.)
1600 if (alock->is_Lock()) {
1601 // Seach for MemBarAcquire node and delete it also.
1602 MemBarNode* membar = fallthroughproj->unique_ctrl_out()->as_MemBar();
1603 assert(membar != NULL && membar->Opcode() == Op_MemBarAcquire, "");
1604 Node* ctrlproj = membar->proj_out(TypeFunc::Control);
1605 Node* memproj = membar->proj_out(TypeFunc::Memory);
1606 _igvn.hash_delete(ctrlproj);
1607 _igvn.subsume_node(ctrlproj, fallthroughproj);
1608 _igvn.hash_delete(memproj);
1609 _igvn.subsume_node(memproj, memproj_fallthrough);
1610
1611 // Delete FastLock node also if this Lock node is unique user
1612 // (a loop peeling may clone a Lock node).
1613 Node* flock = alock->as_Lock()->fastlock_node();
1614 if (flock->outcnt() == 1) {
1615 assert(flock->unique_out() == alock, "sanity");
1616 _igvn.hash_delete(flock);
1617 _igvn.subsume_node(flock, top());
1618 }
1619 }
1620
1621 // Seach for MemBarRelease node and delete it also.
1622 if (alock->is_Unlock() && ctrl != NULL && ctrl->is_Proj() &&
1623 ctrl->in(0)->is_MemBar()) {
1624 MemBarNode* membar = ctrl->in(0)->as_MemBar();
1625 assert(membar->Opcode() == Op_MemBarRelease &&
1626 mem->is_Proj() && membar == mem->in(0), "");
1627 _igvn.hash_delete(fallthroughproj);
1628 _igvn.subsume_node(fallthroughproj, ctrl);
1629 _igvn.hash_delete(memproj_fallthrough);
1630 _igvn.subsume_node(memproj_fallthrough, mem);
1631 fallthroughproj = ctrl;
1632 memproj_fallthrough = mem;
1633 ctrl = membar->in(TypeFunc::Control);
1634 mem = membar->in(TypeFunc::Memory);
1635 }
1636
1637 _igvn.hash_delete(fallthroughproj);
1638 _igvn.subsume_node(fallthroughproj, ctrl);
1639 _igvn.hash_delete(memproj_fallthrough);
1640 _igvn.subsume_node(memproj_fallthrough, mem);
1641 return true;
1642 }
1643
1644
1645 //------------------------------expand_lock_node----------------------
1646 void PhaseMacroExpand::expand_lock_node(LockNode *lock) {
1647
1648 Node* ctrl = lock->in(TypeFunc::Control);
1649 Node* mem = lock->in(TypeFunc::Memory);
1650 Node* obj = lock->obj_node();
1651 Node* box = lock->box_node();
1652 Node* flock = lock->fastlock_node();
1653
1654 // Make the merge point
1655 Node *region;
1656 Node *mem_phi;
1657 Node *slow_path;
1658
1659 if (UseOptoBiasInlining) {
1660 /*
1661 * See the full descrition in MacroAssembler::biased_locking_enter().
1662 *
1663 * if( (mark_word & biased_lock_mask) == biased_lock_pattern ) {
1664 * // The object is biased.
1665 * proto_node = klass->prototype_header;
1666 * o_node = thread | proto_node;
1667 * x_node = o_node ^ mark_word;
1668 * if( (x_node & ~age_mask) == 0 ) { // Biased to the current thread ?
1669 * // Done.
1670 * } else {
1671 * if( (x_node & biased_lock_mask) != 0 ) {
1672 * // The klass's prototype header is no longer biased.
1673 * cas(&mark_word, mark_word, proto_node)
1674 * goto cas_lock;
1675 * } else {
1676 * // The klass's prototype header is still biased.
1677 * if( (x_node & epoch_mask) != 0 ) { // Expired epoch?
1678 * old = mark_word;
1679 * new = o_node;
1680 * } else {
1681 * // Different thread or anonymous biased.
1682 * old = mark_word & (epoch_mask | age_mask | biased_lock_mask);
1683 * new = thread | old;
1684 * }
1685 * // Try to rebias.
1686 * if( cas(&mark_word, old, new) == 0 ) {
1687 * // Done.
1688 * } else {
1689 * goto slow_path; // Failed.
1690 * }
1691 * }
1692 * }
1693 * } else {
1694 * // The object is not biased.
1695 * cas_lock:
1696 * if( FastLock(obj) == 0 ) {
1697 * // Done.
1698 * } else {
1699 * slow_path:
1700 * OptoRuntime::complete_monitor_locking_Java(obj);
1701 * }
1702 * }
1703 */
1704
1705 region = new (C, 5) RegionNode(5);
1706 // create a Phi for the memory state
1707 mem_phi = new (C, 5) PhiNode( region, Type::MEMORY, TypeRawPtr::BOTTOM);
1708
1709 Node* fast_lock_region = new (C, 3) RegionNode(3);
1710 Node* fast_lock_mem_phi = new (C, 3) PhiNode( fast_lock_region, Type::MEMORY, TypeRawPtr::BOTTOM);
1711
1712 // First, check mark word for the biased lock pattern.
1713 Node* mark_node = make_load(ctrl, mem, obj, oopDesc::mark_offset_in_bytes(), TypeX_X, TypeX_X->basic_type());
1714
1715 // Get fast path - mark word has the biased lock pattern.
1716 ctrl = opt_bits_test(ctrl, fast_lock_region, 1, mark_node,
1717 markOopDesc::biased_lock_mask_in_place,
1718 markOopDesc::biased_lock_pattern, true);
1719 // fast_lock_region->in(1) is set to slow path.
1720 fast_lock_mem_phi->init_req(1, mem);
1721
1722 // Now check that the lock is biased to the current thread and has
1723 // the same epoch and bias as Klass::_prototype_header.
1724
1725 // Special-case a fresh allocation to avoid building nodes:
1726 Node* klass_node = AllocateNode::Ideal_klass(obj, &_igvn);
1727 if (klass_node == NULL) {
1728 Node* k_adr = basic_plus_adr(obj, oopDesc::klass_offset_in_bytes());
1729 klass_node = transform_later( LoadKlassNode::make(_igvn, mem, k_adr, _igvn.type(k_adr)->is_ptr()) );
1730 #ifdef _LP64
1731 if (UseCompressedOops && klass_node->is_DecodeN()) {
1732 assert(klass_node->in(1)->Opcode() == Op_LoadNKlass, "sanity");
1733 klass_node->in(1)->init_req(0, ctrl);
1734 } else
1735 #endif
1736 klass_node->init_req(0, ctrl);
1737 }
1738 Node *proto_node = make_load(ctrl, mem, klass_node, Klass::prototype_header_offset_in_bytes() + sizeof(oopDesc), TypeX_X, TypeX_X->basic_type());
1739
1740 Node* thread = transform_later(new (C, 1) ThreadLocalNode());
1741 Node* cast_thread = transform_later(new (C, 2) CastP2XNode(ctrl, thread));
1742 Node* o_node = transform_later(new (C, 3) OrXNode(cast_thread, proto_node));
1743 Node* x_node = transform_later(new (C, 3) XorXNode(o_node, mark_node));
1744
1745 // Get slow path - mark word does NOT match the value.
1746 Node* not_biased_ctrl = opt_bits_test(ctrl, region, 3, x_node,
1747 (~markOopDesc::age_mask_in_place), 0);
1748 // region->in(3) is set to fast path - the object is biased to the current thread.
1749 mem_phi->init_req(3, mem);
1750
1751
1752 // Mark word does NOT match the value (thread | Klass::_prototype_header).
1753
1754
1755 // First, check biased pattern.
1756 // Get fast path - _prototype_header has the same biased lock pattern.
1757 ctrl = opt_bits_test(not_biased_ctrl, fast_lock_region, 2, x_node,
1758 markOopDesc::biased_lock_mask_in_place, 0, true);
1759
1760 not_biased_ctrl = fast_lock_region->in(2); // Slow path
1761 // fast_lock_region->in(2) - the prototype header is no longer biased
1762 // and we have to revoke the bias on this object.
1763 // We are going to try to reset the mark of this object to the prototype
1764 // value and fall through to the CAS-based locking scheme.
1765 Node* adr = basic_plus_adr(obj, oopDesc::mark_offset_in_bytes());
1766 Node* cas = new (C, 5) StoreXConditionalNode(not_biased_ctrl, mem, adr,
1767 proto_node, mark_node);
1768 transform_later(cas);
1769 Node* proj = transform_later( new (C, 1) SCMemProjNode(cas));
1770 fast_lock_mem_phi->init_req(2, proj);
1771
1772
1773 // Second, check epoch bits.
1774 Node* rebiased_region = new (C, 3) RegionNode(3);
1775 Node* old_phi = new (C, 3) PhiNode( rebiased_region, TypeX_X);
1776 Node* new_phi = new (C, 3) PhiNode( rebiased_region, TypeX_X);
1777
1778 // Get slow path - mark word does NOT match epoch bits.
1779 Node* epoch_ctrl = opt_bits_test(ctrl, rebiased_region, 1, x_node,
1780 markOopDesc::epoch_mask_in_place, 0);
1781 // The epoch of the current bias is not valid, attempt to rebias the object
1782 // toward the current thread.
1783 rebiased_region->init_req(2, epoch_ctrl);
1784 old_phi->init_req(2, mark_node);
1785 new_phi->init_req(2, o_node);
1786
1787 // rebiased_region->in(1) is set to fast path.
1788 // The epoch of the current bias is still valid but we know
1789 // nothing about the owner; it might be set or it might be clear.
1790 Node* cmask = MakeConX(markOopDesc::biased_lock_mask_in_place |
1791 markOopDesc::age_mask_in_place |
1792 markOopDesc::epoch_mask_in_place);
1793 Node* old = transform_later(new (C, 3) AndXNode(mark_node, cmask));
1794 cast_thread = transform_later(new (C, 2) CastP2XNode(ctrl, thread));
1795 Node* new_mark = transform_later(new (C, 3) OrXNode(cast_thread, old));
1796 old_phi->init_req(1, old);
1797 new_phi->init_req(1, new_mark);
1798
1799 transform_later(rebiased_region);
1800 transform_later(old_phi);
1801 transform_later(new_phi);
1802
1803 // Try to acquire the bias of the object using an atomic operation.
1804 // If this fails we will go in to the runtime to revoke the object's bias.
1805 cas = new (C, 5) StoreXConditionalNode(rebiased_region, mem, adr,
1806 new_phi, old_phi);
1807 transform_later(cas);
1808 proj = transform_later( new (C, 1) SCMemProjNode(cas));
1809
1810 // Get slow path - Failed to CAS.
1811 not_biased_ctrl = opt_bits_test(rebiased_region, region, 4, cas, 0, 0);
1812 mem_phi->init_req(4, proj);
1813 // region->in(4) is set to fast path - the object is rebiased to the current thread.
1814
1815 // Failed to CAS.
1816 slow_path = new (C, 3) RegionNode(3);
1817 Node *slow_mem = new (C, 3) PhiNode( slow_path, Type::MEMORY, TypeRawPtr::BOTTOM);
1818
1819 slow_path->init_req(1, not_biased_ctrl); // Capture slow-control
1820 slow_mem->init_req(1, proj);
1821
1822 // Call CAS-based locking scheme (FastLock node).
1823
1824 transform_later(fast_lock_region);
1825 transform_later(fast_lock_mem_phi);
1826
1827 // Get slow path - FastLock failed to lock the object.
1828 ctrl = opt_bits_test(fast_lock_region, region, 2, flock, 0, 0);
1829 mem_phi->init_req(2, fast_lock_mem_phi);
1830 // region->in(2) is set to fast path - the object is locked to the current thread.
1831
1832 slow_path->init_req(2, ctrl); // Capture slow-control
1833 slow_mem->init_req(2, fast_lock_mem_phi);
1834
1835 transform_later(slow_path);
1836 transform_later(slow_mem);
1837 // Reset lock's memory edge.
1838 lock->set_req(TypeFunc::Memory, slow_mem);
1839
1840 } else {
1841 region = new (C, 3) RegionNode(3);
1842 // create a Phi for the memory state
1843 mem_phi = new (C, 3) PhiNode( region, Type::MEMORY, TypeRawPtr::BOTTOM);
1844
1845 // Optimize test; set region slot 2
1846 slow_path = opt_bits_test(ctrl, region, 2, flock, 0, 0);
1847 mem_phi->init_req(2, mem);
1848 }
1849
1850 // Make slow path call
1851 CallNode *call = make_slow_call( (CallNode *) lock, OptoRuntime::complete_monitor_enter_Type(), OptoRuntime::complete_monitor_locking_Java(), NULL, slow_path, obj, box );
1852
1853 extract_call_projections(call);
1854
1855 // Slow path can only throw asynchronous exceptions, which are always
1856 // de-opted. So the compiler thinks the slow-call can never throw an
1857 // exception. If it DOES throw an exception we would need the debug
1858 // info removed first (since if it throws there is no monitor).
1859 assert ( _ioproj_fallthrough == NULL && _ioproj_catchall == NULL &&
1860 _memproj_catchall == NULL && _catchallcatchproj == NULL, "Unexpected projection from Lock");
1861
1862 // Capture slow path
1863 // disconnect fall-through projection from call and create a new one
1864 // hook up users of fall-through projection to region
1865 Node *slow_ctrl = _fallthroughproj->clone();
1866 transform_later(slow_ctrl);
1867 _igvn.hash_delete(_fallthroughproj);
1868 _fallthroughproj->disconnect_inputs(NULL);
1869 region->init_req(1, slow_ctrl);
1870 // region inputs are now complete
1871 transform_later(region);
1872 _igvn.subsume_node(_fallthroughproj, region);
1873
1874 Node *memproj = transform_later( new(C, 1) ProjNode(call, TypeFunc::Memory) );
1875 mem_phi->init_req(1, memproj );
1876 transform_later(mem_phi);
1877 _igvn.hash_delete(_memproj_fallthrough);
1878 _igvn.subsume_node(_memproj_fallthrough, mem_phi);
1879 }
1880
1881 //------------------------------expand_unlock_node----------------------
1882 void PhaseMacroExpand::expand_unlock_node(UnlockNode *unlock) {
1883
1884 Node* ctrl = unlock->in(TypeFunc::Control);
1885 Node* mem = unlock->in(TypeFunc::Memory);
1886 Node* obj = unlock->obj_node();
1887 Node* box = unlock->box_node();
1888
1889 // No need for a null check on unlock
1890
1891 // Make the merge point
1892 Node *region;
1893 Node *mem_phi;
1894
1895 if (UseOptoBiasInlining) {
1896 // Check for biased locking unlock case, which is a no-op.
1897 // See the full descrition in MacroAssembler::biased_locking_exit().
1898 region = new (C, 4) RegionNode(4);
1899 // create a Phi for the memory state
1900 mem_phi = new (C, 4) PhiNode( region, Type::MEMORY, TypeRawPtr::BOTTOM);
1901 mem_phi->init_req(3, mem);
1902
1903 Node* mark_node = make_load(ctrl, mem, obj, oopDesc::mark_offset_in_bytes(), TypeX_X, TypeX_X->basic_type());
1904 ctrl = opt_bits_test(ctrl, region, 3, mark_node,
1905 markOopDesc::biased_lock_mask_in_place,
1906 markOopDesc::biased_lock_pattern);
1907 } else {
1908 region = new (C, 3) RegionNode(3);
1909 // create a Phi for the memory state
1910 mem_phi = new (C, 3) PhiNode( region, Type::MEMORY, TypeRawPtr::BOTTOM);
1911 }
1912
1913 FastUnlockNode *funlock = new (C, 3) FastUnlockNode( ctrl, obj, box );
1914 funlock = transform_later( funlock )->as_FastUnlock();
1915 // Optimize test; set region slot 2
1916 Node *slow_path = opt_bits_test(ctrl, region, 2, funlock, 0, 0);
1917
1918 CallNode *call = make_slow_call( (CallNode *) unlock, OptoRuntime::complete_monitor_exit_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::complete_monitor_unlocking_C), "complete_monitor_unlocking_C", slow_path, obj, box );
1919
1920 extract_call_projections(call);
1921
1922 assert ( _ioproj_fallthrough == NULL && _ioproj_catchall == NULL &&
1923 _memproj_catchall == NULL && _catchallcatchproj == NULL, "Unexpected projection from Lock");
1924
1925 // No exceptions for unlocking
1926 // Capture slow path
1927 // disconnect fall-through projection from call and create a new one
1928 // hook up users of fall-through projection to region
1929 Node *slow_ctrl = _fallthroughproj->clone();
1930 transform_later(slow_ctrl);
1931 _igvn.hash_delete(_fallthroughproj);
1932 _fallthroughproj->disconnect_inputs(NULL);
1933 region->init_req(1, slow_ctrl);
1934 // region inputs are now complete
1935 transform_later(region);
1936 _igvn.subsume_node(_fallthroughproj, region);
1937
1938 Node *memproj = transform_later( new(C, 1) ProjNode(call, TypeFunc::Memory) );
1939 mem_phi->init_req(1, memproj );
1940 mem_phi->init_req(2, mem);
1941 transform_later(mem_phi);
1942 _igvn.hash_delete(_memproj_fallthrough);
1943 _igvn.subsume_node(_memproj_fallthrough, mem_phi);
1944 }
1945
1946 //------------------------------expand_macro_nodes----------------------
1947 // Returns true if a failure occurred.
1948 bool PhaseMacroExpand::expand_macro_nodes() {
1949 if (C->macro_count() == 0)
1950 return false;
1951 // First, attempt to eliminate locks
1952 bool progress = true;
1953 while (progress) {
1954 progress = false;
1955 for (int i = C->macro_count(); i > 0; i--) {
1956 Node * n = C->macro_node(i-1);
1957 bool success = false;
1958 debug_only(int old_macro_count = C->macro_count(););
1959 if (n->is_AbstractLock()) {
1960 success = eliminate_locking_node(n->as_AbstractLock());
1961 } else if (n->Opcode() == Op_Opaque1 || n->Opcode() == Op_Opaque2) {
1962 _igvn.add_users_to_worklist(n);
1963 _igvn.hash_delete(n);
1964 _igvn.subsume_node(n, n->in(1));
1965 success = true;
1966 }
1967 assert(success == (C->macro_count() < old_macro_count), "elimination reduces macro count");
1968 progress = progress || success;
1969 }
1970 }
1971 // Next, attempt to eliminate allocations
1972 progress = true;
1973 while (progress) {
1974 progress = false;
1975 for (int i = C->macro_count(); i > 0; i--) {
1976 Node * n = C->macro_node(i-1);
1977 bool success = false;
1978 debug_only(int old_macro_count = C->macro_count(););
1979 switch (n->class_id()) {
1980 case Node::Class_Allocate:
1981 case Node::Class_AllocateArray:
1982 success = eliminate_allocate_node(n->as_Allocate());
1983 break;
1984 case Node::Class_Lock:
1985 case Node::Class_Unlock:
1986 assert(!n->as_AbstractLock()->is_eliminated(), "sanity");
1987 break;
1988 default:
1989 assert(false, "unknown node type in macro list");
1990 }
1991 assert(success == (C->macro_count() < old_macro_count), "elimination reduces macro count");
1992 progress = progress || success;
1993 }
1994 }
1995 // Make sure expansion will not cause node limit to be exceeded.
1996 // Worst case is a macro node gets expanded into about 50 nodes.
1997 // Allow 50% more for optimization.
1998 if (C->check_node_count(C->macro_count() * 75, "out of nodes before macro expansion" ) )
1999 return true;
2000
2001 // expand "macro" nodes
2002 // nodes are removed from the macro list as they are processed
2003 while (C->macro_count() > 0) {
2004 int macro_count = C->macro_count();
2005 Node * n = C->macro_node(macro_count-1);
2006 assert(n->is_macro(), "only macro nodes expected here");
2007 if (_igvn.type(n) == Type::TOP || n->in(0)->is_top() ) {
2008 // node is unreachable, so don't try to expand it
2009 C->remove_macro_node(n);
2010 continue;
2011 }
2012 switch (n->class_id()) {
2013 case Node::Class_Allocate:
2014 expand_allocate(n->as_Allocate());
2015 break;
2016 case Node::Class_AllocateArray:
2017 expand_allocate_array(n->as_AllocateArray());
2018 break;
2019 case Node::Class_Lock:
2020 expand_lock_node(n->as_Lock());
2021 break;
2022 case Node::Class_Unlock:
2023 expand_unlock_node(n->as_Unlock());
2024 break;
2025 default:
2026 assert(false, "unknown node type in macro list");
2027 }
2028 assert(C->macro_count() < macro_count, "must have deleted a node from macro list");
2029 if (C->failing()) return true;
2030 }
2031
2032 _igvn.set_delay_transform(false);
2033 _igvn.optimize();
2034 return false;
2035 }
2036
|