1 /*
   2  * Copyright (c) 2005, 2011, 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_ESCAPE_HPP
  26 #define SHARE_VM_OPTO_ESCAPE_HPP
  27 
  28 #include "opto/addnode.hpp"
  29 #include "opto/node.hpp"
  30 #include "utilities/growableArray.hpp"
  31 
  32 //
  33 // Adaptation for C2 of the escape analysis algorithm described in:
  34 //
  35 // [Choi99] Jong-Deok Shoi, Manish Gupta, Mauricio Seffano,
  36 //          Vugranam C. Sreedhar, Sam Midkiff,
  37 //          "Escape Analysis for Java", Procedings of ACM SIGPLAN
  38 //          OOPSLA  Conference, November 1, 1999
  39 //
  40 // The flow-insensitive analysis described in the paper has been implemented.
  41 //
  42 // The analysis requires construction of a "connection graph" (CG) for
  43 // the method being analyzed.  The nodes of the connection graph are:
  44 //
  45 //     -  Java objects (JO)
  46 //     -  Local variables (LV)
  47 //     -  Fields of an object (OF),  these also include array elements
  48 //
  49 // The CG contains 3 types of edges:
  50 //
  51 //   -  PointsTo  (-P>)    {LV, OF} to JO
  52 //   -  Deferred  (-D>)    from {LV, OF} to {LV, OF}
  53 //   -  Field     (-F>)    from JO to OF
  54 //
  55 // The following  utility functions is used by the algorithm:
  56 //
  57 //   PointsTo(n) - n is any CG node, it returns the set of JO that n could
  58 //                 point to.
  59 //
  60 // The algorithm describes how to construct the connection graph
  61 // in the following 4 cases:
  62 //
  63 //          Case                  Edges Created
  64 //
  65 // (1)   p   = new T()              LV -P> JO
  66 // (2)   p   = q                    LV -D> LV
  67 // (3)   p.f = q                    JO -F> OF,  OF -D> LV
  68 // (4)   p   = q.f                  JO -F> OF,  LV -D> OF
  69 //
  70 // In all these cases, p and q are local variables.  For static field
  71 // references, we can construct a local variable containing a reference
  72 // to the static memory.
  73 //
  74 // C2 does not have local variables.  However for the purposes of constructing
  75 // the connection graph, the following IR nodes are treated as local variables:
  76 //     Phi    (pointer values)
  77 //     LoadP, LoadN
  78 //     Proj#5 (value returned from callnodes including allocations)
  79 //     CheckCastPP, CastPP
  80 //
  81 // The LoadP, Proj and CheckCastPP behave like variables assigned to only once.
  82 // Only a Phi can have multiple assignments.  Each input to a Phi is treated
  83 // as an assignment to it.
  84 //
  85 // The following node types are JavaObject:
  86 //
  87 //     phantom_object (general globally escaped object)
  88 //     Allocate
  89 //     AllocateArray
  90 //     Parm  (for incoming arguments)
  91 //     CastX2P ("unsafe" operations)
  92 //     CreateEx
  93 //     ConP
  94 //     LoadKlass
  95 //     ThreadLocal
  96 //     CallStaticJava (which returns Object)
  97 //
  98 // AddP nodes are fields.
  99 //
 100 // After building the graph, a pass is made over the nodes, deleting deferred
 101 // nodes and copying the edges from the target of the deferred edge to the
 102 // source.  This results in a graph with no deferred edges, only:
 103 //
 104 //    LV -P> JO
 105 //    OF -P> JO (the object whose oop is stored in the field)
 106 //    JO -F> OF
 107 //
 108 // Then, for each node which is GlobalEscape, anything it could point to
 109 // is marked GlobalEscape.  Finally, for any node marked ArgEscape, anything
 110 // it could point to is marked ArgEscape.
 111 //
 112 
 113 class  Compile;
 114 class  Node;
 115 class  CallNode;
 116 class  PhiNode;
 117 class  PhaseTransform;
 118 class  Type;
 119 class  TypePtr;
 120 class  VectorSet;
 121 
 122 class PointsToNode {
 123 friend class ConnectionGraph;
 124 public:
 125   typedef enum {
 126     UnknownType = 0,
 127     JavaObject  = 1,
 128     LocalVar    = 2,
 129     Field       = 3
 130   } NodeType;
 131 
 132   typedef enum {
 133     UnknownEscape = 0,
 134     NoEscape      = 1, // A scalar replaceable object with unique type.
 135     ControlEscape = 2, // Complex control flow or some limitations do not
 136                        // allow scalar replacement of not escaping object.
 137     ArgEscape     = 3, // An object passed as argument or referenced by
 138                        // argument (and not globally escape during call).
 139     GlobalEscape  = 4  // An object escapes the method and thread.
 140   } EscapeState;
 141 
 142   typedef enum {
 143     UnknownEdge   = 0,
 144     PointsToEdge  = 1,
 145     DeferredEdge  = 2,
 146     FieldEdge     = 3
 147   } EdgeType;
 148 
 149 private:
 150   enum {
 151     EdgeMask = 3,
 152     EdgeShift = 2,
 153 
 154     INITIAL_EDGE_COUNT = 4
 155   };
 156 
 157   NodeType             _type;
 158   EscapeState          _escape;
 159   GrowableArray<uint>* _edges; // outgoing edges
 160   Node* _node;                 // Ideal node corresponding to this PointsTo node.
 161   int   _offset;               // Object fields offsets.
 162 
 163 public:
 164   PointsToNode():
 165     _type(UnknownType),
 166     _escape(UnknownEscape),
 167     _edges(NULL),
 168     _node(NULL),
 169     _offset(-1) {}
 170 
 171 
 172   EscapeState escape_state() const { return _escape; }
 173   NodeType node_type() const { return _type;}
 174   int offset() { return _offset;}
 175 
 176   void set_offset(int offs) { _offset = offs;}
 177   void set_escape_state(EscapeState state) { _escape = state; }
 178   void set_node_type(NodeType ntype) {
 179     assert(_type == UnknownType || _type == ntype, "Can't change node type");
 180     _type = ntype;
 181   }
 182 
 183   // count of outgoing edges
 184   uint edge_count() const { return (_edges == NULL) ? 0 : _edges->length(); }
 185 
 186   // node index of target of outgoing edge "e"
 187   uint edge_target(uint e) const {
 188     assert(_edges != NULL, "valid edge index");
 189     return (_edges->at(e) >> EdgeShift);
 190   }
 191   // type of outgoing edge "e"
 192   EdgeType edge_type(uint e) const {
 193     assert(_edges != NULL, "valid edge index");
 194     return (EdgeType) (_edges->at(e) & EdgeMask);
 195   }
 196 
 197   // add a edge of the specified type pointing to the specified target
 198   void add_edge(uint targIdx, EdgeType et);
 199 
 200   // remove an edge of the specified type pointing to the specified target
 201   void remove_edge(uint targIdx, EdgeType et);
 202 
 203 #ifndef PRODUCT
 204   void dump(bool print_state=true) const;
 205 #endif
 206 
 207 };
 208 
 209 class ConnectionGraph: public ResourceObj {
 210 private:
 211   GrowableArray<PointsToNode>  _nodes; // Connection graph nodes indexed
 212                                        // by ideal node index.
 213 
 214   Unique_Node_List  _delayed_worklist; // Nodes to be processed before
 215                                        // the call build_connection_graph().
 216 
 217   GrowableArray<MergeMemNode *>  _mergemem_worklist; // List of all MergeMem nodes
 218 
 219   VectorSet                _processed; // Records which nodes have been
 220                                        // processed.
 221 
 222   bool                    _collecting; // Indicates whether escape information
 223                                        // is still being collected. If false,
 224                                        // no new nodes will be processed.
 225 
 226   bool                    _progress;   // Indicates whether new Graph's edges
 227                                        // were created.
 228 
 229   uint                _phantom_object; // Index of globally escaping object
 230                                        // that pointer values loaded from
 231                                        // a field which has not been set
 232                                        // are assumed to point to.
 233   uint                      _oop_null; // ConP(#NULL)->_idx
 234   uint                     _noop_null; // ConN(#NULL)->_idx
 235 
 236   Compile *                  _compile; // Compile object for current compilation
 237   PhaseIterGVN *                _igvn; // Value numbering
 238 
 239   // Address of an element in _nodes.  Used when the element is to be modified
 240   PointsToNode *ptnode_adr(uint idx) const {
 241     // There should be no new ideal nodes during ConnectionGraph build,
 242     // growableArray::adr_at() will throw assert otherwise.
 243     return _nodes.adr_at(idx);
 244   }
 245   uint nodes_size() const { return _nodes.length(); }
 246 
 247   // Add node to ConnectionGraph.
 248   void add_node(Node *n, PointsToNode::NodeType nt, PointsToNode::EscapeState es, bool done);
 249 
 250   // offset of a field reference
 251   int address_offset(Node* adr, PhaseTransform *phase);
 252 
 253   // compute the escape state for arguments to a call
 254   void process_call_arguments(CallNode *call, PhaseTransform *phase);
 255 
 256   // compute the escape state for the return value of a call
 257   void process_call_result(ProjNode *resproj, PhaseTransform *phase);
 258 
 259   // Populate Connection Graph with Ideal nodes.
 260   void record_for_escape_analysis(Node *n, PhaseTransform *phase);
 261 
 262   // Build Connection Graph and set nodes escape state.
 263   void build_connection_graph(Node *n, PhaseTransform *phase);
 264 
 265   // walk the connection graph starting at the node corresponding to "n" and
 266   // add the index of everything it could point to, to "ptset".  This may cause
 267   // Phi's encountered to get (re)processed  (which requires "phase".)
 268   VectorSet* PointsTo(Node * n);
 269 
 270   // Reused structures for PointsTo().
 271   VectorSet            pt_ptset;
 272   VectorSet            pt_visited;
 273   GrowableArray<uint>  pt_worklist;
 274 
 275   //  Edge manipulation.  The "from_i" and "to_i" arguments are the
 276   //  node indices of the source and destination of the edge
 277   void add_pointsto_edge(uint from_i, uint to_i);
 278   void add_deferred_edge(uint from_i, uint to_i);
 279   void add_field_edge(uint from_i, uint to_i, int offs);
 280 
 281   // Add an edge of the specified type pointing to the specified target.
 282   // Set _progress if new edge is added.
 283   void add_edge(PointsToNode *f, uint to_i, PointsToNode::EdgeType et) {
 284     uint e_cnt = f->edge_count();
 285     f->add_edge(to_i, et);
 286     _progress |= (f->edge_count() != e_cnt);
 287   }
 288 
 289   // Add an edge to node given by "to_i" from any field of adr_i whose offset
 290   // matches "offset"  A deferred edge is added if to_i is a LocalVar, and
 291   // a pointsto edge is added if it is a JavaObject
 292   void add_edge_from_fields(uint adr, uint to_i, int offs);
 293 
 294   // Add a deferred  edge from node given by "from_i" to any field
 295   // of adr_i whose offset matches "offset"
 296   void add_deferred_edge_to_fields(uint from_i, uint adr, int offs);
 297 
 298 
 299   // Remove outgoing deferred edges from the node referenced by "ni".
 300   // Any outgoing edges from the target of the deferred edge are copied
 301   // to "ni".
 302   void remove_deferred(uint ni, GrowableArray<uint>* deferred_edges, VectorSet* visited);
 303 
 304   Node_Array _node_map; // used for bookeeping during type splitting
 305                         // Used for the following purposes:
 306                         // Memory Phi    - most recent unique Phi split out
 307                         //                 from this Phi
 308                         // MemNode       - new memory input for this node
 309                         // ChecCastPP    - allocation that this is a cast of
 310                         // allocation    - CheckCastPP of the allocation
 311   bool split_AddP(Node *addp, Node *base,  PhaseGVN  *igvn);
 312   PhiNode *create_split_phi(PhiNode *orig_phi, int alias_idx, GrowableArray<PhiNode *>  &orig_phi_worklist, PhaseGVN  *igvn, bool &new_created);
 313   PhiNode *split_memory_phi(PhiNode *orig_phi, int alias_idx, GrowableArray<PhiNode *>  &orig_phi_worklist, PhaseGVN  *igvn);
 314   void  move_inst_mem(Node* n, GrowableArray<PhiNode *>  &orig_phis, PhaseGVN *igvn);
 315   Node *find_inst_mem(Node *mem, int alias_idx,GrowableArray<PhiNode *>  &orig_phi_worklist,  PhaseGVN  *igvn);
 316 
 317   // Propagate unique types created for unescaped allocated objects
 318   // through the graph
 319   void split_unique_types(GrowableArray<Node *>  &alloc_worklist);
 320 
 321   // manage entries in _node_map
 322   void  set_map(int idx, Node *n)        { _node_map.map(idx, n); }
 323   Node *get_map(int idx)                 { return _node_map[idx]; }
 324   PhiNode *get_map_phi(int idx) {
 325     Node *phi = _node_map[idx];
 326     return (phi == NULL) ? NULL : phi->as_Phi();
 327   }
 328 
 329   // Notify optimizer that a node has been modified
 330   // Node:  This assumes that escape analysis is run before
 331   //        PhaseIterGVN creation
 332   void record_for_optimizer(Node *n) {
 333     _igvn->_worklist.push(n);
 334   }
 335 
 336   // Set the escape state of a node
 337   void set_escape_state(uint ni, PointsToNode::EscapeState es);
 338 
 339   // Find fields initializing values for allocations.
 340   void find_init_values(Node* n, VectorSet* visited, PhaseTransform* phase);
 341 
 342   // Adjust escape state after Connection Graph is built.
 343   void adjust_escape_state(Node* n);
 344 
 345   // Propagate escape states to referenced nodes.
 346   bool propagate_escape_state(GrowableArray<int>* cg_worklist,
 347                               GrowableArray<uint>* worklist,
 348                               PointsToNode::EscapeState esc_state);
 349 
 350   // Compute the escape information
 351   bool compute_escape();
 352 
 353 public:
 354   ConnectionGraph(Compile *C, PhaseIterGVN *igvn);
 355 
 356   // Check for non-escaping candidates
 357   static bool has_candidates(Compile *C);
 358 
 359   // Perform escape analysis
 360   static void do_analysis(Compile *C, PhaseIterGVN *igvn);
 361 
 362   // escape state of a node
 363   PointsToNode::EscapeState escape_state(Node *n);
 364 
 365 #ifndef PRODUCT
 366   void dump();
 367 #endif
 368 };
 369 
 370 #endif // SHARE_VM_OPTO_ESCAPE_HPP