blob: d57b916f68e71088fe71b02236717471c7c37377 [file] [log] [blame]
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001/*
2 * Copyright (C) 2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "inliner.h"
18
Mathieu Chartiere401d142015-04-22 13:56:20 -070019#include "art_method-inl.h"
Andreas Gampe542451c2016-07-26 09:02:02 -070020#include "base/enums.h"
Andreas Gampe85f1c572018-11-21 13:52:48 -080021#include "base/logging.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000022#include "builder.h"
23#include "class_linker.h"
Vladimir Markob4eb1b12018-05-24 11:09:38 +010024#include "class_root.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000025#include "constant_folding.h"
Vladimir Marko0ebe0d82017-09-21 22:50:39 +010026#include "data_type-inl.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000027#include "dead_code_elimination.h"
Andreas Gampeb95c74b2017-04-20 19:43:21 -070028#include "dex/inline_method_analyser.h"
Vladimir Markobe10e8e2016-01-22 12:09:44 +000029#include "dex/verification_results.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070030#include "dex/verified_method.h"
Calin Juravleec748352015-07-29 13:52:12 +010031#include "driver/compiler_options.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000032#include "driver/dex_compilation_unit.h"
33#include "instruction_simplifier.h"
Scott Wakelingd60a1af2015-07-22 14:32:44 +010034#include "intrinsics.h"
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +000035#include "jit/jit.h"
36#include "jit/jit_code_cache.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000037#include "mirror/class_loader.h"
38#include "mirror/dex_cache.h"
Andreas Gampe52ecb652018-10-24 15:18:21 -070039#include "mirror/object_array-alloc-inl.h"
40#include "mirror/object_array-inl.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000041#include "nodes.h"
Nicolas Geoffray454a4812015-06-09 10:37:32 +010042#include "reference_type_propagation.h"
Matthew Gharritye9288852016-07-14 14:08:16 -070043#include "register_allocator_linear_scan.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070044#include "scoped_thread_state_change-inl.h"
Vladimir Markodc151b22015-10-15 18:02:30 +010045#include "sharpening.h"
David Brazdil4833f5a2015-12-16 10:37:39 +000046#include "ssa_builder.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000047#include "ssa_phi_elimination.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000048#include "thread.h"
49
50namespace art {
51
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +000052// Instruction limit to control memory.
53static constexpr size_t kMaximumNumberOfTotalInstructions = 1024;
54
55// Maximum number of instructions for considering a method small,
56// which we will always try to inline if the other non-instruction limits
57// are not reached.
58static constexpr size_t kMaximumNumberOfInstructionsForSmallMethod = 3;
Nicolas Geoffray5949fa02015-12-18 10:57:10 +000059
60// Limit the number of dex registers that we accumulate while inlining
61// to avoid creating large amount of nested environments.
Nicolas Geoffrayf81621e2017-06-07 13:18:03 +010062static constexpr size_t kMaximumNumberOfCumulatedDexRegisters = 32;
Nicolas Geoffray5949fa02015-12-18 10:57:10 +000063
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +000064// Limit recursive call inlining, which do not benefit from too
65// much inlining compared to code locality.
66static constexpr size_t kMaximumNumberOfRecursiveCalls = 4;
Nicolas Geoffraye418dda2015-08-11 20:03:09 -070067
Calin Juravlee2492d42017-03-20 11:42:13 -070068// Controls the use of inline caches in AOT mode.
Calin Juravle8af70892017-03-28 15:31:44 -070069static constexpr bool kUseAOTInlineCaches = true;
Calin Juravlee2492d42017-03-20 11:42:13 -070070
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +000071// We check for line numbers to make sure the DepthString implementation
72// aligns the output nicely.
73#define LOG_INTERNAL(msg) \
74 static_assert(__LINE__ > 10, "Unhandled line number"); \
75 static_assert(__LINE__ < 10000, "Unhandled line number"); \
76 VLOG(compiler) << DepthString(__LINE__) << msg
77
78#define LOG_TRY() LOG_INTERNAL("Try inlinining call: ")
79#define LOG_NOTE() LOG_INTERNAL("Note: ")
80#define LOG_SUCCESS() LOG_INTERNAL("Success: ")
Igor Murashkin1e065a52017-08-09 13:20:34 -070081#define LOG_FAIL(stats_ptr, stat) MaybeRecordStat(stats_ptr, stat); LOG_INTERNAL("Fail: ")
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +000082#define LOG_FAIL_NO_STAT() LOG_INTERNAL("Fail: ")
83
84std::string HInliner::DepthString(int line) const {
85 std::string value;
86 // Indent according to the inlining depth.
87 size_t count = depth_;
88 // Line numbers get printed in the log, so add a space if the log's line is less
89 // than 1000, and two if less than 100. 10 cannot be reached as it's the copyright.
90 if (!kIsTargetBuild) {
91 if (line < 100) {
92 value += " ";
93 }
94 if (line < 1000) {
95 value += " ";
96 }
97 // Safeguard if this file reaches more than 10000 lines.
98 DCHECK_LT(line, 10000);
99 }
100 for (size_t i = 0; i < count; ++i) {
101 value += " ";
102 }
103 return value;
104}
105
106static size_t CountNumberOfInstructions(HGraph* graph) {
107 size_t number_of_instructions = 0;
108 for (HBasicBlock* block : graph->GetReversePostOrderSkipEntryBlock()) {
109 for (HInstructionIterator instr_it(block->GetInstructions());
110 !instr_it.Done();
111 instr_it.Advance()) {
112 ++number_of_instructions;
113 }
114 }
115 return number_of_instructions;
116}
117
118void HInliner::UpdateInliningBudget() {
119 if (total_number_of_instructions_ >= kMaximumNumberOfTotalInstructions) {
120 // Always try to inline small methods.
121 inlining_budget_ = kMaximumNumberOfInstructionsForSmallMethod;
122 } else {
123 inlining_budget_ = std::max(
124 kMaximumNumberOfInstructionsForSmallMethod,
125 kMaximumNumberOfTotalInstructions - total_number_of_instructions_);
126 }
127}
128
Aart Bik24773202018-04-26 10:28:51 -0700129bool HInliner::Run() {
Vladimir Marko213ee2d2018-06-22 11:56:34 +0100130 if (codegen_->GetCompilerOptions().GetInlineMaxCodeUnits() == 0) {
Aart Bik24773202018-04-26 10:28:51 -0700131 // Inlining effectively disabled.
132 return false;
133 } else if (graph_->IsDebuggable()) {
Nicolas Geoffraye50b8d22015-03-13 08:57:42 +0000134 // For simplicity, we currently never inline when the graph is debuggable. This avoids
135 // doing some logic in the runtime to discover if a method could have been inlined.
Aart Bik24773202018-04-26 10:28:51 -0700136 return false;
Nicolas Geoffraye50b8d22015-03-13 08:57:42 +0000137 }
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000138
Aart Bik24773202018-04-26 10:28:51 -0700139 bool didInline = false;
140
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000141 // Initialize the number of instructions for the method being compiled. Recursive calls
142 // to HInliner::Run have already updated the instruction count.
143 if (outermost_graph_ == graph_) {
144 total_number_of_instructions_ = CountNumberOfInstructions(graph_);
145 }
146
147 UpdateInliningBudget();
148 DCHECK_NE(total_number_of_instructions_, 0u);
149 DCHECK_NE(inlining_budget_, 0u);
150
Roland Levillain6c3af162017-04-27 11:18:56 +0100151 // If we're compiling with a core image (which is only used for
152 // test purposes), honor inlining directives in method names:
Roland Levillain6c3af162017-04-27 11:18:56 +0100153 // - if a method's name contains the substring "$noinline$", do not
Vladimir Marko6be1dbd2018-11-13 13:09:51 +0000154 // inline that method;
155 // - if a method's name contains the substring "$inline$", ensure
156 // that this method is actually inlined.
Vladimir Markobe0c7cf2018-03-19 13:40:56 +0000157 // We limit the latter to AOT compilation, as the JIT may or may not inline
Nicolas Geoffray08490b82017-07-18 12:58:10 +0100158 // depending on the state of classes at runtime.
Vladimir Marko6be1dbd2018-11-13 13:09:51 +0000159 const bool honor_noinline_directives = codegen_->GetCompilerOptions().CompilingWithCoreImage();
Vladimir Markobe0c7cf2018-03-19 13:40:56 +0000160 const bool honor_inline_directives =
161 honor_noinline_directives && Runtime::Current()->IsAotCompiler();
Roland Levillain6c3af162017-04-27 11:18:56 +0100162
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +0000163 // Keep a copy of all blocks when starting the visit.
164 ArenaVector<HBasicBlock*> blocks = graph_->GetReversePostOrder();
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100165 DCHECK(!blocks.empty());
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +0000166 // Because we are changing the graph when inlining,
167 // we just iterate over the blocks of the outer method.
168 // This avoids doing the inlining work again on the inlined blocks.
169 for (HBasicBlock* block : blocks) {
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +0000170 for (HInstruction* instruction = block->GetFirstInstruction(); instruction != nullptr;) {
171 HInstruction* next = instruction->GetNext();
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100172 HInvoke* call = instruction->AsInvoke();
Razvan A Lupusoru3e90a962015-03-27 13:44:44 -0700173 // As long as the call is not intrinsified, it is worth trying to inline.
174 if (call != nullptr && call->GetIntrinsic() == Intrinsics::kNone) {
Vladimir Markobe0c7cf2018-03-19 13:40:56 +0000175 if (honor_noinline_directives) {
Nicolas Geoffrayb703d182017-02-14 18:05:28 +0000176 // Debugging case: directives in method names control or assert on inlining.
177 std::string callee_name = outer_compilation_unit_.GetDexFile()->PrettyMethod(
Andreas Gampe3db70682018-12-26 15:12:03 -0800178 call->GetDexMethodIndex(), /* with_signature= */ false);
Nicolas Geoffrayb703d182017-02-14 18:05:28 +0000179 // Tests prevent inlining by having $noinline$ in their method names.
180 if (callee_name.find("$noinline$") == std::string::npos) {
Aart Bik24773202018-04-26 10:28:51 -0700181 if (TryInline(call)) {
182 didInline = true;
Aart Bik54e45c52018-04-27 13:57:21 -0700183 } else if (honor_inline_directives) {
Nicolas Geoffray1949baf2017-10-17 12:14:53 +0000184 bool should_have_inlined = (callee_name.find("$inline$") != std::string::npos);
185 CHECK(!should_have_inlined) << "Could not inline " << callee_name;
Nicolas Geoffrayb703d182017-02-14 18:05:28 +0000186 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000187 }
Guillaume "Vermeille" Sancheze918d382015-06-03 15:32:41 +0100188 } else {
Vladimir Markobe0c7cf2018-03-19 13:40:56 +0000189 DCHECK(!honor_inline_directives);
Nicolas Geoffrayb703d182017-02-14 18:05:28 +0000190 // Normal case: try to inline.
Aart Bik24773202018-04-26 10:28:51 -0700191 if (TryInline(call)) {
192 didInline = true;
193 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000194 }
195 }
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +0000196 instruction = next;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000197 }
198 }
Aart Bik24773202018-04-26 10:28:51 -0700199
200 return didInline;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000201}
202
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100203static bool IsMethodOrDeclaringClassFinal(ArtMethod* method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700204 REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100205 return method->IsFinal() || method->GetDeclaringClass()->IsFinal();
206}
207
208/**
209 * Given the `resolved_method` looked up in the dex cache, try to find
210 * the actual runtime target of an interface or virtual call.
211 * Return nullptr if the runtime target cannot be proven.
212 */
213static ArtMethod* FindVirtualOrInterfaceTarget(HInvoke* invoke, ArtMethod* resolved_method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700214 REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100215 if (IsMethodOrDeclaringClassFinal(resolved_method)) {
216 // No need to lookup further, the resolved method will be the target.
217 return resolved_method;
218 }
219
220 HInstruction* receiver = invoke->InputAt(0);
221 if (receiver->IsNullCheck()) {
222 // Due to multiple levels of inlining within the same pass, it might be that
223 // null check does not have the reference type of the actual receiver.
224 receiver = receiver->InputAt(0);
225 }
226 ReferenceTypeInfo info = receiver->GetReferenceTypeInfo();
Calin Juravle2e768302015-07-28 14:41:11 +0000227 DCHECK(info.IsValid()) << "Invalid RTI for " << receiver->DebugName();
228 if (!info.IsExact()) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100229 // We currently only support inlining with known receivers.
230 // TODO: Remove this check, we should be able to inline final methods
231 // on unknown receivers.
232 return nullptr;
233 } else if (info.GetTypeHandle()->IsInterface()) {
234 // Statically knowing that the receiver has an interface type cannot
235 // help us find what is the target method.
236 return nullptr;
237 } else if (!resolved_method->GetDeclaringClass()->IsAssignableFrom(info.GetTypeHandle().Get())) {
238 // The method that we're trying to call is not in the receiver's class or super classes.
239 return nullptr;
Nicolas Geoffrayab5327d2016-03-18 11:36:20 +0000240 } else if (info.GetTypeHandle()->IsErroneous()) {
241 // If the type is erroneous, do not go further, as we are going to query the vtable or
242 // imt table, that we can only safely do on non-erroneous classes.
243 return nullptr;
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100244 }
245
246 ClassLinker* cl = Runtime::Current()->GetClassLinker();
Andreas Gampe542451c2016-07-26 09:02:02 -0700247 PointerSize pointer_size = cl->GetImagePointerSize();
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100248 if (invoke->IsInvokeInterface()) {
249 resolved_method = info.GetTypeHandle()->FindVirtualMethodForInterface(
250 resolved_method, pointer_size);
251 } else {
252 DCHECK(invoke->IsInvokeVirtual());
253 resolved_method = info.GetTypeHandle()->FindVirtualMethodForVirtual(
254 resolved_method, pointer_size);
255 }
256
257 if (resolved_method == nullptr) {
258 // The information we had on the receiver was not enough to find
259 // the target method. Since we check above the exact type of the receiver,
260 // the only reason this can happen is an IncompatibleClassChangeError.
261 return nullptr;
Alex Light9139e002015-10-09 15:59:48 -0700262 } else if (!resolved_method->IsInvokable()) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100263 // The information we had on the receiver was not enough to find
264 // the target method. Since we check above the exact type of the receiver,
265 // the only reason this can happen is an IncompatibleClassChangeError.
266 return nullptr;
267 } else if (IsMethodOrDeclaringClassFinal(resolved_method)) {
268 // A final method has to be the target method.
269 return resolved_method;
270 } else if (info.IsExact()) {
271 // If we found a method and the receiver's concrete type is statically
272 // known, we know for sure the target.
273 return resolved_method;
274 } else {
275 // Even if we did find a method, the receiver type was not enough to
276 // statically find the runtime target.
277 return nullptr;
278 }
279}
280
281static uint32_t FindMethodIndexIn(ArtMethod* method,
282 const DexFile& dex_file,
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +0000283 uint32_t name_and_signature_index)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700284 REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100285 if (IsSameDexFile(*method->GetDexFile(), dex_file)) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100286 return method->GetDexMethodIndex();
287 } else {
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +0000288 return method->FindDexMethodIndexInOtherDexFile(dex_file, name_and_signature_index);
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100289 }
290}
291
Vladimir Marko423bebb2019-03-26 15:17:21 +0000292static dex::TypeIndex FindClassIndexIn(ObjPtr<mirror::Class> cls,
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000293 const DexCompilationUnit& compilation_unit)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700294 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000295 const DexFile& dex_file = *compilation_unit.GetDexFile();
Andreas Gampea5b09a62016-11-17 15:21:22 -0800296 dex::TypeIndex index;
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100297 if (cls->GetDexCache() == nullptr) {
David Sehr709b0702016-10-13 09:12:37 -0700298 DCHECK(cls->IsArrayClass()) << cls->PrettyClass();
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000299 index = cls->FindTypeIndexInOtherDexFile(dex_file);
Andreas Gampea5b09a62016-11-17 15:21:22 -0800300 } else if (!cls->GetDexTypeIndex().IsValid()) {
David Sehr709b0702016-10-13 09:12:37 -0700301 DCHECK(cls->IsProxyClass()) << cls->PrettyClass();
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100302 // TODO: deal with proxy classes.
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100303 } else if (IsSameDexFile(cls->GetDexFile(), dex_file)) {
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000304 DCHECK_EQ(cls->GetDexCache(), compilation_unit.GetDexCache().Get());
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000305 index = cls->GetDexTypeIndex();
Nicolas Geoffray491617a2016-07-19 17:06:23 +0100306 } else {
307 index = cls->FindTypeIndexInOtherDexFile(dex_file);
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000308 // We cannot guarantee the entry will resolve to the same class,
Nicolas Geoffray491617a2016-07-19 17:06:23 +0100309 // as there may be different class loaders. So only return the index if it's
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000310 // the right class already resolved with the class loader.
311 if (index.IsValid()) {
Vladimir Marko666ee3d2017-12-11 18:37:36 +0000312 ObjPtr<mirror::Class> resolved = compilation_unit.GetClassLinker()->LookupResolvedType(
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000313 index, compilation_unit.GetDexCache().Get(), compilation_unit.GetClassLoader().Get());
314 if (resolved != cls) {
315 index = dex::TypeIndex::Invalid();
316 }
Nicolas Geoffray491617a2016-07-19 17:06:23 +0100317 }
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100318 }
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000319
320 return index;
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100321}
322
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000323class ScopedProfilingInfoInlineUse {
324 public:
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000325 explicit ScopedProfilingInfoInlineUse(ArtMethod* method, Thread* self)
326 : method_(method),
327 self_(self),
328 // Fetch the profiling info ahead of using it. If it's null when fetching,
329 // we should not call JitCodeCache::DoneInlining.
330 profiling_info_(
331 Runtime::Current()->GetJit()->GetCodeCache()->NotifyCompilerUse(method, self)) {
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000332 }
333
334 ~ScopedProfilingInfoInlineUse() {
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000335 if (profiling_info_ != nullptr) {
Andreas Gampe542451c2016-07-26 09:02:02 -0700336 PointerSize pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000337 DCHECK_EQ(profiling_info_, method_->GetProfilingInfo(pointer_size));
338 Runtime::Current()->GetJit()->GetCodeCache()->DoneCompilerUse(method_, self_);
339 }
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000340 }
341
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000342 ProfilingInfo* GetProfilingInfo() const { return profiling_info_; }
343
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000344 private:
345 ArtMethod* const method_;
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000346 Thread* const self_;
347 ProfilingInfo* const profiling_info_;
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000348};
349
Calin Juravle13439f02017-02-21 01:17:21 -0800350HInliner::InlineCacheType HInliner::GetInlineCacheType(
351 const Handle<mirror::ObjectArray<mirror::Class>>& classes)
352 REQUIRES_SHARED(Locks::mutator_lock_) {
353 uint8_t number_of_types = 0;
354 for (; number_of_types < InlineCache::kIndividualCacheSize; ++number_of_types) {
355 if (classes->Get(number_of_types) == nullptr) {
356 break;
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000357 }
358 }
Calin Juravle13439f02017-02-21 01:17:21 -0800359
360 if (number_of_types == 0) {
361 return kInlineCacheUninitialized;
362 } else if (number_of_types == 1) {
363 return kInlineCacheMonomorphic;
364 } else if (number_of_types == InlineCache::kIndividualCacheSize) {
365 return kInlineCacheMegamorphic;
366 } else {
367 return kInlineCachePolymorphic;
368 }
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000369}
370
Vladimir Marko423bebb2019-03-26 15:17:21 +0000371static ObjPtr<mirror::Class> GetMonomorphicType(Handle<mirror::ObjectArray<mirror::Class>> classes)
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000372 REQUIRES_SHARED(Locks::mutator_lock_) {
373 DCHECK(classes->Get(0) != nullptr);
374 return classes->Get(0);
375}
376
Mingyao Yang063fc772016-08-02 11:02:54 -0700377ArtMethod* HInliner::TryCHADevirtualization(ArtMethod* resolved_method) {
378 if (!resolved_method->HasSingleImplementation()) {
379 return nullptr;
380 }
381 if (Runtime::Current()->IsAotCompiler()) {
382 // No CHA-based devirtulization for AOT compiler (yet).
383 return nullptr;
384 }
Nicolas Geoffray141b63c2019-02-27 14:28:46 +0000385 if (Runtime::Current()->IsZygote()) {
386 // No CHA-based devirtulization for Zygote, as it compiles with
387 // offline information.
388 return nullptr;
389 }
Mingyao Yang063fc772016-08-02 11:02:54 -0700390 if (outermost_graph_->IsCompilingOsr()) {
391 // We do not support HDeoptimize in OSR methods.
392 return nullptr;
393 }
Mingyao Yange8fcd012017-01-20 10:43:30 -0800394 PointerSize pointer_size = caller_compilation_unit_.GetClassLinker()->GetImagePointerSize();
Nicolas Geoffray18ea1c92017-03-27 08:00:18 +0000395 ArtMethod* single_impl = resolved_method->GetSingleImplementation(pointer_size);
396 if (single_impl == nullptr) {
397 return nullptr;
398 }
399 if (single_impl->IsProxyMethod()) {
400 // Proxy method is a generic invoker that's not worth
401 // devirtualizing/inlining. It also causes issues when the proxy
402 // method is in another dex file if we try to rewrite invoke-interface to
403 // invoke-virtual because a proxy method doesn't have a real dex file.
404 return nullptr;
405 }
Nicolas Geoffray8e33e842017-04-03 16:55:16 +0100406 if (!single_impl->GetDeclaringClass()->IsResolved()) {
407 // There's a race with the class loading, which updates the CHA info
408 // before setting the class to resolved. So we just bail for this
409 // rare occurence.
410 return nullptr;
411 }
Nicolas Geoffray18ea1c92017-03-27 08:00:18 +0000412 return single_impl;
Mingyao Yang063fc772016-08-02 11:02:54 -0700413}
414
Vladimir Marko2afaff72018-11-30 17:01:50 +0000415static bool IsMethodUnverified(const CompilerOptions& compiler_options, ArtMethod* method)
David Sehr0225f8e2018-01-31 08:52:24 +0000416 REQUIRES_SHARED(Locks::mutator_lock_) {
Aart Bik2c148f02018-02-02 14:30:35 -0800417 if (!method->GetDeclaringClass()->IsVerified()) {
418 if (Runtime::Current()->UseJitCompilation()) {
419 // We're at runtime, we know this is cold code if the class
420 // is not verified, so don't bother analyzing.
421 return true;
422 }
423 uint16_t class_def_idx = method->GetDeclaringClass()->GetDexClassDefIndex();
Vladimir Marko2afaff72018-11-30 17:01:50 +0000424 if (!compiler_options.IsMethodVerifiedWithoutFailures(method->GetDexMethodIndex(),
425 class_def_idx,
426 *method->GetDexFile())) {
Aart Bik2c148f02018-02-02 14:30:35 -0800427 // Method has soft or hard failures, don't analyze.
428 return true;
429 }
430 }
431 return false;
432}
433
Vladimir Marko2afaff72018-11-30 17:01:50 +0000434static bool AlwaysThrows(const CompilerOptions& compiler_options, ArtMethod* method)
Aart Bik2c148f02018-02-02 14:30:35 -0800435 REQUIRES_SHARED(Locks::mutator_lock_) {
436 DCHECK(method != nullptr);
437 // Skip non-compilable and unverified methods.
Vladimir Marko2afaff72018-11-30 17:01:50 +0000438 if (!method->IsCompilable() || IsMethodUnverified(compiler_options, method)) {
Aart Bik2c148f02018-02-02 14:30:35 -0800439 return false;
440 }
Aart Bika8b8e9b2018-01-09 11:01:02 -0800441 // Skip native methods, methods with try blocks, and methods that are too large.
Aart Bik2c148f02018-02-02 14:30:35 -0800442 CodeItemDataAccessor accessor(method->DexInstructionData());
Aart Bika8b8e9b2018-01-09 11:01:02 -0800443 if (!accessor.HasCodeItem() ||
444 accessor.TriesSize() != 0 ||
445 accessor.InsnsSizeInCodeUnits() > kMaximumNumberOfTotalInstructions) {
446 return false;
447 }
448 // Scan for exits.
449 bool throw_seen = false;
450 for (const DexInstructionPcPair& pair : accessor) {
451 switch (pair.Inst().Opcode()) {
452 case Instruction::RETURN:
453 case Instruction::RETURN_VOID:
454 case Instruction::RETURN_WIDE:
455 case Instruction::RETURN_OBJECT:
456 case Instruction::RETURN_VOID_NO_BARRIER:
457 return false; // found regular control flow back
458 case Instruction::THROW:
459 throw_seen = true;
460 break;
461 default:
462 break;
463 }
464 }
465 return throw_seen;
466}
467
Nicolas Geoffraye418dda2015-08-11 20:03:09 -0700468bool HInliner::TryInline(HInvoke* invoke_instruction) {
Orion Hodsonac141392017-01-13 11:53:47 +0000469 if (invoke_instruction->IsInvokeUnresolved() ||
Orion Hodson4c8e12e2018-05-18 08:33:20 +0100470 invoke_instruction->IsInvokePolymorphic() ||
471 invoke_instruction->IsInvokeCustom()) {
472 return false; // Don't bother to move further if we know the method is unresolved or the
473 // invocation is polymorphic (invoke-{polymorphic,custom}).
Calin Juravle175dc732015-08-25 15:42:32 +0100474 }
475
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000476 ScopedObjectAccess soa(Thread::Current());
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +0100477 uint32_t method_index = invoke_instruction->GetDexMethodIndex();
Nicolas Geoffray9437b782015-03-25 10:08:51 +0000478 const DexFile& caller_dex_file = *caller_compilation_unit_.GetDexFile();
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000479 LOG_TRY() << caller_dex_file.PrettyMethod(method_index);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000480
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +0100481 ArtMethod* resolved_method = invoke_instruction->GetResolvedMethod();
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +0100482 if (resolved_method == nullptr) {
483 DCHECK(invoke_instruction->IsInvokeStaticOrDirect());
484 DCHECK(invoke_instruction->AsInvokeStaticOrDirect()->IsStringInit());
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000485 LOG_FAIL_NO_STAT() << "Not inlining a String.<init> method";
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +0100486 return false;
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000487 }
488 ArtMethod* actual_method = nullptr;
489
490 if (invoke_instruction->IsInvokeStaticOrDirect()) {
Andreas Gampefd2140f2015-12-23 16:30:44 -0800491 actual_method = resolved_method;
Vladimir Marko58155012015-08-19 12:49:41 +0000492 } else {
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +0100493 // Check if we can statically find the method.
494 actual_method = FindVirtualOrInterfaceTarget(invoke_instruction, resolved_method);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000495 }
496
Mingyao Yang063fc772016-08-02 11:02:54 -0700497 bool cha_devirtualize = false;
498 if (actual_method == nullptr) {
499 ArtMethod* method = TryCHADevirtualization(resolved_method);
500 if (method != nullptr) {
501 cha_devirtualize = true;
502 actual_method = method;
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000503 LOG_NOTE() << "Try CHA-based inlining of " << actual_method->PrettyMethod();
Mingyao Yang063fc772016-08-02 11:02:54 -0700504 }
505 }
506
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100507 if (actual_method != nullptr) {
Aart Bikd4e328f2018-01-16 14:14:34 -0800508 // Single target.
Mingyao Yang063fc772016-08-02 11:02:54 -0700509 bool result = TryInlineAndReplace(invoke_instruction,
510 actual_method,
Nicolas Geoffray0f001b72017-01-04 16:46:23 +0000511 ReferenceTypeInfo::CreateInvalid(),
Andreas Gampe3db70682018-12-26 15:12:03 -0800512 /* do_rtp= */ true,
Mingyao Yang063fc772016-08-02 11:02:54 -0700513 cha_devirtualize);
Aart Bikd4e328f2018-01-16 14:14:34 -0800514 if (result) {
515 // Successfully inlined.
516 if (!invoke_instruction->IsInvokeStaticOrDirect()) {
517 if (cha_devirtualize) {
518 // Add dependency due to devirtualization. We've assumed resolved_method
519 // has single implementation.
520 outermost_graph_->AddCHASingleImplementationDependency(resolved_method);
521 MaybeRecordStat(stats_, MethodCompilationStat::kCHAInline);
522 } else {
523 MaybeRecordStat(stats_, MethodCompilationStat::kInlinedInvokeVirtualOrInterface);
524 }
Mingyao Yang063fc772016-08-02 11:02:54 -0700525 }
Vladimir Marko2afaff72018-11-30 17:01:50 +0000526 } else if (!cha_devirtualize && AlwaysThrows(codegen_->GetCompilerOptions(), actual_method)) {
Aart Bikd4e328f2018-01-16 14:14:34 -0800527 // Set always throws property for non-inlined method call with single target
528 // (unless it was obtained through CHA, because that would imply we have
529 // to add the CHA dependency, which seems not worth it).
530 invoke_instruction->SetAlwaysThrows(true);
Calin Juravle69158982016-03-16 11:53:41 +0000531 }
532 return result;
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100533 }
Andreas Gampefd2140f2015-12-23 16:30:44 -0800534 DCHECK(!invoke_instruction->IsInvokeStaticOrDirect());
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100535
Calin Juravle13439f02017-02-21 01:17:21 -0800536 // Try using inline caches.
537 return TryInlineFromInlineCache(caller_dex_file, invoke_instruction, resolved_method);
538}
539
540static Handle<mirror::ObjectArray<mirror::Class>> AllocateInlineCacheHolder(
541 const DexCompilationUnit& compilation_unit,
542 StackHandleScope<1>* hs)
543 REQUIRES_SHARED(Locks::mutator_lock_) {
544 Thread* self = Thread::Current();
545 ClassLinker* class_linker = compilation_unit.GetClassLinker();
546 Handle<mirror::ObjectArray<mirror::Class>> inline_cache = hs->NewHandle(
547 mirror::ObjectArray<mirror::Class>::Alloc(
548 self,
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100549 GetClassRoot<mirror::ObjectArray<mirror::Class>>(class_linker),
Calin Juravle13439f02017-02-21 01:17:21 -0800550 InlineCache::kIndividualCacheSize));
551 if (inline_cache == nullptr) {
552 // We got an OOME. Just clear the exception, and don't inline.
553 DCHECK(self->IsExceptionPending());
554 self->ClearException();
555 VLOG(compiler) << "Out of memory in the compiler when trying to inline";
556 }
557 return inline_cache;
558}
559
Calin Juravleaf44e6c2017-05-23 14:24:55 -0700560bool HInliner::UseOnlyPolymorphicInliningWithNoDeopt() {
561 // If we are compiling AOT or OSR, pretend the call using inline caches is polymorphic and
562 // do not generate a deopt.
563 //
564 // For AOT:
565 // Generating a deopt does not ensure that we will actually capture the new types;
566 // and the danger is that we could be stuck in a loop with "forever" deoptimizations.
567 // Take for example the following scenario:
568 // - we capture the inline cache in one run
569 // - the next run, we deoptimize because we miss a type check, but the method
570 // never becomes hot again
571 // In this case, the inline cache will not be updated in the profile and the AOT code
572 // will keep deoptimizing.
573 // Another scenario is if we use profile compilation for a process which is not allowed
574 // to JIT (e.g. system server). If we deoptimize we will run interpreted code for the
575 // rest of the lifetime.
576 // TODO(calin):
577 // This is a compromise because we will most likely never update the inline cache
578 // in the profile (unless there's another reason to deopt). So we might be stuck with
579 // a sub-optimal inline cache.
580 // We could be smarter when capturing inline caches to mitigate this.
581 // (e.g. by having different thresholds for new and old methods).
582 //
583 // For OSR:
584 // We may come from the interpreter and it may have seen different receiver types.
585 return Runtime::Current()->IsAotCompiler() || outermost_graph_->IsCompilingOsr();
586}
Calin Juravle13439f02017-02-21 01:17:21 -0800587bool HInliner::TryInlineFromInlineCache(const DexFile& caller_dex_file,
588 HInvoke* invoke_instruction,
589 ArtMethod* resolved_method)
590 REQUIRES_SHARED(Locks::mutator_lock_) {
Calin Juravlee2492d42017-03-20 11:42:13 -0700591 if (Runtime::Current()->IsAotCompiler() && !kUseAOTInlineCaches) {
592 return false;
593 }
594
Calin Juravle13439f02017-02-21 01:17:21 -0800595 StackHandleScope<1> hs(Thread::Current());
596 Handle<mirror::ObjectArray<mirror::Class>> inline_cache;
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +0000597 // The Zygote JIT compiles based on a profile, so we shouldn't use runtime inline caches
598 // for it.
599 InlineCacheType inline_cache_type =
600 (Runtime::Current()->IsAotCompiler() || Runtime::Current()->IsZygote())
601 ? GetInlineCacheAOT(caller_dex_file, invoke_instruction, &hs, &inline_cache)
602 : GetInlineCacheJIT(invoke_instruction, &hs, &inline_cache);
Calin Juravle13439f02017-02-21 01:17:21 -0800603
604 switch (inline_cache_type) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000605 case kInlineCacheNoData: {
606 LOG_FAIL_NO_STAT()
Nicolas Geoffrayd2f13ba2019-06-04 16:48:58 +0100607 << "No inline cache information for call to "
608 << caller_dex_file.PrettyMethod(invoke_instruction->GetDexMethodIndex());
Calin Juravle13439f02017-02-21 01:17:21 -0800609 return false;
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000610 }
Calin Juravle13439f02017-02-21 01:17:21 -0800611
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000612 case kInlineCacheUninitialized: {
613 LOG_FAIL_NO_STAT()
614 << "Interface or virtual call to "
615 << caller_dex_file.PrettyMethod(invoke_instruction->GetDexMethodIndex())
616 << " is not hit and not inlined";
617 return false;
618 }
619
620 case kInlineCacheMonomorphic: {
Vladimir Markocd09e1f2017-11-24 15:02:40 +0000621 MaybeRecordStat(stats_, MethodCompilationStat::kMonomorphicCall);
Calin Juravleaf44e6c2017-05-23 14:24:55 -0700622 if (UseOnlyPolymorphicInliningWithNoDeopt()) {
Calin Juravle13439f02017-02-21 01:17:21 -0800623 return TryInlinePolymorphicCall(invoke_instruction, resolved_method, inline_cache);
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000624 } else {
Calin Juravle13439f02017-02-21 01:17:21 -0800625 return TryInlineMonomorphicCall(invoke_instruction, resolved_method, inline_cache);
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000626 }
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000627 }
Calin Juravle13439f02017-02-21 01:17:21 -0800628
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000629 case kInlineCachePolymorphic: {
Vladimir Markocd09e1f2017-11-24 15:02:40 +0000630 MaybeRecordStat(stats_, MethodCompilationStat::kPolymorphicCall);
Calin Juravle13439f02017-02-21 01:17:21 -0800631 return TryInlinePolymorphicCall(invoke_instruction, resolved_method, inline_cache);
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000632 }
Calin Juravle13439f02017-02-21 01:17:21 -0800633
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000634 case kInlineCacheMegamorphic: {
635 LOG_FAIL_NO_STAT()
636 << "Interface or virtual call to "
637 << caller_dex_file.PrettyMethod(invoke_instruction->GetDexMethodIndex())
638 << " is megamorphic and not inlined";
Vladimir Markocd09e1f2017-11-24 15:02:40 +0000639 MaybeRecordStat(stats_, MethodCompilationStat::kMegamorphicCall);
Calin Juravle13439f02017-02-21 01:17:21 -0800640 return false;
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000641 }
Calin Juravle13439f02017-02-21 01:17:21 -0800642
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000643 case kInlineCacheMissingTypes: {
644 LOG_FAIL_NO_STAT()
645 << "Interface or virtual call to "
646 << caller_dex_file.PrettyMethod(invoke_instruction->GetDexMethodIndex())
647 << " is missing types and not inlined";
Calin Juravle13439f02017-02-21 01:17:21 -0800648 return false;
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000649 }
Calin Juravle13439f02017-02-21 01:17:21 -0800650 }
651 UNREACHABLE();
652}
653
654HInliner::InlineCacheType HInliner::GetInlineCacheJIT(
655 HInvoke* invoke_instruction,
656 StackHandleScope<1>* hs,
657 /*out*/Handle<mirror::ObjectArray<mirror::Class>>* inline_cache)
658 REQUIRES_SHARED(Locks::mutator_lock_) {
659 DCHECK(Runtime::Current()->UseJitCompilation());
660
661 ArtMethod* caller = graph_->GetArtMethod();
662 // Under JIT, we should always know the caller.
663 DCHECK(caller != nullptr);
664 ScopedProfilingInfoInlineUse spiis(caller, Thread::Current());
665 ProfilingInfo* profiling_info = spiis.GetProfilingInfo();
666
667 if (profiling_info == nullptr) {
668 return kInlineCacheNoData;
669 }
670
671 *inline_cache = AllocateInlineCacheHolder(caller_compilation_unit_, hs);
672 if (inline_cache->Get() == nullptr) {
673 // We can't extract any data if we failed to allocate;
674 return kInlineCacheNoData;
675 } else {
676 Runtime::Current()->GetJit()->GetCodeCache()->CopyInlineCacheInto(
677 *profiling_info->GetInlineCache(invoke_instruction->GetDexPc()),
678 *inline_cache);
679 return GetInlineCacheType(*inline_cache);
680 }
681}
682
683HInliner::InlineCacheType HInliner::GetInlineCacheAOT(
684 const DexFile& caller_dex_file,
685 HInvoke* invoke_instruction,
686 StackHandleScope<1>* hs,
687 /*out*/Handle<mirror::ObjectArray<mirror::Class>>* inline_cache)
688 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko1a2a5cd2018-11-07 15:39:48 +0000689 const ProfileCompilationInfo* pci = codegen_->GetCompilerOptions().GetProfileCompilationInfo();
Calin Juravle13439f02017-02-21 01:17:21 -0800690 if (pci == nullptr) {
691 return kInlineCacheNoData;
692 }
693
Calin Juravlecc3171a2017-05-19 16:47:53 -0700694 std::unique_ptr<ProfileCompilationInfo::OfflineProfileMethodInfo> offline_profile =
Calin Juravle4ad95212019-09-23 23:39:41 -0400695 pci->GetHotMethodInfo(MethodReference(
696 &caller_dex_file, caller_compilation_unit_.GetDexMethodIndex()));
Calin Juravlecc3171a2017-05-19 16:47:53 -0700697 if (offline_profile == nullptr) {
Calin Juravle13439f02017-02-21 01:17:21 -0800698 return kInlineCacheNoData; // no profile information for this invocation.
699 }
700
701 *inline_cache = AllocateInlineCacheHolder(caller_compilation_unit_, hs);
702 if (inline_cache == nullptr) {
703 // We can't extract any data if we failed to allocate;
704 return kInlineCacheNoData;
705 } else {
706 return ExtractClassesFromOfflineProfile(invoke_instruction,
Calin Juravlecc3171a2017-05-19 16:47:53 -0700707 *(offline_profile.get()),
Calin Juravle13439f02017-02-21 01:17:21 -0800708 *inline_cache);
709 }
710}
711
712HInliner::InlineCacheType HInliner::ExtractClassesFromOfflineProfile(
713 const HInvoke* invoke_instruction,
714 const ProfileCompilationInfo::OfflineProfileMethodInfo& offline_profile,
715 /*out*/Handle<mirror::ObjectArray<mirror::Class>> inline_cache)
716 REQUIRES_SHARED(Locks::mutator_lock_) {
Calin Juravlee6f87cc2017-05-24 17:41:05 -0700717 const auto it = offline_profile.inline_caches->find(invoke_instruction->GetDexPc());
718 if (it == offline_profile.inline_caches->end()) {
Calin Juravle13439f02017-02-21 01:17:21 -0800719 return kInlineCacheUninitialized;
720 }
721
722 const ProfileCompilationInfo::DexPcData& dex_pc_data = it->second;
723
724 if (dex_pc_data.is_missing_types) {
725 return kInlineCacheMissingTypes;
726 }
727 if (dex_pc_data.is_megamorphic) {
728 return kInlineCacheMegamorphic;
729 }
730
731 DCHECK_LE(dex_pc_data.classes.size(), InlineCache::kIndividualCacheSize);
732 Thread* self = Thread::Current();
733 // We need to resolve the class relative to the containing dex file.
734 // So first, build a mapping from the index of dex file in the profile to
735 // its dex cache. This will avoid repeating the lookup when walking over
736 // the inline cache types.
737 std::vector<ObjPtr<mirror::DexCache>> dex_profile_index_to_dex_cache(
738 offline_profile.dex_references.size());
739 for (size_t i = 0; i < offline_profile.dex_references.size(); i++) {
740 bool found = false;
Vladimir Marko213ee2d2018-06-22 11:56:34 +0100741 for (const DexFile* dex_file : codegen_->GetCompilerOptions().GetDexFilesForOatFile()) {
Calin Juravle13439f02017-02-21 01:17:21 -0800742 if (offline_profile.dex_references[i].MatchesDex(dex_file)) {
743 dex_profile_index_to_dex_cache[i] =
744 caller_compilation_unit_.GetClassLinker()->FindDexCache(self, *dex_file);
745 found = true;
746 }
747 }
748 if (!found) {
749 VLOG(compiler) << "Could not find profiled dex file: "
Calin Juravle4ba700a2019-09-16 15:45:17 -0700750 << offline_profile.dex_references[i].profile_key;
Calin Juravle13439f02017-02-21 01:17:21 -0800751 return kInlineCacheMissingTypes;
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100752 }
753 }
754
Calin Juravle13439f02017-02-21 01:17:21 -0800755 // Walk over the classes and resolve them. If we cannot find a type we return
756 // kInlineCacheMissingTypes.
757 int ic_index = 0;
758 for (const ProfileCompilationInfo::ClassReference& class_ref : dex_pc_data.classes) {
759 ObjPtr<mirror::DexCache> dex_cache =
760 dex_profile_index_to_dex_cache[class_ref.dex_profile_index];
761 DCHECK(dex_cache != nullptr);
Calin Juravle08556882017-05-26 16:40:45 -0700762
763 if (!dex_cache->GetDexFile()->IsTypeIndexValid(class_ref.type_index)) {
764 VLOG(compiler) << "Profile data corrupt: type index " << class_ref.type_index
765 << "is invalid in location" << dex_cache->GetDexFile()->GetLocation();
766 return kInlineCacheNoData;
767 }
Vladimir Marko666ee3d2017-12-11 18:37:36 +0000768 ObjPtr<mirror::Class> clazz = caller_compilation_unit_.GetClassLinker()->LookupResolvedType(
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000769 class_ref.type_index,
770 dex_cache,
771 caller_compilation_unit_.GetClassLoader().Get());
Calin Juravle13439f02017-02-21 01:17:21 -0800772 if (clazz != nullptr) {
773 inline_cache->Set(ic_index++, clazz);
774 } else {
775 VLOG(compiler) << "Could not resolve class from inline cache in AOT mode "
776 << caller_compilation_unit_.GetDexFile()->PrettyMethod(
777 invoke_instruction->GetDexMethodIndex()) << " : "
778 << caller_compilation_unit_
779 .GetDexFile()->StringByTypeIdx(class_ref.type_index);
780 return kInlineCacheMissingTypes;
781 }
782 }
783 return GetInlineCacheType(inline_cache);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100784}
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000785
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000786HInstanceFieldGet* HInliner::BuildGetReceiverClass(ClassLinker* class_linker,
787 HInstruction* receiver,
788 uint32_t dex_pc) const {
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100789 ArtField* field = GetClassRoot<mirror::Object>(class_linker)->GetInstanceField(0);
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000790 DCHECK_EQ(std::string(field->GetName()), "shadow$_klass_");
Vladimir Markoca6fff82017-10-03 14:49:14 +0100791 HInstanceFieldGet* result = new (graph_->GetAllocator()) HInstanceFieldGet(
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000792 receiver,
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +0000793 field,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100794 DataType::Type::kReference,
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000795 field->GetOffset(),
796 field->IsVolatile(),
797 field->GetDexFieldIndex(),
798 field->GetDeclaringClass()->GetDexClassDefIndex(),
799 *field->GetDexFile(),
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000800 dex_pc);
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000801 // The class of a field is effectively final, and does not have any memory dependencies.
802 result->SetSideEffects(SideEffects::None());
803 return result;
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000804}
805
Nicolas Geoffray4c0b4bc2017-03-17 13:08:26 +0000806static ArtMethod* ResolveMethodFromInlineCache(Handle<mirror::Class> klass,
807 ArtMethod* resolved_method,
808 HInstruction* invoke_instruction,
809 PointerSize pointer_size)
810 REQUIRES_SHARED(Locks::mutator_lock_) {
811 if (Runtime::Current()->IsAotCompiler()) {
812 // We can get unrelated types when working with profiles (corruption,
813 // systme updates, or anyone can write to it). So first check if the class
814 // actually implements the declaring class of the method that is being
815 // called in bytecode.
816 // Note: the lookup methods used below require to have assignable types.
817 if (!resolved_method->GetDeclaringClass()->IsAssignableFrom(klass.Get())) {
818 return nullptr;
819 }
820 }
821
822 if (invoke_instruction->IsInvokeInterface()) {
823 resolved_method = klass->FindVirtualMethodForInterface(resolved_method, pointer_size);
824 } else {
825 DCHECK(invoke_instruction->IsInvokeVirtual());
826 resolved_method = klass->FindVirtualMethodForVirtual(resolved_method, pointer_size);
827 }
828 DCHECK(resolved_method != nullptr);
829 return resolved_method;
830}
831
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100832bool HInliner::TryInlineMonomorphicCall(HInvoke* invoke_instruction,
833 ArtMethod* resolved_method,
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000834 Handle<mirror::ObjectArray<mirror::Class>> classes) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000835 DCHECK(invoke_instruction->IsInvokeVirtual() || invoke_instruction->IsInvokeInterface())
836 << invoke_instruction->DebugName();
837
Andreas Gampea5b09a62016-11-17 15:21:22 -0800838 dex::TypeIndex class_index = FindClassIndexIn(
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000839 GetMonomorphicType(classes), caller_compilation_unit_);
Andreas Gampea5b09a62016-11-17 15:21:22 -0800840 if (!class_index.IsValid()) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +0000841 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedDexCache)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000842 << "Call to " << ArtMethod::PrettyMethod(resolved_method)
843 << " from inline cache is not inlined because its class is not"
844 << " accessible to the caller";
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100845 return false;
846 }
847
848 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
Andreas Gampe542451c2016-07-26 09:02:02 -0700849 PointerSize pointer_size = class_linker->GetImagePointerSize();
Nicolas Geoffray4c0b4bc2017-03-17 13:08:26 +0000850 Handle<mirror::Class> monomorphic_type = handles_->NewHandle(GetMonomorphicType(classes));
851 resolved_method = ResolveMethodFromInlineCache(
852 monomorphic_type, resolved_method, invoke_instruction, pointer_size);
853
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000854 LOG_NOTE() << "Try inline monomorphic call to " << resolved_method->PrettyMethod();
Nicolas Geoffray4c0b4bc2017-03-17 13:08:26 +0000855 if (resolved_method == nullptr) {
856 // Bogus AOT profile, bail.
857 DCHECK(Runtime::Current()->IsAotCompiler());
858 return false;
859 }
860
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100861 HInstruction* receiver = invoke_instruction->InputAt(0);
862 HInstruction* cursor = invoke_instruction->GetPrevious();
863 HBasicBlock* bb_cursor = invoke_instruction->GetBlock();
Mingyao Yang063fc772016-08-02 11:02:54 -0700864 if (!TryInlineAndReplace(invoke_instruction,
865 resolved_method,
Andreas Gampe3db70682018-12-26 15:12:03 -0800866 ReferenceTypeInfo::Create(monomorphic_type, /* is_exact= */ true),
867 /* do_rtp= */ false,
868 /* cha_devirtualize= */ false)) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100869 return false;
870 }
871
872 // We successfully inlined, now add a guard.
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000873 AddTypeGuard(receiver,
874 cursor,
875 bb_cursor,
876 class_index,
Nicolas Geoffray5247c082017-01-13 14:17:29 +0000877 monomorphic_type,
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000878 invoke_instruction,
Andreas Gampe3db70682018-12-26 15:12:03 -0800879 /* with_deoptimization= */ true);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100880
881 // Run type propagation to get the guard typed, and eventually propagate the
882 // type of the receiver.
Vladimir Marko456307a2016-04-19 14:12:13 +0000883 ReferenceTypePropagation rtp_fixup(graph_,
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000884 outer_compilation_unit_.GetClassLoader(),
Vladimir Marko456307a2016-04-19 14:12:13 +0000885 outer_compilation_unit_.GetDexCache(),
886 handles_,
Andreas Gampe3db70682018-12-26 15:12:03 -0800887 /* is_first_run= */ false);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100888 rtp_fixup.Run();
889
Vladimir Markocd09e1f2017-11-24 15:02:40 +0000890 MaybeRecordStat(stats_, MethodCompilationStat::kInlinedMonomorphicCall);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100891 return true;
892}
893
Mingyao Yang063fc772016-08-02 11:02:54 -0700894void HInliner::AddCHAGuard(HInstruction* invoke_instruction,
895 uint32_t dex_pc,
896 HInstruction* cursor,
897 HBasicBlock* bb_cursor) {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100898 HShouldDeoptimizeFlag* deopt_flag = new (graph_->GetAllocator())
899 HShouldDeoptimizeFlag(graph_->GetAllocator(), dex_pc);
900 HInstruction* compare = new (graph_->GetAllocator()) HNotEqual(
Mingyao Yang063fc772016-08-02 11:02:54 -0700901 deopt_flag, graph_->GetIntConstant(0, dex_pc));
Vladimir Markoca6fff82017-10-03 14:49:14 +0100902 HInstruction* deopt = new (graph_->GetAllocator()) HDeoptimize(
903 graph_->GetAllocator(), compare, DeoptimizationKind::kCHA, dex_pc);
Mingyao Yang063fc772016-08-02 11:02:54 -0700904
905 if (cursor != nullptr) {
906 bb_cursor->InsertInstructionAfter(deopt_flag, cursor);
907 } else {
908 bb_cursor->InsertInstructionBefore(deopt_flag, bb_cursor->GetFirstInstruction());
909 }
Mingyao Yangb0b051a2016-11-17 09:04:53 -0800910 bb_cursor->InsertInstructionAfter(compare, deopt_flag);
911 bb_cursor->InsertInstructionAfter(deopt, compare);
912
913 // Add receiver as input to aid CHA guard optimization later.
914 deopt_flag->AddInput(invoke_instruction->InputAt(0));
915 DCHECK_EQ(deopt_flag->InputCount(), 1u);
Mingyao Yang063fc772016-08-02 11:02:54 -0700916 deopt->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
Mingyao Yangb0b051a2016-11-17 09:04:53 -0800917 outermost_graph_->IncrementNumberOfCHAGuards();
Mingyao Yang063fc772016-08-02 11:02:54 -0700918}
919
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000920HInstruction* HInliner::AddTypeGuard(HInstruction* receiver,
921 HInstruction* cursor,
922 HBasicBlock* bb_cursor,
Andreas Gampea5b09a62016-11-17 15:21:22 -0800923 dex::TypeIndex class_index,
Nicolas Geoffray5247c082017-01-13 14:17:29 +0000924 Handle<mirror::Class> klass,
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000925 HInstruction* invoke_instruction,
926 bool with_deoptimization) {
927 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
928 HInstanceFieldGet* receiver_class = BuildGetReceiverClass(
929 class_linker, receiver, invoke_instruction->GetDexPc());
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000930 if (cursor != nullptr) {
931 bb_cursor->InsertInstructionAfter(receiver_class, cursor);
932 } else {
933 bb_cursor->InsertInstructionBefore(receiver_class, bb_cursor->GetFirstInstruction());
934 }
Nicolas Geoffray56876342016-12-16 16:09:08 +0000935
936 const DexFile& caller_dex_file = *caller_compilation_unit_.GetDexFile();
Calin Juravle07f01df2017-04-28 19:58:01 -0700937 bool is_referrer;
938 ArtMethod* outermost_art_method = outermost_graph_->GetArtMethod();
939 if (outermost_art_method == nullptr) {
940 DCHECK(Runtime::Current()->IsAotCompiler());
941 // We are in AOT mode and we don't have an ART method to determine
942 // if the inlined method belongs to the referrer. Assume it doesn't.
943 is_referrer = false;
944 } else {
945 is_referrer = klass.Get() == outermost_art_method->GetDeclaringClass();
946 }
947
Nicolas Geoffray56876342016-12-16 16:09:08 +0000948 // Note that we will just compare the classes, so we don't need Java semantics access checks.
949 // Note that the type index and the dex file are relative to the method this type guard is
950 // inlined into.
Vladimir Markoca6fff82017-10-03 14:49:14 +0100951 HLoadClass* load_class = new (graph_->GetAllocator()) HLoadClass(graph_->GetCurrentMethod(),
952 class_index,
953 caller_dex_file,
954 klass,
955 is_referrer,
956 invoke_instruction->GetDexPc(),
Andreas Gampe3db70682018-12-26 15:12:03 -0800957 /* needs_access_check= */ false);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +0000958 HLoadClass::LoadKind kind = HSharpening::ComputeLoadClassKind(
Vladimir Markobb089b62018-06-28 17:30:16 +0100959 load_class, codegen_, caller_compilation_unit_);
Nicolas Geoffray83c8e272017-01-31 14:36:37 +0000960 DCHECK(kind != HLoadClass::LoadKind::kInvalid)
961 << "We should always be able to reference a class for inline caches";
Vladimir Marko28e012a2017-12-07 11:22:59 +0000962 // Load kind must be set before inserting the instruction into the graph.
Nicolas Geoffray83c8e272017-01-31 14:36:37 +0000963 load_class->SetLoadKind(kind);
Vladimir Marko28e012a2017-12-07 11:22:59 +0000964 bb_cursor->InsertInstructionAfter(load_class, receiver_class);
Calin Juravle13439f02017-02-21 01:17:21 -0800965 // In AOT mode, we will most likely load the class from BSS, which will involve a call
966 // to the runtime. In this case, the load instruction will need an environment so copy
967 // it from the invoke instruction.
968 if (load_class->NeedsEnvironment()) {
969 DCHECK(Runtime::Current()->IsAotCompiler());
970 load_class->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
971 }
Nicolas Geoffray56876342016-12-16 16:09:08 +0000972
Vladimir Markoca6fff82017-10-03 14:49:14 +0100973 HNotEqual* compare = new (graph_->GetAllocator()) HNotEqual(load_class, receiver_class);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000974 bb_cursor->InsertInstructionAfter(compare, load_class);
975 if (with_deoptimization) {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100976 HDeoptimize* deoptimize = new (graph_->GetAllocator()) HDeoptimize(
977 graph_->GetAllocator(),
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +0000978 compare,
979 receiver,
Nicolas Geoffray4e92c3c2017-05-08 09:34:26 +0100980 Runtime::Current()->IsAotCompiler()
981 ? DeoptimizationKind::kAotInlineCache
982 : DeoptimizationKind::kJitInlineCache,
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +0000983 invoke_instruction->GetDexPc());
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000984 bb_cursor->InsertInstructionAfter(deoptimize, compare);
985 deoptimize->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +0000986 DCHECK_EQ(invoke_instruction->InputAt(0), receiver);
987 receiver->ReplaceUsesDominatedBy(deoptimize, deoptimize);
988 deoptimize->SetReferenceTypeInfo(receiver->GetReferenceTypeInfo());
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000989 }
990 return compare;
991}
992
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000993bool HInliner::TryInlinePolymorphicCall(HInvoke* invoke_instruction,
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100994 ArtMethod* resolved_method,
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000995 Handle<mirror::ObjectArray<mirror::Class>> classes) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000996 DCHECK(invoke_instruction->IsInvokeVirtual() || invoke_instruction->IsInvokeInterface())
997 << invoke_instruction->DebugName();
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000998
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000999 if (TryInlinePolymorphicCallToSameTarget(invoke_instruction, resolved_method, classes)) {
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001000 return true;
1001 }
1002
1003 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
Andreas Gampe542451c2016-07-26 09:02:02 -07001004 PointerSize pointer_size = class_linker->GetImagePointerSize();
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001005
1006 bool all_targets_inlined = true;
1007 bool one_target_inlined = false;
1008 for (size_t i = 0; i < InlineCache::kIndividualCacheSize; ++i) {
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +00001009 if (classes->Get(i) == nullptr) {
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001010 break;
1011 }
1012 ArtMethod* method = nullptr;
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001013
1014 Handle<mirror::Class> handle = handles_->NewHandle(classes->Get(i));
Nicolas Geoffray4c0b4bc2017-03-17 13:08:26 +00001015 method = ResolveMethodFromInlineCache(
1016 handle, resolved_method, invoke_instruction, pointer_size);
1017 if (method == nullptr) {
1018 DCHECK(Runtime::Current()->IsAotCompiler());
1019 // AOT profile is bogus. This loop expects to iterate over all entries,
1020 // so just just continue.
1021 all_targets_inlined = false;
1022 continue;
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001023 }
1024
1025 HInstruction* receiver = invoke_instruction->InputAt(0);
1026 HInstruction* cursor = invoke_instruction->GetPrevious();
1027 HBasicBlock* bb_cursor = invoke_instruction->GetBlock();
1028
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001029 dex::TypeIndex class_index = FindClassIndexIn(handle.Get(), caller_compilation_unit_);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001030 HInstruction* return_replacement = nullptr;
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001031 LOG_NOTE() << "Try inline polymorphic call to " << method->PrettyMethod();
Andreas Gampea5b09a62016-11-17 15:21:22 -08001032 if (!class_index.IsValid() ||
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001033 !TryBuildAndInline(invoke_instruction,
1034 method,
Andreas Gampe3db70682018-12-26 15:12:03 -08001035 ReferenceTypeInfo::Create(handle, /* is_exact= */ true),
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001036 &return_replacement)) {
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001037 all_targets_inlined = false;
1038 } else {
1039 one_target_inlined = true;
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001040
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001041 LOG_SUCCESS() << "Polymorphic call to " << ArtMethod::PrettyMethod(resolved_method)
1042 << " has inlined " << ArtMethod::PrettyMethod(method);
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00001043
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001044 // If we have inlined all targets before, and this receiver is the last seen,
1045 // we deoptimize instead of keeping the original invoke instruction.
Calin Juravleaf44e6c2017-05-23 14:24:55 -07001046 bool deoptimize = !UseOnlyPolymorphicInliningWithNoDeopt() &&
1047 all_targets_inlined &&
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001048 (i != InlineCache::kIndividualCacheSize - 1) &&
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +00001049 (classes->Get(i + 1) == nullptr);
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01001050
Nicolas Geoffray56876342016-12-16 16:09:08 +00001051 HInstruction* compare = AddTypeGuard(receiver,
1052 cursor,
1053 bb_cursor,
1054 class_index,
Nicolas Geoffray5247c082017-01-13 14:17:29 +00001055 handle,
Nicolas Geoffray56876342016-12-16 16:09:08 +00001056 invoke_instruction,
1057 deoptimize);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001058 if (deoptimize) {
1059 if (return_replacement != nullptr) {
1060 invoke_instruction->ReplaceWith(return_replacement);
1061 }
1062 invoke_instruction->GetBlock()->RemoveInstruction(invoke_instruction);
1063 // Because the inline cache data can be populated concurrently, we force the end of the
Nicolas Geoffray4c0b4bc2017-03-17 13:08:26 +00001064 // iteration. Otherwise, we could see a new receiver type.
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001065 break;
1066 } else {
1067 CreateDiamondPatternForPolymorphicInline(compare, return_replacement, invoke_instruction);
1068 }
1069 }
1070 }
1071
1072 if (!one_target_inlined) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001073 LOG_FAIL_NO_STAT()
1074 << "Call to " << ArtMethod::PrettyMethod(resolved_method)
1075 << " from inline cache is not inlined because none"
1076 << " of its targets could be inlined";
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001077 return false;
1078 }
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00001079
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001080 MaybeRecordStat(stats_, MethodCompilationStat::kInlinedPolymorphicCall);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001081
1082 // Run type propagation to get the guards typed.
Vladimir Marko456307a2016-04-19 14:12:13 +00001083 ReferenceTypePropagation rtp_fixup(graph_,
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001084 outer_compilation_unit_.GetClassLoader(),
Vladimir Marko456307a2016-04-19 14:12:13 +00001085 outer_compilation_unit_.GetDexCache(),
1086 handles_,
Andreas Gampe3db70682018-12-26 15:12:03 -08001087 /* is_first_run= */ false);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001088 rtp_fixup.Run();
1089 return true;
1090}
1091
1092void HInliner::CreateDiamondPatternForPolymorphicInline(HInstruction* compare,
1093 HInstruction* return_replacement,
1094 HInstruction* invoke_instruction) {
1095 uint32_t dex_pc = invoke_instruction->GetDexPc();
1096 HBasicBlock* cursor_block = compare->GetBlock();
1097 HBasicBlock* original_invoke_block = invoke_instruction->GetBlock();
Vladimir Markoca6fff82017-10-03 14:49:14 +01001098 ArenaAllocator* allocator = graph_->GetAllocator();
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001099
1100 // Spit the block after the compare: `cursor_block` will now be the start of the diamond,
1101 // and the returned block is the start of the then branch (that could contain multiple blocks).
1102 HBasicBlock* then = cursor_block->SplitAfterForInlining(compare);
1103
1104 // Split the block containing the invoke before and after the invoke. The returned block
1105 // of the split before will contain the invoke and will be the otherwise branch of
1106 // the diamond. The returned block of the split after will be the merge block
1107 // of the diamond.
1108 HBasicBlock* end_then = invoke_instruction->GetBlock();
1109 HBasicBlock* otherwise = end_then->SplitBeforeForInlining(invoke_instruction);
1110 HBasicBlock* merge = otherwise->SplitAfterForInlining(invoke_instruction);
1111
1112 // If the methods we are inlining return a value, we create a phi in the merge block
1113 // that will have the `invoke_instruction and the `return_replacement` as inputs.
1114 if (return_replacement != nullptr) {
1115 HPhi* phi = new (allocator) HPhi(
1116 allocator, kNoRegNumber, 0, HPhi::ToPhiType(invoke_instruction->GetType()), dex_pc);
1117 merge->AddPhi(phi);
1118 invoke_instruction->ReplaceWith(phi);
1119 phi->AddInput(return_replacement);
1120 phi->AddInput(invoke_instruction);
1121 }
1122
1123 // Add the control flow instructions.
1124 otherwise->AddInstruction(new (allocator) HGoto(dex_pc));
1125 end_then->AddInstruction(new (allocator) HGoto(dex_pc));
1126 cursor_block->AddInstruction(new (allocator) HIf(compare, dex_pc));
1127
1128 // Add the newly created blocks to the graph.
1129 graph_->AddBlock(then);
1130 graph_->AddBlock(otherwise);
1131 graph_->AddBlock(merge);
1132
1133 // Set up successor (and implictly predecessor) relations.
1134 cursor_block->AddSuccessor(otherwise);
1135 cursor_block->AddSuccessor(then);
1136 end_then->AddSuccessor(merge);
1137 otherwise->AddSuccessor(merge);
1138
1139 // Set up dominance information.
1140 then->SetDominator(cursor_block);
1141 cursor_block->AddDominatedBlock(then);
1142 otherwise->SetDominator(cursor_block);
1143 cursor_block->AddDominatedBlock(otherwise);
1144 merge->SetDominator(cursor_block);
1145 cursor_block->AddDominatedBlock(merge);
1146
1147 // Update the revert post order.
1148 size_t index = IndexOfElement(graph_->reverse_post_order_, cursor_block);
1149 MakeRoomFor(&graph_->reverse_post_order_, 1, index);
1150 graph_->reverse_post_order_[++index] = then;
1151 index = IndexOfElement(graph_->reverse_post_order_, end_then);
1152 MakeRoomFor(&graph_->reverse_post_order_, 2, index);
1153 graph_->reverse_post_order_[++index] = otherwise;
1154 graph_->reverse_post_order_[++index] = merge;
1155
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001156
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00001157 graph_->UpdateLoopAndTryInformationOfNewBlock(
Andreas Gampe3db70682018-12-26 15:12:03 -08001158 then, original_invoke_block, /* replace_if_back_edge= */ false);
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00001159 graph_->UpdateLoopAndTryInformationOfNewBlock(
Andreas Gampe3db70682018-12-26 15:12:03 -08001160 otherwise, original_invoke_block, /* replace_if_back_edge= */ false);
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00001161
1162 // In case the original invoke location was a back edge, we need to update
1163 // the loop to now have the merge block as a back edge.
1164 graph_->UpdateLoopAndTryInformationOfNewBlock(
Andreas Gampe3db70682018-12-26 15:12:03 -08001165 merge, original_invoke_block, /* replace_if_back_edge= */ true);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001166}
1167
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +00001168bool HInliner::TryInlinePolymorphicCallToSameTarget(
1169 HInvoke* invoke_instruction,
1170 ArtMethod* resolved_method,
1171 Handle<mirror::ObjectArray<mirror::Class>> classes) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001172 // This optimization only works under JIT for now.
Calin Juravle13439f02017-02-21 01:17:21 -08001173 if (!Runtime::Current()->UseJitCompilation()) {
1174 return false;
1175 }
1176
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001177 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
Andreas Gampe542451c2016-07-26 09:02:02 -07001178 PointerSize pointer_size = class_linker->GetImagePointerSize();
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001179
1180 DCHECK(resolved_method != nullptr);
1181 ArtMethod* actual_method = nullptr;
Nicolas Geoffray4f97a212016-02-25 16:17:54 +00001182 size_t method_index = invoke_instruction->IsInvokeVirtual()
1183 ? invoke_instruction->AsInvokeVirtual()->GetVTableIndex()
1184 : invoke_instruction->AsInvokeInterface()->GetImtIndex();
1185
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001186 // Check whether we are actually calling the same method among
1187 // the different types seen.
1188 for (size_t i = 0; i < InlineCache::kIndividualCacheSize; ++i) {
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +00001189 if (classes->Get(i) == nullptr) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001190 break;
1191 }
1192 ArtMethod* new_method = nullptr;
1193 if (invoke_instruction->IsInvokeInterface()) {
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +00001194 new_method = classes->Get(i)->GetImt(pointer_size)->Get(
Matthew Gharrity465ecc82016-07-19 21:32:52 +00001195 method_index, pointer_size);
Nicolas Geoffray4f97a212016-02-25 16:17:54 +00001196 if (new_method->IsRuntimeMethod()) {
1197 // Bail out as soon as we see a conflict trampoline in one of the target's
1198 // interface table.
1199 return false;
1200 }
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001201 } else {
1202 DCHECK(invoke_instruction->IsInvokeVirtual());
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +00001203 new_method = classes->Get(i)->GetEmbeddedVTableEntry(method_index, pointer_size);
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001204 }
Nicolas Geoffray4f97a212016-02-25 16:17:54 +00001205 DCHECK(new_method != nullptr);
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001206 if (actual_method == nullptr) {
1207 actual_method = new_method;
1208 } else if (actual_method != new_method) {
1209 // Different methods, bailout.
1210 return false;
1211 }
1212 }
1213
1214 HInstruction* receiver = invoke_instruction->InputAt(0);
1215 HInstruction* cursor = invoke_instruction->GetPrevious();
1216 HBasicBlock* bb_cursor = invoke_instruction->GetBlock();
1217
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01001218 HInstruction* return_replacement = nullptr;
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001219 if (!TryBuildAndInline(invoke_instruction,
1220 actual_method,
1221 ReferenceTypeInfo::CreateInvalid(),
1222 &return_replacement)) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001223 return false;
1224 }
1225
1226 // We successfully inlined, now add a guard.
1227 HInstanceFieldGet* receiver_class = BuildGetReceiverClass(
1228 class_linker, receiver, invoke_instruction->GetDexPc());
1229
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001230 DataType::Type type = Is64BitInstructionSet(graph_->GetInstructionSet())
1231 ? DataType::Type::kInt64
1232 : DataType::Type::kInt32;
Vladimir Markoca6fff82017-10-03 14:49:14 +01001233 HClassTableGet* class_table_get = new (graph_->GetAllocator()) HClassTableGet(
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001234 receiver_class,
1235 type,
Vladimir Markoa1de9182016-02-25 11:37:38 +00001236 invoke_instruction->IsInvokeVirtual() ? HClassTableGet::TableKind::kVTable
1237 : HClassTableGet::TableKind::kIMTable,
Nicolas Geoffray4f97a212016-02-25 16:17:54 +00001238 method_index,
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001239 invoke_instruction->GetDexPc());
1240
1241 HConstant* constant;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001242 if (type == DataType::Type::kInt64) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001243 constant = graph_->GetLongConstant(
1244 reinterpret_cast<intptr_t>(actual_method), invoke_instruction->GetDexPc());
1245 } else {
1246 constant = graph_->GetIntConstant(
1247 reinterpret_cast<intptr_t>(actual_method), invoke_instruction->GetDexPc());
1248 }
1249
Vladimir Markoca6fff82017-10-03 14:49:14 +01001250 HNotEqual* compare = new (graph_->GetAllocator()) HNotEqual(class_table_get, constant);
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001251 if (cursor != nullptr) {
1252 bb_cursor->InsertInstructionAfter(receiver_class, cursor);
1253 } else {
1254 bb_cursor->InsertInstructionBefore(receiver_class, bb_cursor->GetFirstInstruction());
1255 }
1256 bb_cursor->InsertInstructionAfter(class_table_get, receiver_class);
1257 bb_cursor->InsertInstructionAfter(compare, class_table_get);
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01001258
1259 if (outermost_graph_->IsCompilingOsr()) {
1260 CreateDiamondPatternForPolymorphicInline(compare, return_replacement, invoke_instruction);
1261 } else {
Vladimir Markoca6fff82017-10-03 14:49:14 +01001262 HDeoptimize* deoptimize = new (graph_->GetAllocator()) HDeoptimize(
1263 graph_->GetAllocator(),
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +00001264 compare,
1265 receiver,
Nicolas Geoffray4e92c3c2017-05-08 09:34:26 +01001266 DeoptimizationKind::kJitSameTarget,
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +00001267 invoke_instruction->GetDexPc());
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01001268 bb_cursor->InsertInstructionAfter(deoptimize, compare);
1269 deoptimize->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
1270 if (return_replacement != nullptr) {
1271 invoke_instruction->ReplaceWith(return_replacement);
1272 }
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +00001273 receiver->ReplaceUsesDominatedBy(deoptimize, deoptimize);
Nicolas Geoffray1be7cbd2016-04-29 13:56:01 +01001274 invoke_instruction->GetBlock()->RemoveInstruction(invoke_instruction);
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +00001275 deoptimize->SetReferenceTypeInfo(receiver->GetReferenceTypeInfo());
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01001276 }
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001277
1278 // Run type propagation to get the guard typed.
Vladimir Marko456307a2016-04-19 14:12:13 +00001279 ReferenceTypePropagation rtp_fixup(graph_,
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001280 outer_compilation_unit_.GetClassLoader(),
Vladimir Marko456307a2016-04-19 14:12:13 +00001281 outer_compilation_unit_.GetDexCache(),
1282 handles_,
Andreas Gampe3db70682018-12-26 15:12:03 -08001283 /* is_first_run= */ false);
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001284 rtp_fixup.Run();
1285
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001286 MaybeRecordStat(stats_, MethodCompilationStat::kInlinedPolymorphicCall);
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001287
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001288 LOG_SUCCESS() << "Inlined same polymorphic target " << actual_method->PrettyMethod();
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001289 return true;
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001290}
1291
Mingyao Yang063fc772016-08-02 11:02:54 -07001292bool HInliner::TryInlineAndReplace(HInvoke* invoke_instruction,
1293 ArtMethod* method,
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001294 ReferenceTypeInfo receiver_type,
Mingyao Yang063fc772016-08-02 11:02:54 -07001295 bool do_rtp,
1296 bool cha_devirtualize) {
Mingyao Yang6b1aebe2017-11-27 15:39:04 -08001297 DCHECK(!invoke_instruction->IsIntrinsic());
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001298 HInstruction* return_replacement = nullptr;
Mingyao Yang063fc772016-08-02 11:02:54 -07001299 uint32_t dex_pc = invoke_instruction->GetDexPc();
1300 HInstruction* cursor = invoke_instruction->GetPrevious();
1301 HBasicBlock* bb_cursor = invoke_instruction->GetBlock();
Mingyao Yang6b1aebe2017-11-27 15:39:04 -08001302 bool should_remove_invoke_instruction = false;
1303
1304 // If invoke_instruction is devirtualized to a different method, give intrinsics
1305 // another chance before we try to inline it.
Nicolas Geoffray76d4bb0f32018-09-21 12:58:45 +01001306 if (invoke_instruction->GetResolvedMethod() != method && method->IsIntrinsic()) {
Mingyao Yang6b1aebe2017-11-27 15:39:04 -08001307 MaybeRecordStat(stats_, MethodCompilationStat::kIntrinsicRecognized);
1308 if (invoke_instruction->IsInvokeInterface()) {
1309 // We don't intrinsify an invoke-interface directly.
1310 // Replace the invoke-interface with an invoke-virtual.
1311 HInvokeVirtual* new_invoke = new (graph_->GetAllocator()) HInvokeVirtual(
1312 graph_->GetAllocator(),
1313 invoke_instruction->GetNumberOfArguments(),
1314 invoke_instruction->GetType(),
1315 invoke_instruction->GetDexPc(),
1316 invoke_instruction->GetDexMethodIndex(), // Use interface method's dex method index.
1317 method,
1318 method->GetMethodIndex());
Nicolas Geoffray76d4bb0f32018-09-21 12:58:45 +01001319 DCHECK_NE(new_invoke->GetIntrinsic(), Intrinsics::kNone);
Mingyao Yang6b1aebe2017-11-27 15:39:04 -08001320 HInputsRef inputs = invoke_instruction->GetInputs();
1321 for (size_t index = 0; index != inputs.size(); ++index) {
1322 new_invoke->SetArgumentAt(index, inputs[index]);
1323 }
1324 invoke_instruction->GetBlock()->InsertInstructionBefore(new_invoke, invoke_instruction);
1325 new_invoke->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
1326 if (invoke_instruction->GetType() == DataType::Type::kReference) {
1327 new_invoke->SetReferenceTypeInfo(invoke_instruction->GetReferenceTypeInfo());
1328 }
Mingyao Yang6b1aebe2017-11-27 15:39:04 -08001329 return_replacement = new_invoke;
1330 // invoke_instruction is replaced with new_invoke.
1331 should_remove_invoke_instruction = true;
1332 } else {
Nicolas Geoffray76d4bb0f32018-09-21 12:58:45 +01001333 invoke_instruction->SetResolvedMethod(method);
Mingyao Yang6b1aebe2017-11-27 15:39:04 -08001334 }
1335 } else if (!TryBuildAndInline(invoke_instruction, method, receiver_type, &return_replacement)) {
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +00001336 if (invoke_instruction->IsInvokeInterface()) {
Nicolas Geoffray18ea1c92017-03-27 08:00:18 +00001337 DCHECK(!method->IsProxyMethod());
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +00001338 // Turn an invoke-interface into an invoke-virtual. An invoke-virtual is always
1339 // better than an invoke-interface because:
1340 // 1) In the best case, the interface call has one more indirection (to fetch the IMT).
1341 // 2) We will not go to the conflict trampoline with an invoke-virtual.
1342 // TODO: Consider sharpening once it is not dependent on the compiler driver.
Nicolas Geoffray18ea1c92017-03-27 08:00:18 +00001343
1344 if (method->IsDefault() && !method->IsCopied()) {
1345 // Changing to invoke-virtual cannot be done on an original default method
1346 // since it's not in any vtable. Devirtualization by exact type/inline-cache
1347 // always uses a method in the iftable which is never an original default
1348 // method.
1349 // On the other hand, inlining an original default method by CHA is fine.
1350 DCHECK(cha_devirtualize);
1351 return false;
1352 }
1353
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +00001354 const DexFile& caller_dex_file = *caller_compilation_unit_.GetDexFile();
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +01001355 uint32_t dex_method_index = FindMethodIndexIn(
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +00001356 method, caller_dex_file, invoke_instruction->GetDexMethodIndex());
Andreas Gampee2abbc62017-09-15 11:59:26 -07001357 if (dex_method_index == dex::kDexNoIndex) {
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +00001358 return false;
1359 }
Vladimir Markoca6fff82017-10-03 14:49:14 +01001360 HInvokeVirtual* new_invoke = new (graph_->GetAllocator()) HInvokeVirtual(
1361 graph_->GetAllocator(),
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +00001362 invoke_instruction->GetNumberOfArguments(),
1363 invoke_instruction->GetType(),
1364 invoke_instruction->GetDexPc(),
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +01001365 dex_method_index,
1366 method,
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +00001367 method->GetMethodIndex());
1368 HInputsRef inputs = invoke_instruction->GetInputs();
1369 for (size_t index = 0; index != inputs.size(); ++index) {
1370 new_invoke->SetArgumentAt(index, inputs[index]);
1371 }
1372 invoke_instruction->GetBlock()->InsertInstructionBefore(new_invoke, invoke_instruction);
1373 new_invoke->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001374 if (invoke_instruction->GetType() == DataType::Type::kReference) {
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +00001375 new_invoke->SetReferenceTypeInfo(invoke_instruction->GetReferenceTypeInfo());
1376 }
1377 return_replacement = new_invoke;
Mingyao Yang6b1aebe2017-11-27 15:39:04 -08001378 // invoke_instruction is replaced with new_invoke.
1379 should_remove_invoke_instruction = true;
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +00001380 } else {
1381 // TODO: Consider sharpening an invoke virtual once it is not dependent on the
1382 // compiler driver.
1383 return false;
1384 }
Mingyao Yang6b1aebe2017-11-27 15:39:04 -08001385 } else {
1386 // invoke_instruction is inlined.
1387 should_remove_invoke_instruction = true;
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001388 }
Mingyao Yang6b1aebe2017-11-27 15:39:04 -08001389
Mingyao Yang063fc772016-08-02 11:02:54 -07001390 if (cha_devirtualize) {
1391 AddCHAGuard(invoke_instruction, dex_pc, cursor, bb_cursor);
1392 }
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001393 if (return_replacement != nullptr) {
1394 invoke_instruction->ReplaceWith(return_replacement);
1395 }
Mingyao Yang6b1aebe2017-11-27 15:39:04 -08001396 if (should_remove_invoke_instruction) {
1397 invoke_instruction->GetBlock()->RemoveInstruction(invoke_instruction);
1398 }
David Brazdil94ab38f2016-06-21 17:48:19 +01001399 FixUpReturnReferenceType(method, return_replacement);
1400 if (do_rtp && ReturnTypeMoreSpecific(invoke_instruction, return_replacement)) {
1401 // Actual return value has a more specific type than the method's declared
1402 // return type. Run RTP again on the outer graph to propagate it.
1403 ReferenceTypePropagation(graph_,
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001404 outer_compilation_unit_.GetClassLoader(),
David Brazdil94ab38f2016-06-21 17:48:19 +01001405 outer_compilation_unit_.GetDexCache(),
1406 handles_,
Andreas Gampe3db70682018-12-26 15:12:03 -08001407 /* is_first_run= */ false).Run();
David Brazdil94ab38f2016-06-21 17:48:19 +01001408 }
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001409 return true;
1410}
1411
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001412size_t HInliner::CountRecursiveCallsOf(ArtMethod* method) const {
1413 const HInliner* current = this;
1414 size_t count = 0;
1415 do {
1416 if (current->graph_->GetArtMethod() == method) {
1417 ++count;
1418 }
1419 current = current->parent_;
1420 } while (current != nullptr);
1421 return count;
1422}
1423
Vladimir Marko213ee2d2018-06-22 11:56:34 +01001424static inline bool MayInline(const CompilerOptions& compiler_options,
1425 const DexFile& inlined_from,
1426 const DexFile& inlined_into) {
Vladimir Marko213ee2d2018-06-22 11:56:34 +01001427 // We're not allowed to inline across dex files if we're the no-inline-from dex file.
1428 if (!IsSameDexFile(inlined_from, inlined_into) &&
1429 ContainsElement(compiler_options.GetNoInlineFromDexFile(), &inlined_from)) {
1430 return false;
1431 }
1432
1433 return true;
1434}
1435
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001436bool HInliner::TryBuildAndInline(HInvoke* invoke_instruction,
1437 ArtMethod* method,
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001438 ReferenceTypeInfo receiver_type,
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001439 HInstruction** return_replacement) {
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01001440 if (method->IsProxyMethod()) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001441 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedProxy)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001442 << "Method " << method->PrettyMethod()
1443 << " is not inlined because of unimplemented inline support for proxy methods.";
1444 return false;
1445 }
1446
1447 if (CountRecursiveCallsOf(method) > kMaximumNumberOfRecursiveCalls) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001448 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedRecursiveBudget)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001449 << "Method "
1450 << method->PrettyMethod()
1451 << " is not inlined because it has reached its recursive call budget.";
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01001452 return false;
1453 }
1454
Jeff Haodcdc85b2015-12-04 14:06:18 -08001455 // Check whether we're allowed to inline. The outermost compilation unit is the relevant
1456 // dex file here (though the transitivity of an inline chain would allow checking the calller).
Vladimir Marko213ee2d2018-06-22 11:56:34 +01001457 if (!MayInline(codegen_->GetCompilerOptions(),
1458 *method->GetDexFile(),
1459 *outer_compilation_unit_.GetDexFile())) {
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001460 if (TryPatternSubstitution(invoke_instruction, method, return_replacement)) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001461 LOG_SUCCESS() << "Successfully replaced pattern of invoke "
1462 << method->PrettyMethod();
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001463 MaybeRecordStat(stats_, MethodCompilationStat::kReplacedInvokeWithSimplePattern);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001464 return true;
1465 }
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001466 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedWont)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001467 << "Won't inline " << method->PrettyMethod() << " in "
1468 << outer_compilation_unit_.GetDexFile()->GetLocation() << " ("
1469 << caller_compilation_unit_.GetDexFile()->GetLocation() << ") from "
1470 << method->GetDexFile()->GetLocation();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001471 return false;
1472 }
1473
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001474 bool same_dex_file = IsSameDexFile(*outer_compilation_unit_.GetDexFile(), *method->GetDexFile());
1475
David Sehr0225f8e2018-01-31 08:52:24 +00001476 CodeItemDataAccessor accessor(method->DexInstructionData());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001477
Mathieu Chartier808c7a52017-12-15 11:19:33 -08001478 if (!accessor.HasCodeItem()) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001479 LOG_FAIL_NO_STAT()
1480 << "Method " << method->PrettyMethod() << " is not inlined because it is native";
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001481 return false;
1482 }
1483
Vladimir Marko213ee2d2018-06-22 11:56:34 +01001484 size_t inline_max_code_units = codegen_->GetCompilerOptions().GetInlineMaxCodeUnits();
Mathieu Chartier808c7a52017-12-15 11:19:33 -08001485 if (accessor.InsnsSizeInCodeUnits() > inline_max_code_units) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001486 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedCodeItem)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001487 << "Method " << method->PrettyMethod()
1488 << " is not inlined because its code item is too big: "
Mathieu Chartier808c7a52017-12-15 11:19:33 -08001489 << accessor.InsnsSizeInCodeUnits()
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001490 << " > "
1491 << inline_max_code_units;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001492 return false;
1493 }
1494
Mathieu Chartier808c7a52017-12-15 11:19:33 -08001495 if (accessor.TriesSize() != 0) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001496 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedTryCatch)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001497 << "Method " << method->PrettyMethod() << " is not inlined because of try block";
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001498 return false;
1499 }
1500
Nicolas Geoffray250a3782016-04-20 16:27:53 +01001501 if (!method->IsCompilable()) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001502 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedNotVerified)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001503 << "Method " << method->PrettyMethod()
1504 << " has soft failures un-handled by the compiler, so it cannot be inlined";
Aart Bik897df032018-02-07 13:29:11 -08001505 return false;
Nicolas Geoffray250a3782016-04-20 16:27:53 +01001506 }
1507
Vladimir Marko2afaff72018-11-30 17:01:50 +00001508 if (IsMethodUnverified(codegen_->GetCompilerOptions(), method)) {
Aart Bik2c148f02018-02-02 14:30:35 -08001509 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedNotVerified)
1510 << "Method " << method->PrettyMethod()
1511 << " couldn't be verified, so it cannot be inlined";
1512 return false;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001513 }
1514
Roland Levillain4c0eb422015-04-24 16:43:49 +01001515 if (invoke_instruction->IsInvokeStaticOrDirect() &&
1516 invoke_instruction->AsInvokeStaticOrDirect()->IsStaticWithImplicitClinitCheck()) {
1517 // Case of a static method that cannot be inlined because it implicitly
1518 // requires an initialization check of its declaring class.
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001519 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedDexCache)
1520 << "Method " << method->PrettyMethod()
1521 << " is not inlined because it is static and requires a clinit"
1522 << " check that cannot be emitted due to Dex cache limitations";
Roland Levillain4c0eb422015-04-24 16:43:49 +01001523 return false;
1524 }
1525
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001526 if (!TryBuildAndInlineHelper(
1527 invoke_instruction, method, receiver_type, same_dex_file, return_replacement)) {
Nicolas Geoffrayc0365b12015-03-18 18:31:52 +00001528 return false;
1529 }
1530
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001531 LOG_SUCCESS() << method->PrettyMethod();
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001532 MaybeRecordStat(stats_, MethodCompilationStat::kInlinedInvoke);
Nicolas Geoffrayc0365b12015-03-18 18:31:52 +00001533 return true;
1534}
1535
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001536static HInstruction* GetInvokeInputForArgVRegIndex(HInvoke* invoke_instruction,
1537 size_t arg_vreg_index)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001538 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001539 size_t input_index = 0;
1540 for (size_t i = 0; i < arg_vreg_index; ++i, ++input_index) {
1541 DCHECK_LT(input_index, invoke_instruction->GetNumberOfArguments());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001542 if (DataType::Is64BitType(invoke_instruction->InputAt(input_index)->GetType())) {
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001543 ++i;
1544 DCHECK_NE(i, arg_vreg_index);
1545 }
1546 }
1547 DCHECK_LT(input_index, invoke_instruction->GetNumberOfArguments());
1548 return invoke_instruction->InputAt(input_index);
1549}
1550
1551// Try to recognize known simple patterns and replace invoke call with appropriate instructions.
1552bool HInliner::TryPatternSubstitution(HInvoke* invoke_instruction,
1553 ArtMethod* resolved_method,
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001554 HInstruction** return_replacement) {
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001555 InlineMethod inline_method;
1556 if (!InlineMethodAnalyser::AnalyseMethodCode(resolved_method, &inline_method)) {
1557 return false;
1558 }
1559
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001560 switch (inline_method.opcode) {
1561 case kInlineOpNop:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001562 DCHECK_EQ(invoke_instruction->GetType(), DataType::Type::kVoid);
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001563 *return_replacement = nullptr;
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001564 break;
1565 case kInlineOpReturnArg:
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001566 *return_replacement = GetInvokeInputForArgVRegIndex(invoke_instruction,
1567 inline_method.d.return_data.arg);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001568 break;
1569 case kInlineOpNonWideConst:
1570 if (resolved_method->GetShorty()[0] == 'L') {
1571 DCHECK_EQ(inline_method.d.data, 0u);
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001572 *return_replacement = graph_->GetNullConstant();
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001573 } else {
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001574 *return_replacement = graph_->GetIntConstant(static_cast<int32_t>(inline_method.d.data));
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001575 }
1576 break;
1577 case kInlineOpIGet: {
1578 const InlineIGetIPutData& data = inline_method.d.ifield_data;
1579 if (data.method_is_static || data.object_arg != 0u) {
1580 // TODO: Needs null check.
1581 return false;
1582 }
1583 HInstruction* obj = GetInvokeInputForArgVRegIndex(invoke_instruction, data.object_arg);
Vladimir Markof44d36c2017-03-14 14:18:46 +00001584 HInstanceFieldGet* iget = CreateInstanceFieldGet(data.field_idx, resolved_method, obj);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001585 DCHECK_EQ(iget->GetFieldOffset().Uint32Value(), data.field_offset);
1586 DCHECK_EQ(iget->IsVolatile() ? 1u : 0u, data.is_volatile);
1587 invoke_instruction->GetBlock()->InsertInstructionBefore(iget, invoke_instruction);
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001588 *return_replacement = iget;
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001589 break;
1590 }
1591 case kInlineOpIPut: {
1592 const InlineIGetIPutData& data = inline_method.d.ifield_data;
1593 if (data.method_is_static || data.object_arg != 0u) {
1594 // TODO: Needs null check.
1595 return false;
1596 }
1597 HInstruction* obj = GetInvokeInputForArgVRegIndex(invoke_instruction, data.object_arg);
1598 HInstruction* value = GetInvokeInputForArgVRegIndex(invoke_instruction, data.src_arg);
Vladimir Markof44d36c2017-03-14 14:18:46 +00001599 HInstanceFieldSet* iput = CreateInstanceFieldSet(data.field_idx, resolved_method, obj, value);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001600 DCHECK_EQ(iput->GetFieldOffset().Uint32Value(), data.field_offset);
1601 DCHECK_EQ(iput->IsVolatile() ? 1u : 0u, data.is_volatile);
1602 invoke_instruction->GetBlock()->InsertInstructionBefore(iput, invoke_instruction);
1603 if (data.return_arg_plus1 != 0u) {
1604 size_t return_arg = data.return_arg_plus1 - 1u;
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001605 *return_replacement = GetInvokeInputForArgVRegIndex(invoke_instruction, return_arg);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001606 }
1607 break;
1608 }
Vladimir Marko354efa62016-02-04 19:46:56 +00001609 case kInlineOpConstructor: {
1610 const InlineConstructorData& data = inline_method.d.constructor_data;
1611 // Get the indexes to arrays for easier processing.
1612 uint16_t iput_field_indexes[] = {
1613 data.iput0_field_index, data.iput1_field_index, data.iput2_field_index
1614 };
1615 uint16_t iput_args[] = { data.iput0_arg, data.iput1_arg, data.iput2_arg };
1616 static_assert(arraysize(iput_args) == arraysize(iput_field_indexes), "Size mismatch");
1617 // Count valid field indexes.
1618 size_t number_of_iputs = 0u;
1619 while (number_of_iputs != arraysize(iput_field_indexes) &&
1620 iput_field_indexes[number_of_iputs] != DexFile::kDexNoIndex16) {
1621 // Check that there are no duplicate valid field indexes.
1622 DCHECK_EQ(0, std::count(iput_field_indexes + number_of_iputs + 1,
1623 iput_field_indexes + arraysize(iput_field_indexes),
1624 iput_field_indexes[number_of_iputs]));
1625 ++number_of_iputs;
1626 }
1627 // Check that there are no valid field indexes in the rest of the array.
1628 DCHECK_EQ(0, std::count_if(iput_field_indexes + number_of_iputs,
1629 iput_field_indexes + arraysize(iput_field_indexes),
1630 [](uint16_t index) { return index != DexFile::kDexNoIndex16; }));
1631
1632 // Create HInstanceFieldSet for each IPUT that stores non-zero data.
Andreas Gampe3db70682018-12-26 15:12:03 -08001633 HInstruction* obj = GetInvokeInputForArgVRegIndex(invoke_instruction,
1634 /* arg_vreg_index= */ 0u);
Vladimir Marko354efa62016-02-04 19:46:56 +00001635 bool needs_constructor_barrier = false;
1636 for (size_t i = 0; i != number_of_iputs; ++i) {
1637 HInstruction* value = GetInvokeInputForArgVRegIndex(invoke_instruction, iput_args[i]);
Roland Levillain1a653882016-03-18 18:05:57 +00001638 if (!value->IsConstant() || !value->AsConstant()->IsZeroBitPattern()) {
Vladimir Marko354efa62016-02-04 19:46:56 +00001639 uint16_t field_index = iput_field_indexes[i];
Vladimir Markof44d36c2017-03-14 14:18:46 +00001640 bool is_final;
1641 HInstanceFieldSet* iput =
1642 CreateInstanceFieldSet(field_index, resolved_method, obj, value, &is_final);
Vladimir Marko354efa62016-02-04 19:46:56 +00001643 invoke_instruction->GetBlock()->InsertInstructionBefore(iput, invoke_instruction);
1644
1645 // Check whether the field is final. If it is, we need to add a barrier.
Vladimir Markof44d36c2017-03-14 14:18:46 +00001646 if (is_final) {
Vladimir Marko354efa62016-02-04 19:46:56 +00001647 needs_constructor_barrier = true;
1648 }
1649 }
1650 }
1651 if (needs_constructor_barrier) {
Vladimir Marko1a2a5cd2018-11-07 15:39:48 +00001652 // See DexCompilationUnit::RequiresConstructorBarrier for more details.
Igor Murashkind01745e2017-04-05 16:40:31 -07001653 DCHECK(obj != nullptr) << "only non-static methods can have a constructor fence";
1654
1655 HConstructorFence* constructor_fence =
Vladimir Markoca6fff82017-10-03 14:49:14 +01001656 new (graph_->GetAllocator()) HConstructorFence(obj, kNoDexPc, graph_->GetAllocator());
Igor Murashkind01745e2017-04-05 16:40:31 -07001657 invoke_instruction->GetBlock()->InsertInstructionBefore(constructor_fence,
1658 invoke_instruction);
Vladimir Marko354efa62016-02-04 19:46:56 +00001659 }
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001660 *return_replacement = nullptr;
Vladimir Marko354efa62016-02-04 19:46:56 +00001661 break;
1662 }
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001663 default:
1664 LOG(FATAL) << "UNREACHABLE";
1665 UNREACHABLE();
1666 }
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001667 return true;
1668}
1669
Vladimir Markof44d36c2017-03-14 14:18:46 +00001670HInstanceFieldGet* HInliner::CreateInstanceFieldGet(uint32_t field_index,
1671 ArtMethod* referrer,
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001672 HInstruction* obj)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001673 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markof44d36c2017-03-14 14:18:46 +00001674 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1675 ArtField* resolved_field =
Andreas Gampe3db70682018-12-26 15:12:03 -08001676 class_linker->LookupResolvedField(field_index, referrer, /* is_static= */ false);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001677 DCHECK(resolved_field != nullptr);
Vladimir Markoca6fff82017-10-03 14:49:14 +01001678 HInstanceFieldGet* iget = new (graph_->GetAllocator()) HInstanceFieldGet(
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001679 obj,
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00001680 resolved_field,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001681 DataType::FromShorty(resolved_field->GetTypeDescriptor()[0]),
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001682 resolved_field->GetOffset(),
1683 resolved_field->IsVolatile(),
1684 field_index,
1685 resolved_field->GetDeclaringClass()->GetDexClassDefIndex(),
Vladimir Markof44d36c2017-03-14 14:18:46 +00001686 *referrer->GetDexFile(),
Vladimir Markoadda4352016-01-29 10:24:41 +00001687 // Read barrier generates a runtime call in slow path and we need a valid
1688 // dex pc for the associated stack map. 0 is bogus but valid. Bug: 26854537.
Andreas Gampe3db70682018-12-26 15:12:03 -08001689 /* dex_pc= */ 0);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001690 if (iget->GetType() == DataType::Type::kReference) {
Vladimir Marko456307a2016-04-19 14:12:13 +00001691 // Use the same dex_cache that we used for field lookup as the hint_dex_cache.
Vladimir Markof44d36c2017-03-14 14:18:46 +00001692 Handle<mirror::DexCache> dex_cache = handles_->NewHandle(referrer->GetDexCache());
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001693 ReferenceTypePropagation rtp(graph_,
1694 outer_compilation_unit_.GetClassLoader(),
1695 dex_cache,
1696 handles_,
Andreas Gampe3db70682018-12-26 15:12:03 -08001697 /* is_first_run= */ false);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001698 rtp.Visit(iget);
1699 }
1700 return iget;
1701}
1702
Vladimir Markof44d36c2017-03-14 14:18:46 +00001703HInstanceFieldSet* HInliner::CreateInstanceFieldSet(uint32_t field_index,
1704 ArtMethod* referrer,
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001705 HInstruction* obj,
Vladimir Markof44d36c2017-03-14 14:18:46 +00001706 HInstruction* value,
1707 bool* is_final)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001708 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markof44d36c2017-03-14 14:18:46 +00001709 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1710 ArtField* resolved_field =
Andreas Gampe3db70682018-12-26 15:12:03 -08001711 class_linker->LookupResolvedField(field_index, referrer, /* is_static= */ false);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001712 DCHECK(resolved_field != nullptr);
Vladimir Markof44d36c2017-03-14 14:18:46 +00001713 if (is_final != nullptr) {
1714 // This information is needed only for constructors.
1715 DCHECK(referrer->IsConstructor());
1716 *is_final = resolved_field->IsFinal();
1717 }
Vladimir Markoca6fff82017-10-03 14:49:14 +01001718 HInstanceFieldSet* iput = new (graph_->GetAllocator()) HInstanceFieldSet(
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001719 obj,
1720 value,
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00001721 resolved_field,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001722 DataType::FromShorty(resolved_field->GetTypeDescriptor()[0]),
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001723 resolved_field->GetOffset(),
1724 resolved_field->IsVolatile(),
1725 field_index,
1726 resolved_field->GetDeclaringClass()->GetDexClassDefIndex(),
Vladimir Markof44d36c2017-03-14 14:18:46 +00001727 *referrer->GetDexFile(),
Vladimir Markoadda4352016-01-29 10:24:41 +00001728 // Read barrier generates a runtime call in slow path and we need a valid
1729 // dex pc for the associated stack map. 0 is bogus but valid. Bug: 26854537.
Andreas Gampe3db70682018-12-26 15:12:03 -08001730 /* dex_pc= */ 0);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001731 return iput;
1732}
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +00001733
Vladimir Markob1d0ee12017-04-20 19:50:32 +01001734template <typename T>
Vladimir Markoc524e9e2019-03-26 10:54:50 +00001735static inline Handle<T> NewHandleIfDifferent(ObjPtr<T> object,
Vladimir Markob1d0ee12017-04-20 19:50:32 +01001736 Handle<T> hint,
1737 VariableSizedHandleScope* handles)
1738 REQUIRES_SHARED(Locks::mutator_lock_) {
1739 return (object != hint.Get()) ? handles->NewHandle(object) : hint;
1740}
1741
Vladimir Marko6be1dbd2018-11-13 13:09:51 +00001742static bool CanEncodeInlinedMethodInStackMap(const DexFile& caller_dex_file, ArtMethod* callee)
1743 REQUIRES_SHARED(Locks::mutator_lock_) {
1744 if (!Runtime::Current()->IsAotCompiler()) {
1745 // JIT can always encode methods in stack maps.
1746 return true;
1747 }
1748 if (IsSameDexFile(caller_dex_file, *callee->GetDexFile())) {
1749 return true;
1750 }
1751 // TODO(ngeoffray): Support more AOT cases for inlining:
1752 // - methods in multidex
1753 // - methods in boot image for on-device non-PIC compilation.
1754 return false;
1755}
1756
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001757bool HInliner::TryBuildAndInlineHelper(HInvoke* invoke_instruction,
1758 ArtMethod* resolved_method,
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001759 ReferenceTypeInfo receiver_type,
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001760 bool same_dex_file,
1761 HInstruction** return_replacement) {
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001762 DCHECK(!(resolved_method->IsStatic() && receiver_type.IsValid()));
Nicolas Geoffrayc0365b12015-03-18 18:31:52 +00001763 ScopedObjectAccess soa(Thread::Current());
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08001764 const dex::CodeItem* code_item = resolved_method->GetCodeItem();
Guillaume "Vermeille" Sanchezae09d2d2015-05-29 10:52:55 +01001765 const DexFile& callee_dex_file = *resolved_method->GetDexFile();
1766 uint32_t method_index = resolved_method->GetDexMethodIndex();
David Sehr0225f8e2018-01-31 08:52:24 +00001767 CodeItemDebugInfoAccessor code_item_accessor(resolved_method->DexInstructionDebugInfo());
Calin Juravle2e768302015-07-28 14:41:11 +00001768 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
Vladimir Markob1d0ee12017-04-20 19:50:32 +01001769 Handle<mirror::DexCache> dex_cache = NewHandleIfDifferent(resolved_method->GetDexCache(),
1770 caller_compilation_unit_.GetDexCache(),
1771 handles_);
1772 Handle<mirror::ClassLoader> class_loader =
1773 NewHandleIfDifferent(resolved_method->GetDeclaringClass()->GetClassLoader(),
1774 caller_compilation_unit_.GetClassLoader(),
1775 handles_);
Nicolas Geoffrayf1aedb12016-07-28 03:49:14 +01001776
Vladimir Markoa2c211c2018-11-01 09:50:52 +00001777 Handle<mirror::Class> compiling_class = handles_->NewHandle(resolved_method->GetDeclaringClass());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001778 DexCompilationUnit dex_compilation_unit(
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001779 class_loader,
Nicolas Geoffray5b82d332016-02-18 14:22:32 +00001780 class_linker,
1781 callee_dex_file,
1782 code_item,
1783 resolved_method->GetDeclaringClass()->GetDexClassDefIndex(),
1784 method_index,
1785 resolved_method->GetAccessFlags(),
Andreas Gampe3db70682018-12-26 15:12:03 -08001786 /* verified_method= */ nullptr,
Vladimir Markoa2c211c2018-11-01 09:50:52 +00001787 dex_cache,
1788 compiling_class);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001789
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +01001790 InvokeType invoke_type = invoke_instruction->GetInvokeType();
Nicolas Geoffray35071052015-06-09 15:43:38 +01001791 if (invoke_type == kInterface) {
1792 // We have statically resolved the dispatch. To please the class linker
1793 // at runtime, we change this call as if it was a virtual call.
1794 invoke_type = kVirtual;
1795 }
David Brazdil3f523062016-02-29 16:53:33 +00001796
Hans Boehm206348c2018-12-05 11:11:33 -08001797 bool caller_dead_reference_safe = graph_->IsDeadReferenceSafe();
1798 const dex::ClassDef& callee_class = resolved_method->GetClassDef();
1799 // MethodContainsRSensitiveAccess is currently slow, but HasDeadReferenceSafeAnnotation()
1800 // is currently rarely true.
1801 bool callee_dead_reference_safe =
1802 annotations::HasDeadReferenceSafeAnnotation(callee_dex_file, callee_class)
1803 && !annotations::MethodContainsRSensitiveAccess(callee_dex_file, callee_class, method_index);
1804
David Brazdil3f523062016-02-29 16:53:33 +00001805 const int32_t caller_instruction_counter = graph_->GetCurrentInstructionId();
Vladimir Markoca6fff82017-10-03 14:49:14 +01001806 HGraph* callee_graph = new (graph_->GetAllocator()) HGraph(
1807 graph_->GetAllocator(),
1808 graph_->GetArenaStack(),
Guillaume "Vermeille" Sanchezae09d2d2015-05-29 10:52:55 +01001809 callee_dex_file,
Nicolas Geoffray0a23d742015-05-07 11:57:35 +01001810 method_index,
Vladimir Markoa0431112018-06-25 09:32:54 +01001811 codegen_->GetCompilerOptions().GetInstructionSet(),
Nicolas Geoffray35071052015-06-09 15:43:38 +01001812 invoke_type,
Hans Boehm206348c2018-12-05 11:11:33 -08001813 callee_dead_reference_safe,
Nicolas Geoffray0a23d742015-05-07 11:57:35 +01001814 graph_->IsDebuggable(),
Andreas Gampe3db70682018-12-26 15:12:03 -08001815 /* osr= */ false,
Nicolas Geoffraya48c3df2019-06-27 13:11:12 +00001816 /* is_shared_jit_code= */ graph_->IsCompilingForSharedJitCode(),
1817 /* start_instruction_id= */ caller_instruction_counter);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001818 callee_graph->SetArtMethod(resolved_method);
David Brazdil5e8b1372015-01-23 14:39:08 +00001819
Vladimir Marko438709f2017-02-23 18:56:13 +00001820 // When they are needed, allocate `inline_stats_` on the Arena instead
Roland Levillaina8013fd2016-04-04 15:34:31 +01001821 // of on the stack, as Clang might produce a stack frame too large
1822 // for this function, that would not fit the requirements of the
1823 // `-Wframe-larger-than` option.
Vladimir Marko438709f2017-02-23 18:56:13 +00001824 if (stats_ != nullptr) {
1825 // Reuse one object for all inline attempts from this caller to keep Arena memory usage low.
1826 if (inline_stats_ == nullptr) {
Vladimir Markoca6fff82017-10-03 14:49:14 +01001827 void* storage = graph_->GetAllocator()->Alloc<OptimizingCompilerStats>(kArenaAllocMisc);
Vladimir Marko438709f2017-02-23 18:56:13 +00001828 inline_stats_ = new (storage) OptimizingCompilerStats;
1829 } else {
1830 inline_stats_->Reset();
1831 }
1832 }
David Brazdil5e8b1372015-01-23 14:39:08 +00001833 HGraphBuilder builder(callee_graph,
Mathieu Chartier808c7a52017-12-15 11:19:33 -08001834 code_item_accessor,
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001835 &dex_compilation_unit,
1836 &outer_compilation_unit_,
Nicolas Geoffray83c8e272017-01-31 14:36:37 +00001837 codegen_,
Vladimir Marko438709f2017-02-23 18:56:13 +00001838 inline_stats_,
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +00001839 resolved_method->GetQuickenedInfo(),
David Brazdildee58d62016-04-07 09:54:26 +00001840 handles_);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001841
David Brazdildee58d62016-04-07 09:54:26 +00001842 if (builder.BuildGraph() != kAnalysisSuccess) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001843 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedCannotBuild)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001844 << "Method " << callee_dex_file.PrettyMethod(method_index)
1845 << " could not be built, so cannot be inlined";
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001846 return false;
1847 }
1848
Vladimir Markoa0431112018-06-25 09:32:54 +01001849 if (!RegisterAllocator::CanAllocateRegistersFor(
1850 *callee_graph, codegen_->GetCompilerOptions().GetInstructionSet())) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001851 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedRegisterAllocator)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001852 << "Method " << callee_dex_file.PrettyMethod(method_index)
1853 << " cannot be inlined because of the register allocator";
Nicolas Geoffray259136f2014-12-17 23:21:58 +00001854 return false;
1855 }
1856
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001857 size_t parameter_index = 0;
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001858 bool run_rtp = false;
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001859 for (HInstructionIterator instructions(callee_graph->GetEntryBlock()->GetInstructions());
1860 !instructions.Done();
1861 instructions.Advance()) {
1862 HInstruction* current = instructions.Current();
1863 if (current->IsParameterValue()) {
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001864 HInstruction* argument = invoke_instruction->InputAt(parameter_index);
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001865 if (argument->IsNullConstant()) {
1866 current->ReplaceWith(callee_graph->GetNullConstant());
1867 } else if (argument->IsIntConstant()) {
1868 current->ReplaceWith(callee_graph->GetIntConstant(argument->AsIntConstant()->GetValue()));
1869 } else if (argument->IsLongConstant()) {
1870 current->ReplaceWith(callee_graph->GetLongConstant(argument->AsLongConstant()->GetValue()));
1871 } else if (argument->IsFloatConstant()) {
1872 current->ReplaceWith(
1873 callee_graph->GetFloatConstant(argument->AsFloatConstant()->GetValue()));
1874 } else if (argument->IsDoubleConstant()) {
1875 current->ReplaceWith(
1876 callee_graph->GetDoubleConstant(argument->AsDoubleConstant()->GetValue()));
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001877 } else if (argument->GetType() == DataType::Type::kReference) {
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001878 if (!resolved_method->IsStatic() && parameter_index == 0 && receiver_type.IsValid()) {
1879 run_rtp = true;
1880 current->SetReferenceTypeInfo(receiver_type);
1881 } else {
1882 current->SetReferenceTypeInfo(argument->GetReferenceTypeInfo());
1883 }
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001884 current->AsParameterValue()->SetCanBeNull(argument->CanBeNull());
1885 }
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001886 ++parameter_index;
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001887 }
1888 }
1889
David Brazdil94ab38f2016-06-21 17:48:19 +01001890 // We have replaced formal arguments with actual arguments. If actual types
1891 // are more specific than the declared ones, run RTP again on the inner graph.
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001892 if (run_rtp || ArgumentTypesMoreSpecific(invoke_instruction, resolved_method)) {
David Brazdil94ab38f2016-06-21 17:48:19 +01001893 ReferenceTypePropagation(callee_graph,
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001894 outer_compilation_unit_.GetClassLoader(),
David Brazdil94ab38f2016-06-21 17:48:19 +01001895 dex_compilation_unit.GetDexCache(),
1896 handles_,
Andreas Gampe3db70682018-12-26 15:12:03 -08001897 /* is_first_run= */ false).Run();
David Brazdil94ab38f2016-06-21 17:48:19 +01001898 }
1899
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001900 RunOptimizations(callee_graph, code_item, dex_compilation_unit);
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +00001901
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001902 HBasicBlock* exit_block = callee_graph->GetExitBlock();
1903 if (exit_block == nullptr) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001904 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedInfiniteLoop)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001905 << "Method " << callee_dex_file.PrettyMethod(method_index)
1906 << " could not be inlined because it has an infinite loop";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001907 return false;
1908 }
1909
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00001910 bool has_one_return = false;
Vladimir Marko60584552015-09-03 13:35:12 +00001911 for (HBasicBlock* predecessor : exit_block->GetPredecessors()) {
1912 if (predecessor->GetLastInstruction()->IsThrow()) {
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00001913 if (invoke_instruction->GetBlock()->IsTryBlock()) {
1914 // TODO(ngeoffray): Support adding HTryBoundary in Hgraph::InlineInto.
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001915 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedTryCatch)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001916 << "Method " << callee_dex_file.PrettyMethod(method_index)
1917 << " could not be inlined because one branch always throws and"
1918 << " caller is in a try/catch block";
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00001919 return false;
1920 } else if (graph_->GetExitBlock() == nullptr) {
1921 // TODO(ngeoffray): Support adding HExit in the caller graph.
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001922 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedInfiniteLoop)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001923 << "Method " << callee_dex_file.PrettyMethod(method_index)
1924 << " could not be inlined because one branch always throws and"
1925 << " caller does not have an exit block";
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00001926 return false;
Nicolas Geoffray1eede6a2017-03-02 16:14:53 +00001927 } else if (graph_->HasIrreducibleLoops()) {
1928 // TODO(ngeoffray): Support re-computing loop information to graphs with
1929 // irreducible loops?
1930 VLOG(compiler) << "Method " << callee_dex_file.PrettyMethod(method_index)
1931 << " could not be inlined because one branch always throws and"
1932 << " caller has irreducible loops";
1933 return false;
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00001934 }
1935 } else {
1936 has_one_return = true;
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001937 }
1938 }
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00001939
1940 if (!has_one_return) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001941 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedAlwaysThrows)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001942 << "Method " << callee_dex_file.PrettyMethod(method_index)
1943 << " could not be inlined because it always throws";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001944 return false;
1945 }
1946
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001947 size_t number_of_instructions = 0;
Vladimir Marko2c45bc92016-10-25 16:54:12 +01001948 // Skip the entry block, it does not contain instructions that prevent inlining.
1949 for (HBasicBlock* block : callee_graph->GetReversePostOrderSkipEntryBlock()) {
David Sehrc757dec2016-11-04 15:48:34 -07001950 if (block->IsLoopHeader()) {
1951 if (block->GetLoopInformation()->IsIrreducible()) {
1952 // Don't inline methods with irreducible loops, they could prevent some
1953 // optimizations to run.
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001954 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedIrreducibleLoop)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001955 << "Method " << callee_dex_file.PrettyMethod(method_index)
1956 << " could not be inlined because it contains an irreducible loop";
David Sehrc757dec2016-11-04 15:48:34 -07001957 return false;
1958 }
1959 if (!block->GetLoopInformation()->HasExitEdge()) {
1960 // Don't inline methods with loops without exit, since they cause the
1961 // loop information to be computed incorrectly when updating after
1962 // inlining.
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001963 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedLoopWithoutExit)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001964 << "Method " << callee_dex_file.PrettyMethod(method_index)
1965 << " could not be inlined because it contains a loop with no exit";
David Sehrc757dec2016-11-04 15:48:34 -07001966 return false;
1967 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001968 }
1969
1970 for (HInstructionIterator instr_it(block->GetInstructions());
1971 !instr_it.Done();
1972 instr_it.Advance()) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001973 if (++number_of_instructions >= inlining_budget_) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001974 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedInstructionBudget)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001975 << "Method " << callee_dex_file.PrettyMethod(method_index)
1976 << " is not inlined because the outer method has reached"
1977 << " its instruction budget limit.";
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001978 return false;
1979 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001980 HInstruction* current = instr_it.Current();
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001981 if (current->NeedsEnvironment() &&
1982 (total_number_of_dex_registers_ >= kMaximumNumberOfCumulatedDexRegisters)) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001983 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedEnvironmentBudget)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001984 << "Method " << callee_dex_file.PrettyMethod(method_index)
1985 << " is not inlined because its caller has reached"
1986 << " its environment budget limit.";
Nicolas Geoffray5949fa02015-12-18 10:57:10 +00001987 return false;
1988 }
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001989
Nicolas Geoffrayfbdfa6d2017-02-03 10:43:13 +00001990 if (current->NeedsEnvironment() &&
1991 !CanEncodeInlinedMethodInStackMap(*caller_compilation_unit_.GetDexFile(),
1992 resolved_method)) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001993 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedStackMaps)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001994 << "Method " << callee_dex_file.PrettyMethod(method_index)
1995 << " could not be inlined because " << current->DebugName()
1996 << " needs an environment, is in a different dex file"
1997 << ", and cannot be encoded in the stack maps.";
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001998 return false;
1999 }
Nicolas Geoffray9437b782015-03-25 10:08:51 +00002000
Vladimir Markodc151b22015-10-15 18:02:30 +01002001 if (!same_dex_file && current->NeedsDexCacheOfDeclaringClass()) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +00002002 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedDexCache)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00002003 << "Method " << callee_dex_file.PrettyMethod(method_index)
2004 << " could not be inlined because " << current->DebugName()
2005 << " it is in a different dex file and requires access to the dex cache";
Nicolas Geoffray9437b782015-03-25 10:08:51 +00002006 return false;
2007 }
Nicolas Geoffrayd9309292015-10-31 22:21:31 +00002008
Nicolas Geoffrayd9309292015-10-31 22:21:31 +00002009 if (current->IsUnresolvedStaticFieldGet() ||
2010 current->IsUnresolvedInstanceFieldGet() ||
2011 current->IsUnresolvedStaticFieldSet() ||
2012 current->IsUnresolvedInstanceFieldSet()) {
2013 // Entrypoint for unresolved fields does not handle inlined frames.
Vladimir Markocd09e1f2017-11-24 15:02:40 +00002014 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedUnresolvedEntrypoint)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00002015 << "Method " << callee_dex_file.PrettyMethod(method_index)
2016 << " could not be inlined because it is using an unresolved"
2017 << " entrypoint";
Nicolas Geoffrayd9309292015-10-31 22:21:31 +00002018 return false;
2019 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002020 }
2021 }
David Brazdil3f523062016-02-29 16:53:33 +00002022 DCHECK_EQ(caller_instruction_counter, graph_->GetCurrentInstructionId())
2023 << "No instructions can be added to the outer graph while inner graph is being built";
2024
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00002025 // Inline the callee graph inside the caller graph.
David Brazdil3f523062016-02-29 16:53:33 +00002026 const int32_t callee_instruction_counter = callee_graph->GetCurrentInstructionId();
2027 graph_->SetCurrentInstructionId(callee_instruction_counter);
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00002028 *return_replacement = callee_graph->InlineInto(graph_, invoke_instruction);
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00002029 // Update our budget for other inlining attempts in `caller_graph`.
2030 total_number_of_instructions_ += number_of_instructions;
2031 UpdateInliningBudget();
David Brazdil3f523062016-02-29 16:53:33 +00002032
2033 DCHECK_EQ(callee_instruction_counter, callee_graph->GetCurrentInstructionId())
2034 << "No instructions can be added to the inner graph during inlining into the outer graph";
2035
Vladimir Marko438709f2017-02-23 18:56:13 +00002036 if (stats_ != nullptr) {
2037 DCHECK(inline_stats_ != nullptr);
2038 inline_stats_->AddTo(stats_);
2039 }
2040
Hans Boehm206348c2018-12-05 11:11:33 -08002041 if (caller_dead_reference_safe && !callee_dead_reference_safe) {
2042 // Caller was dead reference safe, but is not anymore, since we inlined dead
2043 // reference unsafe code. Prior transformations remain valid, since they did not
2044 // affect the inlined code.
2045 graph_->MarkDeadReferenceUnsafe();
2046 }
2047
Vladimir Markobe10e8e2016-01-22 12:09:44 +00002048 return true;
2049}
Calin Juravle2e768302015-07-28 14:41:11 +00002050
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00002051void HInliner::RunOptimizations(HGraph* callee_graph,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08002052 const dex::CodeItem* code_item,
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00002053 const DexCompilationUnit& dex_compilation_unit) {
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01002054 // Note: if the outermost_graph_ is being compiled OSR, we should not run any
2055 // optimization that could lead to a HDeoptimize. The following optimizations do not.
Vladimir Marko438709f2017-02-23 18:56:13 +00002056 HDeadCodeElimination dce(callee_graph, inline_stats_, "dead_code_elimination$inliner");
Andreas Gampeca620d72016-11-08 08:09:33 -08002057 HConstantFolding fold(callee_graph, "constant_folding$inliner");
Vladimir Markobb089b62018-06-28 17:30:16 +01002058 InstructionSimplifier simplify(callee_graph, codegen_, inline_stats_);
Roland Levillaina3aef2e2016-04-06 17:45:58 +01002059
2060 HOptimization* optimizations[] = {
Roland Levillaina3aef2e2016-04-06 17:45:58 +01002061 &simplify,
2062 &fold,
2063 &dce,
2064 };
2065
2066 for (size_t i = 0; i < arraysize(optimizations); ++i) {
2067 HOptimization* optimization = optimizations[i];
2068 optimization->Run();
2069 }
2070
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00002071 // Bail early for pathological cases on the environment (for example recursive calls,
2072 // or too large environment).
2073 if (total_number_of_dex_registers_ >= kMaximumNumberOfCumulatedDexRegisters) {
2074 LOG_NOTE() << "Calls in " << callee_graph->GetArtMethod()->PrettyMethod()
2075 << " will not be inlined because the outer method has reached"
2076 << " its environment budget limit.";
2077 return;
Roland Levillaina3aef2e2016-04-06 17:45:58 +01002078 }
2079
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00002080 // Bail early if we know we already are over the limit.
2081 size_t number_of_instructions = CountNumberOfInstructions(callee_graph);
2082 if (number_of_instructions > inlining_budget_) {
2083 LOG_NOTE() << "Calls in " << callee_graph->GetArtMethod()->PrettyMethod()
2084 << " will not be inlined because the outer method has reached"
2085 << " its instruction budget limit. " << number_of_instructions;
2086 return;
2087 }
2088
Mathieu Chartier698ebbc2018-01-05 11:00:42 -08002089 CodeItemDataAccessor accessor(callee_graph->GetDexFile(), code_item);
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00002090 HInliner inliner(callee_graph,
2091 outermost_graph_,
2092 codegen_,
2093 outer_compilation_unit_,
2094 dex_compilation_unit,
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00002095 handles_,
2096 inline_stats_,
Mathieu Chartier808c7a52017-12-15 11:19:33 -08002097 total_number_of_dex_registers_ + accessor.RegistersSize(),
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00002098 total_number_of_instructions_ + number_of_instructions,
2099 this,
2100 depth_ + 1);
2101 inliner.Run();
Roland Levillaina3aef2e2016-04-06 17:45:58 +01002102}
2103
David Brazdil94ab38f2016-06-21 17:48:19 +01002104static bool IsReferenceTypeRefinement(ReferenceTypeInfo declared_rti,
2105 bool declared_can_be_null,
2106 HInstruction* actual_obj)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002107 REQUIRES_SHARED(Locks::mutator_lock_) {
David Brazdil94ab38f2016-06-21 17:48:19 +01002108 if (declared_can_be_null && !actual_obj->CanBeNull()) {
2109 return true;
2110 }
2111
2112 ReferenceTypeInfo actual_rti = actual_obj->GetReferenceTypeInfo();
2113 return (actual_rti.IsExact() && !declared_rti.IsExact()) ||
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00002114 declared_rti.IsStrictSupertypeOf(actual_rti);
David Brazdil94ab38f2016-06-21 17:48:19 +01002115}
2116
Vladimir Markob45528c2017-07-27 14:14:28 +01002117ReferenceTypeInfo HInliner::GetClassRTI(ObjPtr<mirror::Class> klass) {
David Brazdil94ab38f2016-06-21 17:48:19 +01002118 return ReferenceTypePropagation::IsAdmissible(klass)
2119 ? ReferenceTypeInfo::Create(handles_->NewHandle(klass))
2120 : graph_->GetInexactObjectRti();
2121}
2122
2123bool HInliner::ArgumentTypesMoreSpecific(HInvoke* invoke_instruction, ArtMethod* resolved_method) {
2124 // If this is an instance call, test whether the type of the `this` argument
2125 // is more specific than the class which declares the method.
2126 if (!resolved_method->IsStatic()) {
2127 if (IsReferenceTypeRefinement(GetClassRTI(resolved_method->GetDeclaringClass()),
Andreas Gampe3db70682018-12-26 15:12:03 -08002128 /* declared_can_be_null= */ false,
David Brazdil94ab38f2016-06-21 17:48:19 +01002129 invoke_instruction->InputAt(0u))) {
2130 return true;
2131 }
2132 }
2133
David Brazdil94ab38f2016-06-21 17:48:19 +01002134 // Iterate over the list of parameter types and test whether any of the
2135 // actual inputs has a more specific reference type than the type declared in
2136 // the signature.
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08002137 const dex::TypeList* param_list = resolved_method->GetParameterTypeList();
David Brazdil94ab38f2016-06-21 17:48:19 +01002138 for (size_t param_idx = 0,
2139 input_idx = resolved_method->IsStatic() ? 0 : 1,
2140 e = (param_list == nullptr ? 0 : param_list->Size());
2141 param_idx < e;
2142 ++param_idx, ++input_idx) {
2143 HInstruction* input = invoke_instruction->InputAt(input_idx);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002144 if (input->GetType() == DataType::Type::kReference) {
Vladimir Markob45528c2017-07-27 14:14:28 +01002145 ObjPtr<mirror::Class> param_cls = resolved_method->LookupResolvedClassFromTypeIndex(
2146 param_list->GetTypeItem(param_idx).type_idx_);
David Brazdil94ab38f2016-06-21 17:48:19 +01002147 if (IsReferenceTypeRefinement(GetClassRTI(param_cls),
Andreas Gampe3db70682018-12-26 15:12:03 -08002148 /* declared_can_be_null= */ true,
David Brazdil94ab38f2016-06-21 17:48:19 +01002149 input)) {
2150 return true;
2151 }
2152 }
2153 }
2154
2155 return false;
2156}
2157
2158bool HInliner::ReturnTypeMoreSpecific(HInvoke* invoke_instruction,
2159 HInstruction* return_replacement) {
Alex Light68289a52015-12-15 17:30:30 -08002160 // Check the integrity of reference types and run another type propagation if needed.
David Brazdil4833f5a2015-12-16 10:37:39 +00002161 if (return_replacement != nullptr) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002162 if (return_replacement->GetType() == DataType::Type::kReference) {
David Brazdil94ab38f2016-06-21 17:48:19 +01002163 // Test if the return type is a refinement of the declared return type.
2164 if (IsReferenceTypeRefinement(invoke_instruction->GetReferenceTypeInfo(),
Andreas Gampe3db70682018-12-26 15:12:03 -08002165 /* declared_can_be_null= */ true,
David Brazdil94ab38f2016-06-21 17:48:19 +01002166 return_replacement)) {
2167 return true;
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00002168 } else if (return_replacement->IsInstanceFieldGet()) {
2169 HInstanceFieldGet* field_get = return_replacement->AsInstanceFieldGet();
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00002170 if (field_get->GetFieldInfo().GetField() ==
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002171 GetClassRoot<mirror::Object>()->GetInstanceField(0)) {
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00002172 return true;
2173 }
David Brazdil94ab38f2016-06-21 17:48:19 +01002174 }
2175 } else if (return_replacement->IsInstanceOf()) {
2176 // Inlining InstanceOf into an If may put a tighter bound on reference types.
2177 return true;
2178 }
2179 }
2180
2181 return false;
2182}
2183
2184void HInliner::FixUpReturnReferenceType(ArtMethod* resolved_method,
2185 HInstruction* return_replacement) {
2186 if (return_replacement != nullptr) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002187 if (return_replacement->GetType() == DataType::Type::kReference) {
David Brazdil4833f5a2015-12-16 10:37:39 +00002188 if (!return_replacement->GetReferenceTypeInfo().IsValid()) {
2189 // Make sure that we have a valid type for the return. We may get an invalid one when
2190 // we inline invokes with multiple branches and create a Phi for the result.
2191 // TODO: we could be more precise by merging the phi inputs but that requires
2192 // some functionality from the reference type propagation.
2193 DCHECK(return_replacement->IsPhi());
Vladimir Markob45528c2017-07-27 14:14:28 +01002194 ObjPtr<mirror::Class> cls = resolved_method->LookupResolvedReturnType();
David Brazdil94ab38f2016-06-21 17:48:19 +01002195 return_replacement->SetReferenceTypeInfo(GetClassRTI(cls));
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01002196 }
Calin Juravlecdfed3d2015-10-26 14:05:01 +00002197 }
Calin Juravle2e768302015-07-28 14:41:11 +00002198 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002199}
2200
2201} // namespace art