1 /*
2  * Copyright (c) 1998, 2020, Oracle and/or its affiliates. All rights reserved.
3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4  *
5  * This code is free software; you can redistribute it and/or modify it
6  * under the terms of the GNU General Public License version 2 only, as
7  * published by the Free Software Foundation.
8  *
9  * This code is distributed in the hope that it will be useful, but WITHOUT
10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
12  * version 2 for more details (a copy is included in the LICENSE file that
13  * accompanied this code).
14  *
15  * You should have received a copy of the GNU General Public License version
16  * 2 along with this work; if not, write to the Free Software Foundation,
17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18  *
19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20  * or visit www.oracle.com if you need additional information or have any
21  * questions.
22  *
23  */
24 
25 #include "precompiled.hpp"
26 #include "asm/assembler.inline.hpp"
27 #include "asm/macroAssembler.inline.hpp"
28 #include "code/compiledIC.hpp"
29 #include "code/debugInfo.hpp"
30 #include "code/debugInfoRec.hpp"
31 #include "compiler/compileBroker.hpp"
32 #include "compiler/compilerDirectives.hpp"
33 #include "compiler/disassembler.hpp"
34 #include "compiler/oopMap.hpp"
35 #include "gc/shared/barrierSet.hpp"
36 #include "gc/shared/c2/barrierSetC2.hpp"
37 #include "memory/allocation.inline.hpp"
38 #include "opto/ad.hpp"
39 #include "opto/block.hpp"
40 #include "opto/c2compiler.hpp"
41 #include "opto/callnode.hpp"
42 #include "opto/cfgnode.hpp"
43 #include "opto/locknode.hpp"
44 #include "opto/machnode.hpp"
45 #include "opto/node.hpp"
46 #include "opto/optoreg.hpp"
47 #include "opto/output.hpp"
48 #include "opto/regalloc.hpp"
49 #include "opto/runtime.hpp"
50 #include "opto/subnode.hpp"
51 #include "opto/type.hpp"
52 #include "runtime/handles.inline.hpp"
53 #include "runtime/sharedRuntime.hpp"
54 #include "utilities/macros.hpp"
55 #include "utilities/powerOfTwo.hpp"
56 #include "utilities/xmlstream.hpp"
57 
58 #ifndef PRODUCT
59 #define DEBUG_ARG(x) , x
60 #else
61 #define DEBUG_ARG(x)
62 #endif
63 
64 //------------------------------Scheduling----------------------------------
65 // This class contains all the information necessary to implement instruction
66 // scheduling and bundling.
67 class Scheduling {
68 
69 private:
70   // Arena to use
71   Arena *_arena;
72 
73   // Control-Flow Graph info
74   PhaseCFG *_cfg;
75 
76   // Register Allocation info
77   PhaseRegAlloc *_regalloc;
78 
79   // Number of nodes in the method
80   uint _node_bundling_limit;
81 
82   // List of scheduled nodes. Generated in reverse order
83   Node_List _scheduled;
84 
85   // List of nodes currently available for choosing for scheduling
86   Node_List _available;
87 
88   // For each instruction beginning a bundle, the number of following
89   // nodes to be bundled with it.
90   Bundle *_node_bundling_base;
91 
92   // Mapping from register to Node
93   Node_List _reg_node;
94 
95   // Free list for pinch nodes.
96   Node_List _pinch_free_list;
97 
98   // Latency from the beginning of the containing basic block (base 1)
99   // for each node.
100   unsigned short *_node_latency;
101 
102   // Number of uses of this node within the containing basic block.
103   short *_uses;
104 
105   // Schedulable portion of current block.  Skips Region/Phi/CreateEx up
106   // front, branch+proj at end.  Also skips Catch/CProj (same as
107   // branch-at-end), plus just-prior exception-throwing call.
108   uint _bb_start, _bb_end;
109 
110   // Latency from the end of the basic block as scheduled
111   unsigned short *_current_latency;
112 
113   // Remember the next node
114   Node *_next_node;
115 
116   // Use this for an unconditional branch delay slot
117   Node *_unconditional_delay_slot;
118 
119   // Pointer to a Nop
120   MachNopNode *_nop;
121 
122   // Length of the current bundle, in instructions
123   uint _bundle_instr_count;
124 
125   // Current Cycle number, for computing latencies and bundling
126   uint _bundle_cycle_number;
127 
128   // Bundle information
129   Pipeline_Use_Element _bundle_use_elements[resource_count];
130   Pipeline_Use         _bundle_use;
131 
132   // Dump the available list
133   void dump_available() const;
134 
135 public:
136   Scheduling(Arena *arena, Compile &compile);
137 
138   // Destructor
139   NOT_PRODUCT( ~Scheduling(); )
140 
141   // Step ahead "i" cycles
142   void step(uint i);
143 
144   // Step ahead 1 cycle, and clear the bundle state (for example,
145   // at a branch target)
146   void step_and_clear();
147 
node_bundling(const Node * n)148   Bundle* node_bundling(const Node *n) {
149     assert(valid_bundle_info(n), "oob");
150     return (&_node_bundling_base[n->_idx]);
151   }
152 
valid_bundle_info(const Node * n) const153   bool valid_bundle_info(const Node *n) const {
154     return (_node_bundling_limit > n->_idx);
155   }
156 
starts_bundle(const Node * n) const157   bool starts_bundle(const Node *n) const {
158     return (_node_bundling_limit > n->_idx && _node_bundling_base[n->_idx].starts_bundle());
159   }
160 
161   // Do the scheduling
162   void DoScheduling();
163 
164   // Compute the local latencies walking forward over the list of
165   // nodes for a basic block
166   void ComputeLocalLatenciesForward(const Block *bb);
167 
168   // Compute the register antidependencies within a basic block
169   void ComputeRegisterAntidependencies(Block *bb);
170   void verify_do_def( Node *n, OptoReg::Name def, const char *msg );
171   void verify_good_schedule( Block *b, const char *msg );
172   void anti_do_def( Block *b, Node *def, OptoReg::Name def_reg, int is_def );
173   void anti_do_use( Block *b, Node *use, OptoReg::Name use_reg );
174 
175   // Add a node to the current bundle
176   void AddNodeToBundle(Node *n, const Block *bb);
177 
178   // Add a node to the list of available nodes
179   void AddNodeToAvailableList(Node *n);
180 
181   // Compute the local use count for the nodes in a block, and compute
182   // the list of instructions with no uses in the block as available
183   void ComputeUseCount(const Block *bb);
184 
185   // Choose an instruction from the available list to add to the bundle
186   Node * ChooseNodeToBundle();
187 
188   // See if this Node fits into the currently accumulating bundle
189   bool NodeFitsInBundle(Node *n);
190 
191   // Decrement the use count for a node
192  void DecrementUseCounts(Node *n, const Block *bb);
193 
194   // Garbage collect pinch nodes for reuse by other blocks.
195   void garbage_collect_pinch_nodes();
196   // Clean up a pinch node for reuse (helper for above).
197   void cleanup_pinch( Node *pinch );
198 
199   // Information for statistics gathering
200 #ifndef PRODUCT
201 private:
202   // Gather information on size of nops relative to total
203   uint _branches, _unconditional_delays;
204 
205   static uint _total_nop_size, _total_method_size;
206   static uint _total_branches, _total_unconditional_delays;
207   static uint _total_instructions_per_bundle[Pipeline::_max_instrs_per_cycle+1];
208 
209 public:
210   static void print_statistics();
211 
increment_instructions_per_bundle(uint i)212   static void increment_instructions_per_bundle(uint i) {
213     _total_instructions_per_bundle[i]++;
214   }
215 
increment_nop_size(uint s)216   static void increment_nop_size(uint s) {
217     _total_nop_size += s;
218   }
219 
increment_method_size(uint s)220   static void increment_method_size(uint s) {
221     _total_method_size += s;
222   }
223 #endif
224 
225 };
226 
227 
PhaseOutput()228 PhaseOutput::PhaseOutput()
229   : Phase(Phase::Output),
230     _code_buffer("Compile::Fill_buffer"),
231     _first_block_size(0),
232     _handler_table(),
233     _inc_table(),
234     _oop_map_set(NULL),
235     _scratch_buffer_blob(NULL),
236     _scratch_locs_memory(NULL),
237     _scratch_const_size(-1),
238     _in_scratch_emit_size(false),
239     _frame_slots(0),
240     _code_offsets(),
241     _node_bundling_limit(0),
242     _node_bundling_base(NULL),
243     _orig_pc_slot(0),
244     _orig_pc_slot_offset_in_bytes(0),
245     _buf_sizes(),
246     _block(NULL),
247     _index(0) {
248   C->set_output(this);
249   if (C->stub_name() == NULL) {
250     _orig_pc_slot = C->fixed_slots() - (sizeof(address) / VMRegImpl::stack_slot_size);
251   }
252 }
253 
~PhaseOutput()254 PhaseOutput::~PhaseOutput() {
255   C->set_output(NULL);
256   if (_scratch_buffer_blob != NULL) {
257     BufferBlob::free(_scratch_buffer_blob);
258   }
259 }
260 
perform_mach_node_analysis()261 void PhaseOutput::perform_mach_node_analysis() {
262   // Late barrier analysis must be done after schedule and bundle
263   // Otherwise liveness based spilling will fail
264   BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
265   bs->late_barrier_analysis();
266 
267   pd_perform_mach_node_analysis();
268 }
269 
270 // Convert Nodes to instruction bits and pass off to the VM
Output()271 void PhaseOutput::Output() {
272   // RootNode goes
273   assert( C->cfg()->get_root_block()->number_of_nodes() == 0, "" );
274 
275   // The number of new nodes (mostly MachNop) is proportional to
276   // the number of java calls and inner loops which are aligned.
277   if ( C->check_node_count((NodeLimitFudgeFactor + C->java_calls()*3 +
278                             C->inner_loops()*(OptoLoopAlignment-1)),
279                            "out of nodes before code generation" ) ) {
280     return;
281   }
282   // Make sure I can find the Start Node
283   Block *entry = C->cfg()->get_block(1);
284   Block *broot = C->cfg()->get_root_block();
285 
286   const StartNode *start = entry->head()->as_Start();
287 
288   // Replace StartNode with prolog
289   MachPrologNode *prolog = new MachPrologNode();
290   entry->map_node(prolog, 0);
291   C->cfg()->map_node_to_block(prolog, entry);
292   C->cfg()->unmap_node_from_block(start); // start is no longer in any block
293 
294   // Virtual methods need an unverified entry point
295 
296   if( C->is_osr_compilation() ) {
297     if( PoisonOSREntry ) {
298       // TODO: Should use a ShouldNotReachHereNode...
299       C->cfg()->insert( broot, 0, new MachBreakpointNode() );
300     }
301   } else {
302     if( C->method() && !C->method()->flags().is_static() ) {
303       // Insert unvalidated entry point
304       C->cfg()->insert( broot, 0, new MachUEPNode() );
305     }
306 
307   }
308 
309   // Break before main entry point
310   if ((C->method() && C->directive()->BreakAtExecuteOption) ||
311       (OptoBreakpoint && C->is_method_compilation())       ||
312       (OptoBreakpointOSR && C->is_osr_compilation())       ||
313       (OptoBreakpointC2R && !C->method())                   ) {
314     // checking for C->method() means that OptoBreakpoint does not apply to
315     // runtime stubs or frame converters
316     C->cfg()->insert( entry, 1, new MachBreakpointNode() );
317   }
318 
319   // Insert epilogs before every return
320   for (uint i = 0; i < C->cfg()->number_of_blocks(); i++) {
321     Block* block = C->cfg()->get_block(i);
322     if (!block->is_connector() && block->non_connector_successor(0) == C->cfg()->get_root_block()) { // Found a program exit point?
323       Node* m = block->end();
324       if (m->is_Mach() && m->as_Mach()->ideal_Opcode() != Op_Halt) {
325         MachEpilogNode* epilog = new MachEpilogNode(m->as_Mach()->ideal_Opcode() == Op_Return);
326         block->add_inst(epilog);
327         C->cfg()->map_node_to_block(epilog, block);
328       }
329     }
330   }
331 
332   // Keeper of sizing aspects
333   _buf_sizes = BufferSizingData();
334 
335   // Initialize code buffer
336   estimate_buffer_size(_buf_sizes._const);
337   if (C->failing()) return;
338 
339   // Pre-compute the length of blocks and replace
340   // long branches with short if machine supports it.
341   // Must be done before ScheduleAndBundle due to SPARC delay slots
342   uint* blk_starts = NEW_RESOURCE_ARRAY(uint, C->cfg()->number_of_blocks() + 1);
343   blk_starts[0] = 0;
344   shorten_branches(blk_starts);
345 
346   ScheduleAndBundle();
347   if (C->failing()) {
348     return;
349   }
350 
351   perform_mach_node_analysis();
352 
353   // Complete sizing of codebuffer
354   CodeBuffer* cb = init_buffer();
355   if (cb == NULL || C->failing()) {
356     return;
357   }
358 
359   BuildOopMaps();
360 
361   if (C->failing())  {
362     return;
363   }
364 
365   fill_buffer(cb, blk_starts);
366 }
367 
need_stack_bang(int frame_size_in_bytes) const368 bool PhaseOutput::need_stack_bang(int frame_size_in_bytes) const {
369   // Determine if we need to generate a stack overflow check.
370   // Do it if the method is not a stub function and
371   // has java calls or has frame size > vm_page_size/8.
372   // The debug VM checks that deoptimization doesn't trigger an
373   // unexpected stack overflow (compiled method stack banging should
374   // guarantee it doesn't happen) so we always need the stack bang in
375   // a debug VM.
376   return (UseStackBanging && C->stub_function() == NULL &&
377           (C->has_java_calls() || frame_size_in_bytes > os::vm_page_size()>>3
378            DEBUG_ONLY(|| true)));
379 }
380 
need_register_stack_bang() const381 bool PhaseOutput::need_register_stack_bang() const {
382   // Determine if we need to generate a register stack overflow check.
383   // This is only used on architectures which have split register
384   // and memory stacks (ie. IA64).
385   // Bang if the method is not a stub function and has java calls
386   return (C->stub_function() == NULL && C->has_java_calls());
387 }
388 
389 
390 // Compute the size of first NumberOfLoopInstrToAlign instructions at the top
391 // of a loop. When aligning a loop we need to provide enough instructions
392 // in cpu's fetch buffer to feed decoders. The loop alignment could be
393 // avoided if we have enough instructions in fetch buffer at the head of a loop.
394 // By default, the size is set to 999999 by Block's constructor so that
395 // a loop will be aligned if the size is not reset here.
396 //
397 // Note: Mach instructions could contain several HW instructions
398 // so the size is estimated only.
399 //
compute_loop_first_inst_sizes()400 void PhaseOutput::compute_loop_first_inst_sizes() {
401   // The next condition is used to gate the loop alignment optimization.
402   // Don't aligned a loop if there are enough instructions at the head of a loop
403   // or alignment padding is larger then MaxLoopPad. By default, MaxLoopPad
404   // is equal to OptoLoopAlignment-1 except on new Intel cpus, where it is
405   // equal to 11 bytes which is the largest address NOP instruction.
406   if (MaxLoopPad < OptoLoopAlignment - 1) {
407     uint last_block = C->cfg()->number_of_blocks() - 1;
408     for (uint i = 1; i <= last_block; i++) {
409       Block* block = C->cfg()->get_block(i);
410       // Check the first loop's block which requires an alignment.
411       if (block->loop_alignment() > (uint)relocInfo::addr_unit()) {
412         uint sum_size = 0;
413         uint inst_cnt = NumberOfLoopInstrToAlign;
414         inst_cnt = block->compute_first_inst_size(sum_size, inst_cnt, C->regalloc());
415 
416         // Check subsequent fallthrough blocks if the loop's first
417         // block(s) does not have enough instructions.
418         Block *nb = block;
419         while(inst_cnt > 0 &&
420               i < last_block &&
421               !C->cfg()->get_block(i + 1)->has_loop_alignment() &&
422               !nb->has_successor(block)) {
423           i++;
424           nb = C->cfg()->get_block(i);
425           inst_cnt  = nb->compute_first_inst_size(sum_size, inst_cnt, C->regalloc());
426         } // while( inst_cnt > 0 && i < last_block  )
427 
428         block->set_first_inst_size(sum_size);
429       } // f( b->head()->is_Loop() )
430     } // for( i <= last_block )
431   } // if( MaxLoopPad < OptoLoopAlignment-1 )
432 }
433 
434 // The architecture description provides short branch variants for some long
435 // branch instructions. Replace eligible long branches with short branches.
shorten_branches(uint * blk_starts)436 void PhaseOutput::shorten_branches(uint* blk_starts) {
437   // Compute size of each block, method size, and relocation information size
438   uint nblocks  = C->cfg()->number_of_blocks();
439 
440   uint*      jmp_offset = NEW_RESOURCE_ARRAY(uint,nblocks);
441   uint*      jmp_size   = NEW_RESOURCE_ARRAY(uint,nblocks);
442   int*       jmp_nidx   = NEW_RESOURCE_ARRAY(int ,nblocks);
443 
444   // Collect worst case block paddings
445   int* block_worst_case_pad = NEW_RESOURCE_ARRAY(int, nblocks);
446   memset(block_worst_case_pad, 0, nblocks * sizeof(int));
447 
448   DEBUG_ONLY( uint *jmp_target = NEW_RESOURCE_ARRAY(uint,nblocks); )
449   DEBUG_ONLY( uint *jmp_rule = NEW_RESOURCE_ARRAY(uint,nblocks); )
450 
451   bool has_short_branch_candidate = false;
452 
453   // Initialize the sizes to 0
454   int code_size  = 0;          // Size in bytes of generated code
455   int stub_size  = 0;          // Size in bytes of all stub entries
456   // Size in bytes of all relocation entries, including those in local stubs.
457   // Start with 2-bytes of reloc info for the unvalidated entry point
458   int reloc_size = 1;          // Number of relocation entries
459 
460   // Make three passes.  The first computes pessimistic blk_starts,
461   // relative jmp_offset and reloc_size information.  The second performs
462   // short branch substitution using the pessimistic sizing.  The
463   // third inserts nops where needed.
464 
465   // Step one, perform a pessimistic sizing pass.
466   uint last_call_adr = max_juint;
467   uint last_avoid_back_to_back_adr = max_juint;
468   uint nop_size = (new MachNopNode())->size(C->regalloc());
469   for (uint i = 0; i < nblocks; i++) { // For all blocks
470     Block* block = C->cfg()->get_block(i);
471     _block = block;
472 
473     // During short branch replacement, we store the relative (to blk_starts)
474     // offset of jump in jmp_offset, rather than the absolute offset of jump.
475     // This is so that we do not need to recompute sizes of all nodes when
476     // we compute correct blk_starts in our next sizing pass.
477     jmp_offset[i] = 0;
478     jmp_size[i]   = 0;
479     jmp_nidx[i]   = -1;
480     DEBUG_ONLY( jmp_target[i] = 0; )
481     DEBUG_ONLY( jmp_rule[i]   = 0; )
482 
483     // Sum all instruction sizes to compute block size
484     uint last_inst = block->number_of_nodes();
485     uint blk_size = 0;
486     for (uint j = 0; j < last_inst; j++) {
487       _index = j;
488       Node* nj = block->get_node(_index);
489       // Handle machine instruction nodes
490       if (nj->is_Mach()) {
491         MachNode* mach = nj->as_Mach();
492         blk_size += (mach->alignment_required() - 1) * relocInfo::addr_unit(); // assume worst case padding
493         reloc_size += mach->reloc();
494         if (mach->is_MachCall()) {
495           // add size information for trampoline stub
496           // class CallStubImpl is platform-specific and defined in the *.ad files.
497           stub_size  += CallStubImpl::size_call_trampoline();
498           reloc_size += CallStubImpl::reloc_call_trampoline();
499 
500           MachCallNode *mcall = mach->as_MachCall();
501           // This destination address is NOT PC-relative
502 
503           mcall->method_set((intptr_t)mcall->entry_point());
504 
505           if (mcall->is_MachCallJava() && mcall->as_MachCallJava()->_method) {
506             stub_size  += CompiledStaticCall::to_interp_stub_size();
507             reloc_size += CompiledStaticCall::reloc_to_interp_stub();
508 #if INCLUDE_AOT
509             stub_size  += CompiledStaticCall::to_aot_stub_size();
510             reloc_size += CompiledStaticCall::reloc_to_aot_stub();
511 #endif
512           }
513         } else if (mach->is_MachSafePoint()) {
514           // If call/safepoint are adjacent, account for possible
515           // nop to disambiguate the two safepoints.
516           // ScheduleAndBundle() can rearrange nodes in a block,
517           // check for all offsets inside this block.
518           if (last_call_adr >= blk_starts[i]) {
519             blk_size += nop_size;
520           }
521         }
522         if (mach->avoid_back_to_back(MachNode::AVOID_BEFORE)) {
523           // Nop is inserted between "avoid back to back" instructions.
524           // ScheduleAndBundle() can rearrange nodes in a block,
525           // check for all offsets inside this block.
526           if (last_avoid_back_to_back_adr >= blk_starts[i]) {
527             blk_size += nop_size;
528           }
529         }
530         if (mach->may_be_short_branch()) {
531           if (!nj->is_MachBranch()) {
532 #ifndef PRODUCT
533             nj->dump(3);
534 #endif
535             Unimplemented();
536           }
537           assert(jmp_nidx[i] == -1, "block should have only one branch");
538           jmp_offset[i] = blk_size;
539           jmp_size[i]   = nj->size(C->regalloc());
540           jmp_nidx[i]   = j;
541           has_short_branch_candidate = true;
542         }
543       }
544       blk_size += nj->size(C->regalloc());
545       // Remember end of call offset
546       if (nj->is_MachCall() && !nj->is_MachCallLeaf()) {
547         last_call_adr = blk_starts[i]+blk_size;
548       }
549       // Remember end of avoid_back_to_back offset
550       if (nj->is_Mach() && nj->as_Mach()->avoid_back_to_back(MachNode::AVOID_AFTER)) {
551         last_avoid_back_to_back_adr = blk_starts[i]+blk_size;
552       }
553     }
554 
555     // When the next block starts a loop, we may insert pad NOP
556     // instructions.  Since we cannot know our future alignment,
557     // assume the worst.
558     if (i < nblocks - 1) {
559       Block* nb = C->cfg()->get_block(i + 1);
560       int max_loop_pad = nb->code_alignment()-relocInfo::addr_unit();
561       if (max_loop_pad > 0) {
562         assert(is_power_of_2(max_loop_pad+relocInfo::addr_unit()), "");
563         // Adjust last_call_adr and/or last_avoid_back_to_back_adr.
564         // If either is the last instruction in this block, bump by
565         // max_loop_pad in lock-step with blk_size, so sizing
566         // calculations in subsequent blocks still can conservatively
567         // detect that it may the last instruction in this block.
568         if (last_call_adr == blk_starts[i]+blk_size) {
569           last_call_adr += max_loop_pad;
570         }
571         if (last_avoid_back_to_back_adr == blk_starts[i]+blk_size) {
572           last_avoid_back_to_back_adr += max_loop_pad;
573         }
574         blk_size += max_loop_pad;
575         block_worst_case_pad[i + 1] = max_loop_pad;
576       }
577     }
578 
579     // Save block size; update total method size
580     blk_starts[i+1] = blk_starts[i]+blk_size;
581   }
582 
583   // Step two, replace eligible long jumps.
584   bool progress = true;
585   uint last_may_be_short_branch_adr = max_juint;
586   while (has_short_branch_candidate && progress) {
587     progress = false;
588     has_short_branch_candidate = false;
589     int adjust_block_start = 0;
590     for (uint i = 0; i < nblocks; i++) {
591       Block* block = C->cfg()->get_block(i);
592       int idx = jmp_nidx[i];
593       MachNode* mach = (idx == -1) ? NULL: block->get_node(idx)->as_Mach();
594       if (mach != NULL && mach->may_be_short_branch()) {
595 #ifdef ASSERT
596         assert(jmp_size[i] > 0 && mach->is_MachBranch(), "sanity");
597         int j;
598         // Find the branch; ignore trailing NOPs.
599         for (j = block->number_of_nodes()-1; j>=0; j--) {
600           Node* n = block->get_node(j);
601           if (!n->is_Mach() || n->as_Mach()->ideal_Opcode() != Op_Con)
602             break;
603         }
604         assert(j >= 0 && j == idx && block->get_node(j) == (Node*)mach, "sanity");
605 #endif
606         int br_size = jmp_size[i];
607         int br_offs = blk_starts[i] + jmp_offset[i];
608 
609         // This requires the TRUE branch target be in succs[0]
610         uint bnum = block->non_connector_successor(0)->_pre_order;
611         int offset = blk_starts[bnum] - br_offs;
612         if (bnum > i) { // adjust following block's offset
613           offset -= adjust_block_start;
614         }
615 
616         // This block can be a loop header, account for the padding
617         // in the previous block.
618         int block_padding = block_worst_case_pad[i];
619         assert(i == 0 || block_padding == 0 || br_offs >= block_padding, "Should have at least a padding on top");
620         // In the following code a nop could be inserted before
621         // the branch which will increase the backward distance.
622         bool needs_padding = ((uint)(br_offs - block_padding) == last_may_be_short_branch_adr);
623         assert(!needs_padding || jmp_offset[i] == 0, "padding only branches at the beginning of block");
624 
625         if (needs_padding && offset <= 0)
626           offset -= nop_size;
627 
628         if (C->matcher()->is_short_branch_offset(mach->rule(), br_size, offset)) {
629           // We've got a winner.  Replace this branch.
630           MachNode* replacement = mach->as_MachBranch()->short_branch_version();
631 
632           // Update the jmp_size.
633           int new_size = replacement->size(C->regalloc());
634           int diff     = br_size - new_size;
635           assert(diff >= (int)nop_size, "short_branch size should be smaller");
636           // Conservatively take into account padding between
637           // avoid_back_to_back branches. Previous branch could be
638           // converted into avoid_back_to_back branch during next
639           // rounds.
640           if (needs_padding && replacement->avoid_back_to_back(MachNode::AVOID_BEFORE)) {
641             jmp_offset[i] += nop_size;
642             diff -= nop_size;
643           }
644           adjust_block_start += diff;
645           block->map_node(replacement, idx);
646           mach->subsume_by(replacement, C);
647           mach = replacement;
648           progress = true;
649 
650           jmp_size[i] = new_size;
651           DEBUG_ONLY( jmp_target[i] = bnum; );
652           DEBUG_ONLY( jmp_rule[i] = mach->rule(); );
653         } else {
654           // The jump distance is not short, try again during next iteration.
655           has_short_branch_candidate = true;
656         }
657       } // (mach->may_be_short_branch())
658       if (mach != NULL && (mach->may_be_short_branch() ||
659                            mach->avoid_back_to_back(MachNode::AVOID_AFTER))) {
660         last_may_be_short_branch_adr = blk_starts[i] + jmp_offset[i] + jmp_size[i];
661       }
662       blk_starts[i+1] -= adjust_block_start;
663     }
664   }
665 
666 #ifdef ASSERT
667   for (uint i = 0; i < nblocks; i++) { // For all blocks
668     if (jmp_target[i] != 0) {
669       int br_size = jmp_size[i];
670       int offset = blk_starts[jmp_target[i]]-(blk_starts[i] + jmp_offset[i]);
671       if (!C->matcher()->is_short_branch_offset(jmp_rule[i], br_size, offset)) {
672         tty->print_cr("target (%d) - jmp_offset(%d) = offset (%d), jump_size(%d), jmp_block B%d, target_block B%d", blk_starts[jmp_target[i]], blk_starts[i] + jmp_offset[i], offset, br_size, i, jmp_target[i]);
673       }
674       assert(C->matcher()->is_short_branch_offset(jmp_rule[i], br_size, offset), "Displacement too large for short jmp");
675     }
676   }
677 #endif
678 
679   // Step 3, compute the offsets of all blocks, will be done in fill_buffer()
680   // after ScheduleAndBundle().
681 
682   // ------------------
683   // Compute size for code buffer
684   code_size = blk_starts[nblocks];
685 
686   // Relocation records
687   reloc_size += 1;              // Relo entry for exception handler
688 
689   // Adjust reloc_size to number of record of relocation info
690   // Min is 2 bytes, max is probably 6 or 8, with a tax up to 25% for
691   // a relocation index.
692   // The CodeBuffer will expand the locs array if this estimate is too low.
693   reloc_size *= 10 / sizeof(relocInfo);
694 
695   _buf_sizes._reloc = reloc_size;
696   _buf_sizes._code  = code_size;
697   _buf_sizes._stub  = stub_size;
698 }
699 
700 //------------------------------FillLocArray-----------------------------------
701 // Create a bit of debug info and append it to the array.  The mapping is from
702 // Java local or expression stack to constant, register or stack-slot.  For
703 // doubles, insert 2 mappings and return 1 (to tell the caller that the next
704 // entry has been taken care of and caller should skip it).
new_loc_value(PhaseRegAlloc * ra,OptoReg::Name regnum,Location::Type l_type)705 static LocationValue *new_loc_value( PhaseRegAlloc *ra, OptoReg::Name regnum, Location::Type l_type ) {
706   // This should never have accepted Bad before
707   assert(OptoReg::is_valid(regnum), "location must be valid");
708   return (OptoReg::is_reg(regnum))
709          ? new LocationValue(Location::new_reg_loc(l_type, OptoReg::as_VMReg(regnum)) )
710          : new LocationValue(Location::new_stk_loc(l_type,  ra->reg2offset(regnum)));
711 }
712 
713 
714 ObjectValue*
sv_for_node_id(GrowableArray<ScopeValue * > * objs,int id)715 PhaseOutput::sv_for_node_id(GrowableArray<ScopeValue*> *objs, int id) {
716   for (int i = 0; i < objs->length(); i++) {
717     assert(objs->at(i)->is_object(), "corrupt object cache");
718     ObjectValue* sv = (ObjectValue*) objs->at(i);
719     if (sv->id() == id) {
720       return sv;
721     }
722   }
723   // Otherwise..
724   return NULL;
725 }
726 
set_sv_for_object_node(GrowableArray<ScopeValue * > * objs,ObjectValue * sv)727 void PhaseOutput::set_sv_for_object_node(GrowableArray<ScopeValue*> *objs,
728                                      ObjectValue* sv ) {
729   assert(sv_for_node_id(objs, sv->id()) == NULL, "Precondition");
730   objs->append(sv);
731 }
732 
733 
FillLocArray(int idx,MachSafePointNode * sfpt,Node * local,GrowableArray<ScopeValue * > * array,GrowableArray<ScopeValue * > * objs)734 void PhaseOutput::FillLocArray( int idx, MachSafePointNode* sfpt, Node *local,
735                             GrowableArray<ScopeValue*> *array,
736                             GrowableArray<ScopeValue*> *objs ) {
737   assert( local, "use _top instead of null" );
738   if (array->length() != idx) {
739     assert(array->length() == idx + 1, "Unexpected array count");
740     // Old functionality:
741     //   return
742     // New functionality:
743     //   Assert if the local is not top. In product mode let the new node
744     //   override the old entry.
745     assert(local == C->top(), "LocArray collision");
746     if (local == C->top()) {
747       return;
748     }
749     array->pop();
750   }
751   const Type *t = local->bottom_type();
752 
753   // Is it a safepoint scalar object node?
754   if (local->is_SafePointScalarObject()) {
755     SafePointScalarObjectNode* spobj = local->as_SafePointScalarObject();
756 
757     ObjectValue* sv = sv_for_node_id(objs, spobj->_idx);
758     if (sv == NULL) {
759       ciKlass* cik = t->is_oopptr()->klass();
760       assert(cik->is_instance_klass() ||
761              cik->is_array_klass(), "Not supported allocation.");
762       sv = new ObjectValue(spobj->_idx,
763                            new ConstantOopWriteValue(cik->java_mirror()->constant_encoding()));
764       set_sv_for_object_node(objs, sv);
765 
766       uint first_ind = spobj->first_index(sfpt->jvms());
767       for (uint i = 0; i < spobj->n_fields(); i++) {
768         Node* fld_node = sfpt->in(first_ind+i);
769         (void)FillLocArray(sv->field_values()->length(), sfpt, fld_node, sv->field_values(), objs);
770       }
771     }
772     array->append(sv);
773     return;
774   }
775 
776   // Grab the register number for the local
777   OptoReg::Name regnum = C->regalloc()->get_reg_first(local);
778   if( OptoReg::is_valid(regnum) ) {// Got a register/stack?
779     // Record the double as two float registers.
780     // The register mask for such a value always specifies two adjacent
781     // float registers, with the lower register number even.
782     // Normally, the allocation of high and low words to these registers
783     // is irrelevant, because nearly all operations on register pairs
784     // (e.g., StoreD) treat them as a single unit.
785     // Here, we assume in addition that the words in these two registers
786     // stored "naturally" (by operations like StoreD and double stores
787     // within the interpreter) such that the lower-numbered register
788     // is written to the lower memory address.  This may seem like
789     // a machine dependency, but it is not--it is a requirement on
790     // the author of the <arch>.ad file to ensure that, for every
791     // even/odd double-register pair to which a double may be allocated,
792     // the word in the even single-register is stored to the first
793     // memory word.  (Note that register numbers are completely
794     // arbitrary, and are not tied to any machine-level encodings.)
795 #ifdef _LP64
796     if( t->base() == Type::DoubleBot || t->base() == Type::DoubleCon ) {
797       array->append(new ConstantIntValue((jint)0));
798       array->append(new_loc_value( C->regalloc(), regnum, Location::dbl ));
799     } else if ( t->base() == Type::Long ) {
800       array->append(new ConstantIntValue((jint)0));
801       array->append(new_loc_value( C->regalloc(), regnum, Location::lng ));
802     } else if ( t->base() == Type::RawPtr ) {
803       // jsr/ret return address which must be restored into a the full
804       // width 64-bit stack slot.
805       array->append(new_loc_value( C->regalloc(), regnum, Location::lng ));
806     }
807 #else //_LP64
808     if( t->base() == Type::DoubleBot || t->base() == Type::DoubleCon || t->base() == Type::Long ) {
809       // Repack the double/long as two jints.
810       // The convention the interpreter uses is that the second local
811       // holds the first raw word of the native double representation.
812       // This is actually reasonable, since locals and stack arrays
813       // grow downwards in all implementations.
814       // (If, on some machine, the interpreter's Java locals or stack
815       // were to grow upwards, the embedded doubles would be word-swapped.)
816       array->append(new_loc_value( C->regalloc(), OptoReg::add(regnum,1), Location::normal ));
817       array->append(new_loc_value( C->regalloc(),              regnum   , Location::normal ));
818     }
819 #endif //_LP64
820     else if( (t->base() == Type::FloatBot || t->base() == Type::FloatCon) &&
821              OptoReg::is_reg(regnum) ) {
822       array->append(new_loc_value( C->regalloc(), regnum, Matcher::float_in_double()
823                                                       ? Location::float_in_dbl : Location::normal ));
824     } else if( t->base() == Type::Int && OptoReg::is_reg(regnum) ) {
825       array->append(new_loc_value( C->regalloc(), regnum, Matcher::int_in_long
826                                                       ? Location::int_in_long : Location::normal ));
827     } else if( t->base() == Type::NarrowOop ) {
828       array->append(new_loc_value( C->regalloc(), regnum, Location::narrowoop ));
829     } else {
830       array->append(new_loc_value( C->regalloc(), regnum, C->regalloc()->is_oop(local) ? Location::oop : Location::normal ));
831     }
832     return;
833   }
834 
835   // No register.  It must be constant data.
836   switch (t->base()) {
837     case Type::Half:              // Second half of a double
838       ShouldNotReachHere();       // Caller should skip 2nd halves
839       break;
840     case Type::AnyPtr:
841       array->append(new ConstantOopWriteValue(NULL));
842       break;
843     case Type::AryPtr:
844     case Type::InstPtr:          // fall through
845       array->append(new ConstantOopWriteValue(t->isa_oopptr()->const_oop()->constant_encoding()));
846       break;
847     case Type::NarrowOop:
848       if (t == TypeNarrowOop::NULL_PTR) {
849         array->append(new ConstantOopWriteValue(NULL));
850       } else {
851         array->append(new ConstantOopWriteValue(t->make_ptr()->isa_oopptr()->const_oop()->constant_encoding()));
852       }
853       break;
854     case Type::Int:
855       array->append(new ConstantIntValue(t->is_int()->get_con()));
856       break;
857     case Type::RawPtr:
858       // A return address (T_ADDRESS).
859       assert((intptr_t)t->is_ptr()->get_con() < (intptr_t)0x10000, "must be a valid BCI");
860 #ifdef _LP64
861       // Must be restored to the full-width 64-bit stack slot.
862       array->append(new ConstantLongValue(t->is_ptr()->get_con()));
863 #else
864       array->append(new ConstantIntValue(t->is_ptr()->get_con()));
865 #endif
866       break;
867     case Type::FloatCon: {
868       float f = t->is_float_constant()->getf();
869       array->append(new ConstantIntValue(jint_cast(f)));
870       break;
871     }
872     case Type::DoubleCon: {
873       jdouble d = t->is_double_constant()->getd();
874 #ifdef _LP64
875       array->append(new ConstantIntValue((jint)0));
876       array->append(new ConstantDoubleValue(d));
877 #else
878       // Repack the double as two jints.
879     // The convention the interpreter uses is that the second local
880     // holds the first raw word of the native double representation.
881     // This is actually reasonable, since locals and stack arrays
882     // grow downwards in all implementations.
883     // (If, on some machine, the interpreter's Java locals or stack
884     // were to grow upwards, the embedded doubles would be word-swapped.)
885     jlong_accessor acc;
886     acc.long_value = jlong_cast(d);
887     array->append(new ConstantIntValue(acc.words[1]));
888     array->append(new ConstantIntValue(acc.words[0]));
889 #endif
890       break;
891     }
892     case Type::Long: {
893       jlong d = t->is_long()->get_con();
894 #ifdef _LP64
895       array->append(new ConstantIntValue((jint)0));
896       array->append(new ConstantLongValue(d));
897 #else
898       // Repack the long as two jints.
899     // The convention the interpreter uses is that the second local
900     // holds the first raw word of the native double representation.
901     // This is actually reasonable, since locals and stack arrays
902     // grow downwards in all implementations.
903     // (If, on some machine, the interpreter's Java locals or stack
904     // were to grow upwards, the embedded doubles would be word-swapped.)
905     jlong_accessor acc;
906     acc.long_value = d;
907     array->append(new ConstantIntValue(acc.words[1]));
908     array->append(new ConstantIntValue(acc.words[0]));
909 #endif
910       break;
911     }
912     case Type::Top:               // Add an illegal value here
913       array->append(new LocationValue(Location()));
914       break;
915     default:
916       ShouldNotReachHere();
917       break;
918   }
919 }
920 
921 // Determine if this node starts a bundle
starts_bundle(const Node * n) const922 bool PhaseOutput::starts_bundle(const Node *n) const {
923   return (_node_bundling_limit > n->_idx &&
924           _node_bundling_base[n->_idx].starts_bundle());
925 }
926 
927 //--------------------------Process_OopMap_Node--------------------------------
Process_OopMap_Node(MachNode * mach,int current_offset)928 void PhaseOutput::Process_OopMap_Node(MachNode *mach, int current_offset) {
929   // Handle special safepoint nodes for synchronization
930   MachSafePointNode *sfn   = mach->as_MachSafePoint();
931   MachCallNode      *mcall;
932 
933   int safepoint_pc_offset = current_offset;
934   bool is_method_handle_invoke = false;
935   bool return_oop = false;
936 
937   // Add the safepoint in the DebugInfoRecorder
938   if( !mach->is_MachCall() ) {
939     mcall = NULL;
940     C->debug_info()->add_safepoint(safepoint_pc_offset, sfn->_oop_map);
941   } else {
942     mcall = mach->as_MachCall();
943 
944     // Is the call a MethodHandle call?
945     if (mcall->is_MachCallJava()) {
946       if (mcall->as_MachCallJava()->_method_handle_invoke) {
947         assert(C->has_method_handle_invokes(), "must have been set during call generation");
948         is_method_handle_invoke = true;
949       }
950     }
951 
952     // Check if a call returns an object.
953     if (mcall->returns_pointer()) {
954       return_oop = true;
955     }
956     safepoint_pc_offset += mcall->ret_addr_offset();
957     C->debug_info()->add_safepoint(safepoint_pc_offset, mcall->_oop_map);
958   }
959 
960   // Loop over the JVMState list to add scope information
961   // Do not skip safepoints with a NULL method, they need monitor info
962   JVMState* youngest_jvms = sfn->jvms();
963   int max_depth = youngest_jvms->depth();
964 
965   // Allocate the object pool for scalar-replaced objects -- the map from
966   // small-integer keys (which can be recorded in the local and ostack
967   // arrays) to descriptions of the object state.
968   GrowableArray<ScopeValue*> *objs = new GrowableArray<ScopeValue*>();
969 
970   // Visit scopes from oldest to youngest.
971   for (int depth = 1; depth <= max_depth; depth++) {
972     JVMState* jvms = youngest_jvms->of_depth(depth);
973     int idx;
974     ciMethod* method = jvms->has_method() ? jvms->method() : NULL;
975     // Safepoints that do not have method() set only provide oop-map and monitor info
976     // to support GC; these do not support deoptimization.
977     int num_locs = (method == NULL) ? 0 : jvms->loc_size();
978     int num_exps = (method == NULL) ? 0 : jvms->stk_size();
979     int num_mon  = jvms->nof_monitors();
980     assert(method == NULL || jvms->bci() < 0 || num_locs == method->max_locals(),
981            "JVMS local count must match that of the method");
982 
983     // Add Local and Expression Stack Information
984 
985     // Insert locals into the locarray
986     GrowableArray<ScopeValue*> *locarray = new GrowableArray<ScopeValue*>(num_locs);
987     for( idx = 0; idx < num_locs; idx++ ) {
988       FillLocArray( idx, sfn, sfn->local(jvms, idx), locarray, objs );
989     }
990 
991     // Insert expression stack entries into the exparray
992     GrowableArray<ScopeValue*> *exparray = new GrowableArray<ScopeValue*>(num_exps);
993     for( idx = 0; idx < num_exps; idx++ ) {
994       FillLocArray( idx,  sfn, sfn->stack(jvms, idx), exparray, objs );
995     }
996 
997     // Add in mappings of the monitors
998     assert( !method ||
999             !method->is_synchronized() ||
1000             method->is_native() ||
1001             num_mon > 0 ||
1002             !GenerateSynchronizationCode,
1003             "monitors must always exist for synchronized methods");
1004 
1005     // Build the growable array of ScopeValues for exp stack
1006     GrowableArray<MonitorValue*> *monarray = new GrowableArray<MonitorValue*>(num_mon);
1007 
1008     // Loop over monitors and insert into array
1009     for (idx = 0; idx < num_mon; idx++) {
1010       // Grab the node that defines this monitor
1011       Node* box_node = sfn->monitor_box(jvms, idx);
1012       Node* obj_node = sfn->monitor_obj(jvms, idx);
1013 
1014       // Create ScopeValue for object
1015       ScopeValue *scval = NULL;
1016 
1017       if (obj_node->is_SafePointScalarObject()) {
1018         SafePointScalarObjectNode* spobj = obj_node->as_SafePointScalarObject();
1019         scval = PhaseOutput::sv_for_node_id(objs, spobj->_idx);
1020         if (scval == NULL) {
1021           const Type *t = spobj->bottom_type();
1022           ciKlass* cik = t->is_oopptr()->klass();
1023           assert(cik->is_instance_klass() ||
1024                  cik->is_array_klass(), "Not supported allocation.");
1025           ObjectValue* sv = new ObjectValue(spobj->_idx,
1026                                             new ConstantOopWriteValue(cik->java_mirror()->constant_encoding()));
1027           PhaseOutput::set_sv_for_object_node(objs, sv);
1028 
1029           uint first_ind = spobj->first_index(youngest_jvms);
1030           for (uint i = 0; i < spobj->n_fields(); i++) {
1031             Node* fld_node = sfn->in(first_ind+i);
1032             (void)FillLocArray(sv->field_values()->length(), sfn, fld_node, sv->field_values(), objs);
1033           }
1034           scval = sv;
1035         }
1036       } else if (!obj_node->is_Con()) {
1037         OptoReg::Name obj_reg = C->regalloc()->get_reg_first(obj_node);
1038         if( obj_node->bottom_type()->base() == Type::NarrowOop ) {
1039           scval = new_loc_value( C->regalloc(), obj_reg, Location::narrowoop );
1040         } else {
1041           scval = new_loc_value( C->regalloc(), obj_reg, Location::oop );
1042         }
1043       } else {
1044         const TypePtr *tp = obj_node->get_ptr_type();
1045         scval = new ConstantOopWriteValue(tp->is_oopptr()->const_oop()->constant_encoding());
1046       }
1047 
1048       OptoReg::Name box_reg = BoxLockNode::reg(box_node);
1049       Location basic_lock = Location::new_stk_loc(Location::normal,C->regalloc()->reg2offset(box_reg));
1050       bool eliminated = (box_node->is_BoxLock() && box_node->as_BoxLock()->is_eliminated());
1051       monarray->append(new MonitorValue(scval, basic_lock, eliminated));
1052     }
1053 
1054     // We dump the object pool first, since deoptimization reads it in first.
1055     C->debug_info()->dump_object_pool(objs);
1056 
1057     // Build first class objects to pass to scope
1058     DebugToken *locvals = C->debug_info()->create_scope_values(locarray);
1059     DebugToken *expvals = C->debug_info()->create_scope_values(exparray);
1060     DebugToken *monvals = C->debug_info()->create_monitor_values(monarray);
1061 
1062     // Make method available for all Safepoints
1063     ciMethod* scope_method = method ? method : C->method();
1064     // Describe the scope here
1065     assert(jvms->bci() >= InvocationEntryBci && jvms->bci() <= 0x10000, "must be a valid or entry BCI");
1066     assert(!jvms->should_reexecute() || depth == max_depth, "reexecute allowed only for the youngest");
1067     // Now we can describe the scope.
1068     methodHandle null_mh;
1069     bool rethrow_exception = false;
1070     C->debug_info()->describe_scope(safepoint_pc_offset, null_mh, scope_method, jvms->bci(), jvms->should_reexecute(), rethrow_exception, is_method_handle_invoke, return_oop, locvals, expvals, monvals);
1071   } // End jvms loop
1072 
1073   // Mark the end of the scope set.
1074   C->debug_info()->end_safepoint(safepoint_pc_offset);
1075 }
1076 
1077 
1078 
1079 // A simplified version of Process_OopMap_Node, to handle non-safepoints.
1080 class NonSafepointEmitter {
1081     Compile*  C;
1082     JVMState* _pending_jvms;
1083     int       _pending_offset;
1084 
1085     void emit_non_safepoint();
1086 
1087  public:
NonSafepointEmitter(Compile * compile)1088     NonSafepointEmitter(Compile* compile) {
1089       this->C = compile;
1090       _pending_jvms = NULL;
1091       _pending_offset = 0;
1092     }
1093 
observe_instruction(Node * n,int pc_offset)1094     void observe_instruction(Node* n, int pc_offset) {
1095       if (!C->debug_info()->recording_non_safepoints())  return;
1096 
1097       Node_Notes* nn = C->node_notes_at(n->_idx);
1098       if (nn == NULL || nn->jvms() == NULL)  return;
1099       if (_pending_jvms != NULL &&
1100           _pending_jvms->same_calls_as(nn->jvms())) {
1101         // Repeated JVMS?  Stretch it up here.
1102         _pending_offset = pc_offset;
1103       } else {
1104         if (_pending_jvms != NULL &&
1105             _pending_offset < pc_offset) {
1106           emit_non_safepoint();
1107         }
1108         _pending_jvms = NULL;
1109         if (pc_offset > C->debug_info()->last_pc_offset()) {
1110           // This is the only way _pending_jvms can become non-NULL:
1111           _pending_jvms = nn->jvms();
1112           _pending_offset = pc_offset;
1113         }
1114       }
1115     }
1116 
1117     // Stay out of the way of real safepoints:
observe_safepoint(JVMState * jvms,int pc_offset)1118     void observe_safepoint(JVMState* jvms, int pc_offset) {
1119       if (_pending_jvms != NULL &&
1120           !_pending_jvms->same_calls_as(jvms) &&
1121           _pending_offset < pc_offset) {
1122         emit_non_safepoint();
1123       }
1124       _pending_jvms = NULL;
1125     }
1126 
flush_at_end()1127     void flush_at_end() {
1128       if (_pending_jvms != NULL) {
1129         emit_non_safepoint();
1130       }
1131       _pending_jvms = NULL;
1132     }
1133 };
1134 
emit_non_safepoint()1135 void NonSafepointEmitter::emit_non_safepoint() {
1136   JVMState* youngest_jvms = _pending_jvms;
1137   int       pc_offset     = _pending_offset;
1138 
1139   // Clear it now:
1140   _pending_jvms = NULL;
1141 
1142   DebugInformationRecorder* debug_info = C->debug_info();
1143   assert(debug_info->recording_non_safepoints(), "sanity");
1144 
1145   debug_info->add_non_safepoint(pc_offset);
1146   int max_depth = youngest_jvms->depth();
1147 
1148   // Visit scopes from oldest to youngest.
1149   for (int depth = 1; depth <= max_depth; depth++) {
1150     JVMState* jvms = youngest_jvms->of_depth(depth);
1151     ciMethod* method = jvms->has_method() ? jvms->method() : NULL;
1152     assert(!jvms->should_reexecute() || depth==max_depth, "reexecute allowed only for the youngest");
1153     methodHandle null_mh;
1154     debug_info->describe_scope(pc_offset, null_mh, method, jvms->bci(), jvms->should_reexecute());
1155   }
1156 
1157   // Mark the end of the scope set.
1158   debug_info->end_non_safepoint(pc_offset);
1159 }
1160 
1161 //------------------------------init_buffer------------------------------------
estimate_buffer_size(int & const_req)1162 void PhaseOutput::estimate_buffer_size(int& const_req) {
1163 
1164   // Set the initially allocated size
1165   const_req = initial_const_capacity;
1166 
1167   // The extra spacing after the code is necessary on some platforms.
1168   // Sometimes we need to patch in a jump after the last instruction,
1169   // if the nmethod has been deoptimized.  (See 4932387, 4894843.)
1170 
1171   // Compute the byte offset where we can store the deopt pc.
1172   if (C->fixed_slots() != 0) {
1173     _orig_pc_slot_offset_in_bytes = C->regalloc()->reg2offset(OptoReg::stack2reg(_orig_pc_slot));
1174   }
1175 
1176   // Compute prolog code size
1177   _method_size = 0;
1178   _frame_slots = OptoReg::reg2stack(C->matcher()->_old_SP) + C->regalloc()->_framesize;
1179 #if defined(IA64) && !defined(AIX)
1180   if (save_argument_registers()) {
1181     // 4815101: this is a stub with implicit and unknown precision fp args.
1182     // The usual spill mechanism can only generate stfd's in this case, which
1183     // doesn't work if the fp reg to spill contains a single-precision denorm.
1184     // Instead, we hack around the normal spill mechanism using stfspill's and
1185     // ldffill's in the MachProlog and MachEpilog emit methods.  We allocate
1186     // space here for the fp arg regs (f8-f15) we're going to thusly spill.
1187     //
1188     // If we ever implement 16-byte 'registers' == stack slots, we can
1189     // get rid of this hack and have SpillCopy generate stfspill/ldffill
1190     // instead of stfd/stfs/ldfd/ldfs.
1191     _frame_slots += 8*(16/BytesPerInt);
1192   }
1193 #endif
1194   assert(_frame_slots >= 0 && _frame_slots < 1000000, "sanity check");
1195 
1196   if (C->has_mach_constant_base_node()) {
1197     uint add_size = 0;
1198     // Fill the constant table.
1199     // Note:  This must happen before shorten_branches.
1200     for (uint i = 0; i < C->cfg()->number_of_blocks(); i++) {
1201       Block* b = C->cfg()->get_block(i);
1202 
1203       for (uint j = 0; j < b->number_of_nodes(); j++) {
1204         Node* n = b->get_node(j);
1205 
1206         // If the node is a MachConstantNode evaluate the constant
1207         // value section.
1208         if (n->is_MachConstant()) {
1209           MachConstantNode* machcon = n->as_MachConstant();
1210           machcon->eval_constant(C);
1211         } else if (n->is_Mach()) {
1212           // On Power there are more nodes that issue constants.
1213           add_size += (n->as_Mach()->ins_num_consts() * 8);
1214         }
1215       }
1216     }
1217 
1218     // Calculate the offsets of the constants and the size of the
1219     // constant table (including the padding to the next section).
1220     constant_table().calculate_offsets_and_size();
1221     const_req = constant_table().size() + add_size;
1222   }
1223 
1224   // Initialize the space for the BufferBlob used to find and verify
1225   // instruction size in MachNode::emit_size()
1226   init_scratch_buffer_blob(const_req);
1227 }
1228 
init_buffer()1229 CodeBuffer* PhaseOutput::init_buffer() {
1230   int stub_req  = _buf_sizes._stub;
1231   int code_req  = _buf_sizes._code;
1232   int const_req = _buf_sizes._const;
1233 
1234   int pad_req   = NativeCall::instruction_size;
1235 
1236   BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
1237   stub_req += bs->estimate_stub_size();
1238 
1239   // nmethod and CodeBuffer count stubs & constants as part of method's code.
1240   // class HandlerImpl is platform-specific and defined in the *.ad files.
1241   int exception_handler_req = HandlerImpl::size_exception_handler() + MAX_stubs_size; // add marginal slop for handler
1242   int deopt_handler_req     = HandlerImpl::size_deopt_handler()     + MAX_stubs_size; // add marginal slop for handler
1243   stub_req += MAX_stubs_size;   // ensure per-stub margin
1244   code_req += MAX_inst_size;    // ensure per-instruction margin
1245 
1246   if (StressCodeBuffers)
1247     code_req = const_req = stub_req = exception_handler_req = deopt_handler_req = 0x10;  // force expansion
1248 
1249   int total_req =
1250           const_req +
1251           code_req +
1252           pad_req +
1253           stub_req +
1254           exception_handler_req +
1255           deopt_handler_req;               // deopt handler
1256 
1257   if (C->has_method_handle_invokes())
1258     total_req += deopt_handler_req;  // deopt MH handler
1259 
1260   CodeBuffer* cb = code_buffer();
1261   cb->initialize(total_req, _buf_sizes._reloc);
1262 
1263   // Have we run out of code space?
1264   if ((cb->blob() == NULL) || (!CompileBroker::should_compile_new_jobs())) {
1265     C->record_failure("CodeCache is full");
1266     return NULL;
1267   }
1268   // Configure the code buffer.
1269   cb->initialize_consts_size(const_req);
1270   cb->initialize_stubs_size(stub_req);
1271   cb->initialize_oop_recorder(C->env()->oop_recorder());
1272 
1273   // fill in the nop array for bundling computations
1274   MachNode *_nop_list[Bundle::_nop_count];
1275   Bundle::initialize_nops(_nop_list);
1276 
1277   return cb;
1278 }
1279 
1280 //------------------------------fill_buffer------------------------------------
fill_buffer(CodeBuffer * cb,uint * blk_starts)1281 void PhaseOutput::fill_buffer(CodeBuffer* cb, uint* blk_starts) {
1282   // blk_starts[] contains offsets calculated during short branches processing,
1283   // offsets should not be increased during following steps.
1284 
1285   // Compute the size of first NumberOfLoopInstrToAlign instructions at head
1286   // of a loop. It is used to determine the padding for loop alignment.
1287   compute_loop_first_inst_sizes();
1288 
1289   // Create oopmap set.
1290   _oop_map_set = new OopMapSet();
1291 
1292   // !!!!! This preserves old handling of oopmaps for now
1293   C->debug_info()->set_oopmaps(_oop_map_set);
1294 
1295   uint nblocks  = C->cfg()->number_of_blocks();
1296   // Count and start of implicit null check instructions
1297   uint inct_cnt = 0;
1298   uint *inct_starts = NEW_RESOURCE_ARRAY(uint, nblocks+1);
1299 
1300   // Count and start of calls
1301   uint *call_returns = NEW_RESOURCE_ARRAY(uint, nblocks+1);
1302 
1303   uint  return_offset = 0;
1304   int nop_size = (new MachNopNode())->size(C->regalloc());
1305 
1306   int previous_offset = 0;
1307   int current_offset  = 0;
1308   int last_call_offset = -1;
1309   int last_avoid_back_to_back_offset = -1;
1310 #ifdef ASSERT
1311   uint* jmp_target = NEW_RESOURCE_ARRAY(uint,nblocks);
1312   uint* jmp_offset = NEW_RESOURCE_ARRAY(uint,nblocks);
1313   uint* jmp_size   = NEW_RESOURCE_ARRAY(uint,nblocks);
1314   uint* jmp_rule   = NEW_RESOURCE_ARRAY(uint,nblocks);
1315 #endif
1316 
1317   // Create an array of unused labels, one for each basic block, if printing is enabled
1318 #if defined(SUPPORT_OPTO_ASSEMBLY)
1319   int *node_offsets      = NULL;
1320   uint node_offset_limit = C->unique();
1321 
1322   if (C->print_assembly()) {
1323     node_offsets = NEW_RESOURCE_ARRAY(int, node_offset_limit);
1324   }
1325   if (node_offsets != NULL) {
1326     // We need to initialize. Unused array elements may contain garbage and mess up PrintOptoAssembly.
1327     memset(node_offsets, 0, node_offset_limit*sizeof(int));
1328   }
1329 #endif
1330 
1331   NonSafepointEmitter non_safepoints(C);  // emit non-safepoints lazily
1332 
1333   // Emit the constant table.
1334   if (C->has_mach_constant_base_node()) {
1335     constant_table().emit(*cb);
1336   }
1337 
1338   // Create an array of labels, one for each basic block
1339   Label *blk_labels = NEW_RESOURCE_ARRAY(Label, nblocks+1);
1340   for (uint i=0; i <= nblocks; i++) {
1341     blk_labels[i].init();
1342   }
1343 
1344   // Now fill in the code buffer
1345   Node *delay_slot = NULL;
1346   for (uint i = 0; i < nblocks; i++) {
1347     Block* block = C->cfg()->get_block(i);
1348     _block = block;
1349     Node* head = block->head();
1350 
1351     // If this block needs to start aligned (i.e, can be reached other
1352     // than by falling-thru from the previous block), then force the
1353     // start of a new bundle.
1354     if (Pipeline::requires_bundling() && starts_bundle(head)) {
1355       cb->flush_bundle(true);
1356     }
1357 
1358 #ifdef ASSERT
1359     if (!block->is_connector()) {
1360       stringStream st;
1361       block->dump_head(C->cfg(), &st);
1362       MacroAssembler(cb).block_comment(st.as_string());
1363     }
1364     jmp_target[i] = 0;
1365     jmp_offset[i] = 0;
1366     jmp_size[i]   = 0;
1367     jmp_rule[i]   = 0;
1368 #endif
1369     int blk_offset = current_offset;
1370 
1371     // Define the label at the beginning of the basic block
1372     MacroAssembler(cb).bind(blk_labels[block->_pre_order]);
1373 
1374     uint last_inst = block->number_of_nodes();
1375 
1376     // Emit block normally, except for last instruction.
1377     // Emit means "dump code bits into code buffer".
1378     for (uint j = 0; j<last_inst; j++) {
1379       _index = j;
1380 
1381       // Get the node
1382       Node* n = block->get_node(j);
1383 
1384       // See if delay slots are supported
1385       if (valid_bundle_info(n) && node_bundling(n)->used_in_unconditional_delay()) {
1386         assert(delay_slot == NULL, "no use of delay slot node");
1387         assert(n->size(C->regalloc()) == Pipeline::instr_unit_size(), "delay slot instruction wrong size");
1388 
1389         delay_slot = n;
1390         continue;
1391       }
1392 
1393       // If this starts a new instruction group, then flush the current one
1394       // (but allow split bundles)
1395       if (Pipeline::requires_bundling() && starts_bundle(n))
1396         cb->flush_bundle(false);
1397 
1398       // Special handling for SafePoint/Call Nodes
1399       bool is_mcall = false;
1400       if (n->is_Mach()) {
1401         MachNode *mach = n->as_Mach();
1402         is_mcall = n->is_MachCall();
1403         bool is_sfn = n->is_MachSafePoint();
1404 
1405         // If this requires all previous instructions be flushed, then do so
1406         if (is_sfn || is_mcall || mach->alignment_required() != 1) {
1407           cb->flush_bundle(true);
1408           current_offset = cb->insts_size();
1409         }
1410 
1411         // A padding may be needed again since a previous instruction
1412         // could be moved to delay slot.
1413 
1414         // align the instruction if necessary
1415         int padding = mach->compute_padding(current_offset);
1416         // Make sure safepoint node for polling is distinct from a call's
1417         // return by adding a nop if needed.
1418         if (is_sfn && !is_mcall && padding == 0 && current_offset == last_call_offset) {
1419           padding = nop_size;
1420         }
1421         if (padding == 0 && mach->avoid_back_to_back(MachNode::AVOID_BEFORE) &&
1422             current_offset == last_avoid_back_to_back_offset) {
1423           // Avoid back to back some instructions.
1424           padding = nop_size;
1425         }
1426 
1427         if (padding > 0) {
1428           assert((padding % nop_size) == 0, "padding is not a multiple of NOP size");
1429           int nops_cnt = padding / nop_size;
1430           MachNode *nop = new MachNopNode(nops_cnt);
1431           block->insert_node(nop, j++);
1432           last_inst++;
1433           C->cfg()->map_node_to_block(nop, block);
1434           // Ensure enough space.
1435           cb->insts()->maybe_expand_to_ensure_remaining(MAX_inst_size);
1436           if ((cb->blob() == NULL) || (!CompileBroker::should_compile_new_jobs())) {
1437             C->record_failure("CodeCache is full");
1438             return;
1439           }
1440           nop->emit(*cb, C->regalloc());
1441           cb->flush_bundle(true);
1442           current_offset = cb->insts_size();
1443         }
1444 
1445         // Remember the start of the last call in a basic block
1446         if (is_mcall) {
1447           MachCallNode *mcall = mach->as_MachCall();
1448 
1449           // This destination address is NOT PC-relative
1450           mcall->method_set((intptr_t)mcall->entry_point());
1451 
1452           // Save the return address
1453           call_returns[block->_pre_order] = current_offset + mcall->ret_addr_offset();
1454 
1455           if (mcall->is_MachCallLeaf()) {
1456             is_mcall = false;
1457             is_sfn = false;
1458           }
1459         }
1460 
1461         // sfn will be valid whenever mcall is valid now because of inheritance
1462         if (is_sfn || is_mcall) {
1463 
1464           // Handle special safepoint nodes for synchronization
1465           if (!is_mcall) {
1466             MachSafePointNode *sfn = mach->as_MachSafePoint();
1467             // !!!!! Stubs only need an oopmap right now, so bail out
1468             if (sfn->jvms()->method() == NULL) {
1469               // Write the oopmap directly to the code blob??!!
1470               continue;
1471             }
1472           } // End synchronization
1473 
1474           non_safepoints.observe_safepoint(mach->as_MachSafePoint()->jvms(),
1475                                            current_offset);
1476           Process_OopMap_Node(mach, current_offset);
1477         } // End if safepoint
1478 
1479           // If this is a null check, then add the start of the previous instruction to the list
1480         else if( mach->is_MachNullCheck() ) {
1481           inct_starts[inct_cnt++] = previous_offset;
1482         }
1483 
1484           // If this is a branch, then fill in the label with the target BB's label
1485         else if (mach->is_MachBranch()) {
1486           // This requires the TRUE branch target be in succs[0]
1487           uint block_num = block->non_connector_successor(0)->_pre_order;
1488 
1489           // Try to replace long branch if delay slot is not used,
1490           // it is mostly for back branches since forward branch's
1491           // distance is not updated yet.
1492           bool delay_slot_is_used = valid_bundle_info(n) &&
1493                                     C->output()->node_bundling(n)->use_unconditional_delay();
1494           if (!delay_slot_is_used && mach->may_be_short_branch()) {
1495             assert(delay_slot == NULL, "not expecting delay slot node");
1496             int br_size = n->size(C->regalloc());
1497             int offset = blk_starts[block_num] - current_offset;
1498             if (block_num >= i) {
1499               // Current and following block's offset are not
1500               // finalized yet, adjust distance by the difference
1501               // between calculated and final offsets of current block.
1502               offset -= (blk_starts[i] - blk_offset);
1503             }
1504             // In the following code a nop could be inserted before
1505             // the branch which will increase the backward distance.
1506             bool needs_padding = (current_offset == last_avoid_back_to_back_offset);
1507             if (needs_padding && offset <= 0)
1508               offset -= nop_size;
1509 
1510             if (C->matcher()->is_short_branch_offset(mach->rule(), br_size, offset)) {
1511               // We've got a winner.  Replace this branch.
1512               MachNode* replacement = mach->as_MachBranch()->short_branch_version();
1513 
1514               // Update the jmp_size.
1515               int new_size = replacement->size(C->regalloc());
1516               assert((br_size - new_size) >= (int)nop_size, "short_branch size should be smaller");
1517               // Insert padding between avoid_back_to_back branches.
1518               if (needs_padding && replacement->avoid_back_to_back(MachNode::AVOID_BEFORE)) {
1519                 MachNode *nop = new MachNopNode();
1520                 block->insert_node(nop, j++);
1521                 C->cfg()->map_node_to_block(nop, block);
1522                 last_inst++;
1523                 nop->emit(*cb, C->regalloc());
1524                 cb->flush_bundle(true);
1525                 current_offset = cb->insts_size();
1526               }
1527 #ifdef ASSERT
1528               jmp_target[i] = block_num;
1529               jmp_offset[i] = current_offset - blk_offset;
1530               jmp_size[i]   = new_size;
1531               jmp_rule[i]   = mach->rule();
1532 #endif
1533               block->map_node(replacement, j);
1534               mach->subsume_by(replacement, C);
1535               n    = replacement;
1536               mach = replacement;
1537             }
1538           }
1539           mach->as_MachBranch()->label_set( &blk_labels[block_num], block_num );
1540         } else if (mach->ideal_Opcode() == Op_Jump) {
1541           for (uint h = 0; h < block->_num_succs; h++) {
1542             Block* succs_block = block->_succs[h];
1543             for (uint j = 1; j < succs_block->num_preds(); j++) {
1544               Node* jpn = succs_block->pred(j);
1545               if (jpn->is_JumpProj() && jpn->in(0) == mach) {
1546                 uint block_num = succs_block->non_connector()->_pre_order;
1547                 Label *blkLabel = &blk_labels[block_num];
1548                 mach->add_case_label(jpn->as_JumpProj()->proj_no(), blkLabel);
1549               }
1550             }
1551           }
1552         }
1553 #ifdef ASSERT
1554           // Check that oop-store precedes the card-mark
1555         else if (mach->ideal_Opcode() == Op_StoreCM) {
1556           uint storeCM_idx = j;
1557           int count = 0;
1558           for (uint prec = mach->req(); prec < mach->len(); prec++) {
1559             Node *oop_store = mach->in(prec);  // Precedence edge
1560             if (oop_store == NULL) continue;
1561             count++;
1562             uint i4;
1563             for (i4 = 0; i4 < last_inst; ++i4) {
1564               if (block->get_node(i4) == oop_store) {
1565                 break;
1566               }
1567             }
1568             // Note: This test can provide a false failure if other precedence
1569             // edges have been added to the storeCMNode.
1570             assert(i4 == last_inst || i4 < storeCM_idx, "CM card-mark executes before oop-store");
1571           }
1572           assert(count > 0, "storeCM expects at least one precedence edge");
1573         }
1574 #endif
1575         else if (!n->is_Proj()) {
1576           // Remember the beginning of the previous instruction, in case
1577           // it's followed by a flag-kill and a null-check.  Happens on
1578           // Intel all the time, with add-to-memory kind of opcodes.
1579           previous_offset = current_offset;
1580         }
1581 
1582         // Not an else-if!
1583         // If this is a trap based cmp then add its offset to the list.
1584         if (mach->is_TrapBasedCheckNode()) {
1585           inct_starts[inct_cnt++] = current_offset;
1586         }
1587       }
1588 
1589       // Verify that there is sufficient space remaining
1590       cb->insts()->maybe_expand_to_ensure_remaining(MAX_inst_size);
1591       if ((cb->blob() == NULL) || (!CompileBroker::should_compile_new_jobs())) {
1592         C->record_failure("CodeCache is full");
1593         return;
1594       }
1595 
1596       // Save the offset for the listing
1597 #if defined(SUPPORT_OPTO_ASSEMBLY)
1598       if ((node_offsets != NULL) && (n->_idx < node_offset_limit)) {
1599         node_offsets[n->_idx] = cb->insts_size();
1600       }
1601 #endif
1602       assert(!C->failing(), "Should not reach here if failing.");
1603 
1604       // "Normal" instruction case
1605       DEBUG_ONLY(uint instr_offset = cb->insts_size());
1606       n->emit(*cb, C->regalloc());
1607       current_offset  = cb->insts_size();
1608 
1609       // Above we only verified that there is enough space in the instruction section.
1610       // However, the instruction may emit stubs that cause code buffer expansion.
1611       // Bail out here if expansion failed due to a lack of code cache space.
1612       if (C->failing()) {
1613         return;
1614       }
1615 
1616 #ifdef ASSERT
1617       uint n_size = n->size(C->regalloc());
1618       if (n_size < (current_offset-instr_offset)) {
1619         MachNode* mach = n->as_Mach();
1620         n->dump();
1621         mach->dump_format(C->regalloc(), tty);
1622         tty->print_cr(" n_size (%d), current_offset (%d), instr_offset (%d)", n_size, current_offset, instr_offset);
1623         Disassembler::decode(cb->insts_begin() + instr_offset, cb->insts_begin() + current_offset + 1, tty);
1624         tty->print_cr(" ------------------- ");
1625         BufferBlob* blob = this->scratch_buffer_blob();
1626         address blob_begin = blob->content_begin();
1627         Disassembler::decode(blob_begin, blob_begin + n_size + 1, tty);
1628         assert(false, "wrong size of mach node");
1629       }
1630 #endif
1631       non_safepoints.observe_instruction(n, current_offset);
1632 
1633       // mcall is last "call" that can be a safepoint
1634       // record it so we can see if a poll will directly follow it
1635       // in which case we'll need a pad to make the PcDesc sites unique
1636       // see  5010568. This can be slightly inaccurate but conservative
1637       // in the case that return address is not actually at current_offset.
1638       // This is a small price to pay.
1639 
1640       if (is_mcall) {
1641         last_call_offset = current_offset;
1642       }
1643 
1644       if (n->is_Mach() && n->as_Mach()->avoid_back_to_back(MachNode::AVOID_AFTER)) {
1645         // Avoid back to back some instructions.
1646         last_avoid_back_to_back_offset = current_offset;
1647       }
1648 
1649       // See if this instruction has a delay slot
1650       if (valid_bundle_info(n) && node_bundling(n)->use_unconditional_delay()) {
1651         guarantee(delay_slot != NULL, "expecting delay slot node");
1652 
1653         // Back up 1 instruction
1654         cb->set_insts_end(cb->insts_end() - Pipeline::instr_unit_size());
1655 
1656         // Save the offset for the listing
1657 #if defined(SUPPORT_OPTO_ASSEMBLY)
1658         if ((node_offsets != NULL) && (delay_slot->_idx < node_offset_limit)) {
1659           node_offsets[delay_slot->_idx] = cb->insts_size();
1660         }
1661 #endif
1662 
1663         // Support a SafePoint in the delay slot
1664         if (delay_slot->is_MachSafePoint()) {
1665           MachNode *mach = delay_slot->as_Mach();
1666           // !!!!! Stubs only need an oopmap right now, so bail out
1667           if (!mach->is_MachCall() && mach->as_MachSafePoint()->jvms()->method() == NULL) {
1668             // Write the oopmap directly to the code blob??!!
1669             delay_slot = NULL;
1670             continue;
1671           }
1672 
1673           int adjusted_offset = current_offset - Pipeline::instr_unit_size();
1674           non_safepoints.observe_safepoint(mach->as_MachSafePoint()->jvms(),
1675                                            adjusted_offset);
1676           // Generate an OopMap entry
1677           Process_OopMap_Node(mach, adjusted_offset);
1678         }
1679 
1680         // Insert the delay slot instruction
1681         delay_slot->emit(*cb, C->regalloc());
1682 
1683         // Don't reuse it
1684         delay_slot = NULL;
1685       }
1686 
1687     } // End for all instructions in block
1688 
1689     // If the next block is the top of a loop, pad this block out to align
1690     // the loop top a little. Helps prevent pipe stalls at loop back branches.
1691     if (i < nblocks-1) {
1692       Block *nb = C->cfg()->get_block(i + 1);
1693       int padding = nb->alignment_padding(current_offset);
1694       if( padding > 0 ) {
1695         MachNode *nop = new MachNopNode(padding / nop_size);
1696         block->insert_node(nop, block->number_of_nodes());
1697         C->cfg()->map_node_to_block(nop, block);
1698         nop->emit(*cb, C->regalloc());
1699         current_offset = cb->insts_size();
1700       }
1701     }
1702     // Verify that the distance for generated before forward
1703     // short branches is still valid.
1704     guarantee((int)(blk_starts[i+1] - blk_starts[i]) >= (current_offset - blk_offset), "shouldn't increase block size");
1705 
1706     // Save new block start offset
1707     blk_starts[i] = blk_offset;
1708   } // End of for all blocks
1709   blk_starts[nblocks] = current_offset;
1710 
1711   non_safepoints.flush_at_end();
1712 
1713   // Offset too large?
1714   if (C->failing())  return;
1715 
1716   // Define a pseudo-label at the end of the code
1717   MacroAssembler(cb).bind( blk_labels[nblocks] );
1718 
1719   // Compute the size of the first block
1720   _first_block_size = blk_labels[1].loc_pos() - blk_labels[0].loc_pos();
1721 
1722 #ifdef ASSERT
1723   for (uint i = 0; i < nblocks; i++) { // For all blocks
1724     if (jmp_target[i] != 0) {
1725       int br_size = jmp_size[i];
1726       int offset = blk_starts[jmp_target[i]]-(blk_starts[i] + jmp_offset[i]);
1727       if (!C->matcher()->is_short_branch_offset(jmp_rule[i], br_size, offset)) {
1728         tty->print_cr("target (%d) - jmp_offset(%d) = offset (%d), jump_size(%d), jmp_block B%d, target_block B%d", blk_starts[jmp_target[i]], blk_starts[i] + jmp_offset[i], offset, br_size, i, jmp_target[i]);
1729         assert(false, "Displacement too large for short jmp");
1730       }
1731     }
1732   }
1733 #endif
1734 
1735   BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
1736   bs->emit_stubs(*cb);
1737   if (C->failing())  return;
1738 
1739 #ifndef PRODUCT
1740   // Information on the size of the method, without the extraneous code
1741   Scheduling::increment_method_size(cb->insts_size());
1742 #endif
1743 
1744   // ------------------
1745   // Fill in exception table entries.
1746   FillExceptionTables(inct_cnt, call_returns, inct_starts, blk_labels);
1747 
1748   // Only java methods have exception handlers and deopt handlers
1749   // class HandlerImpl is platform-specific and defined in the *.ad files.
1750   if (C->method()) {
1751     // Emit the exception handler code.
1752     _code_offsets.set_value(CodeOffsets::Exceptions, HandlerImpl::emit_exception_handler(*cb));
1753     if (C->failing()) {
1754       return; // CodeBuffer::expand failed
1755     }
1756     // Emit the deopt handler code.
1757     _code_offsets.set_value(CodeOffsets::Deopt, HandlerImpl::emit_deopt_handler(*cb));
1758 
1759     // Emit the MethodHandle deopt handler code (if required).
1760     if (C->has_method_handle_invokes() && !C->failing()) {
1761       // We can use the same code as for the normal deopt handler, we
1762       // just need a different entry point address.
1763       _code_offsets.set_value(CodeOffsets::DeoptMH, HandlerImpl::emit_deopt_handler(*cb));
1764     }
1765   }
1766 
1767   // One last check for failed CodeBuffer::expand:
1768   if ((cb->blob() == NULL) || (!CompileBroker::should_compile_new_jobs())) {
1769     C->record_failure("CodeCache is full");
1770     return;
1771   }
1772 
1773 #if defined(SUPPORT_ABSTRACT_ASSEMBLY) || defined(SUPPORT_ASSEMBLY) || defined(SUPPORT_OPTO_ASSEMBLY)
1774   if (C->print_assembly()) {
1775     tty->cr();
1776     tty->print_cr("============================= C2-compiled nmethod ==============================");
1777   }
1778 #endif
1779 
1780 #if defined(SUPPORT_OPTO_ASSEMBLY)
1781   // Dump the assembly code, including basic-block numbers
1782   if (C->print_assembly()) {
1783     ttyLocker ttyl;  // keep the following output all in one block
1784     if (!VMThread::should_terminate()) {  // test this under the tty lock
1785       // This output goes directly to the tty, not the compiler log.
1786       // To enable tools to match it up with the compilation activity,
1787       // be sure to tag this tty output with the compile ID.
1788       if (xtty != NULL) {
1789         xtty->head("opto_assembly compile_id='%d'%s", C->compile_id(),
1790                    C->is_osr_compilation() ? " compile_kind='osr'" : "");
1791       }
1792       if (C->method() != NULL) {
1793         tty->print_cr("----------------------- MetaData before Compile_id = %d ------------------------", C->compile_id());
1794         C->method()->print_metadata();
1795       } else if (C->stub_name() != NULL) {
1796         tty->print_cr("----------------------------- RuntimeStub %s -------------------------------", C->stub_name());
1797       }
1798       tty->cr();
1799       tty->print_cr("------------------------ OptoAssembly for Compile_id = %d -----------------------", C->compile_id());
1800       dump_asm(node_offsets, node_offset_limit);
1801       tty->print_cr("--------------------------------------------------------------------------------");
1802       if (xtty != NULL) {
1803         // print_metadata and dump_asm above may safepoint which makes us loose the ttylock.
1804         // Retake lock too make sure the end tag is coherent, and that xmlStream->pop_tag is done
1805         // thread safe
1806         ttyLocker ttyl2;
1807         xtty->tail("opto_assembly");
1808       }
1809     }
1810   }
1811 #endif
1812 }
1813 
FillExceptionTables(uint cnt,uint * call_returns,uint * inct_starts,Label * blk_labels)1814 void PhaseOutput::FillExceptionTables(uint cnt, uint *call_returns, uint *inct_starts, Label *blk_labels) {
1815   _inc_table.set_size(cnt);
1816 
1817   uint inct_cnt = 0;
1818   for (uint i = 0; i < C->cfg()->number_of_blocks(); i++) {
1819     Block* block = C->cfg()->get_block(i);
1820     Node *n = NULL;
1821     int j;
1822 
1823     // Find the branch; ignore trailing NOPs.
1824     for (j = block->number_of_nodes() - 1; j >= 0; j--) {
1825       n = block->get_node(j);
1826       if (!n->is_Mach() || n->as_Mach()->ideal_Opcode() != Op_Con) {
1827         break;
1828       }
1829     }
1830 
1831     // If we didn't find anything, continue
1832     if (j < 0) {
1833       continue;
1834     }
1835 
1836     // Compute ExceptionHandlerTable subtable entry and add it
1837     // (skip empty blocks)
1838     if (n->is_Catch()) {
1839 
1840       // Get the offset of the return from the call
1841       uint call_return = call_returns[block->_pre_order];
1842 #ifdef ASSERT
1843       assert( call_return > 0, "no call seen for this basic block" );
1844       while (block->get_node(--j)->is_MachProj()) ;
1845       assert(block->get_node(j)->is_MachCall(), "CatchProj must follow call");
1846 #endif
1847       // last instruction is a CatchNode, find it's CatchProjNodes
1848       int nof_succs = block->_num_succs;
1849       // allocate space
1850       GrowableArray<intptr_t> handler_bcis(nof_succs);
1851       GrowableArray<intptr_t> handler_pcos(nof_succs);
1852       // iterate through all successors
1853       for (int j = 0; j < nof_succs; j++) {
1854         Block* s = block->_succs[j];
1855         bool found_p = false;
1856         for (uint k = 1; k < s->num_preds(); k++) {
1857           Node* pk = s->pred(k);
1858           if (pk->is_CatchProj() && pk->in(0) == n) {
1859             const CatchProjNode* p = pk->as_CatchProj();
1860             found_p = true;
1861             // add the corresponding handler bci & pco information
1862             if (p->_con != CatchProjNode::fall_through_index) {
1863               // p leads to an exception handler (and is not fall through)
1864               assert(s == C->cfg()->get_block(s->_pre_order), "bad numbering");
1865               // no duplicates, please
1866               if (!handler_bcis.contains(p->handler_bci())) {
1867                 uint block_num = s->non_connector()->_pre_order;
1868                 handler_bcis.append(p->handler_bci());
1869                 handler_pcos.append(blk_labels[block_num].loc_pos());
1870               }
1871             }
1872           }
1873         }
1874         assert(found_p, "no matching predecessor found");
1875         // Note:  Due to empty block removal, one block may have
1876         // several CatchProj inputs, from the same Catch.
1877       }
1878 
1879       // Set the offset of the return from the call
1880       assert(handler_bcis.find(-1) != -1, "must have default handler");
1881       _handler_table.add_subtable(call_return, &handler_bcis, NULL, &handler_pcos);
1882       continue;
1883     }
1884 
1885     // Handle implicit null exception table updates
1886     if (n->is_MachNullCheck()) {
1887       uint block_num = block->non_connector_successor(0)->_pre_order;
1888       _inc_table.append(inct_starts[inct_cnt++], blk_labels[block_num].loc_pos());
1889       continue;
1890     }
1891     // Handle implicit exception table updates: trap instructions.
1892     if (n->is_Mach() && n->as_Mach()->is_TrapBasedCheckNode()) {
1893       uint block_num = block->non_connector_successor(0)->_pre_order;
1894       _inc_table.append(inct_starts[inct_cnt++], blk_labels[block_num].loc_pos());
1895       continue;
1896     }
1897   } // End of for all blocks fill in exception table entries
1898 }
1899 
1900 // Static Variables
1901 #ifndef PRODUCT
1902 uint Scheduling::_total_nop_size = 0;
1903 uint Scheduling::_total_method_size = 0;
1904 uint Scheduling::_total_branches = 0;
1905 uint Scheduling::_total_unconditional_delays = 0;
1906 uint Scheduling::_total_instructions_per_bundle[Pipeline::_max_instrs_per_cycle+1];
1907 #endif
1908 
1909 // Initializer for class Scheduling
1910 
Scheduling(Arena * arena,Compile & compile)1911 Scheduling::Scheduling(Arena *arena, Compile &compile)
1912         : _arena(arena),
1913           _cfg(compile.cfg()),
1914           _regalloc(compile.regalloc()),
1915           _scheduled(arena),
1916           _available(arena),
1917           _reg_node(arena),
1918           _pinch_free_list(arena),
1919           _next_node(NULL),
1920           _bundle_instr_count(0),
1921           _bundle_cycle_number(0),
1922           _bundle_use(0, 0, resource_count, &_bundle_use_elements[0])
1923 #ifndef PRODUCT
1924         , _branches(0)
1925         , _unconditional_delays(0)
1926 #endif
1927 {
1928   // Create a MachNopNode
1929   _nop = new MachNopNode();
1930 
1931   // Now that the nops are in the array, save the count
1932   // (but allow entries for the nops)
1933   _node_bundling_limit = compile.unique();
1934   uint node_max = _regalloc->node_regs_max_index();
1935 
1936   compile.output()->set_node_bundling_limit(_node_bundling_limit);
1937 
1938   // This one is persistent within the Compile class
1939   _node_bundling_base = NEW_ARENA_ARRAY(compile.comp_arena(), Bundle, node_max);
1940 
1941   // Allocate space for fixed-size arrays
1942   _node_latency    = NEW_ARENA_ARRAY(arena, unsigned short, node_max);
1943   _uses            = NEW_ARENA_ARRAY(arena, short,          node_max);
1944   _current_latency = NEW_ARENA_ARRAY(arena, unsigned short, node_max);
1945 
1946   // Clear the arrays
1947   for (uint i = 0; i < node_max; i++) {
1948     ::new (&_node_bundling_base[i]) Bundle();
1949   }
1950   memset(_node_latency,       0, node_max * sizeof(unsigned short));
1951   memset(_uses,               0, node_max * sizeof(short));
1952   memset(_current_latency,    0, node_max * sizeof(unsigned short));
1953 
1954   // Clear the bundling information
1955   memcpy(_bundle_use_elements, Pipeline_Use::elaborated_elements, sizeof(Pipeline_Use::elaborated_elements));
1956 
1957   // Get the last node
1958   Block* block = _cfg->get_block(_cfg->number_of_blocks() - 1);
1959 
1960   _next_node = block->get_node(block->number_of_nodes() - 1);
1961 }
1962 
1963 #ifndef PRODUCT
1964 // Scheduling destructor
~Scheduling()1965 Scheduling::~Scheduling() {
1966   _total_branches             += _branches;
1967   _total_unconditional_delays += _unconditional_delays;
1968 }
1969 #endif
1970 
1971 // Step ahead "i" cycles
step(uint i)1972 void Scheduling::step(uint i) {
1973 
1974   Bundle *bundle = node_bundling(_next_node);
1975   bundle->set_starts_bundle();
1976 
1977   // Update the bundle record, but leave the flags information alone
1978   if (_bundle_instr_count > 0) {
1979     bundle->set_instr_count(_bundle_instr_count);
1980     bundle->set_resources_used(_bundle_use.resourcesUsed());
1981   }
1982 
1983   // Update the state information
1984   _bundle_instr_count = 0;
1985   _bundle_cycle_number += i;
1986   _bundle_use.step(i);
1987 }
1988 
step_and_clear()1989 void Scheduling::step_and_clear() {
1990   Bundle *bundle = node_bundling(_next_node);
1991   bundle->set_starts_bundle();
1992 
1993   // Update the bundle record
1994   if (_bundle_instr_count > 0) {
1995     bundle->set_instr_count(_bundle_instr_count);
1996     bundle->set_resources_used(_bundle_use.resourcesUsed());
1997 
1998     _bundle_cycle_number += 1;
1999   }
2000 
2001   // Clear the bundling information
2002   _bundle_instr_count = 0;
2003   _bundle_use.reset();
2004 
2005   memcpy(_bundle_use_elements,
2006          Pipeline_Use::elaborated_elements,
2007          sizeof(Pipeline_Use::elaborated_elements));
2008 }
2009 
2010 // Perform instruction scheduling and bundling over the sequence of
2011 // instructions in backwards order.
ScheduleAndBundle()2012 void PhaseOutput::ScheduleAndBundle() {
2013 
2014   // Don't optimize this if it isn't a method
2015   if (!C->method())
2016     return;
2017 
2018   // Don't optimize this if scheduling is disabled
2019   if (!C->do_scheduling())
2020     return;
2021 
2022   // Scheduling code works only with pairs (8 bytes) maximum.
2023   if (C->max_vector_size() > 8)
2024     return;
2025 
2026   Compile::TracePhase tp("isched", &timers[_t_instrSched]);
2027 
2028   // Create a data structure for all the scheduling information
2029   Scheduling scheduling(Thread::current()->resource_area(), *C);
2030 
2031   // Walk backwards over each basic block, computing the needed alignment
2032   // Walk over all the basic blocks
2033   scheduling.DoScheduling();
2034 
2035 #ifndef PRODUCT
2036   if (C->trace_opto_output()) {
2037     tty->print("\n---- After ScheduleAndBundle ----\n");
2038     for (uint i = 0; i < C->cfg()->number_of_blocks(); i++) {
2039       tty->print("\nBB#%03d:\n", i);
2040       Block* block = C->cfg()->get_block(i);
2041       for (uint j = 0; j < block->number_of_nodes(); j++) {
2042         Node* n = block->get_node(j);
2043         OptoReg::Name reg = C->regalloc()->get_reg_first(n);
2044         tty->print(" %-6s ", reg >= 0 && reg < REG_COUNT ? Matcher::regName[reg] : "");
2045         n->dump();
2046       }
2047     }
2048   }
2049 #endif
2050 }
2051 
2052 // Compute the latency of all the instructions.  This is fairly simple,
2053 // because we already have a legal ordering.  Walk over the instructions
2054 // from first to last, and compute the latency of the instruction based
2055 // on the latency of the preceding instruction(s).
ComputeLocalLatenciesForward(const Block * bb)2056 void Scheduling::ComputeLocalLatenciesForward(const Block *bb) {
2057 #ifndef PRODUCT
2058   if (_cfg->C->trace_opto_output())
2059     tty->print("# -> ComputeLocalLatenciesForward\n");
2060 #endif
2061 
2062   // Walk over all the schedulable instructions
2063   for( uint j=_bb_start; j < _bb_end; j++ ) {
2064 
2065     // This is a kludge, forcing all latency calculations to start at 1.
2066     // Used to allow latency 0 to force an instruction to the beginning
2067     // of the bb
2068     uint latency = 1;
2069     Node *use = bb->get_node(j);
2070     uint nlen = use->len();
2071 
2072     // Walk over all the inputs
2073     for ( uint k=0; k < nlen; k++ ) {
2074       Node *def = use->in(k);
2075       if (!def)
2076         continue;
2077 
2078       uint l = _node_latency[def->_idx] + use->latency(k);
2079       if (latency < l)
2080         latency = l;
2081     }
2082 
2083     _node_latency[use->_idx] = latency;
2084 
2085 #ifndef PRODUCT
2086     if (_cfg->C->trace_opto_output()) {
2087       tty->print("# latency %4d: ", latency);
2088       use->dump();
2089     }
2090 #endif
2091   }
2092 
2093 #ifndef PRODUCT
2094   if (_cfg->C->trace_opto_output())
2095     tty->print("# <- ComputeLocalLatenciesForward\n");
2096 #endif
2097 
2098 } // end ComputeLocalLatenciesForward
2099 
2100 // See if this node fits into the present instruction bundle
NodeFitsInBundle(Node * n)2101 bool Scheduling::NodeFitsInBundle(Node *n) {
2102   uint n_idx = n->_idx;
2103 
2104   // If this is the unconditional delay instruction, then it fits
2105   if (n == _unconditional_delay_slot) {
2106 #ifndef PRODUCT
2107     if (_cfg->C->trace_opto_output())
2108       tty->print("#     NodeFitsInBundle [%4d]: TRUE; is in unconditional delay slot\n", n->_idx);
2109 #endif
2110     return (true);
2111   }
2112 
2113   // If the node cannot be scheduled this cycle, skip it
2114   if (_current_latency[n_idx] > _bundle_cycle_number) {
2115 #ifndef PRODUCT
2116     if (_cfg->C->trace_opto_output())
2117       tty->print("#     NodeFitsInBundle [%4d]: FALSE; latency %4d > %d\n",
2118                  n->_idx, _current_latency[n_idx], _bundle_cycle_number);
2119 #endif
2120     return (false);
2121   }
2122 
2123   const Pipeline *node_pipeline = n->pipeline();
2124 
2125   uint instruction_count = node_pipeline->instructionCount();
2126   if (node_pipeline->mayHaveNoCode() && n->size(_regalloc) == 0)
2127     instruction_count = 0;
2128   else if (node_pipeline->hasBranchDelay() && !_unconditional_delay_slot)
2129     instruction_count++;
2130 
2131   if (_bundle_instr_count + instruction_count > Pipeline::_max_instrs_per_cycle) {
2132 #ifndef PRODUCT
2133     if (_cfg->C->trace_opto_output())
2134       tty->print("#     NodeFitsInBundle [%4d]: FALSE; too many instructions: %d > %d\n",
2135                  n->_idx, _bundle_instr_count + instruction_count, Pipeline::_max_instrs_per_cycle);
2136 #endif
2137     return (false);
2138   }
2139 
2140   // Don't allow non-machine nodes to be handled this way
2141   if (!n->is_Mach() && instruction_count == 0)
2142     return (false);
2143 
2144   // See if there is any overlap
2145   uint delay = _bundle_use.full_latency(0, node_pipeline->resourceUse());
2146 
2147   if (delay > 0) {
2148 #ifndef PRODUCT
2149     if (_cfg->C->trace_opto_output())
2150       tty->print("#     NodeFitsInBundle [%4d]: FALSE; functional units overlap\n", n_idx);
2151 #endif
2152     return false;
2153   }
2154 
2155 #ifndef PRODUCT
2156   if (_cfg->C->trace_opto_output())
2157     tty->print("#     NodeFitsInBundle [%4d]:  TRUE\n", n_idx);
2158 #endif
2159 
2160   return true;
2161 }
2162 
ChooseNodeToBundle()2163 Node * Scheduling::ChooseNodeToBundle() {
2164   uint siz = _available.size();
2165 
2166   if (siz == 0) {
2167 
2168 #ifndef PRODUCT
2169     if (_cfg->C->trace_opto_output())
2170       tty->print("#   ChooseNodeToBundle: NULL\n");
2171 #endif
2172     return (NULL);
2173   }
2174 
2175   // Fast path, if only 1 instruction in the bundle
2176   if (siz == 1) {
2177 #ifndef PRODUCT
2178     if (_cfg->C->trace_opto_output()) {
2179       tty->print("#   ChooseNodeToBundle (only 1): ");
2180       _available[0]->dump();
2181     }
2182 #endif
2183     return (_available[0]);
2184   }
2185 
2186   // Don't bother, if the bundle is already full
2187   if (_bundle_instr_count < Pipeline::_max_instrs_per_cycle) {
2188     for ( uint i = 0; i < siz; i++ ) {
2189       Node *n = _available[i];
2190 
2191       // Skip projections, we'll handle them another way
2192       if (n->is_Proj())
2193         continue;
2194 
2195       // This presupposed that instructions are inserted into the
2196       // available list in a legality order; i.e. instructions that
2197       // must be inserted first are at the head of the list
2198       if (NodeFitsInBundle(n)) {
2199 #ifndef PRODUCT
2200         if (_cfg->C->trace_opto_output()) {
2201           tty->print("#   ChooseNodeToBundle: ");
2202           n->dump();
2203         }
2204 #endif
2205         return (n);
2206       }
2207     }
2208   }
2209 
2210   // Nothing fits in this bundle, choose the highest priority
2211 #ifndef PRODUCT
2212   if (_cfg->C->trace_opto_output()) {
2213     tty->print("#   ChooseNodeToBundle: ");
2214     _available[0]->dump();
2215   }
2216 #endif
2217 
2218   return _available[0];
2219 }
2220 
AddNodeToAvailableList(Node * n)2221 void Scheduling::AddNodeToAvailableList(Node *n) {
2222   assert( !n->is_Proj(), "projections never directly made available" );
2223 #ifndef PRODUCT
2224   if (_cfg->C->trace_opto_output()) {
2225     tty->print("#   AddNodeToAvailableList: ");
2226     n->dump();
2227   }
2228 #endif
2229 
2230   int latency = _current_latency[n->_idx];
2231 
2232   // Insert in latency order (insertion sort)
2233   uint i;
2234   for ( i=0; i < _available.size(); i++ )
2235     if (_current_latency[_available[i]->_idx] > latency)
2236       break;
2237 
2238   // Special Check for compares following branches
2239   if( n->is_Mach() && _scheduled.size() > 0 ) {
2240     int op = n->as_Mach()->ideal_Opcode();
2241     Node *last = _scheduled[0];
2242     if( last->is_MachIf() && last->in(1) == n &&
2243         ( op == Op_CmpI ||
2244           op == Op_CmpU ||
2245           op == Op_CmpUL ||
2246           op == Op_CmpP ||
2247           op == Op_CmpF ||
2248           op == Op_CmpD ||
2249           op == Op_CmpL ) ) {
2250 
2251       // Recalculate position, moving to front of same latency
2252       for ( i=0 ; i < _available.size(); i++ )
2253         if (_current_latency[_available[i]->_idx] >= latency)
2254           break;
2255     }
2256   }
2257 
2258   // Insert the node in the available list
2259   _available.insert(i, n);
2260 
2261 #ifndef PRODUCT
2262   if (_cfg->C->trace_opto_output())
2263     dump_available();
2264 #endif
2265 }
2266 
DecrementUseCounts(Node * n,const Block * bb)2267 void Scheduling::DecrementUseCounts(Node *n, const Block *bb) {
2268   for ( uint i=0; i < n->len(); i++ ) {
2269     Node *def = n->in(i);
2270     if (!def) continue;
2271     if( def->is_Proj() )        // If this is a machine projection, then
2272       def = def->in(0);         // propagate usage thru to the base instruction
2273 
2274     if(_cfg->get_block_for_node(def) != bb) { // Ignore if not block-local
2275       continue;
2276     }
2277 
2278     // Compute the latency
2279     uint l = _bundle_cycle_number + n->latency(i);
2280     if (_current_latency[def->_idx] < l)
2281       _current_latency[def->_idx] = l;
2282 
2283     // If this does not have uses then schedule it
2284     if ((--_uses[def->_idx]) == 0)
2285       AddNodeToAvailableList(def);
2286   }
2287 }
2288 
AddNodeToBundle(Node * n,const Block * bb)2289 void Scheduling::AddNodeToBundle(Node *n, const Block *bb) {
2290 #ifndef PRODUCT
2291   if (_cfg->C->trace_opto_output()) {
2292     tty->print("#   AddNodeToBundle: ");
2293     n->dump();
2294   }
2295 #endif
2296 
2297   // Remove this from the available list
2298   uint i;
2299   for (i = 0; i < _available.size(); i++)
2300     if (_available[i] == n)
2301       break;
2302   assert(i < _available.size(), "entry in _available list not found");
2303   _available.remove(i);
2304 
2305   // See if this fits in the current bundle
2306   const Pipeline *node_pipeline = n->pipeline();
2307   const Pipeline_Use& node_usage = node_pipeline->resourceUse();
2308 
2309   // Check for instructions to be placed in the delay slot. We
2310   // do this before we actually schedule the current instruction,
2311   // because the delay slot follows the current instruction.
2312   if (Pipeline::_branch_has_delay_slot &&
2313       node_pipeline->hasBranchDelay() &&
2314       !_unconditional_delay_slot) {
2315 
2316     uint siz = _available.size();
2317 
2318     // Conditional branches can support an instruction that
2319     // is unconditionally executed and not dependent by the
2320     // branch, OR a conditionally executed instruction if
2321     // the branch is taken.  In practice, this means that
2322     // the first instruction at the branch target is
2323     // copied to the delay slot, and the branch goes to
2324     // the instruction after that at the branch target
2325     if ( n->is_MachBranch() ) {
2326 
2327       assert( !n->is_MachNullCheck(), "should not look for delay slot for Null Check" );
2328       assert( !n->is_Catch(),         "should not look for delay slot for Catch" );
2329 
2330 #ifndef PRODUCT
2331       _branches++;
2332 #endif
2333 
2334       // At least 1 instruction is on the available list
2335       // that is not dependent on the branch
2336       for (uint i = 0; i < siz; i++) {
2337         Node *d = _available[i];
2338         const Pipeline *avail_pipeline = d->pipeline();
2339 
2340         // Don't allow safepoints in the branch shadow, that will
2341         // cause a number of difficulties
2342         if ( avail_pipeline->instructionCount() == 1 &&
2343              !avail_pipeline->hasMultipleBundles() &&
2344              !avail_pipeline->hasBranchDelay() &&
2345              Pipeline::instr_has_unit_size() &&
2346              d->size(_regalloc) == Pipeline::instr_unit_size() &&
2347              NodeFitsInBundle(d) &&
2348              !node_bundling(d)->used_in_delay()) {
2349 
2350           if (d->is_Mach() && !d->is_MachSafePoint()) {
2351             // A node that fits in the delay slot was found, so we need to
2352             // set the appropriate bits in the bundle pipeline information so
2353             // that it correctly indicates resource usage.  Later, when we
2354             // attempt to add this instruction to the bundle, we will skip
2355             // setting the resource usage.
2356             _unconditional_delay_slot = d;
2357             node_bundling(n)->set_use_unconditional_delay();
2358             node_bundling(d)->set_used_in_unconditional_delay();
2359             _bundle_use.add_usage(avail_pipeline->resourceUse());
2360             _current_latency[d->_idx] = _bundle_cycle_number;
2361             _next_node = d;
2362             ++_bundle_instr_count;
2363 #ifndef PRODUCT
2364             _unconditional_delays++;
2365 #endif
2366             break;
2367           }
2368         }
2369       }
2370     }
2371 
2372     // No delay slot, add a nop to the usage
2373     if (!_unconditional_delay_slot) {
2374       // See if adding an instruction in the delay slot will overflow
2375       // the bundle.
2376       if (!NodeFitsInBundle(_nop)) {
2377 #ifndef PRODUCT
2378         if (_cfg->C->trace_opto_output())
2379           tty->print("#  *** STEP(1 instruction for delay slot) ***\n");
2380 #endif
2381         step(1);
2382       }
2383 
2384       _bundle_use.add_usage(_nop->pipeline()->resourceUse());
2385       _next_node = _nop;
2386       ++_bundle_instr_count;
2387     }
2388 
2389     // See if the instruction in the delay slot requires a
2390     // step of the bundles
2391     if (!NodeFitsInBundle(n)) {
2392 #ifndef PRODUCT
2393       if (_cfg->C->trace_opto_output())
2394         tty->print("#  *** STEP(branch won't fit) ***\n");
2395 #endif
2396       // Update the state information
2397       _bundle_instr_count = 0;
2398       _bundle_cycle_number += 1;
2399       _bundle_use.step(1);
2400     }
2401   }
2402 
2403   // Get the number of instructions
2404   uint instruction_count = node_pipeline->instructionCount();
2405   if (node_pipeline->mayHaveNoCode() && n->size(_regalloc) == 0)
2406     instruction_count = 0;
2407 
2408   // Compute the latency information
2409   uint delay = 0;
2410 
2411   if (instruction_count > 0 || !node_pipeline->mayHaveNoCode()) {
2412     int relative_latency = _current_latency[n->_idx] - _bundle_cycle_number;
2413     if (relative_latency < 0)
2414       relative_latency = 0;
2415 
2416     delay = _bundle_use.full_latency(relative_latency, node_usage);
2417 
2418     // Does not fit in this bundle, start a new one
2419     if (delay > 0) {
2420       step(delay);
2421 
2422 #ifndef PRODUCT
2423       if (_cfg->C->trace_opto_output())
2424         tty->print("#  *** STEP(%d) ***\n", delay);
2425 #endif
2426     }
2427   }
2428 
2429   // If this was placed in the delay slot, ignore it
2430   if (n != _unconditional_delay_slot) {
2431 
2432     if (delay == 0) {
2433       if (node_pipeline->hasMultipleBundles()) {
2434 #ifndef PRODUCT
2435         if (_cfg->C->trace_opto_output())
2436           tty->print("#  *** STEP(multiple instructions) ***\n");
2437 #endif
2438         step(1);
2439       }
2440 
2441       else if (instruction_count + _bundle_instr_count > Pipeline::_max_instrs_per_cycle) {
2442 #ifndef PRODUCT
2443         if (_cfg->C->trace_opto_output())
2444           tty->print("#  *** STEP(%d >= %d instructions) ***\n",
2445                      instruction_count + _bundle_instr_count,
2446                      Pipeline::_max_instrs_per_cycle);
2447 #endif
2448         step(1);
2449       }
2450     }
2451 
2452     if (node_pipeline->hasBranchDelay() && !_unconditional_delay_slot)
2453       _bundle_instr_count++;
2454 
2455     // Set the node's latency
2456     _current_latency[n->_idx] = _bundle_cycle_number;
2457 
2458     // Now merge the functional unit information
2459     if (instruction_count > 0 || !node_pipeline->mayHaveNoCode())
2460       _bundle_use.add_usage(node_usage);
2461 
2462     // Increment the number of instructions in this bundle
2463     _bundle_instr_count += instruction_count;
2464 
2465     // Remember this node for later
2466     if (n->is_Mach())
2467       _next_node = n;
2468   }
2469 
2470   // It's possible to have a BoxLock in the graph and in the _bbs mapping but
2471   // not in the bb->_nodes array.  This happens for debug-info-only BoxLocks.
2472   // 'Schedule' them (basically ignore in the schedule) but do not insert them
2473   // into the block.  All other scheduled nodes get put in the schedule here.
2474   int op = n->Opcode();
2475   if( (op == Op_Node && n->req() == 0) || // anti-dependence node OR
2476       (op != Op_Node &&         // Not an unused antidepedence node and
2477        // not an unallocated boxlock
2478        (OptoReg::is_valid(_regalloc->get_reg_first(n)) || op != Op_BoxLock)) ) {
2479 
2480     // Push any trailing projections
2481     if( bb->get_node(bb->number_of_nodes()-1) != n ) {
2482       for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
2483         Node *foi = n->fast_out(i);
2484         if( foi->is_Proj() )
2485           _scheduled.push(foi);
2486       }
2487     }
2488 
2489     // Put the instruction in the schedule list
2490     _scheduled.push(n);
2491   }
2492 
2493 #ifndef PRODUCT
2494   if (_cfg->C->trace_opto_output())
2495     dump_available();
2496 #endif
2497 
2498   // Walk all the definitions, decrementing use counts, and
2499   // if a definition has a 0 use count, place it in the available list.
2500   DecrementUseCounts(n,bb);
2501 }
2502 
2503 // This method sets the use count within a basic block.  We will ignore all
2504 // uses outside the current basic block.  As we are doing a backwards walk,
2505 // any node we reach that has a use count of 0 may be scheduled.  This also
2506 // avoids the problem of cyclic references from phi nodes, as long as phi
2507 // nodes are at the front of the basic block.  This method also initializes
2508 // the available list to the set of instructions that have no uses within this
2509 // basic block.
ComputeUseCount(const Block * bb)2510 void Scheduling::ComputeUseCount(const Block *bb) {
2511 #ifndef PRODUCT
2512   if (_cfg->C->trace_opto_output())
2513     tty->print("# -> ComputeUseCount\n");
2514 #endif
2515 
2516   // Clear the list of available and scheduled instructions, just in case
2517   _available.clear();
2518   _scheduled.clear();
2519 
2520   // No delay slot specified
2521   _unconditional_delay_slot = NULL;
2522 
2523 #ifdef ASSERT
2524   for( uint i=0; i < bb->number_of_nodes(); i++ )
2525     assert( _uses[bb->get_node(i)->_idx] == 0, "_use array not clean" );
2526 #endif
2527 
2528   // Force the _uses count to never go to zero for unscheduable pieces
2529   // of the block
2530   for( uint k = 0; k < _bb_start; k++ )
2531     _uses[bb->get_node(k)->_idx] = 1;
2532   for( uint l = _bb_end; l < bb->number_of_nodes(); l++ )
2533     _uses[bb->get_node(l)->_idx] = 1;
2534 
2535   // Iterate backwards over the instructions in the block.  Don't count the
2536   // branch projections at end or the block header instructions.
2537   for( uint j = _bb_end-1; j >= _bb_start; j-- ) {
2538     Node *n = bb->get_node(j);
2539     if( n->is_Proj() ) continue; // Projections handled another way
2540 
2541     // Account for all uses
2542     for ( uint k = 0; k < n->len(); k++ ) {
2543       Node *inp = n->in(k);
2544       if (!inp) continue;
2545       assert(inp != n, "no cycles allowed" );
2546       if (_cfg->get_block_for_node(inp) == bb) { // Block-local use?
2547         if (inp->is_Proj()) { // Skip through Proj's
2548           inp = inp->in(0);
2549         }
2550         ++_uses[inp->_idx];     // Count 1 block-local use
2551       }
2552     }
2553 
2554     // If this instruction has a 0 use count, then it is available
2555     if (!_uses[n->_idx]) {
2556       _current_latency[n->_idx] = _bundle_cycle_number;
2557       AddNodeToAvailableList(n);
2558     }
2559 
2560 #ifndef PRODUCT
2561     if (_cfg->C->trace_opto_output()) {
2562       tty->print("#   uses: %3d: ", _uses[n->_idx]);
2563       n->dump();
2564     }
2565 #endif
2566   }
2567 
2568 #ifndef PRODUCT
2569   if (_cfg->C->trace_opto_output())
2570     tty->print("# <- ComputeUseCount\n");
2571 #endif
2572 }
2573 
2574 // This routine performs scheduling on each basic block in reverse order,
2575 // using instruction latencies and taking into account function unit
2576 // availability.
DoScheduling()2577 void Scheduling::DoScheduling() {
2578 #ifndef PRODUCT
2579   if (_cfg->C->trace_opto_output())
2580     tty->print("# -> DoScheduling\n");
2581 #endif
2582 
2583   Block *succ_bb = NULL;
2584   Block *bb;
2585   Compile* C = Compile::current();
2586 
2587   // Walk over all the basic blocks in reverse order
2588   for (int i = _cfg->number_of_blocks() - 1; i >= 0; succ_bb = bb, i--) {
2589     bb = _cfg->get_block(i);
2590 
2591 #ifndef PRODUCT
2592     if (_cfg->C->trace_opto_output()) {
2593       tty->print("#  Schedule BB#%03d (initial)\n", i);
2594       for (uint j = 0; j < bb->number_of_nodes(); j++) {
2595         bb->get_node(j)->dump();
2596       }
2597     }
2598 #endif
2599 
2600     // On the head node, skip processing
2601     if (bb == _cfg->get_root_block()) {
2602       continue;
2603     }
2604 
2605     // Skip empty, connector blocks
2606     if (bb->is_connector())
2607       continue;
2608 
2609     // If the following block is not the sole successor of
2610     // this one, then reset the pipeline information
2611     if (bb->_num_succs != 1 || bb->non_connector_successor(0) != succ_bb) {
2612 #ifndef PRODUCT
2613       if (_cfg->C->trace_opto_output()) {
2614         tty->print("*** bundle start of next BB, node %d, for %d instructions\n",
2615                    _next_node->_idx, _bundle_instr_count);
2616       }
2617 #endif
2618       step_and_clear();
2619     }
2620 
2621     // Leave untouched the starting instruction, any Phis, a CreateEx node
2622     // or Top.  bb->get_node(_bb_start) is the first schedulable instruction.
2623     _bb_end = bb->number_of_nodes()-1;
2624     for( _bb_start=1; _bb_start <= _bb_end; _bb_start++ ) {
2625       Node *n = bb->get_node(_bb_start);
2626       // Things not matched, like Phinodes and ProjNodes don't get scheduled.
2627       // Also, MachIdealNodes do not get scheduled
2628       if( !n->is_Mach() ) continue;     // Skip non-machine nodes
2629       MachNode *mach = n->as_Mach();
2630       int iop = mach->ideal_Opcode();
2631       if( iop == Op_CreateEx ) continue; // CreateEx is pinned
2632       if( iop == Op_Con ) continue;      // Do not schedule Top
2633       if( iop == Op_Node &&     // Do not schedule PhiNodes, ProjNodes
2634           mach->pipeline() == MachNode::pipeline_class() &&
2635           !n->is_SpillCopy() && !n->is_MachMerge() )  // Breakpoints, Prolog, etc
2636         continue;
2637       break;                    // Funny loop structure to be sure...
2638     }
2639     // Compute last "interesting" instruction in block - last instruction we
2640     // might schedule.  _bb_end points just after last schedulable inst.  We
2641     // normally schedule conditional branches (despite them being forced last
2642     // in the block), because they have delay slots we can fill.  Calls all
2643     // have their delay slots filled in the template expansions, so we don't
2644     // bother scheduling them.
2645     Node *last = bb->get_node(_bb_end);
2646     // Ignore trailing NOPs.
2647     while (_bb_end > 0 && last->is_Mach() &&
2648            last->as_Mach()->ideal_Opcode() == Op_Con) {
2649       last = bb->get_node(--_bb_end);
2650     }
2651     assert(!last->is_Mach() || last->as_Mach()->ideal_Opcode() != Op_Con, "");
2652     if( last->is_Catch() ||
2653         (last->is_Mach() && last->as_Mach()->ideal_Opcode() == Op_Halt) ) {
2654       // There might be a prior call.  Skip it.
2655       while (_bb_start < _bb_end && bb->get_node(--_bb_end)->is_MachProj());
2656     } else if( last->is_MachNullCheck() ) {
2657       // Backup so the last null-checked memory instruction is
2658       // outside the schedulable range. Skip over the nullcheck,
2659       // projection, and the memory nodes.
2660       Node *mem = last->in(1);
2661       do {
2662         _bb_end--;
2663       } while (mem != bb->get_node(_bb_end));
2664     } else {
2665       // Set _bb_end to point after last schedulable inst.
2666       _bb_end++;
2667     }
2668 
2669     assert( _bb_start <= _bb_end, "inverted block ends" );
2670 
2671     // Compute the register antidependencies for the basic block
2672     ComputeRegisterAntidependencies(bb);
2673     if (C->failing())  return;  // too many D-U pinch points
2674 
2675     // Compute intra-bb latencies for the nodes
2676     ComputeLocalLatenciesForward(bb);
2677 
2678     // Compute the usage within the block, and set the list of all nodes
2679     // in the block that have no uses within the block.
2680     ComputeUseCount(bb);
2681 
2682     // Schedule the remaining instructions in the block
2683     while ( _available.size() > 0 ) {
2684       Node *n = ChooseNodeToBundle();
2685       guarantee(n != NULL, "no nodes available");
2686       AddNodeToBundle(n,bb);
2687     }
2688 
2689     assert( _scheduled.size() == _bb_end - _bb_start, "wrong number of instructions" );
2690 #ifdef ASSERT
2691     for( uint l = _bb_start; l < _bb_end; l++ ) {
2692       Node *n = bb->get_node(l);
2693       uint m;
2694       for( m = 0; m < _bb_end-_bb_start; m++ )
2695         if( _scheduled[m] == n )
2696           break;
2697       assert( m < _bb_end-_bb_start, "instruction missing in schedule" );
2698     }
2699 #endif
2700 
2701     // Now copy the instructions (in reverse order) back to the block
2702     for ( uint k = _bb_start; k < _bb_end; k++ )
2703       bb->map_node(_scheduled[_bb_end-k-1], k);
2704 
2705 #ifndef PRODUCT
2706     if (_cfg->C->trace_opto_output()) {
2707       tty->print("#  Schedule BB#%03d (final)\n", i);
2708       uint current = 0;
2709       for (uint j = 0; j < bb->number_of_nodes(); j++) {
2710         Node *n = bb->get_node(j);
2711         if( valid_bundle_info(n) ) {
2712           Bundle *bundle = node_bundling(n);
2713           if (bundle->instr_count() > 0 || bundle->flags() > 0) {
2714             tty->print("*** Bundle: ");
2715             bundle->dump();
2716           }
2717           n->dump();
2718         }
2719       }
2720     }
2721 #endif
2722 #ifdef ASSERT
2723     verify_good_schedule(bb,"after block local scheduling");
2724 #endif
2725   }
2726 
2727 #ifndef PRODUCT
2728   if (_cfg->C->trace_opto_output())
2729     tty->print("# <- DoScheduling\n");
2730 #endif
2731 
2732   // Record final node-bundling array location
2733   _regalloc->C->output()->set_node_bundling_base(_node_bundling_base);
2734 
2735 } // end DoScheduling
2736 
2737 // Verify that no live-range used in the block is killed in the block by a
2738 // wrong DEF.  This doesn't verify live-ranges that span blocks.
2739 
2740 // Check for edge existence.  Used to avoid adding redundant precedence edges.
edge_from_to(Node * from,Node * to)2741 static bool edge_from_to( Node *from, Node *to ) {
2742   for( uint i=0; i<from->len(); i++ )
2743     if( from->in(i) == to )
2744       return true;
2745   return false;
2746 }
2747 
2748 #ifdef ASSERT
verify_do_def(Node * n,OptoReg::Name def,const char * msg)2749 void Scheduling::verify_do_def( Node *n, OptoReg::Name def, const char *msg ) {
2750   // Check for bad kills
2751   if( OptoReg::is_valid(def) ) { // Ignore stores & control flow
2752     Node *prior_use = _reg_node[def];
2753     if( prior_use && !edge_from_to(prior_use,n) ) {
2754       tty->print("%s = ",OptoReg::as_VMReg(def)->name());
2755       n->dump();
2756       tty->print_cr("...");
2757       prior_use->dump();
2758       assert(edge_from_to(prior_use,n), "%s", msg);
2759     }
2760     _reg_node.map(def,NULL); // Kill live USEs
2761   }
2762 }
2763 
verify_good_schedule(Block * b,const char * msg)2764 void Scheduling::verify_good_schedule( Block *b, const char *msg ) {
2765 
2766   // Zap to something reasonable for the verify code
2767   _reg_node.clear();
2768 
2769   // Walk over the block backwards.  Check to make sure each DEF doesn't
2770   // kill a live value (other than the one it's supposed to).  Add each
2771   // USE to the live set.
2772   for( uint i = b->number_of_nodes()-1; i >= _bb_start; i-- ) {
2773     Node *n = b->get_node(i);
2774     int n_op = n->Opcode();
2775     if( n_op == Op_MachProj && n->ideal_reg() == MachProjNode::fat_proj ) {
2776       // Fat-proj kills a slew of registers
2777       RegMask rm = n->out_RegMask();// Make local copy
2778       while( rm.is_NotEmpty() ) {
2779         OptoReg::Name kill = rm.find_first_elem();
2780         rm.Remove(kill);
2781         verify_do_def( n, kill, msg );
2782       }
2783     } else if( n_op != Op_Node ) { // Avoid brand new antidependence nodes
2784       // Get DEF'd registers the normal way
2785       verify_do_def( n, _regalloc->get_reg_first(n), msg );
2786       verify_do_def( n, _regalloc->get_reg_second(n), msg );
2787     }
2788 
2789     // Now make all USEs live
2790     for( uint i=1; i<n->req(); i++ ) {
2791       Node *def = n->in(i);
2792       assert(def != 0, "input edge required");
2793       OptoReg::Name reg_lo = _regalloc->get_reg_first(def);
2794       OptoReg::Name reg_hi = _regalloc->get_reg_second(def);
2795       if( OptoReg::is_valid(reg_lo) ) {
2796         assert(!_reg_node[reg_lo] || edge_from_to(_reg_node[reg_lo],def), "%s", msg);
2797         _reg_node.map(reg_lo,n);
2798       }
2799       if( OptoReg::is_valid(reg_hi) ) {
2800         assert(!_reg_node[reg_hi] || edge_from_to(_reg_node[reg_hi],def), "%s", msg);
2801         _reg_node.map(reg_hi,n);
2802       }
2803     }
2804 
2805   }
2806 
2807   // Zap to something reasonable for the Antidependence code
2808   _reg_node.clear();
2809 }
2810 #endif
2811 
2812 // Conditionally add precedence edges.  Avoid putting edges on Projs.
add_prec_edge_from_to(Node * from,Node * to)2813 static void add_prec_edge_from_to( Node *from, Node *to ) {
2814   if( from->is_Proj() ) {       // Put precedence edge on Proj's input
2815     assert( from->req() == 1 && (from->len() == 1 || from->in(1)==0), "no precedence edges on projections" );
2816     from = from->in(0);
2817   }
2818   if( from != to &&             // No cycles (for things like LD L0,[L0+4] )
2819       !edge_from_to( from, to ) ) // Avoid duplicate edge
2820     from->add_prec(to);
2821 }
2822 
anti_do_def(Block * b,Node * def,OptoReg::Name def_reg,int is_def)2823 void Scheduling::anti_do_def( Block *b, Node *def, OptoReg::Name def_reg, int is_def ) {
2824   if( !OptoReg::is_valid(def_reg) ) // Ignore stores & control flow
2825     return;
2826 
2827   Node *pinch = _reg_node[def_reg]; // Get pinch point
2828   if ((pinch == NULL) || _cfg->get_block_for_node(pinch) != b || // No pinch-point yet?
2829       is_def ) {    // Check for a true def (not a kill)
2830     _reg_node.map(def_reg,def); // Record def/kill as the optimistic pinch-point
2831     return;
2832   }
2833 
2834   Node *kill = def;             // Rename 'def' to more descriptive 'kill'
2835   debug_only( def = (Node*)((intptr_t)0xdeadbeef); )
2836 
2837   // After some number of kills there _may_ be a later def
2838   Node *later_def = NULL;
2839 
2840   Compile* C = Compile::current();
2841 
2842   // Finding a kill requires a real pinch-point.
2843   // Check for not already having a pinch-point.
2844   // Pinch points are Op_Node's.
2845   if( pinch->Opcode() != Op_Node ) { // Or later-def/kill as pinch-point?
2846     later_def = pinch;            // Must be def/kill as optimistic pinch-point
2847     if ( _pinch_free_list.size() > 0) {
2848       pinch = _pinch_free_list.pop();
2849     } else {
2850       pinch = new Node(1); // Pinch point to-be
2851     }
2852     if (pinch->_idx >= _regalloc->node_regs_max_index()) {
2853       _cfg->C->record_method_not_compilable("too many D-U pinch points");
2854       return;
2855     }
2856     _cfg->map_node_to_block(pinch, b);      // Pretend it's valid in this block (lazy init)
2857     _reg_node.map(def_reg,pinch); // Record pinch-point
2858     //regalloc()->set_bad(pinch->_idx); // Already initialized this way.
2859     if( later_def->outcnt() == 0 || later_def->ideal_reg() == MachProjNode::fat_proj ) { // Distinguish def from kill
2860       pinch->init_req(0, C->top());     // set not NULL for the next call
2861       add_prec_edge_from_to(later_def,pinch); // Add edge from kill to pinch
2862       later_def = NULL;           // and no later def
2863     }
2864     pinch->set_req(0,later_def);  // Hook later def so we can find it
2865   } else {                        // Else have valid pinch point
2866     if( pinch->in(0) )            // If there is a later-def
2867       later_def = pinch->in(0);   // Get it
2868   }
2869 
2870   // Add output-dependence edge from later def to kill
2871   if( later_def )               // If there is some original def
2872     add_prec_edge_from_to(later_def,kill); // Add edge from def to kill
2873 
2874   // See if current kill is also a use, and so is forced to be the pinch-point.
2875   if( pinch->Opcode() == Op_Node ) {
2876     Node *uses = kill->is_Proj() ? kill->in(0) : kill;
2877     for( uint i=1; i<uses->req(); i++ ) {
2878       if( _regalloc->get_reg_first(uses->in(i)) == def_reg ||
2879           _regalloc->get_reg_second(uses->in(i)) == def_reg ) {
2880         // Yes, found a use/kill pinch-point
2881         pinch->set_req(0,NULL);  //
2882         pinch->replace_by(kill); // Move anti-dep edges up
2883         pinch = kill;
2884         _reg_node.map(def_reg,pinch);
2885         return;
2886       }
2887     }
2888   }
2889 
2890   // Add edge from kill to pinch-point
2891   add_prec_edge_from_to(kill,pinch);
2892 }
2893 
anti_do_use(Block * b,Node * use,OptoReg::Name use_reg)2894 void Scheduling::anti_do_use( Block *b, Node *use, OptoReg::Name use_reg ) {
2895   if( !OptoReg::is_valid(use_reg) ) // Ignore stores & control flow
2896     return;
2897   Node *pinch = _reg_node[use_reg]; // Get pinch point
2898   // Check for no later def_reg/kill in block
2899   if ((pinch != NULL) && _cfg->get_block_for_node(pinch) == b &&
2900       // Use has to be block-local as well
2901       _cfg->get_block_for_node(use) == b) {
2902     if( pinch->Opcode() == Op_Node && // Real pinch-point (not optimistic?)
2903         pinch->req() == 1 ) {   // pinch not yet in block?
2904       pinch->del_req(0);        // yank pointer to later-def, also set flag
2905       // Insert the pinch-point in the block just after the last use
2906       b->insert_node(pinch, b->find_node(use) + 1);
2907       _bb_end++;                // Increase size scheduled region in block
2908     }
2909 
2910     add_prec_edge_from_to(pinch,use);
2911   }
2912 }
2913 
2914 // We insert antidependences between the reads and following write of
2915 // allocated registers to prevent illegal code motion. Hopefully, the
2916 // number of added references should be fairly small, especially as we
2917 // are only adding references within the current basic block.
ComputeRegisterAntidependencies(Block * b)2918 void Scheduling::ComputeRegisterAntidependencies(Block *b) {
2919 
2920 #ifdef ASSERT
2921   verify_good_schedule(b,"before block local scheduling");
2922 #endif
2923 
2924   // A valid schedule, for each register independently, is an endless cycle
2925   // of: a def, then some uses (connected to the def by true dependencies),
2926   // then some kills (defs with no uses), finally the cycle repeats with a new
2927   // def.  The uses are allowed to float relative to each other, as are the
2928   // kills.  No use is allowed to slide past a kill (or def).  This requires
2929   // antidependencies between all uses of a single def and all kills that
2930   // follow, up to the next def.  More edges are redundant, because later defs
2931   // & kills are already serialized with true or antidependencies.  To keep
2932   // the edge count down, we add a 'pinch point' node if there's more than
2933   // one use or more than one kill/def.
2934 
2935   // We add dependencies in one bottom-up pass.
2936 
2937   // For each instruction we handle it's DEFs/KILLs, then it's USEs.
2938 
2939   // For each DEF/KILL, we check to see if there's a prior DEF/KILL for this
2940   // register.  If not, we record the DEF/KILL in _reg_node, the
2941   // register-to-def mapping.  If there is a prior DEF/KILL, we insert a
2942   // "pinch point", a new Node that's in the graph but not in the block.
2943   // We put edges from the prior and current DEF/KILLs to the pinch point.
2944   // We put the pinch point in _reg_node.  If there's already a pinch point
2945   // we merely add an edge from the current DEF/KILL to the pinch point.
2946 
2947   // After doing the DEF/KILLs, we handle USEs.  For each used register, we
2948   // put an edge from the pinch point to the USE.
2949 
2950   // To be expedient, the _reg_node array is pre-allocated for the whole
2951   // compilation.  _reg_node is lazily initialized; it either contains a NULL,
2952   // or a valid def/kill/pinch-point, or a leftover node from some prior
2953   // block.  Leftover node from some prior block is treated like a NULL (no
2954   // prior def, so no anti-dependence needed).  Valid def is distinguished by
2955   // it being in the current block.
2956   bool fat_proj_seen = false;
2957   uint last_safept = _bb_end-1;
2958   Node* end_node         = (_bb_end-1 >= _bb_start) ? b->get_node(last_safept) : NULL;
2959   Node* last_safept_node = end_node;
2960   for( uint i = _bb_end-1; i >= _bb_start; i-- ) {
2961     Node *n = b->get_node(i);
2962     int is_def = n->outcnt();   // def if some uses prior to adding precedence edges
2963     if( n->is_MachProj() && n->ideal_reg() == MachProjNode::fat_proj ) {
2964       // Fat-proj kills a slew of registers
2965       // This can add edges to 'n' and obscure whether or not it was a def,
2966       // hence the is_def flag.
2967       fat_proj_seen = true;
2968       RegMask rm = n->out_RegMask();// Make local copy
2969       while( rm.is_NotEmpty() ) {
2970         OptoReg::Name kill = rm.find_first_elem();
2971         rm.Remove(kill);
2972         anti_do_def( b, n, kill, is_def );
2973       }
2974     } else {
2975       // Get DEF'd registers the normal way
2976       anti_do_def( b, n, _regalloc->get_reg_first(n), is_def );
2977       anti_do_def( b, n, _regalloc->get_reg_second(n), is_def );
2978     }
2979 
2980     // Kill projections on a branch should appear to occur on the
2981     // branch, not afterwards, so grab the masks from the projections
2982     // and process them.
2983     if (n->is_MachBranch() || (n->is_Mach() && n->as_Mach()->ideal_Opcode() == Op_Jump)) {
2984       for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
2985         Node* use = n->fast_out(i);
2986         if (use->is_Proj()) {
2987           RegMask rm = use->out_RegMask();// Make local copy
2988           while( rm.is_NotEmpty() ) {
2989             OptoReg::Name kill = rm.find_first_elem();
2990             rm.Remove(kill);
2991             anti_do_def( b, n, kill, false );
2992           }
2993         }
2994       }
2995     }
2996 
2997     // Check each register used by this instruction for a following DEF/KILL
2998     // that must occur afterward and requires an anti-dependence edge.
2999     for( uint j=0; j<n->req(); j++ ) {
3000       Node *def = n->in(j);
3001       if( def ) {
3002         assert( !def->is_MachProj() || def->ideal_reg() != MachProjNode::fat_proj, "" );
3003         anti_do_use( b, n, _regalloc->get_reg_first(def) );
3004         anti_do_use( b, n, _regalloc->get_reg_second(def) );
3005       }
3006     }
3007     // Do not allow defs of new derived values to float above GC
3008     // points unless the base is definitely available at the GC point.
3009 
3010     Node *m = b->get_node(i);
3011 
3012     // Add precedence edge from following safepoint to use of derived pointer
3013     if( last_safept_node != end_node &&
3014         m != last_safept_node) {
3015       for (uint k = 1; k < m->req(); k++) {
3016         const Type *t = m->in(k)->bottom_type();
3017         if( t->isa_oop_ptr() &&
3018             t->is_ptr()->offset() != 0 ) {
3019           last_safept_node->add_prec( m );
3020           break;
3021         }
3022       }
3023     }
3024 
3025     if( n->jvms() ) {           // Precedence edge from derived to safept
3026       // Check if last_safept_node was moved by pinch-point insertion in anti_do_use()
3027       if( b->get_node(last_safept) != last_safept_node ) {
3028         last_safept = b->find_node(last_safept_node);
3029       }
3030       for( uint j=last_safept; j > i; j-- ) {
3031         Node *mach = b->get_node(j);
3032         if( mach->is_Mach() && mach->as_Mach()->ideal_Opcode() == Op_AddP )
3033           mach->add_prec( n );
3034       }
3035       last_safept = i;
3036       last_safept_node = m;
3037     }
3038   }
3039 
3040   if (fat_proj_seen) {
3041     // Garbage collect pinch nodes that were not consumed.
3042     // They are usually created by a fat kill MachProj for a call.
3043     garbage_collect_pinch_nodes();
3044   }
3045 }
3046 
3047 // Garbage collect pinch nodes for reuse by other blocks.
3048 //
3049 // The block scheduler's insertion of anti-dependence
3050 // edges creates many pinch nodes when the block contains
3051 // 2 or more Calls.  A pinch node is used to prevent a
3052 // combinatorial explosion of edges.  If a set of kills for a
3053 // register is anti-dependent on a set of uses (or defs), rather
3054 // than adding an edge in the graph between each pair of kill
3055 // and use (or def), a pinch is inserted between them:
3056 //
3057 //            use1   use2  use3
3058 //                \   |   /
3059 //                 \  |  /
3060 //                  pinch
3061 //                 /  |  \
3062 //                /   |   \
3063 //            kill1 kill2 kill3
3064 //
3065 // One pinch node is created per register killed when
3066 // the second call is encountered during a backwards pass
3067 // over the block.  Most of these pinch nodes are never
3068 // wired into the graph because the register is never
3069 // used or def'ed in the block.
3070 //
garbage_collect_pinch_nodes()3071 void Scheduling::garbage_collect_pinch_nodes() {
3072 #ifndef PRODUCT
3073   if (_cfg->C->trace_opto_output()) tty->print("Reclaimed pinch nodes:");
3074 #endif
3075   int trace_cnt = 0;
3076   for (uint k = 0; k < _reg_node.Size(); k++) {
3077     Node* pinch = _reg_node[k];
3078     if ((pinch != NULL) && pinch->Opcode() == Op_Node &&
3079         // no predecence input edges
3080         (pinch->req() == pinch->len() || pinch->in(pinch->req()) == NULL) ) {
3081       cleanup_pinch(pinch);
3082       _pinch_free_list.push(pinch);
3083       _reg_node.map(k, NULL);
3084 #ifndef PRODUCT
3085       if (_cfg->C->trace_opto_output()) {
3086         trace_cnt++;
3087         if (trace_cnt > 40) {
3088           tty->print("\n");
3089           trace_cnt = 0;
3090         }
3091         tty->print(" %d", pinch->_idx);
3092       }
3093 #endif
3094     }
3095   }
3096 #ifndef PRODUCT
3097   if (_cfg->C->trace_opto_output()) tty->print("\n");
3098 #endif
3099 }
3100 
3101 // Clean up a pinch node for reuse.
cleanup_pinch(Node * pinch)3102 void Scheduling::cleanup_pinch( Node *pinch ) {
3103   assert (pinch && pinch->Opcode() == Op_Node && pinch->req() == 1, "just checking");
3104 
3105   for (DUIterator_Last imin, i = pinch->last_outs(imin); i >= imin; ) {
3106     Node* use = pinch->last_out(i);
3107     uint uses_found = 0;
3108     for (uint j = use->req(); j < use->len(); j++) {
3109       if (use->in(j) == pinch) {
3110         use->rm_prec(j);
3111         uses_found++;
3112       }
3113     }
3114     assert(uses_found > 0, "must be a precedence edge");
3115     i -= uses_found;    // we deleted 1 or more copies of this edge
3116   }
3117   // May have a later_def entry
3118   pinch->set_req(0, NULL);
3119 }
3120 
3121 #ifndef PRODUCT
3122 
dump_available() const3123 void Scheduling::dump_available() const {
3124   tty->print("#Availist  ");
3125   for (uint i = 0; i < _available.size(); i++)
3126     tty->print(" N%d/l%d", _available[i]->_idx,_current_latency[_available[i]->_idx]);
3127   tty->cr();
3128 }
3129 
3130 // Print Scheduling Statistics
print_statistics()3131 void Scheduling::print_statistics() {
3132   // Print the size added by nops for bundling
3133   tty->print("Nops added %d bytes to total of %d bytes",
3134              _total_nop_size, _total_method_size);
3135   if (_total_method_size > 0)
3136     tty->print(", for %.2f%%",
3137                ((double)_total_nop_size) / ((double) _total_method_size) * 100.0);
3138   tty->print("\n");
3139 
3140   // Print the number of branch shadows filled
3141   if (Pipeline::_branch_has_delay_slot) {
3142     tty->print("Of %d branches, %d had unconditional delay slots filled",
3143                _total_branches, _total_unconditional_delays);
3144     if (_total_branches > 0)
3145       tty->print(", for %.2f%%",
3146                  ((double)_total_unconditional_delays) / ((double)_total_branches) * 100.0);
3147     tty->print("\n");
3148   }
3149 
3150   uint total_instructions = 0, total_bundles = 0;
3151 
3152   for (uint i = 1; i <= Pipeline::_max_instrs_per_cycle; i++) {
3153     uint bundle_count   = _total_instructions_per_bundle[i];
3154     total_instructions += bundle_count * i;
3155     total_bundles      += bundle_count;
3156   }
3157 
3158   if (total_bundles > 0)
3159     tty->print("Average ILP (excluding nops) is %.2f\n",
3160                ((double)total_instructions) / ((double)total_bundles));
3161 }
3162 #endif
3163 
3164 //-----------------------init_scratch_buffer_blob------------------------------
3165 // Construct a temporary BufferBlob and cache it for this compile.
init_scratch_buffer_blob(int const_size)3166 void PhaseOutput::init_scratch_buffer_blob(int const_size) {
3167   // If there is already a scratch buffer blob allocated and the
3168   // constant section is big enough, use it.  Otherwise free the
3169   // current and allocate a new one.
3170   BufferBlob* blob = scratch_buffer_blob();
3171   if ((blob != NULL) && (const_size <= _scratch_const_size)) {
3172     // Use the current blob.
3173   } else {
3174     if (blob != NULL) {
3175       BufferBlob::free(blob);
3176     }
3177 
3178     ResourceMark rm;
3179     _scratch_const_size = const_size;
3180     int size = C2Compiler::initial_code_buffer_size(const_size);
3181     blob = BufferBlob::create("Compile::scratch_buffer", size);
3182     // Record the buffer blob for next time.
3183     set_scratch_buffer_blob(blob);
3184     // Have we run out of code space?
3185     if (scratch_buffer_blob() == NULL) {
3186       // Let CompilerBroker disable further compilations.
3187       C->record_failure("Not enough space for scratch buffer in CodeCache");
3188       return;
3189     }
3190   }
3191 
3192   // Initialize the relocation buffers
3193   relocInfo* locs_buf = (relocInfo*) blob->content_end() - MAX_locs_size;
3194   set_scratch_locs_memory(locs_buf);
3195 }
3196 
3197 
3198 //-----------------------scratch_emit_size-------------------------------------
3199 // Helper function that computes size by emitting code
scratch_emit_size(const Node * n)3200 uint PhaseOutput::scratch_emit_size(const Node* n) {
3201   // Start scratch_emit_size section.
3202   set_in_scratch_emit_size(true);
3203 
3204   // Emit into a trash buffer and count bytes emitted.
3205   // This is a pretty expensive way to compute a size,
3206   // but it works well enough if seldom used.
3207   // All common fixed-size instructions are given a size
3208   // method by the AD file.
3209   // Note that the scratch buffer blob and locs memory are
3210   // allocated at the beginning of the compile task, and
3211   // may be shared by several calls to scratch_emit_size.
3212   // The allocation of the scratch buffer blob is particularly
3213   // expensive, since it has to grab the code cache lock.
3214   BufferBlob* blob = this->scratch_buffer_blob();
3215   assert(blob != NULL, "Initialize BufferBlob at start");
3216   assert(blob->size() > MAX_inst_size, "sanity");
3217   relocInfo* locs_buf = scratch_locs_memory();
3218   address blob_begin = blob->content_begin();
3219   address blob_end   = (address)locs_buf;
3220   assert(blob->contains(blob_end), "sanity");
3221   CodeBuffer buf(blob_begin, blob_end - blob_begin);
3222   buf.initialize_consts_size(_scratch_const_size);
3223   buf.initialize_stubs_size(MAX_stubs_size);
3224   assert(locs_buf != NULL, "sanity");
3225   int lsize = MAX_locs_size / 3;
3226   buf.consts()->initialize_shared_locs(&locs_buf[lsize * 0], lsize);
3227   buf.insts()->initialize_shared_locs( &locs_buf[lsize * 1], lsize);
3228   buf.stubs()->initialize_shared_locs( &locs_buf[lsize * 2], lsize);
3229   // Mark as scratch buffer.
3230   buf.consts()->set_scratch_emit();
3231   buf.insts()->set_scratch_emit();
3232   buf.stubs()->set_scratch_emit();
3233 
3234   // Do the emission.
3235 
3236   Label fakeL; // Fake label for branch instructions.
3237   Label*   saveL = NULL;
3238   uint save_bnum = 0;
3239   bool is_branch = n->is_MachBranch();
3240   if (is_branch) {
3241     MacroAssembler masm(&buf);
3242     masm.bind(fakeL);
3243     n->as_MachBranch()->save_label(&saveL, &save_bnum);
3244     n->as_MachBranch()->label_set(&fakeL, 0);
3245   }
3246   n->emit(buf, C->regalloc());
3247 
3248   // Emitting into the scratch buffer should not fail
3249   assert (!C->failing(), "Must not have pending failure. Reason is: %s", C->failure_reason());
3250 
3251   if (is_branch) // Restore label.
3252     n->as_MachBranch()->label_set(saveL, save_bnum);
3253 
3254   // End scratch_emit_size section.
3255   set_in_scratch_emit_size(false);
3256 
3257   return buf.insts_size();
3258 }
3259 
install()3260 void PhaseOutput::install() {
3261   if (C->stub_function() != NULL) {
3262     install_stub(C->stub_name(),
3263                  C->save_argument_registers());
3264   } else {
3265     install_code(C->method(),
3266                  C->entry_bci(),
3267                  CompileBroker::compiler2(),
3268                  C->has_unsafe_access(),
3269                  SharedRuntime::is_wide_vector(C->max_vector_size()),
3270                  C->rtm_state());
3271   }
3272 }
3273 
install_code(ciMethod * target,int entry_bci,AbstractCompiler * compiler,bool has_unsafe_access,bool has_wide_vectors,RTMState rtm_state)3274 void PhaseOutput::install_code(ciMethod*         target,
3275                                int               entry_bci,
3276                                AbstractCompiler* compiler,
3277                                bool              has_unsafe_access,
3278                                bool              has_wide_vectors,
3279                                RTMState          rtm_state) {
3280   // Check if we want to skip execution of all compiled code.
3281   {
3282 #ifndef PRODUCT
3283     if (OptoNoExecute) {
3284       C->record_method_not_compilable("+OptoNoExecute");  // Flag as failed
3285       return;
3286     }
3287 #endif
3288     Compile::TracePhase tp("install_code", &timers[_t_registerMethod]);
3289 
3290     if (C->is_osr_compilation()) {
3291       _code_offsets.set_value(CodeOffsets::Verified_Entry, 0);
3292       _code_offsets.set_value(CodeOffsets::OSR_Entry, _first_block_size);
3293     } else {
3294       _code_offsets.set_value(CodeOffsets::Verified_Entry, _first_block_size);
3295       _code_offsets.set_value(CodeOffsets::OSR_Entry, 0);
3296     }
3297 
3298     C->env()->register_method(target,
3299                                      entry_bci,
3300                                      &_code_offsets,
3301                                      _orig_pc_slot_offset_in_bytes,
3302                                      code_buffer(),
3303                                      frame_size_in_words(),
3304                                      oop_map_set(),
3305                                      &_handler_table,
3306                                      inc_table(),
3307                                      compiler,
3308                                      has_unsafe_access,
3309                                      SharedRuntime::is_wide_vector(C->max_vector_size()),
3310                                      C->rtm_state());
3311 
3312     if (C->log() != NULL) { // Print code cache state into compiler log
3313       C->log()->code_cache_state();
3314     }
3315   }
3316 }
install_stub(const char * stub_name,bool caller_must_gc_arguments)3317 void PhaseOutput::install_stub(const char* stub_name,
3318                                bool        caller_must_gc_arguments) {
3319   // Entry point will be accessed using stub_entry_point();
3320   if (code_buffer() == NULL) {
3321     Matcher::soft_match_failure();
3322   } else {
3323     if (PrintAssembly && (WizardMode || Verbose))
3324       tty->print_cr("### Stub::%s", stub_name);
3325 
3326     if (!C->failing()) {
3327       assert(C->fixed_slots() == 0, "no fixed slots used for runtime stubs");
3328 
3329       // Make the NMethod
3330       // For now we mark the frame as never safe for profile stackwalking
3331       RuntimeStub *rs = RuntimeStub::new_runtime_stub(stub_name,
3332                                                       code_buffer(),
3333                                                       CodeOffsets::frame_never_safe,
3334                                                       // _code_offsets.value(CodeOffsets::Frame_Complete),
3335                                                       frame_size_in_words(),
3336                                                       oop_map_set(),
3337                                                       caller_must_gc_arguments);
3338       assert(rs != NULL && rs->is_runtime_stub(), "sanity check");
3339 
3340       C->set_stub_entry_point(rs->entry_point());
3341     }
3342   }
3343 }
3344 
3345 // Support for bundling info
node_bundling(const Node * n)3346 Bundle* PhaseOutput::node_bundling(const Node *n) {
3347   assert(valid_bundle_info(n), "oob");
3348   return &_node_bundling_base[n->_idx];
3349 }
3350 
valid_bundle_info(const Node * n)3351 bool PhaseOutput::valid_bundle_info(const Node *n) {
3352   return (_node_bundling_limit > n->_idx);
3353 }
3354 
3355 //------------------------------frame_size_in_words-----------------------------
3356 // frame_slots in units of words
frame_size_in_words() const3357 int PhaseOutput::frame_size_in_words() const {
3358   // shift is 0 in LP32 and 1 in LP64
3359   const int shift = (LogBytesPerWord - LogBytesPerInt);
3360   int words = _frame_slots >> shift;
3361   assert( words << shift == _frame_slots, "frame size must be properly aligned in LP64" );
3362   return words;
3363 }
3364 
3365 // To bang the stack of this compiled method we use the stack size
3366 // that the interpreter would need in case of a deoptimization. This
3367 // removes the need to bang the stack in the deoptimization blob which
3368 // in turn simplifies stack overflow handling.
bang_size_in_bytes() const3369 int PhaseOutput::bang_size_in_bytes() const {
3370   return MAX2(frame_size_in_bytes() + os::extra_bang_size_in_bytes(), C->interpreter_frame_size());
3371 }
3372 
3373 //------------------------------dump_asm---------------------------------------
3374 // Dump formatted assembly
3375 #if defined(SUPPORT_OPTO_ASSEMBLY)
dump_asm_on(outputStream * st,int * pcs,uint pc_limit)3376 void PhaseOutput::dump_asm_on(outputStream* st, int* pcs, uint pc_limit) {
3377 
3378   int pc_digits = 3; // #chars required for pc
3379   int sb_chars  = 3; // #chars for "start bundle" indicator
3380   int tab_size  = 8;
3381   if (pcs != NULL) {
3382     int max_pc = 0;
3383     for (uint i = 0; i < pc_limit; i++) {
3384       max_pc = (max_pc < pcs[i]) ? pcs[i] : max_pc;
3385     }
3386     pc_digits  = ((max_pc < 4096) ? 3 : ((max_pc < 65536) ? 4 : ((max_pc < 65536*256) ? 6 : 8))); // #chars required for pc
3387   }
3388   int prefix_len = ((pc_digits + sb_chars + tab_size - 1)/tab_size)*tab_size;
3389 
3390   bool cut_short = false;
3391   st->print_cr("#");
3392   st->print("#  ");  C->tf()->dump_on(st);  st->cr();
3393   st->print_cr("#");
3394 
3395   // For all blocks
3396   int pc = 0x0;                 // Program counter
3397   char starts_bundle = ' ';
3398   C->regalloc()->dump_frame();
3399 
3400   Node *n = NULL;
3401   for (uint i = 0; i < C->cfg()->number_of_blocks(); i++) {
3402     if (VMThread::should_terminate()) {
3403       cut_short = true;
3404       break;
3405     }
3406     Block* block = C->cfg()->get_block(i);
3407     if (block->is_connector() && !Verbose) {
3408       continue;
3409     }
3410     n = block->head();
3411     if ((pcs != NULL) && (n->_idx < pc_limit)) {
3412       pc = pcs[n->_idx];
3413       st->print("%*.*x", pc_digits, pc_digits, pc);
3414     }
3415     st->fill_to(prefix_len);
3416     block->dump_head(C->cfg(), st);
3417     if (block->is_connector()) {
3418       st->fill_to(prefix_len);
3419       st->print_cr("# Empty connector block");
3420     } else if (block->num_preds() == 2 && block->pred(1)->is_CatchProj() && block->pred(1)->as_CatchProj()->_con == CatchProjNode::fall_through_index) {
3421       st->fill_to(prefix_len);
3422       st->print_cr("# Block is sole successor of call");
3423     }
3424 
3425     // For all instructions
3426     Node *delay = NULL;
3427     for (uint j = 0; j < block->number_of_nodes(); j++) {
3428       if (VMThread::should_terminate()) {
3429         cut_short = true;
3430         break;
3431       }
3432       n = block->get_node(j);
3433       if (valid_bundle_info(n)) {
3434         Bundle* bundle = node_bundling(n);
3435         if (bundle->used_in_unconditional_delay()) {
3436           delay = n;
3437           continue;
3438         }
3439         if (bundle->starts_bundle()) {
3440           starts_bundle = '+';
3441         }
3442       }
3443 
3444       if (WizardMode) {
3445         n->dump();
3446       }
3447 
3448       if( !n->is_Region() &&    // Dont print in the Assembly
3449           !n->is_Phi() &&       // a few noisely useless nodes
3450           !n->is_Proj() &&
3451           !n->is_MachTemp() &&
3452           !n->is_SafePointScalarObject() &&
3453           !n->is_Catch() &&     // Would be nice to print exception table targets
3454           !n->is_MergeMem() &&  // Not very interesting
3455           !n->is_top() &&       // Debug info table constants
3456           !(n->is_Con() && !n->is_Mach())// Debug info table constants
3457           ) {
3458         if ((pcs != NULL) && (n->_idx < pc_limit)) {
3459           pc = pcs[n->_idx];
3460           st->print("%*.*x", pc_digits, pc_digits, pc);
3461         } else {
3462           st->fill_to(pc_digits);
3463         }
3464         st->print(" %c ", starts_bundle);
3465         starts_bundle = ' ';
3466         st->fill_to(prefix_len);
3467         n->format(C->regalloc(), st);
3468         st->cr();
3469       }
3470 
3471       // If we have an instruction with a delay slot, and have seen a delay,
3472       // then back up and print it
3473       if (valid_bundle_info(n) && node_bundling(n)->use_unconditional_delay()) {
3474         // Coverity finding - Explicit null dereferenced.
3475         guarantee(delay != NULL, "no unconditional delay instruction");
3476         if (WizardMode) delay->dump();
3477 
3478         if (node_bundling(delay)->starts_bundle())
3479           starts_bundle = '+';
3480         if ((pcs != NULL) && (n->_idx < pc_limit)) {
3481           pc = pcs[n->_idx];
3482           st->print("%*.*x", pc_digits, pc_digits, pc);
3483         } else {
3484           st->fill_to(pc_digits);
3485         }
3486         st->print(" %c ", starts_bundle);
3487         starts_bundle = ' ';
3488         st->fill_to(prefix_len);
3489         delay->format(C->regalloc(), st);
3490         st->cr();
3491         delay = NULL;
3492       }
3493 
3494       // Dump the exception table as well
3495       if( n->is_Catch() && (Verbose || WizardMode) ) {
3496         // Print the exception table for this offset
3497         _handler_table.print_subtable_for(pc);
3498       }
3499       st->bol(); // Make sure we start on a new line
3500     }
3501     st->cr(); // one empty line between blocks
3502     assert(cut_short || delay == NULL, "no unconditional delay branch");
3503   } // End of per-block dump
3504 
3505   if (cut_short)  st->print_cr("*** disassembly is cut short ***");
3506 }
3507 #endif
3508 
3509 #ifndef PRODUCT
print_statistics()3510 void PhaseOutput::print_statistics() {
3511   Scheduling::print_statistics();
3512 }
3513 #endif
3514