1 /*
   2  * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #ifndef SHARE_VM_OPTO_MATCHER_HPP
  26 #define SHARE_VM_OPTO_MATCHER_HPP
  27 
  28 #include "libadt/vectset.hpp"
  29 #include "memory/resourceArea.hpp"
  30 #include "opto/node.hpp"
  31 #include "opto/phaseX.hpp"
  32 #include "opto/regmask.hpp"
  33 
  34 class Compile;
  35 class Node;
  36 class MachNode;
  37 class MachTypeNode;
  38 class MachOper;
  39 
  40 //---------------------------Matcher-------------------------------------------
  41 class Matcher : public PhaseTransform {
  42   friend class VMStructs;
  43   // Private arena of State objects
  44   ResourceArea _states_arena;
  45 
  46   VectorSet   _visited;         // Visit bits
  47 
  48   // Used to control the Label pass
  49   VectorSet   _shared;          // Shared Ideal Node
  50   VectorSet   _dontcare;        // Nothing the matcher cares about
  51 
  52   // Private methods which perform the actual matching and reduction
  53   // Walks the label tree, generating machine nodes
  54   MachNode *ReduceInst( State *s, int rule, Node *&mem);
  55   void ReduceInst_Chain_Rule( State *s, int rule, Node *&mem, MachNode *mach);
  56   uint ReduceInst_Interior(State *s, int rule, Node *&mem, MachNode *mach, uint num_opnds);
  57   void ReduceOper( State *s, int newrule, Node *&mem, MachNode *mach );
  58 
  59   // If this node already matched using "rule", return the MachNode for it.
  60   MachNode* find_shared_node(Node* n, uint rule);
  61 
  62   // Convert a dense opcode number to an expanded rule number
  63   const int *_reduceOp;
  64   const int *_leftOp;
  65   const int *_rightOp;
  66 
  67   // Map dense opcode number to info on when rule is swallowed constant.
  68   const bool *_swallowed;
  69 
  70   // Map dense rule number to determine if this is an instruction chain rule
  71   const uint _begin_inst_chain_rule;
  72   const uint _end_inst_chain_rule;
  73 
  74   // We want to clone constants and possible CmpI-variants.
  75   // If we do not clone CmpI, then we can have many instances of
  76   // condition codes alive at once.  This is OK on some chips and
  77   // bad on others.  Hence the machine-dependent table lookup.
  78   const char *_must_clone;
  79 
  80   // Find shared Nodes, or Nodes that otherwise are Matcher roots
  81   void find_shared( Node *n );
  82 
  83   // Debug and profile information for nodes in old space:
  84   GrowableArray<Node_Notes*>* _old_node_note_array;
  85 
  86   // Node labeling iterator for instruction selection
  87   Node *Label_Root( const Node *n, State *svec, Node *control, const Node *mem );
  88 
  89   Node *transform( Node *dummy );
  90 
  91   Node_List &_proj_list;        // For Machine nodes killing many values
  92 
  93   Node_Array _shared_nodes;
  94 
  95   debug_only(Node_Array _old2new_map;)   // Map roots of ideal-trees to machine-roots
  96   debug_only(Node_Array _new2old_map;)   // Maps machine nodes back to ideal
  97 
  98   // Accessors for the inherited field PhaseTransform::_nodes:
  99   void   grow_new_node_array(uint idx_limit) {
 100     _nodes.map(idx_limit-1, NULL);
 101   }
 102   bool    has_new_node(const Node* n) const {
 103     return _nodes.at(n->_idx) != NULL;
 104   }
 105   Node*       new_node(const Node* n) const {
 106     assert(has_new_node(n), "set before get");
 107     return _nodes.at(n->_idx);
 108   }
 109   void    set_new_node(const Node* n, Node *nn) {
 110     assert(!has_new_node(n), "set only once");
 111     _nodes.map(n->_idx, nn);
 112   }
 113 
 114 #ifdef ASSERT
 115   // Make sure only new nodes are reachable from this node
 116   void verify_new_nodes_only(Node* root);
 117 
 118   Node* _mem_node;   // Ideal memory node consumed by mach node
 119 #endif
 120 
 121   // Mach node for ConP #NULL
 122   MachNode* _mach_null;
 123 
 124 public:
 125   int LabelRootDepth;
 126   // Convert ideal machine register to a register mask for spill-loads
 127   static const RegMask *idealreg2regmask[];
 128   RegMask *idealreg2spillmask  [_last_machine_leaf];
 129   RegMask *idealreg2debugmask  [_last_machine_leaf];
 130   RegMask *idealreg2mhdebugmask[_last_machine_leaf];
 131   void init_spill_mask( Node *ret );
 132   // Convert machine register number to register mask
 133   static uint mreg2regmask_max;
 134   static RegMask mreg2regmask[];
 135   static RegMask STACK_ONLY_mask;
 136 
 137   MachNode* mach_null() const { return _mach_null; }
 138 
 139   bool    is_shared( Node *n ) { return _shared.test(n->_idx) != 0; }
 140   void   set_shared( Node *n ) {  _shared.set(n->_idx); }
 141   bool   is_visited( Node *n ) { return _visited.test(n->_idx) != 0; }
 142   void  set_visited( Node *n ) { _visited.set(n->_idx); }
 143   bool  is_dontcare( Node *n ) { return _dontcare.test(n->_idx) != 0; }
 144   void set_dontcare( Node *n ) {  _dontcare.set(n->_idx); }
 145 
 146   // Mode bit to tell DFA and expand rules whether we are running after
 147   // (or during) register selection.  Usually, the matcher runs before,
 148   // but it will also get called to generate post-allocation spill code.
 149   // In this situation, it is a deadly error to attempt to allocate more
 150   // temporary registers.
 151   bool _allocation_started;
 152 
 153   // Machine register names
 154   static const char *regName[];
 155   // Machine register encodings
 156   static const unsigned char _regEncode[];
 157   // Machine Node names
 158   const char **_ruleName;
 159   // Rules that are cheaper to rematerialize than to spill
 160   static const uint _begin_rematerialize;
 161   static const uint _end_rematerialize;
 162 
 163   // An array of chars, from 0 to _last_Mach_Reg.
 164   // No Save       = 'N' (for register windows)
 165   // Save on Entry = 'E'
 166   // Save on Call  = 'C'
 167   // Always Save   = 'A' (same as SOE + SOC)
 168   const char *_register_save_policy;
 169   const char *_c_reg_save_policy;
 170   // Convert a machine register to a machine register type, so-as to
 171   // properly match spill code.
 172   const int *_register_save_type;
 173   // Maps from machine register to boolean; true if machine register can
 174   // be holding a call argument in some signature.
 175   static bool can_be_java_arg( int reg );
 176   // Maps from machine register to boolean; true if machine register holds
 177   // a spillable argument.
 178   static bool is_spillable_arg( int reg );
 179 
 180   // List of IfFalse or IfTrue Nodes that indicate a taken null test.
 181   // List is valid in the post-matching space.
 182   Node_List _null_check_tests;
 183   void collect_null_checks( Node *proj, Node *orig_proj );
 184   void validate_null_checks( );
 185 
 186   Matcher( Node_List &proj_list );
 187 
 188   // Select instructions for entire method
 189   void  match( );
 190   // Helper for match
 191   OptoReg::Name warp_incoming_stk_arg( VMReg reg );
 192 
 193   // Transform, then walk.  Does implicit DCE while walking.
 194   // Name changed from "transform" to avoid it being virtual.
 195   Node *xform( Node *old_space_node, int Nodes );
 196 
 197   // Match a single Ideal Node - turn it into a 1-Node tree; Label & Reduce.
 198   MachNode *match_tree( const Node *n );
 199   MachNode *match_sfpt( SafePointNode *sfpt );
 200   // Helper for match_sfpt
 201   OptoReg::Name warp_outgoing_stk_arg( VMReg reg, OptoReg::Name begin_out_arg_area, OptoReg::Name &out_arg_limit_per_call );
 202 
 203   // Initialize first stack mask and related masks.
 204   void init_first_stack_mask();
 205 
 206   // If we should save-on-entry this register
 207   bool is_save_on_entry( int reg );
 208 
 209   // Fixup the save-on-entry registers
 210   void Fixup_Save_On_Entry( );
 211 
 212   // --- Frame handling ---
 213 
 214   // Register number of the stack slot corresponding to the incoming SP.
 215   // Per the Big Picture in the AD file, it is:
 216   //   SharedInfo::stack0 + locks + in_preserve_stack_slots + pad2.
 217   OptoReg::Name _old_SP;
 218 
 219   // Register number of the stack slot corresponding to the highest incoming
 220   // argument on the stack.  Per the Big Picture in the AD file, it is:
 221   //   _old_SP + out_preserve_stack_slots + incoming argument size.
 222   OptoReg::Name _in_arg_limit;
 223 
 224   // Register number of the stack slot corresponding to the new SP.
 225   // Per the Big Picture in the AD file, it is:
 226   //   _in_arg_limit + pad0
 227   OptoReg::Name _new_SP;
 228 
 229   // Register number of the stack slot corresponding to the highest outgoing
 230   // argument on the stack.  Per the Big Picture in the AD file, it is:
 231   //   _new_SP + max outgoing arguments of all calls
 232   OptoReg::Name _out_arg_limit;
 233 
 234   OptoRegPair *_parm_regs;        // Array of machine registers per argument
 235   RegMask *_calling_convention_mask; // Array of RegMasks per argument
 236 
 237   // Does matcher have a match rule for this ideal node?
 238   static const bool has_match_rule(int opcode);
 239   static const bool _hasMatchRule[_last_opcode];
 240 
 241   // Does matcher have a match rule for this ideal node and is the
 242   // predicate (if there is one) true?
 243   // NOTE: If this function is used more commonly in the future, ADLC
 244   // should generate this one.
 245   static const bool match_rule_supported(int opcode);
 246 
 247   // Used to determine if we have fast l2f conversion
 248   // USII has it, USIII doesn't
 249   static const bool convL2FSupported(void);
 250 
 251   // Vector width in bytes
 252   static const int vector_width_in_bytes(BasicType bt);
 253 
 254   // Limits on vector size (number of elements).
 255   static const int max_vector_size(const BasicType bt);
 256   static const int min_vector_size(const BasicType bt);
 257   static const bool vector_size_supported(const BasicType bt, int size) {
 258     return (Matcher::max_vector_size(bt) >= size &&
 259             Matcher::min_vector_size(bt) <= size);
 260   }
 261 
 262   // Vector ideal reg
 263   static const int vector_ideal_reg(int len);
 264   static const int vector_shift_count_ideal_reg(int len);
 265 
 266   // CPU supports misaligned vectors store/load.
 267   static const bool misaligned_vectors_ok();
 268 
 269   // Used to determine a "low complexity" 64-bit constant.  (Zero is simple.)
 270   // The standard of comparison is one (StoreL ConL) vs. two (StoreI ConI).
 271   // Depends on the details of 64-bit constant generation on the CPU.
 272   static const bool isSimpleConstant64(jlong con);
 273 
 274   // These calls are all generated by the ADLC
 275 
 276   // TRUE - grows up, FALSE - grows down (Intel)
 277   virtual bool stack_direction() const;
 278 
 279   // Java-Java calling convention
 280   // (what you use when Java calls Java)
 281 
 282   // Alignment of stack in bytes, standard Intel word alignment is 4.
 283   // Sparc probably wants at least double-word (8).
 284   static uint stack_alignment_in_bytes();
 285   // Alignment of stack, measured in stack slots.
 286   // The size of stack slots is defined by VMRegImpl::stack_slot_size.
 287   static uint stack_alignment_in_slots() {
 288     return stack_alignment_in_bytes() / (VMRegImpl::stack_slot_size);
 289   }
 290 
 291   // Array mapping arguments to registers.  Argument 0 is usually the 'this'
 292   // pointer.  Registers can include stack-slots and regular registers.
 293   static void calling_convention( BasicType *, VMRegPair *, uint len, bool is_outgoing );
 294 
 295   // Convert a sig into a calling convention register layout
 296   // and find interesting things about it.
 297   static OptoReg::Name  find_receiver( bool is_outgoing );
 298   // Return address register.  On Intel it is a stack-slot.  On PowerPC
 299   // it is the Link register.  On Sparc it is r31?
 300   virtual OptoReg::Name return_addr() const;
 301   RegMask              _return_addr_mask;
 302   // Return value register.  On Intel it is EAX.  On Sparc i0/o0.
 303   static OptoRegPair   return_value(int ideal_reg, bool is_outgoing);
 304   static OptoRegPair c_return_value(int ideal_reg, bool is_outgoing);
 305   RegMask                     _return_value_mask;
 306   // Inline Cache Register
 307   static OptoReg::Name  inline_cache_reg();
 308   static int            inline_cache_reg_encode();
 309 
 310   // Register for DIVI projection of divmodI
 311   static RegMask divI_proj_mask();
 312   // Register for MODI projection of divmodI
 313   static RegMask modI_proj_mask();
 314 
 315   // Register for DIVL projection of divmodL
 316   static RegMask divL_proj_mask();
 317   // Register for MODL projection of divmodL
 318   static RegMask modL_proj_mask();
 319 
 320   // Use hardware DIV instruction when it is faster than
 321   // a code which use multiply for division by constant.
 322   static bool use_asm_for_ldiv_by_con( jlong divisor );
 323 
 324   static const RegMask method_handle_invoke_SP_save_mask();
 325 
 326   // Java-Interpreter calling convention
 327   // (what you use when calling between compiled-Java and Interpreted-Java
 328 
 329   // Number of callee-save + always-save registers
 330   // Ignores frame pointer and "special" registers
 331   static int  number_of_saved_registers();
 332 
 333   // The Method-klass-holder may be passed in the inline_cache_reg
 334   // and then expanded into the inline_cache_reg and a method_oop register
 335 
 336   static OptoReg::Name  interpreter_method_oop_reg();
 337   static int            interpreter_method_oop_reg_encode();
 338 
 339   static OptoReg::Name  compiler_method_oop_reg();
 340   static const RegMask &compiler_method_oop_reg_mask();
 341   static int            compiler_method_oop_reg_encode();
 342 
 343   // Interpreter's Frame Pointer Register
 344   static OptoReg::Name  interpreter_frame_pointer_reg();
 345 
 346   // Java-Native calling convention
 347   // (what you use when intercalling between Java and C++ code)
 348 
 349   // Array mapping arguments to registers.  Argument 0 is usually the 'this'
 350   // pointer.  Registers can include stack-slots and regular registers.
 351   static void c_calling_convention( BasicType*, VMRegPair *, uint );
 352   // Frame pointer. The frame pointer is kept at the base of the stack
 353   // and so is probably the stack pointer for most machines.  On Intel
 354   // it is ESP.  On the PowerPC it is R1.  On Sparc it is SP.
 355   OptoReg::Name  c_frame_pointer() const;
 356   static RegMask c_frame_ptr_mask;
 357 
 358   // !!!!! Special stuff for building ScopeDescs
 359   virtual int      regnum_to_fpu_offset(int regnum);
 360 
 361   // Is this branch offset small enough to be addressed by a short branch?
 362   bool is_short_branch_offset(int rule, int br_size, int offset);
 363 
 364   // Optional scaling for the parameter to the ClearArray/CopyArray node.
 365   static const bool init_array_count_is_in_bytes;
 366 
 367   // Threshold small size (in bytes) for a ClearArray/CopyArray node.
 368   // Anything this size or smaller may get converted to discrete scalar stores.
 369   static const int init_array_short_size;
 370 
 371   // Some hardware needs 2 CMOV's for longs.
 372   static const int long_cmove_cost();
 373 
 374   // Some hardware have expensive CMOV for float and double.
 375   static const int float_cmove_cost();
 376 
 377   // Should the Matcher clone shifts on addressing modes, expecting them to
 378   // be subsumed into complex addressing expressions or compute them into
 379   // registers?  True for Intel but false for most RISCs
 380   static const bool clone_shift_expressions;
 381 
 382   static bool narrow_oop_use_complex_address();
 383   static bool narrow_klass_use_complex_address();
 384 
 385   // Generate implicit null check for narrow oops if it can fold
 386   // into address expression (x64).
 387   //
 388   // [R12 + narrow_oop_reg<<3 + offset] // fold into address expression
 389   // NullCheck narrow_oop_reg
 390   //
 391   // When narrow oops can't fold into address expression (Sparc) and
 392   // base is not null use decode_not_null and normal implicit null check.
 393   // Note, decode_not_null node can be used here since it is referenced
 394   // only on non null path but it requires special handling, see
 395   // collect_null_checks():
 396   //
 397   // decode_not_null narrow_oop_reg, oop_reg // 'shift' and 'add base'
 398   // [oop_reg + offset]
 399   // NullCheck oop_reg
 400   //
 401   // With Zero base and when narrow oops can not fold into address
 402   // expression use normal implicit null check since only shift
 403   // is needed to decode narrow oop.
 404   //
 405   // decode narrow_oop_reg, oop_reg // only 'shift'
 406   // [oop_reg + offset]
 407   // NullCheck oop_reg
 408   //
 409   inline static bool gen_narrow_oop_implicit_null_checks() {
 410     return Universe::narrow_oop_use_implicit_null_checks() &&
 411            (narrow_oop_use_complex_address() ||
 412             Universe::narrow_oop_base() != NULL);
 413   }
 414 
 415   // Is it better to copy float constants, or load them directly from memory?
 416   // Intel can load a float constant from a direct address, requiring no
 417   // extra registers.  Most RISCs will have to materialize an address into a
 418   // register first, so they may as well materialize the constant immediately.
 419   static const bool rematerialize_float_constants;
 420 
 421   // If CPU can load and store mis-aligned doubles directly then no fixup is
 422   // needed.  Else we split the double into 2 integer pieces and move it
 423   // piece-by-piece.  Only happens when passing doubles into C code or when
 424   // calling i2c adapters as the Java calling convention forces doubles to be
 425   // aligned.
 426   static const bool misaligned_doubles_ok;
 427 
 428   // Perform a platform dependent implicit null fixup.  This is needed
 429   // on windows95 to take care of some unusual register constraints.
 430   void pd_implicit_null_fixup(MachNode *load, uint idx);
 431 
 432   // Advertise here if the CPU requires explicit rounding operations
 433   // to implement the UseStrictFP mode.
 434   static const bool strict_fp_requires_explicit_rounding;
 435 
 436   // Are floats conerted to double when stored to stack during deoptimization?
 437   static bool float_in_double();
 438   // Do ints take an entire long register or just half?
 439   static const bool int_in_long;
 440 
 441   // Do the processor's shift instructions only use the low 5/6 bits
 442   // of the count for 32/64 bit ints? If not we need to do the masking
 443   // ourselves.
 444   static const bool need_masked_shift_count;
 445 
 446   // This routine is run whenever a graph fails to match.
 447   // If it returns, the compiler should bailout to interpreter without error.
 448   // In non-product mode, SoftMatchFailure is false to detect non-canonical
 449   // graphs.  Print a message and exit.
 450   static void soft_match_failure() {
 451     if( SoftMatchFailure ) return;
 452     else { fatal("SoftMatchFailure is not allowed except in product"); }
 453   }
 454 
 455   // Check for a following volatile memory barrier without an
 456   // intervening load and thus we don't need a barrier here.  We
 457   // retain the Node to act as a compiler ordering barrier.
 458   static bool post_store_load_barrier(const Node* mb);
 459 
 460 
 461 #ifdef ASSERT
 462   void dump_old2new_map();      // machine-independent to machine-dependent
 463 
 464   Node* find_old_node(Node* new_node) {
 465     return _new2old_map[new_node->_idx];
 466   }
 467 #endif
 468 };
 469 
 470 #endif // SHARE_VM_OPTO_MATCHER_HPP