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