1 /*
2 * Copyright (c) 1997, 2025, 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 #ifndef SHARE_OPTO_MATCHER_HPP
26 #define SHARE_OPTO_MATCHER_HPP
27
28 #include "libadt/vectset.hpp"
29 #include "memory/resourceArea.hpp"
30 #include "oops/compressedKlass.hpp"
31 #include "oops/compressedOops.hpp"
32 #include "opto/node.hpp"
33 #include "opto/phaseX.hpp"
34 #include "opto/regmask.hpp"
35 #include "opto/subnode.hpp"
36 #include "runtime/vm_version.hpp"
37
38 class Compile;
39 class Node;
40 class MachNode;
41 class MachTypeNode;
42 class MachOper;
43
44 //---------------------------Matcher-------------------------------------------
45 class Matcher : public PhaseTransform {
46 public:
47
48 // Machine-dependent definitions
49 #include CPU_HEADER(matcher)
50
51 // State and MStack class used in xform() and find_shared() iterative methods.
52 enum Node_State { Pre_Visit, // node has to be pre-visited
53 Visit, // visit node
54 Post_Visit, // post-visit node
55 Alt_Post_Visit // alternative post-visit path
56 };
57
58 class MStack: public Node_Stack {
59 public:
60 MStack(int size) : Node_Stack(size) { }
61
62 void push(Node *n, Node_State ns) {
63 Node_Stack::push(n, (uint)ns);
64 }
65 void push(Node *n, Node_State ns, Node *parent, int indx) {
66 Node_Stack::push(parent, (uint)indx);
67 Node_Stack::push(n, (uint)ns);
68 }
69 Node *parent() {
70 pop();
71 return node();
72 }
73 Node_State state() const {
74 return (Node_State)index();
75 }
76 void set_state(Node_State ns) {
77 set_index((uint)ns);
78 }
79 };
80
81 private:
82 // Private arena of State objects
83 ResourceArea _states_arena;
84
85 // Map old nodes to new nodes
86 Node_List _new_nodes;
87
88 VectorSet _visited; // Visit bits
89
90 // Used to control the Label pass
91 VectorSet _shared; // Shared Ideal Node
92 VectorSet _dontcare; // Nothing the matcher cares about
93
94 // Private methods which perform the actual matching and reduction
95 // Walks the label tree, generating machine nodes
96 MachNode *ReduceInst( State *s, int rule, Node *&mem);
97 void ReduceInst_Chain_Rule( State *s, int rule, Node *&mem, MachNode *mach);
98 uint ReduceInst_Interior(State *s, int rule, Node *&mem, MachNode *mach, uint num_opnds);
99 void ReduceOper( State *s, int newrule, Node *&mem, MachNode *mach );
100
101 // If this node already matched using "rule", return the MachNode for it.
102 MachNode* find_shared_node(Node* n, uint rule);
103
104 // Convert a dense opcode number to an expanded rule number
105 const int *_reduceOp;
106 const int *_leftOp;
107 const int *_rightOp;
108
109 // Map dense opcode number to info on when rule is swallowed constant.
110 const bool *_swallowed;
111
112 // Map dense rule number to determine if this is an instruction chain rule
113 const uint _begin_inst_chain_rule;
114 const uint _end_inst_chain_rule;
115
116 // We want to clone constants and possible CmpI-variants.
117 // If we do not clone CmpI, then we can have many instances of
118 // condition codes alive at once. This is OK on some chips and
119 // bad on others. Hence the machine-dependent table lookup.
120 const char *_must_clone;
121
122 // Find shared Nodes, or Nodes that otherwise are Matcher roots
123 void find_shared( Node *n );
124 bool find_shared_visit(MStack& mstack, Node* n, uint opcode, bool& mem_op, int& mem_addr_idx);
125 void find_shared_post_visit(Node* n, uint opcode);
126
127 bool is_vshift_con_pattern(Node* n, Node* m);
128
129 // Debug and profile information for nodes in old space:
130 GrowableArray<Node_Notes*>* _old_node_note_array;
131
132 // Node labeling iterator for instruction selection
133 Node* Label_Root(const Node* n, State* svec, Node* control, Node*& mem);
134
135 Node *transform( Node *dummy );
136
137 Node_List _projection_list; // For Machine nodes killing many values
138
139 Node_Array _shared_nodes;
140
141 #ifndef PRODUCT
142 Node_Array _old2new_map; // Map roots of ideal-trees to machine-roots
143 Node_Array _new2old_map; // Maps machine nodes back to ideal
144 VectorSet _reused; // Ideal IGV identifiers reused by machine nodes
145 #endif // !PRODUCT
146
147 void grow_new_node_array(uint idx_limit) {
148 _new_nodes.map(idx_limit-1, nullptr);
149 }
150 bool has_new_node(const Node* n) const {
151 return _new_nodes.at(n->_idx) != nullptr;
152 }
153 Node* new_node(const Node* n) const {
154 assert(has_new_node(n), "set before get");
155 return _new_nodes.at(n->_idx);
156 }
157 void set_new_node(const Node* n, Node *nn) {
158 assert(!has_new_node(n), "set only once");
159 _new_nodes.map(n->_idx, nn);
160 }
161
162 #ifdef ASSERT
163 // Make sure only new nodes are reachable from this node
164 void verify_new_nodes_only(Node* root);
165
166 Node* _mem_node; // Ideal memory node consumed by mach node
167 #endif
168
169 // Mach node for ConP #null
170 MachNode* _mach_null;
171
172 void handle_precedence_edges(Node* n, MachNode *mach);
173
174 public:
175 int LabelRootDepth;
176 // Convert ideal machine register to a register mask for spill-loads
177 static const RegMask *idealreg2regmask[];
178 RegMask *idealreg2spillmask [_last_machine_leaf];
179 RegMask *idealreg2debugmask [_last_machine_leaf];
180 void init_spill_mask( Node *ret );
181 // Convert machine register number to register mask
182 static uint mreg2regmask_max;
183 static RegMask mreg2regmask[];
184 static RegMask STACK_ONLY_mask;
185 static RegMask caller_save_regmask;
186 static RegMask caller_save_regmask_exclude_soe;
187
188 MachNode* mach_null() const { return _mach_null; }
189
190 bool is_shared( Node *n ) { return _shared.test(n->_idx) != 0; }
191 void set_shared( Node *n ) { _shared.set(n->_idx); }
192 bool is_visited( Node *n ) { return _visited.test(n->_idx) != 0; }
193 void set_visited( Node *n ) { _visited.set(n->_idx); }
194 bool is_dontcare( Node *n ) { return _dontcare.test(n->_idx) != 0; }
195 void set_dontcare( Node *n ) { _dontcare.set(n->_idx); }
196
197 // Mode bit to tell DFA and expand rules whether we are running after
198 // (or during) register selection. Usually, the matcher runs before,
199 // but it will also get called to generate post-allocation spill code.
200 // In this situation, it is a deadly error to attempt to allocate more
201 // temporary registers.
202 bool _allocation_started;
203
204 // Machine register names
205 static const char *regName[];
206 // Machine register encodings
207 static const unsigned char _regEncode[];
208 // Machine Node names
209 const char **_ruleName;
210 // Rules that are cheaper to rematerialize than to spill
211 static const uint _begin_rematerialize;
212 static const uint _end_rematerialize;
213
214 // An array of chars, from 0 to _last_Mach_Reg.
215 // No Save = 'N' (for register windows)
216 // Save on Entry = 'E'
217 // Save on Call = 'C'
218 // Always Save = 'A' (same as SOE + SOC)
219 const char *_register_save_policy;
220 const char *_c_reg_save_policy;
221 // Convert a machine register to a machine register type, so-as to
222 // properly match spill code.
223 const int *_register_save_type;
224 // Maps from machine register to boolean; true if machine register can
225 // be holding a call argument in some signature.
226 static bool can_be_java_arg( int reg );
227 // Maps from machine register to boolean; true if machine register holds
228 // a spillable argument.
229 static bool is_spillable_arg( int reg );
230 // Number of integer live ranges that constitute high register pressure
231 static uint int_pressure_limit();
232 // Number of float live ranges that constitute high register pressure
233 static uint float_pressure_limit();
234
235 // List of IfFalse or IfTrue Nodes that indicate a taken null test.
236 // List is valid in the post-matching space.
237 Node_List _null_check_tests;
238 void collect_null_checks( Node *proj, Node *orig_proj );
239 void validate_null_checks( );
240
241 Matcher();
242
243 // Get a projection node at position pos
244 Node* get_projection(uint pos) {
245 return _projection_list[pos];
246 }
247
248 // Push a projection node onto the projection list
249 void push_projection(Node* node) {
250 _projection_list.push(node);
251 }
252
253 Node* pop_projection() {
254 return _projection_list.pop();
255 }
256
257 // Number of nodes in the projection list
258 uint number_of_projections() const {
259 return _projection_list.size();
260 }
261
262 // Select instructions for entire method
263 void match();
264
265 // Helper for match
266 OptoReg::Name warp_incoming_stk_arg( VMReg reg );
267
268 // Transform, then walk. Does implicit DCE while walking.
269 // Name changed from "transform" to avoid it being virtual.
270 Node *xform( Node *old_space_node, int Nodes );
271
272 // Match a single Ideal Node - turn it into a 1-Node tree; Label & Reduce.
273 MachNode *match_tree( const Node *n );
274 MachNode *match_sfpt( SafePointNode *sfpt );
275 // Helper for match_sfpt
276 OptoReg::Name warp_outgoing_stk_arg( VMReg reg, OptoReg::Name begin_out_arg_area, OptoReg::Name &out_arg_limit_per_call );
277
278 // Initialize first stack mask and related masks.
279 void init_first_stack_mask();
280
281 // If we should save-on-entry this register
282 bool is_save_on_entry( int reg );
283
284 // Fixup the save-on-entry registers
285 void Fixup_Save_On_Entry( );
286
287 // --- Frame handling ---
288
289 // Register number of the stack slot corresponding to the incoming SP.
290 // Per the Big Picture in the AD file, it is:
291 // SharedInfo::stack0 + locks + in_preserve_stack_slots + pad2.
292 OptoReg::Name _old_SP;
293
294 // Register number of the stack slot corresponding to the highest incoming
295 // argument on the stack. Per the Big Picture in the AD file, it is:
296 // _old_SP + out_preserve_stack_slots + incoming argument size.
297 OptoReg::Name _in_arg_limit;
298
299 // Register number of the stack slot corresponding to the new SP.
300 // Per the Big Picture in the AD file, it is:
301 // _in_arg_limit + pad0
302 OptoReg::Name _new_SP;
303
304 // Register number of the stack slot corresponding to the highest outgoing
305 // argument on the stack. Per the Big Picture in the AD file, it is:
306 // _new_SP + max outgoing arguments of all calls
307 OptoReg::Name _out_arg_limit;
308
309 OptoRegPair *_parm_regs; // Array of machine registers per argument
310 RegMask *_calling_convention_mask; // Array of RegMasks per argument
311
312 // Does matcher have a match rule for this ideal node?
313 static bool has_match_rule(int opcode);
314 static const bool _hasMatchRule[_last_opcode];
315
316 // Does matcher have a match rule for this ideal node and is the
317 // predicate (if there is one) true?
318 // NOTE: If this function is used more commonly in the future, ADLC
319 // should generate this one.
320 static bool match_rule_supported(int opcode);
321
322 // Identify extra cases that we might want to vectorize automatically
323 // And exclude cases which are not profitable to auto-vectorize.
324 static bool match_rule_supported_auto_vectorization(int opcode, int vlen, BasicType bt);
325
326 // identify extra cases that we might want to provide match rules for
327 // e.g. Op_ vector nodes and other intrinsics while guarding with vlen
328 static bool match_rule_supported_vector(int opcode, int vlen, BasicType bt);
329
330 static bool match_rule_supported_vector_masked(int opcode, int vlen, BasicType bt);
331
332 static bool vector_needs_partial_operations(Node* node, const TypeVect* vt);
333
334 static bool vector_rearrange_requires_load_shuffle(BasicType elem_bt, int vlen);
335
336 static const RegMask* predicate_reg_mask(void);
337
338 // Vector width in bytes
339 static int vector_width_in_bytes(BasicType bt);
340
341 // Limits on vector size (number of elements).
342 static int max_vector_size(const BasicType bt);
343 static int min_vector_size(const BasicType bt);
344 static bool vector_size_supported(const BasicType bt, int size) {
345 return (Matcher::max_vector_size(bt) >= size &&
346 Matcher::min_vector_size(bt) <= size);
347 }
348 // Limits on max vector size (number of elements) for auto-vectorization.
349 static int max_vector_size_auto_vectorization(const BasicType bt);
350
351 // Actual max scalable vector register length.
352 static int scalable_vector_reg_size(const BasicType bt);
353 // Actual max scalable predicate register length.
354 static int scalable_predicate_reg_slots();
355
356 // Vector ideal reg
357 static uint vector_ideal_reg(int len);
358
359 // Vector length
360 static uint vector_length(const Node* n);
361 static uint vector_length(const MachNode* use, const MachOper* opnd);
362
363 // Vector length in bytes
364 static uint vector_length_in_bytes(const Node* n);
365 static uint vector_length_in_bytes(const MachNode* use, const MachOper* opnd);
366
367 // Vector element basic type
368 static BasicType vector_element_basic_type(const Node* n);
369 static BasicType vector_element_basic_type(const MachNode* use, const MachOper* opnd);
370
371 // Vector element basic type is non double word integral type.
372 static bool is_non_long_integral_vector(const Node* n);
373
374 // Check if given booltest condition is unsigned or not
375 static inline bool is_unsigned_booltest_pred(int bt) {
376 return ((bt & BoolTest::unsigned_compare) == BoolTest::unsigned_compare);
377 }
378
379 static bool is_encode_and_store_pattern(const Node* n, const Node* m);
380
381 // These calls are all generated by the ADLC
382
383 // Java-Java calling convention
384 // (what you use when Java calls Java)
385
386 // Alignment of stack in bytes, standard Intel word alignment is 4.
387 // Sparc probably wants at least double-word (8).
388 static uint stack_alignment_in_bytes();
389 // Alignment of stack, measured in stack slots.
390 // The size of stack slots is defined by VMRegImpl::stack_slot_size.
391 static uint stack_alignment_in_slots() {
392 return stack_alignment_in_bytes() / (VMRegImpl::stack_slot_size);
393 }
394
395 // Convert a sig into a calling convention register layout
396 // and find interesting things about it.
397 static OptoReg::Name find_receiver();
398 // Return address register. On Intel it is a stack-slot. On PowerPC
399 // it is the Link register. On Sparc it is r31?
400 virtual OptoReg::Name return_addr() const;
401 RegMask _return_addr_mask;
402 // Return value register. On Intel it is EAX.
403 static OptoRegPair return_value(uint ideal_reg);
404 static OptoRegPair c_return_value(uint ideal_reg);
405 RegMask _return_value_mask;
406 // Inline Cache Register
407 static OptoReg::Name inline_cache_reg();
408 static int inline_cache_reg_encode();
409
410 // Register for DIVI projection of divmodI
411 static RegMask divI_proj_mask();
412 // Register for MODI projection of divmodI
413 static RegMask modI_proj_mask();
414
415 // Register for DIVL projection of divmodL
416 static RegMask divL_proj_mask();
417 // Register for MODL projection of divmodL
418 static RegMask modL_proj_mask();
419
420 // Use hardware DIV instruction when it is faster than
421 // a code which use multiply for division by constant.
422 static bool use_asm_for_ldiv_by_con( jlong divisor );
423
424 // Java-Interpreter calling convention
425 // (what you use when calling between compiled-Java and Interpreted-Java
426
427 // Number of callee-save + always-save registers
428 // Ignores frame pointer and "special" registers
429 static int number_of_saved_registers();
430
431 // The Method-klass-holder may be passed in the inline_cache_reg
432 // and then expanded into the inline_cache_reg and a method_ptr register
433
434 // Interpreter's Frame Pointer Register
435 static OptoReg::Name interpreter_frame_pointer_reg();
436
437 // Java-Native calling convention
438 // (what you use when intercalling between Java and C++ code)
439
440 // Frame pointer. The frame pointer is kept at the base of the stack
441 // and so is probably the stack pointer for most machines. On Intel
442 // it is ESP. On the PowerPC it is R1. On Sparc it is SP.
443 OptoReg::Name c_frame_pointer() const;
444 static RegMask c_frame_ptr_mask;
445
446 // Java-Native vector calling convention
447 static bool supports_vector_calling_convention();
448 static OptoRegPair vector_return_value(uint ideal_reg);
449
450 // Is this branch offset small enough to be addressed by a short branch?
451 bool is_short_branch_offset(int rule, int br_size, int offset);
452
453 // Should the input 'm' of node 'n' be cloned during matching?
454 // Reports back whether the node was cloned or not.
455 bool clone_node(Node* n, Node* m, Matcher::MStack& mstack);
456 bool pd_clone_node(Node* n, Node* m, Matcher::MStack& mstack);
457
458 // Should the Matcher clone shifts on addressing modes, expecting them to
459 // be subsumed into complex addressing expressions or compute them into
460 // registers? True for Intel but false for most RISCs
461 bool pd_clone_address_expressions(AddPNode* m, MStack& mstack, VectorSet& address_visited);
462 // Clone base + offset address expression
463 bool clone_base_plus_offset_address(AddPNode* m, MStack& mstack, VectorSet& address_visited);
464
465 // Generate implicit null check for narrow oops if it can fold
466 // into address expression (x64).
467 //
468 // [R12 + narrow_oop_reg<<3 + offset] // fold into address expression
469 // NullCheck narrow_oop_reg
470 //
471 // When narrow oops can't fold into address expression (Sparc) and
472 // base is not null use decode_not_null and normal implicit null check.
473 // Note, decode_not_null node can be used here since it is referenced
474 // only on non null path but it requires special handling, see
475 // collect_null_checks():
476 //
477 // decode_not_null narrow_oop_reg, oop_reg // 'shift' and 'add base'
478 // [oop_reg + offset]
479 // NullCheck oop_reg
480 //
481 // With Zero base and when narrow oops can not fold into address
482 // expression use normal implicit null check since only shift
483 // is needed to decode narrow oop.
484 //
485 // decode narrow_oop_reg, oop_reg // only 'shift'
486 // [oop_reg + offset]
487 // NullCheck oop_reg
488 //
489 static bool gen_narrow_oop_implicit_null_checks();
490
491 private:
492 void do_postselect_cleanup();
493
494 void specialize_generic_vector_operands();
495 void specialize_mach_node(MachNode* m);
496 void specialize_temp_node(MachTempNode* tmp, MachNode* use, uint idx);
497 MachOper* specialize_vector_operand(MachNode* m, uint opnd_idx);
498
499 static MachOper* pd_specialize_generic_vector_operand(MachOper* generic_opnd, uint ideal_reg, bool is_temp);
500 static bool is_reg2reg_move(MachNode* m);
501 static bool is_generic_vector(MachOper* opnd);
502
503 const RegMask* regmask_for_ideal_register(uint ideal_reg, Node* ret);
504
505 // Graph verification code
506 DEBUG_ONLY( bool verify_after_postselect_cleanup(); )
507
508 public:
509 // This routine is run whenever a graph fails to match.
510 // If it returns, the compiler should bailout to interpreter without error.
511 // In non-product mode, SoftMatchFailure is false to detect non-canonical
512 // graphs. Print a message and exit.
513 static void soft_match_failure() {
514 if( SoftMatchFailure ) return;
515 else { fatal("SoftMatchFailure is not allowed except in product"); }
516 }
517
518 // Check for a following volatile memory barrier without an
519 // intervening load and thus we don't need a barrier here. We
520 // retain the Node to act as a compiler ordering barrier.
521 static bool post_store_load_barrier(const Node* mb);
522
523 // Does n lead to an uncommon trap that can cause deoptimization?
524 static bool branches_to_uncommon_trap(const Node *n);
525
526 #ifndef PRODUCT
527 // Record mach-to-Ideal mapping, reusing the Ideal IGV identifier if possible.
528 void record_new2old(Node* newn, Node* old);
529
530 void dump_old2new_map(); // machine-independent to machine-dependent
531
532 Node* find_old_node(const Node* new_node) {
533 return _new2old_map[new_node->_idx];
534 }
535 #endif // !PRODUCT
536 };
537
538 #endif // SHARE_OPTO_MATCHER_HPP