1 /*
   2  * Copyright (c) 2000, 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_CALLGENERATOR_HPP
  26 #define SHARE_VM_OPTO_CALLGENERATOR_HPP
  27 
  28 #include "compiler/compileBroker.hpp"
  29 #include "opto/callnode.hpp"
  30 #include "opto/compile.hpp"
  31 #include "opto/type.hpp"
  32 #include "runtime/deoptimization.hpp"
  33 
  34 //---------------------------CallGenerator-------------------------------------
  35 // The subclasses of this class handle generation of ideal nodes for
  36 // call sites and method entry points.
  37 
  38 class CallGenerator : public ResourceObj {
  39  public:
  40   enum {
  41     xxxunusedxxx
  42   };
  43 
  44  private:
  45   ciMethod*             _method;                // The method being called.
  46 
  47  protected:
  48   CallGenerator(ciMethod* method) : _method(method) {}
  49 
  50  public:
  51   // Accessors
  52   ciMethod*         method() const              { return _method; }
  53 
  54   // is_inline: At least some code implementing the method is copied here.
  55   virtual bool      is_inline() const           { return false; }
  56   // is_intrinsic: There's a method-specific way of generating the inline code.
  57   virtual bool      is_intrinsic() const        { return false; }
  58   // is_parse: Bytecodes implementing the specific method are copied here.
  59   virtual bool      is_parse() const            { return false; }
  60   // is_virtual: The call uses the receiver type to select or check the method.
  61   virtual bool      is_virtual() const          { return false; }
  62   // is_deferred: The decision whether to inline or not is deferred.
  63   virtual bool      is_deferred() const         { return false; }
  64   // is_predicted: Uses an explicit check against a predicted type.
  65   virtual bool      is_predicted() const        { return false; }
  66   // is_trap: Does not return to the caller.  (E.g., uncommon trap.)
  67   virtual bool      is_trap() const             { return false; }
  68 
  69   // is_late_inline: supports conversion of call into an inline
  70   virtual bool      is_late_inline() const      { return false; }
  71   // same but for method handle calls
  72   virtual bool      is_mh_late_inline() const   { return false; }
  73 
  74   // for method handle calls: have we tried inlinining the call already?
  75   virtual bool      already_attempted() const   { ShouldNotReachHere(); return false; }
  76 
  77   // Replace the call with an inline version of the code
  78   virtual void do_late_inline() { ShouldNotReachHere(); }
  79 
  80   virtual CallStaticJavaNode* call_node() const { ShouldNotReachHere(); return NULL; }
  81 
  82   // Note:  It is possible for a CG to be both inline and virtual.
  83   // (The hashCode intrinsic does a vtable check and an inlined fast path.)
  84 
  85   // Utilities:
  86   const TypeFunc*   tf() const;
  87 
  88   // The given jvms has state and arguments for a call to my method.
  89   // Edges after jvms->argoff() carry all (pre-popped) argument values.
  90   //
  91   // Update the map with state and return values (if any) and return it.
  92   // The return values (0, 1, or 2) must be pushed on the map's stack,
  93   // and the sp of the jvms incremented accordingly.
  94   //
  95   // The jvms is returned on success.  Alternatively, a copy of the
  96   // given jvms, suitably updated, may be returned, in which case the
  97   // caller should discard the original jvms.
  98   //
  99   // The non-Parm edges of the returned map will contain updated global state,
 100   // and one or two edges before jvms->sp() will carry any return values.
 101   // Other map edges may contain locals or monitors, and should not
 102   // be changed in meaning.
 103   //
 104   // If the call traps, the returned map must have a control edge of top.
 105   // If the call can throw, the returned map must report has_exceptions().
 106   //
 107   // If the result is NULL, it means that this CallGenerator was unable
 108   // to handle the given call, and another CallGenerator should be consulted.
 109   virtual JVMState* generate(JVMState* jvms) = 0;
 110 
 111   // How to generate a call site that is inlined:
 112   static CallGenerator* for_inline(ciMethod* m, float expected_uses = -1);
 113   // How to generate code for an on-stack replacement handler.
 114   static CallGenerator* for_osr(ciMethod* m, int osr_bci);
 115 
 116   // How to generate vanilla out-of-line call sites:
 117   static CallGenerator* for_direct_call(ciMethod* m, bool separate_io_projs = false);   // static, special
 118   static CallGenerator* for_virtual_call(ciMethod* m, int vtable_index);  // virtual, interface
 119   static CallGenerator* for_dynamic_call(ciMethod* m);   // invokedynamic
 120 
 121   static CallGenerator* for_method_handle_call(  JVMState* jvms, ciMethod* caller, ciMethod* callee, bool delayed_forbidden);
 122   static CallGenerator* for_method_handle_inline(JVMState* jvms, ciMethod* caller, ciMethod* callee, bool& input_not_const);
 123 
 124   // How to generate a replace a direct call with an inline version
 125   static CallGenerator* for_late_inline(ciMethod* m, CallGenerator* inline_cg);
 126   static CallGenerator* for_mh_late_inline(ciMethod* caller, ciMethod* callee, bool input_not_const);
 127   static CallGenerator* for_string_late_inline(ciMethod* m, CallGenerator* inline_cg);
 128 
 129   // How to make a call but defer the decision whether to inline or not.
 130   static CallGenerator* for_warm_call(WarmCallInfo* ci,
 131                                       CallGenerator* if_cold,
 132                                       CallGenerator* if_hot);
 133 
 134   // How to make a call that optimistically assumes a receiver type:
 135   static CallGenerator* for_predicted_call(ciKlass* predicted_receiver,
 136                                            CallGenerator* if_missed,
 137                                            CallGenerator* if_hit,
 138                                            float hit_prob);
 139 
 140   // How to make a call that optimistically assumes a MethodHandle target:
 141   static CallGenerator* for_predicted_dynamic_call(ciMethodHandle* predicted_method_handle,
 142                                                    CallGenerator* if_missed,
 143                                                    CallGenerator* if_hit,
 144                                                    float hit_prob);
 145 
 146   // How to make a call that gives up and goes back to the interpreter:
 147   static CallGenerator* for_uncommon_trap(ciMethod* m,
 148                                           Deoptimization::DeoptReason reason,
 149                                           Deoptimization::DeoptAction action);
 150 
 151   // Registry for intrinsics:
 152   static CallGenerator* for_intrinsic(ciMethod* m);
 153   static void register_intrinsic(ciMethod* m, CallGenerator* cg);
 154   static CallGenerator* for_predicted_intrinsic(CallGenerator* intrinsic,
 155                                                 CallGenerator* cg);
 156   virtual Node* generate_predicate(JVMState* jvms) { return NULL; };
 157 
 158   virtual void print_inlining_late(const char* msg) { ShouldNotReachHere(); }
 159 
 160   static void print_inlining(Compile* C, ciMethod* callee, int inline_level, int bci, const char* msg) {
 161     if (PrintInlining)
 162       C->print_inlining(callee, inline_level, bci, msg);
 163   }
 164 };
 165 
 166 
 167 //------------------------InlineCallGenerator----------------------------------
 168 class InlineCallGenerator : public CallGenerator {
 169  protected:
 170   InlineCallGenerator(ciMethod* method) : CallGenerator(method) {}
 171 
 172  public:
 173   virtual bool      is_inline() const           { return true; }
 174 };
 175 
 176 
 177 //---------------------------WarmCallInfo--------------------------------------
 178 // A struct to collect information about a given call site.
 179 // Helps sort call sites into "hot", "medium", and "cold".
 180 // Participates in the queueing of "medium" call sites for possible inlining.
 181 class WarmCallInfo : public ResourceObj {
 182  private:
 183 
 184   CallNode*     _call;   // The CallNode which may be inlined.
 185   CallGenerator* _hot_cg;// CG for expanding the call node
 186 
 187   // These are the metrics we use to evaluate call sites:
 188 
 189   float         _count;  // How often do we expect to reach this site?
 190   float         _profit; // How much time do we expect to save by inlining?
 191   float         _work;   // How long do we expect the average call to take?
 192   float         _size;   // How big do we expect the inlined code to be?
 193 
 194   float         _heat;   // Combined score inducing total order on call sites.
 195   WarmCallInfo* _next;   // Next cooler call info in pending queue.
 196 
 197   // Count is the number of times this call site is expected to be executed.
 198   // Large count is favorable for inlining, because the extra compilation
 199   // work will be amortized more completely.
 200 
 201   // Profit is a rough measure of the amount of time we expect to save
 202   // per execution of this site if we inline it.  (1.0 == call overhead)
 203   // Large profit favors inlining.  Negative profit disables inlining.
 204 
 205   // Work is a rough measure of the amount of time a typical out-of-line
 206   // call from this site is expected to take.  (1.0 == call, no-op, return)
 207   // Small work is somewhat favorable for inlining, since methods with
 208   // short "hot" traces are more likely to inline smoothly.
 209 
 210   // Size is the number of graph nodes we expect this method to produce,
 211   // not counting the inlining of any further warm calls it may include.
 212   // Small size favors inlining, since small methods are more likely to
 213   // inline smoothly.  The size is estimated by examining the native code
 214   // if available.  The method bytecodes are also examined, assuming
 215   // empirically observed node counts for each kind of bytecode.
 216 
 217   // Heat is the combined "goodness" of a site's inlining.  If we were
 218   // omniscient, it would be the difference of two sums of future execution
 219   // times of code emitted for this site (amortized across multiple sites if
 220   // sharing applies).  The two sums are for versions of this call site with
 221   // and without inlining.
 222 
 223   // We approximate this mythical quantity by playing with averages,
 224   // rough estimates, and assumptions that history repeats itself.
 225   // The basic formula count * profit is heuristically adjusted
 226   // by looking at the expected compilation and execution times of
 227   // of the inlined call.
 228 
 229   // Note:  Some of these metrics may not be present in the final product,
 230   // but exist in development builds to experiment with inline policy tuning.
 231 
 232   // This heuristic framework does not model well the very significant
 233   // effects of multiple-level inlining.  It is possible to see no immediate
 234   // profit from inlining X->Y, but to get great profit from a subsequent
 235   // inlining X->Y->Z.
 236 
 237   // This framework does not take well into account the problem of N**2 code
 238   // size in a clique of mutually inlinable methods.
 239 
 240   WarmCallInfo*  next() const          { return _next; }
 241   void       set_next(WarmCallInfo* n) { _next = n; }
 242 
 243   static WarmCallInfo _always_hot;
 244   static WarmCallInfo _always_cold;
 245 
 246   // Constructor intitialization of always_hot and always_cold
 247   WarmCallInfo(float c, float p, float w, float s) {
 248     _call = NULL;
 249     _hot_cg = NULL;
 250     _next = NULL;
 251     _count = c;
 252     _profit = p;
 253     _work = w;
 254     _size = s;
 255     _heat = 0;
 256   }
 257 
 258  public:
 259   // Because WarmInfo objects live over the entire lifetime of the
 260   // Compile object, they are allocated into the comp_arena, which
 261   // does not get resource marked or reset during the compile process
 262   void *operator new( size_t x, Compile* C ) { return C->comp_arena()->Amalloc(x); }
 263   void operator delete( void * ) { } // fast deallocation
 264 
 265   static WarmCallInfo* always_hot();
 266   static WarmCallInfo* always_cold();
 267 
 268   WarmCallInfo() {
 269     _call = NULL;
 270     _hot_cg = NULL;
 271     _next = NULL;
 272     _count = _profit = _work = _size = _heat = 0;
 273   }
 274 
 275   CallNode* call() const { return _call; }
 276   float count()    const { return _count; }
 277   float size()     const { return _size; }
 278   float work()     const { return _work; }
 279   float profit()   const { return _profit; }
 280   float heat()     const { return _heat; }
 281 
 282   void set_count(float x)     { _count = x; }
 283   void set_size(float x)      { _size = x; }
 284   void set_work(float x)      { _work = x; }
 285   void set_profit(float x)    { _profit = x; }
 286   void set_heat(float x)      { _heat = x; }
 287 
 288   // Load initial heuristics from profiles, etc.
 289   // The heuristics can be tweaked further by the caller.
 290   void init(JVMState* call_site, ciMethod* call_method, ciCallProfile& profile, float prof_factor);
 291 
 292   static float MAX_VALUE() { return +1.0e10; }
 293   static float MIN_VALUE() { return -1.0e10; }
 294 
 295   float compute_heat() const;
 296 
 297   void set_call(CallNode* call)      { _call = call; }
 298   void set_hot_cg(CallGenerator* cg) { _hot_cg = cg; }
 299 
 300   // Do not queue very hot or very cold calls.
 301   // Make very cold ones out of line immediately.
 302   // Inline very hot ones immediately.
 303   // These queries apply various tunable limits
 304   // to the above metrics in a systematic way.
 305   // Test for coldness before testing for hotness.
 306   bool is_cold() const;
 307   bool is_hot() const;
 308 
 309   // Force a warm call to be hot.  This worklists the call node for inlining.
 310   void make_hot();
 311 
 312   // Force a warm call to be cold.  This worklists the call node for out-of-lining.
 313   void make_cold();
 314 
 315   // A reproducible total ordering, in which heat is the major key.
 316   bool warmer_than(WarmCallInfo* that);
 317 
 318   // List management.  These methods are called with the list head,
 319   // and return the new list head, inserting or removing the receiver.
 320   WarmCallInfo* insert_into(WarmCallInfo* head);
 321   WarmCallInfo* remove_from(WarmCallInfo* head);
 322 
 323 #ifndef PRODUCT
 324   void print() const;
 325   void print_all() const;
 326   int count_all() const;
 327 #endif
 328 };
 329 
 330 #endif // SHARE_VM_OPTO_CALLGENERATOR_HPP