blob: 9e1965d8aab2851ebdadca595095bef871f15123 [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 Marko5868ada2020-05-12 11:50:34 +010024#include "class_root-inl.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
Vladimir Marko0a516052019-10-14 13:00:44 +000050namespace art {
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000051
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
David Srbecky4fa07a52020-03-31 20:52:09 +0100151 // If we're compiling tests, honor inlining directives in method names:
Roland Levillain6c3af162017-04-27 11:18:56 +0100152 // - if a method's name contains the substring "$noinline$", do not
Vladimir Marko6be1dbd2018-11-13 13:09:51 +0000153 // inline that method;
154 // - if a method's name contains the substring "$inline$", ensure
155 // that this method is actually inlined.
Vladimir Markobe0c7cf2018-03-19 13:40:56 +0000156 // We limit the latter to AOT compilation, as the JIT may or may not inline
Nicolas Geoffray08490b82017-07-18 12:58:10 +0100157 // depending on the state of classes at runtime.
David Srbecky4fa07a52020-03-31 20:52:09 +0100158 const bool honor_noinline_directives = codegen_->GetCompilerOptions().CompileArtTest();
Vladimir Markobe0c7cf2018-03-19 13:40:56 +0000159 const bool honor_inline_directives =
160 honor_noinline_directives && Runtime::Current()->IsAotCompiler();
Roland Levillain6c3af162017-04-27 11:18:56 +0100161
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +0000162 // Keep a copy of all blocks when starting the visit.
163 ArenaVector<HBasicBlock*> blocks = graph_->GetReversePostOrder();
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100164 DCHECK(!blocks.empty());
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +0000165 // Because we are changing the graph when inlining,
166 // we just iterate over the blocks of the outer method.
167 // This avoids doing the inlining work again on the inlined blocks.
168 for (HBasicBlock* block : blocks) {
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +0000169 for (HInstruction* instruction = block->GetFirstInstruction(); instruction != nullptr;) {
170 HInstruction* next = instruction->GetNext();
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100171 HInvoke* call = instruction->AsInvoke();
Razvan A Lupusoru3e90a962015-03-27 13:44:44 -0700172 // As long as the call is not intrinsified, it is worth trying to inline.
173 if (call != nullptr && call->GetIntrinsic() == Intrinsics::kNone) {
Vladimir Markobe0c7cf2018-03-19 13:40:56 +0000174 if (honor_noinline_directives) {
Nicolas Geoffrayb703d182017-02-14 18:05:28 +0000175 // Debugging case: directives in method names control or assert on inlining.
Nicolas Geoffraye6c0f2a2020-09-07 08:30:52 +0100176 std::string callee_name =
177 call->GetMethodReference().PrettyMethod(/* with_signature= */ false);
Nicolas Geoffrayb703d182017-02-14 18:05:28 +0000178 // Tests prevent inlining by having $noinline$ in their method names.
179 if (callee_name.find("$noinline$") == std::string::npos) {
Aart Bik24773202018-04-26 10:28:51 -0700180 if (TryInline(call)) {
181 didInline = true;
Aart Bik54e45c52018-04-27 13:57:21 -0700182 } else if (honor_inline_directives) {
Nicolas Geoffray1949baf2017-10-17 12:14:53 +0000183 bool should_have_inlined = (callee_name.find("$inline$") != std::string::npos);
184 CHECK(!should_have_inlined) << "Could not inline " << callee_name;
Nicolas Geoffrayb703d182017-02-14 18:05:28 +0000185 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000186 }
Guillaume "Vermeille" Sancheze918d382015-06-03 15:32:41 +0100187 } else {
Vladimir Markobe0c7cf2018-03-19 13:40:56 +0000188 DCHECK(!honor_inline_directives);
Nicolas Geoffrayb703d182017-02-14 18:05:28 +0000189 // Normal case: try to inline.
Aart Bik24773202018-04-26 10:28:51 -0700190 if (TryInline(call)) {
191 didInline = true;
192 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000193 }
194 }
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +0000195 instruction = next;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000196 }
197 }
Aart Bik24773202018-04-26 10:28:51 -0700198
199 return didInline;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000200}
201
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100202static bool IsMethodOrDeclaringClassFinal(ArtMethod* method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700203 REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100204 return method->IsFinal() || method->GetDeclaringClass()->IsFinal();
205}
206
207/**
208 * Given the `resolved_method` looked up in the dex cache, try to find
209 * the actual runtime target of an interface or virtual call.
210 * Return nullptr if the runtime target cannot be proven.
211 */
Nicolas Geoffraye6c0f2a2020-09-07 08:30:52 +0100212static ArtMethod* FindVirtualOrInterfaceTarget(HInvoke* invoke)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700213 REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffraye6c0f2a2020-09-07 08:30:52 +0100214 ArtMethod* resolved_method = invoke->GetResolvedMethod();
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
Calin Juravle13439f02017-02-21 01:17:21 -0800323HInliner::InlineCacheType HInliner::GetInlineCacheType(
Vladimir Markoe9fb3dc2021-03-10 12:17:53 +0000324 const StackHandleScope<InlineCache::kIndividualCacheSize>& classes) {
325 DCHECK_EQ(classes.NumberOfReferences(), InlineCache::kIndividualCacheSize);
326 uint8_t number_of_types = InlineCache::kIndividualCacheSize - classes.RemainingSlots();
Calin Juravle13439f02017-02-21 01:17:21 -0800327 if (number_of_types == 0) {
328 return kInlineCacheUninitialized;
329 } else if (number_of_types == 1) {
330 return kInlineCacheMonomorphic;
331 } else if (number_of_types == InlineCache::kIndividualCacheSize) {
332 return kInlineCacheMegamorphic;
333 } else {
334 return kInlineCachePolymorphic;
335 }
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000336}
337
Vladimir Markoe9fb3dc2021-03-10 12:17:53 +0000338static inline ObjPtr<mirror::Class> GetMonomorphicType(
339 const StackHandleScope<InlineCache::kIndividualCacheSize>& classes)
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000340 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markoe9fb3dc2021-03-10 12:17:53 +0000341 DCHECK(classes.GetReference(0) != nullptr);
342 return classes.GetReference(0)->AsClass();
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000343}
344
Nicolas Geoffraye1e0e0f2021-04-29 08:57:13 +0000345ArtMethod* HInliner::FindMethodFromCHA(ArtMethod* resolved_method) {
Mingyao Yang063fc772016-08-02 11:02:54 -0700346 if (!resolved_method->HasSingleImplementation()) {
347 return nullptr;
348 }
349 if (Runtime::Current()->IsAotCompiler()) {
350 // No CHA-based devirtulization for AOT compiler (yet).
351 return nullptr;
352 }
Nicolas Geoffray141b63c2019-02-27 14:28:46 +0000353 if (Runtime::Current()->IsZygote()) {
354 // No CHA-based devirtulization for Zygote, as it compiles with
355 // offline information.
356 return nullptr;
357 }
Mingyao Yang063fc772016-08-02 11:02:54 -0700358 if (outermost_graph_->IsCompilingOsr()) {
359 // We do not support HDeoptimize in OSR methods.
360 return nullptr;
361 }
Mingyao Yange8fcd012017-01-20 10:43:30 -0800362 PointerSize pointer_size = caller_compilation_unit_.GetClassLinker()->GetImagePointerSize();
Nicolas Geoffray18ea1c92017-03-27 08:00:18 +0000363 ArtMethod* single_impl = resolved_method->GetSingleImplementation(pointer_size);
364 if (single_impl == nullptr) {
365 return nullptr;
366 }
367 if (single_impl->IsProxyMethod()) {
368 // Proxy method is a generic invoker that's not worth
369 // devirtualizing/inlining. It also causes issues when the proxy
370 // method is in another dex file if we try to rewrite invoke-interface to
371 // invoke-virtual because a proxy method doesn't have a real dex file.
372 return nullptr;
373 }
Nicolas Geoffray8e33e842017-04-03 16:55:16 +0100374 if (!single_impl->GetDeclaringClass()->IsResolved()) {
375 // There's a race with the class loading, which updates the CHA info
376 // before setting the class to resolved. So we just bail for this
377 // rare occurence.
378 return nullptr;
379 }
Nicolas Geoffray18ea1c92017-03-27 08:00:18 +0000380 return single_impl;
Mingyao Yang063fc772016-08-02 11:02:54 -0700381}
382
Vladimir Marko2afaff72018-11-30 17:01:50 +0000383static bool IsMethodUnverified(const CompilerOptions& compiler_options, ArtMethod* method)
David Sehr0225f8e2018-01-31 08:52:24 +0000384 REQUIRES_SHARED(Locks::mutator_lock_) {
Aart Bik2c148f02018-02-02 14:30:35 -0800385 if (!method->GetDeclaringClass()->IsVerified()) {
Vladimir Marko695348f2020-05-19 14:42:02 +0100386 if (compiler_options.IsJitCompiler()) {
Aart Bik2c148f02018-02-02 14:30:35 -0800387 // We're at runtime, we know this is cold code if the class
388 // is not verified, so don't bother analyzing.
389 return true;
390 }
391 uint16_t class_def_idx = method->GetDeclaringClass()->GetDexClassDefIndex();
Vladimir Marko2afaff72018-11-30 17:01:50 +0000392 if (!compiler_options.IsMethodVerifiedWithoutFailures(method->GetDexMethodIndex(),
393 class_def_idx,
394 *method->GetDexFile())) {
Aart Bik2c148f02018-02-02 14:30:35 -0800395 // Method has soft or hard failures, don't analyze.
396 return true;
397 }
398 }
399 return false;
400}
401
Vladimir Marko2afaff72018-11-30 17:01:50 +0000402static bool AlwaysThrows(const CompilerOptions& compiler_options, ArtMethod* method)
Aart Bik2c148f02018-02-02 14:30:35 -0800403 REQUIRES_SHARED(Locks::mutator_lock_) {
404 DCHECK(method != nullptr);
405 // Skip non-compilable and unverified methods.
Vladimir Marko2afaff72018-11-30 17:01:50 +0000406 if (!method->IsCompilable() || IsMethodUnverified(compiler_options, method)) {
Aart Bik2c148f02018-02-02 14:30:35 -0800407 return false;
408 }
Aart Bika8b8e9b2018-01-09 11:01:02 -0800409 // Skip native methods, methods with try blocks, and methods that are too large.
Aart Bik2c148f02018-02-02 14:30:35 -0800410 CodeItemDataAccessor accessor(method->DexInstructionData());
Aart Bika8b8e9b2018-01-09 11:01:02 -0800411 if (!accessor.HasCodeItem() ||
412 accessor.TriesSize() != 0 ||
413 accessor.InsnsSizeInCodeUnits() > kMaximumNumberOfTotalInstructions) {
414 return false;
415 }
416 // Scan for exits.
417 bool throw_seen = false;
418 for (const DexInstructionPcPair& pair : accessor) {
419 switch (pair.Inst().Opcode()) {
420 case Instruction::RETURN:
421 case Instruction::RETURN_VOID:
422 case Instruction::RETURN_WIDE:
423 case Instruction::RETURN_OBJECT:
Aart Bika8b8e9b2018-01-09 11:01:02 -0800424 return false; // found regular control flow back
425 case Instruction::THROW:
426 throw_seen = true;
427 break;
428 default:
429 break;
430 }
431 }
432 return throw_seen;
433}
434
Nicolas Geoffraye418dda2015-08-11 20:03:09 -0700435bool HInliner::TryInline(HInvoke* invoke_instruction) {
Mathieu Chartier8284e9a2020-05-15 17:14:33 -0700436 MaybeRecordStat(stats_, MethodCompilationStat::kTryInline);
437
438 // Don't bother to move further if we know the method is unresolved or the invocation is
439 // polymorphic (invoke-{polymorphic,custom}).
440 if (invoke_instruction->IsInvokeUnresolved()) {
441 MaybeRecordStat(stats_, MethodCompilationStat::kNotInlinedUnresolved);
442 return false;
443 } else if (invoke_instruction->IsInvokePolymorphic()) {
444 MaybeRecordStat(stats_, MethodCompilationStat::kNotInlinedPolymorphic);
445 return false;
446 } else if (invoke_instruction->IsInvokeCustom()) {
447 MaybeRecordStat(stats_, MethodCompilationStat::kNotInlinedCustom);
448 return false;
Calin Juravle175dc732015-08-25 15:42:32 +0100449 }
450
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000451 ScopedObjectAccess soa(Thread::Current());
Nicolas Geoffraye6c0f2a2020-09-07 08:30:52 +0100452 LOG_TRY() << invoke_instruction->GetMethodReference().PrettyMethod();
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000453
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +0100454 ArtMethod* resolved_method = invoke_instruction->GetResolvedMethod();
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +0100455 if (resolved_method == nullptr) {
456 DCHECK(invoke_instruction->IsInvokeStaticOrDirect());
457 DCHECK(invoke_instruction->AsInvokeStaticOrDirect()->IsStringInit());
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000458 LOG_FAIL_NO_STAT() << "Not inlining a String.<init> method";
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +0100459 return false;
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000460 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000461
Nicolas Geoffraye1e0e0f2021-04-29 08:57:13 +0000462 ArtMethod* actual_method = invoke_instruction->IsInvokeStaticOrDirect()
463 ? invoke_instruction->GetResolvedMethod()
464 : FindVirtualOrInterfaceTarget(invoke_instruction);
Eric Holk1868de92020-02-12 09:10:21 -0800465
Nicolas Geoffraye1e0e0f2021-04-29 08:57:13 +0000466 if (actual_method != nullptr) {
467 // Single target.
468 bool result = TryInlineAndReplace(invoke_instruction,
469 actual_method,
470 ReferenceTypeInfo::CreateInvalid(),
471 /* do_rtp= */ true);
472 if (result) {
473 MaybeRecordStat(stats_, MethodCompilationStat::kInlinedInvokeVirtualOrInterface);
474 } else {
475 HInvoke* invoke_to_analyze = nullptr;
476 if (TryDevirtualize(invoke_instruction, actual_method, &invoke_to_analyze)) {
477 // Consider devirtualization as inlining.
478 result = true;
479 MaybeRecordStat(stats_, MethodCompilationStat::kDevirtualized);
Eric Holk1868de92020-02-12 09:10:21 -0800480 } else {
Nicolas Geoffraye1e0e0f2021-04-29 08:57:13 +0000481 invoke_to_analyze = invoke_instruction;
482 }
483 // Set always throws property for non-inlined method call with single
484 // target.
485 if (AlwaysThrows(codegen_->GetCompilerOptions(), actual_method)) {
486 invoke_to_analyze->SetAlwaysThrows(true);
Mingyao Yang063fc772016-08-02 11:02:54 -0700487 }
Calin Juravle69158982016-03-16 11:53:41 +0000488 }
Nicolas Geoffraye1e0e0f2021-04-29 08:57:13 +0000489 return result;
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100490 }
Nicolas Geoffraye1e0e0f2021-04-29 08:57:13 +0000491
492 DCHECK(!invoke_instruction->IsInvokeStaticOrDirect());
493
494 if (TryInlineFromCHA(invoke_instruction)) {
495 return true;
496 }
497 return TryInlineFromInlineCache(invoke_instruction);
498}
499
500bool HInliner::TryInlineFromCHA(HInvoke* invoke_instruction) {
501 ArtMethod* method = FindMethodFromCHA(invoke_instruction->GetResolvedMethod());
502 if (method == nullptr) {
503 return false;
504 }
505 LOG_NOTE() << "Try CHA-based inlining of " << method->PrettyMethod();
506
507 uint32_t dex_pc = invoke_instruction->GetDexPc();
508 HInstruction* cursor = invoke_instruction->GetPrevious();
509 HBasicBlock* bb_cursor = invoke_instruction->GetBlock();
510 if (!TryInlineAndReplace(invoke_instruction,
511 method,
512 ReferenceTypeInfo::CreateInvalid(),
513 /* do_rtp= */ true)) {
514 return false;
515 }
516 AddCHAGuard(invoke_instruction, dex_pc, cursor, bb_cursor);
517 // Add dependency due to devirtualization: we are assuming the resolved method
518 // has a single implementation.
519 outermost_graph_->AddCHASingleImplementationDependency(invoke_instruction->GetResolvedMethod());
520 MaybeRecordStat(stats_, MethodCompilationStat::kCHAInline);
521 return true;
Calin Juravle13439f02017-02-21 01:17:21 -0800522}
523
Calin Juravleaf44e6c2017-05-23 14:24:55 -0700524bool HInliner::UseOnlyPolymorphicInliningWithNoDeopt() {
525 // If we are compiling AOT or OSR, pretend the call using inline caches is polymorphic and
526 // do not generate a deopt.
527 //
528 // For AOT:
529 // Generating a deopt does not ensure that we will actually capture the new types;
530 // and the danger is that we could be stuck in a loop with "forever" deoptimizations.
531 // Take for example the following scenario:
532 // - we capture the inline cache in one run
533 // - the next run, we deoptimize because we miss a type check, but the method
534 // never becomes hot again
535 // In this case, the inline cache will not be updated in the profile and the AOT code
536 // will keep deoptimizing.
537 // Another scenario is if we use profile compilation for a process which is not allowed
538 // to JIT (e.g. system server). If we deoptimize we will run interpreted code for the
539 // rest of the lifetime.
540 // TODO(calin):
541 // This is a compromise because we will most likely never update the inline cache
542 // in the profile (unless there's another reason to deopt). So we might be stuck with
543 // a sub-optimal inline cache.
544 // We could be smarter when capturing inline caches to mitigate this.
545 // (e.g. by having different thresholds for new and old methods).
546 //
547 // For OSR:
548 // We may come from the interpreter and it may have seen different receiver types.
549 return Runtime::Current()->IsAotCompiler() || outermost_graph_->IsCompilingOsr();
550}
Nicolas Geoffraye6c0f2a2020-09-07 08:30:52 +0100551bool HInliner::TryInlineFromInlineCache(HInvoke* invoke_instruction)
Calin Juravle13439f02017-02-21 01:17:21 -0800552 REQUIRES_SHARED(Locks::mutator_lock_) {
Calin Juravlee2492d42017-03-20 11:42:13 -0700553 if (Runtime::Current()->IsAotCompiler() && !kUseAOTInlineCaches) {
554 return false;
555 }
556
Vladimir Markoe9fb3dc2021-03-10 12:17:53 +0000557 StackHandleScope<InlineCache::kIndividualCacheSize> classes(Thread::Current());
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +0000558 // The Zygote JIT compiles based on a profile, so we shouldn't use runtime inline caches
559 // for it.
560 InlineCacheType inline_cache_type =
561 (Runtime::Current()->IsAotCompiler() || Runtime::Current()->IsZygote())
Vladimir Markoe9fb3dc2021-03-10 12:17:53 +0000562 ? GetInlineCacheAOT(invoke_instruction, &classes)
563 : GetInlineCacheJIT(invoke_instruction, &classes);
Calin Juravle13439f02017-02-21 01:17:21 -0800564
565 switch (inline_cache_type) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000566 case kInlineCacheNoData: {
567 LOG_FAIL_NO_STAT()
Nicolas Geoffrayd2f13ba2019-06-04 16:48:58 +0100568 << "No inline cache information for call to "
Nicolas Geoffraye6c0f2a2020-09-07 08:30:52 +0100569 << invoke_instruction->GetMethodReference().PrettyMethod();
Calin Juravle13439f02017-02-21 01:17:21 -0800570 return false;
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000571 }
Calin Juravle13439f02017-02-21 01:17:21 -0800572
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000573 case kInlineCacheUninitialized: {
574 LOG_FAIL_NO_STAT()
575 << "Interface or virtual call to "
Nicolas Geoffraye6c0f2a2020-09-07 08:30:52 +0100576 << invoke_instruction->GetMethodReference().PrettyMethod()
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000577 << " is not hit and not inlined";
578 return false;
579 }
580
581 case kInlineCacheMonomorphic: {
Vladimir Markocd09e1f2017-11-24 15:02:40 +0000582 MaybeRecordStat(stats_, MethodCompilationStat::kMonomorphicCall);
Calin Juravleaf44e6c2017-05-23 14:24:55 -0700583 if (UseOnlyPolymorphicInliningWithNoDeopt()) {
Vladimir Markoe9fb3dc2021-03-10 12:17:53 +0000584 return TryInlinePolymorphicCall(invoke_instruction, classes);
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000585 } else {
Vladimir Markoe9fb3dc2021-03-10 12:17:53 +0000586 return TryInlineMonomorphicCall(invoke_instruction, classes);
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000587 }
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000588 }
Calin Juravle13439f02017-02-21 01:17:21 -0800589
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000590 case kInlineCachePolymorphic: {
Vladimir Markocd09e1f2017-11-24 15:02:40 +0000591 MaybeRecordStat(stats_, MethodCompilationStat::kPolymorphicCall);
Vladimir Markoe9fb3dc2021-03-10 12:17:53 +0000592 return TryInlinePolymorphicCall(invoke_instruction, classes);
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000593 }
Calin Juravle13439f02017-02-21 01:17:21 -0800594
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000595 case kInlineCacheMegamorphic: {
596 LOG_FAIL_NO_STAT()
597 << "Interface or virtual call to "
Nicolas Geoffraye6c0f2a2020-09-07 08:30:52 +0100598 << invoke_instruction->GetMethodReference().PrettyMethod()
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000599 << " is megamorphic and not inlined";
Vladimir Markocd09e1f2017-11-24 15:02:40 +0000600 MaybeRecordStat(stats_, MethodCompilationStat::kMegamorphicCall);
Calin Juravle13439f02017-02-21 01:17:21 -0800601 return false;
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000602 }
Calin Juravle13439f02017-02-21 01:17:21 -0800603
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000604 case kInlineCacheMissingTypes: {
605 LOG_FAIL_NO_STAT()
606 << "Interface or virtual call to "
Nicolas Geoffraye6c0f2a2020-09-07 08:30:52 +0100607 << invoke_instruction->GetMethodReference().PrettyMethod()
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000608 << " is missing types and not inlined";
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 }
612 UNREACHABLE();
613}
614
615HInliner::InlineCacheType HInliner::GetInlineCacheJIT(
616 HInvoke* invoke_instruction,
Vladimir Markoe9fb3dc2021-03-10 12:17:53 +0000617 /*out*/StackHandleScope<InlineCache::kIndividualCacheSize>* classes) {
Vladimir Marko695348f2020-05-19 14:42:02 +0100618 DCHECK(codegen_->GetCompilerOptions().IsJitCompiler());
Calin Juravle13439f02017-02-21 01:17:21 -0800619
620 ArtMethod* caller = graph_->GetArtMethod();
621 // Under JIT, we should always know the caller.
622 DCHECK(caller != nullptr);
Nicolas Geoffray095dc462020-08-17 16:40:28 +0100623 ScopedProfilingInfoUse spiu(Runtime::Current()->GetJit(), caller, Thread::Current());
624 ProfilingInfo* profiling_info = spiu.GetProfilingInfo();
Calin Juravle13439f02017-02-21 01:17:21 -0800625
626 if (profiling_info == nullptr) {
627 return kInlineCacheNoData;
628 }
629
Vladimir Markoe9fb3dc2021-03-10 12:17:53 +0000630 Runtime::Current()->GetJit()->GetCodeCache()->CopyInlineCacheInto(
631 *profiling_info->GetInlineCache(invoke_instruction->GetDexPc()),
632 classes);
633 return GetInlineCacheType(*classes);
Calin Juravle13439f02017-02-21 01:17:21 -0800634}
635
636HInliner::InlineCacheType HInliner::GetInlineCacheAOT(
Calin Juravle13439f02017-02-21 01:17:21 -0800637 HInvoke* invoke_instruction,
Vladimir Markoe9fb3dc2021-03-10 12:17:53 +0000638 /*out*/StackHandleScope<InlineCache::kIndividualCacheSize>* classes) {
639 DCHECK_EQ(classes->NumberOfReferences(), InlineCache::kIndividualCacheSize);
640 DCHECK_EQ(classes->RemainingSlots(), InlineCache::kIndividualCacheSize);
641
Vladimir Marko1a2a5cd2018-11-07 15:39:48 +0000642 const ProfileCompilationInfo* pci = codegen_->GetCompilerOptions().GetProfileCompilationInfo();
Calin Juravle13439f02017-02-21 01:17:21 -0800643 if (pci == nullptr) {
644 return kInlineCacheNoData;
645 }
646
Vladimir Markoa64c1ad2021-03-08 14:27:05 +0000647 ProfileCompilationInfo::MethodHotness hotness = pci->GetMethodHotness(MethodReference(
648 caller_compilation_unit_.GetDexFile(), caller_compilation_unit_.GetDexMethodIndex()));
649 if (!hotness.IsHot()) {
Calin Juravle13439f02017-02-21 01:17:21 -0800650 return kInlineCacheNoData; // no profile information for this invocation.
651 }
652
Vladimir Markoa64c1ad2021-03-08 14:27:05 +0000653 const ProfileCompilationInfo::InlineCacheMap* inline_caches = hotness.GetInlineCacheMap();
654 DCHECK(inline_caches != nullptr);
655 const auto it = inline_caches->find(invoke_instruction->GetDexPc());
656 if (it == inline_caches->end()) {
Calin Juravle13439f02017-02-21 01:17:21 -0800657 return kInlineCacheUninitialized;
658 }
659
660 const ProfileCompilationInfo::DexPcData& dex_pc_data = it->second;
Calin Juravle13439f02017-02-21 01:17:21 -0800661 if (dex_pc_data.is_missing_types) {
662 return kInlineCacheMissingTypes;
663 }
664 if (dex_pc_data.is_megamorphic) {
665 return kInlineCacheMegamorphic;
666 }
Calin Juravle13439f02017-02-21 01:17:21 -0800667 DCHECK_LE(dex_pc_data.classes.size(), InlineCache::kIndividualCacheSize);
Vladimir Markoa64c1ad2021-03-08 14:27:05 +0000668
Calin Juravle13439f02017-02-21 01:17:21 -0800669 Thread* self = Thread::Current();
670 // We need to resolve the class relative to the containing dex file.
671 // So first, build a mapping from the index of dex file in the profile to
672 // its dex cache. This will avoid repeating the lookup when walking over
673 // the inline cache types.
Vladimir Markoa64c1ad2021-03-08 14:27:05 +0000674 ScopedArenaAllocator allocator(graph_->GetArenaStack());
675 ScopedArenaVector<ObjPtr<mirror::DexCache>> dex_profile_index_to_dex_cache(
676 pci->GetNumberOfDexFiles(), nullptr, allocator.Adapter(kArenaAllocMisc));
677 const std::vector<const DexFile*>& dex_files =
678 codegen_->GetCompilerOptions().GetDexFilesForOatFile();
679 for (const ProfileCompilationInfo::ClassReference& class_ref : dex_pc_data.classes) {
680 if (dex_profile_index_to_dex_cache[class_ref.dex_profile_index] == nullptr) {
681 ProfileCompilationInfo::ProfileIndexType profile_index = class_ref.dex_profile_index;
682 const DexFile* dex_file = pci->FindDexFileForProfileIndex(profile_index, dex_files);
683 if (dex_file == nullptr) {
684 VLOG(compiler) << "Could not find profiled dex file: "
685 << pci->DumpDexReference(profile_index);
686 return kInlineCacheMissingTypes;
Calin Juravle13439f02017-02-21 01:17:21 -0800687 }
Vladimir Markoa64c1ad2021-03-08 14:27:05 +0000688 dex_profile_index_to_dex_cache[class_ref.dex_profile_index] =
689 caller_compilation_unit_.GetClassLinker()->FindDexCache(self, *dex_file);
690 DCHECK(dex_profile_index_to_dex_cache[class_ref.dex_profile_index] != nullptr);
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100691 }
692 }
693
Calin Juravle13439f02017-02-21 01:17:21 -0800694 // Walk over the classes and resolve them. If we cannot find a type we return
695 // kInlineCacheMissingTypes.
Calin Juravle13439f02017-02-21 01:17:21 -0800696 for (const ProfileCompilationInfo::ClassReference& class_ref : dex_pc_data.classes) {
697 ObjPtr<mirror::DexCache> dex_cache =
698 dex_profile_index_to_dex_cache[class_ref.dex_profile_index];
699 DCHECK(dex_cache != nullptr);
Calin Juravle08556882017-05-26 16:40:45 -0700700
701 if (!dex_cache->GetDexFile()->IsTypeIndexValid(class_ref.type_index)) {
702 VLOG(compiler) << "Profile data corrupt: type index " << class_ref.type_index
703 << "is invalid in location" << dex_cache->GetDexFile()->GetLocation();
704 return kInlineCacheNoData;
705 }
Vladimir Marko666ee3d2017-12-11 18:37:36 +0000706 ObjPtr<mirror::Class> clazz = caller_compilation_unit_.GetClassLinker()->LookupResolvedType(
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000707 class_ref.type_index,
708 dex_cache,
709 caller_compilation_unit_.GetClassLoader().Get());
Calin Juravle13439f02017-02-21 01:17:21 -0800710 if (clazz != nullptr) {
Vladimir Markoe9fb3dc2021-03-10 12:17:53 +0000711 DCHECK_NE(classes->RemainingSlots(), 0u);
712 classes->NewHandle(clazz);
Calin Juravle13439f02017-02-21 01:17:21 -0800713 } else {
714 VLOG(compiler) << "Could not resolve class from inline cache in AOT mode "
Nicolas Geoffraye6c0f2a2020-09-07 08:30:52 +0100715 << invoke_instruction->GetMethodReference().PrettyMethod()
716 << " : "
Calin Juravle13439f02017-02-21 01:17:21 -0800717 << caller_compilation_unit_
718 .GetDexFile()->StringByTypeIdx(class_ref.type_index);
719 return kInlineCacheMissingTypes;
720 }
721 }
Vladimir Markoa64c1ad2021-03-08 14:27:05 +0000722
Vladimir Markoe9fb3dc2021-03-10 12:17:53 +0000723 return GetInlineCacheType(*classes);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100724}
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000725
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000726HInstanceFieldGet* HInliner::BuildGetReceiverClass(ClassLinker* class_linker,
727 HInstruction* receiver,
728 uint32_t dex_pc) const {
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100729 ArtField* field = GetClassRoot<mirror::Object>(class_linker)->GetInstanceField(0);
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000730 DCHECK_EQ(std::string(field->GetName()), "shadow$_klass_");
Vladimir Markoca6fff82017-10-03 14:49:14 +0100731 HInstanceFieldGet* result = new (graph_->GetAllocator()) HInstanceFieldGet(
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000732 receiver,
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +0000733 field,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100734 DataType::Type::kReference,
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000735 field->GetOffset(),
736 field->IsVolatile(),
737 field->GetDexFieldIndex(),
738 field->GetDeclaringClass()->GetDexClassDefIndex(),
739 *field->GetDexFile(),
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000740 dex_pc);
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000741 // The class of a field is effectively final, and does not have any memory dependencies.
742 result->SetSideEffects(SideEffects::None());
743 return result;
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000744}
745
Nicolas Geoffray4c0b4bc2017-03-17 13:08:26 +0000746static ArtMethod* ResolveMethodFromInlineCache(Handle<mirror::Class> klass,
Nicolas Geoffraye6c0f2a2020-09-07 08:30:52 +0100747 HInvoke* invoke_instruction,
Nicolas Geoffray4c0b4bc2017-03-17 13:08:26 +0000748 PointerSize pointer_size)
749 REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffraye6c0f2a2020-09-07 08:30:52 +0100750 ArtMethod* resolved_method = invoke_instruction->GetResolvedMethod();
Nicolas Geoffray4c0b4bc2017-03-17 13:08:26 +0000751 if (Runtime::Current()->IsAotCompiler()) {
752 // We can get unrelated types when working with profiles (corruption,
753 // systme updates, or anyone can write to it). So first check if the class
754 // actually implements the declaring class of the method that is being
755 // called in bytecode.
756 // Note: the lookup methods used below require to have assignable types.
757 if (!resolved_method->GetDeclaringClass()->IsAssignableFrom(klass.Get())) {
758 return nullptr;
759 }
760 }
761
762 if (invoke_instruction->IsInvokeInterface()) {
763 resolved_method = klass->FindVirtualMethodForInterface(resolved_method, pointer_size);
764 } else {
765 DCHECK(invoke_instruction->IsInvokeVirtual());
766 resolved_method = klass->FindVirtualMethodForVirtual(resolved_method, pointer_size);
767 }
Alex Light2769f012021-03-23 11:58:58 -0700768 // Even if the class exists we can still not have the function the
769 // inline-cache targets if the profile is from far enough in the past/future.
770 // We need to allow this since we don't update boot-profiles very often. This
771 // can occur in boot-profiles with inline-caches.
772 DCHECK(Runtime::Current()->IsAotCompiler() || resolved_method != nullptr);
Nicolas Geoffray4c0b4bc2017-03-17 13:08:26 +0000773 return resolved_method;
774}
775
Vladimir Markoe9fb3dc2021-03-10 12:17:53 +0000776bool HInliner::TryInlineMonomorphicCall(
777 HInvoke* invoke_instruction,
778 const StackHandleScope<InlineCache::kIndividualCacheSize>& classes) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000779 DCHECK(invoke_instruction->IsInvokeVirtual() || invoke_instruction->IsInvokeInterface())
780 << invoke_instruction->DebugName();
781
Andreas Gampea5b09a62016-11-17 15:21:22 -0800782 dex::TypeIndex class_index = FindClassIndexIn(
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000783 GetMonomorphicType(classes), caller_compilation_unit_);
Andreas Gampea5b09a62016-11-17 15:21:22 -0800784 if (!class_index.IsValid()) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +0000785 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedDexCache)
Nicolas Geoffraye6c0f2a2020-09-07 08:30:52 +0100786 << "Call to " << ArtMethod::PrettyMethod(invoke_instruction->GetResolvedMethod())
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000787 << " from inline cache is not inlined because its class is not"
788 << " accessible to the caller";
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100789 return false;
790 }
791
792 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
Andreas Gampe542451c2016-07-26 09:02:02 -0700793 PointerSize pointer_size = class_linker->GetImagePointerSize();
Vladimir Marko02ca05a2020-05-12 13:58:51 +0100794 Handle<mirror::Class> monomorphic_type =
795 graph_->GetHandleCache()->NewHandle(GetMonomorphicType(classes));
Nicolas Geoffraye6c0f2a2020-09-07 08:30:52 +0100796 ArtMethod* resolved_method = ResolveMethodFromInlineCache(
797 monomorphic_type, invoke_instruction, pointer_size);
Nicolas Geoffray4c0b4bc2017-03-17 13:08:26 +0000798 if (resolved_method == nullptr) {
799 // Bogus AOT profile, bail.
800 DCHECK(Runtime::Current()->IsAotCompiler());
801 return false;
802 }
803
Vladimir Markoe9fb3dc2021-03-10 12:17:53 +0000804 LOG_NOTE() << "Try inline monomorphic call to " << resolved_method->PrettyMethod();
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100805 HInstruction* receiver = invoke_instruction->InputAt(0);
806 HInstruction* cursor = invoke_instruction->GetPrevious();
807 HBasicBlock* bb_cursor = invoke_instruction->GetBlock();
Mingyao Yang063fc772016-08-02 11:02:54 -0700808 if (!TryInlineAndReplace(invoke_instruction,
809 resolved_method,
Andreas Gampe3db70682018-12-26 15:12:03 -0800810 ReferenceTypeInfo::Create(monomorphic_type, /* is_exact= */ true),
Nicolas Geoffraye1e0e0f2021-04-29 08:57:13 +0000811 /* do_rtp= */ false)) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100812 return false;
813 }
814
815 // We successfully inlined, now add a guard.
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000816 AddTypeGuard(receiver,
817 cursor,
818 bb_cursor,
819 class_index,
Nicolas Geoffray5247c082017-01-13 14:17:29 +0000820 monomorphic_type,
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000821 invoke_instruction,
Andreas Gampe3db70682018-12-26 15:12:03 -0800822 /* with_deoptimization= */ true);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100823
824 // Run type propagation to get the guard typed, and eventually propagate the
825 // type of the receiver.
Vladimir Marko456307a2016-04-19 14:12:13 +0000826 ReferenceTypePropagation rtp_fixup(graph_,
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000827 outer_compilation_unit_.GetClassLoader(),
Vladimir Marko456307a2016-04-19 14:12:13 +0000828 outer_compilation_unit_.GetDexCache(),
Andreas Gampe3db70682018-12-26 15:12:03 -0800829 /* is_first_run= */ false);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100830 rtp_fixup.Run();
831
Vladimir Markocd09e1f2017-11-24 15:02:40 +0000832 MaybeRecordStat(stats_, MethodCompilationStat::kInlinedMonomorphicCall);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100833 return true;
834}
835
Mingyao Yang063fc772016-08-02 11:02:54 -0700836void HInliner::AddCHAGuard(HInstruction* invoke_instruction,
837 uint32_t dex_pc,
838 HInstruction* cursor,
839 HBasicBlock* bb_cursor) {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100840 HShouldDeoptimizeFlag* deopt_flag = new (graph_->GetAllocator())
841 HShouldDeoptimizeFlag(graph_->GetAllocator(), dex_pc);
842 HInstruction* compare = new (graph_->GetAllocator()) HNotEqual(
Mingyao Yang063fc772016-08-02 11:02:54 -0700843 deopt_flag, graph_->GetIntConstant(0, dex_pc));
Vladimir Markoca6fff82017-10-03 14:49:14 +0100844 HInstruction* deopt = new (graph_->GetAllocator()) HDeoptimize(
845 graph_->GetAllocator(), compare, DeoptimizationKind::kCHA, dex_pc);
Mingyao Yang063fc772016-08-02 11:02:54 -0700846
847 if (cursor != nullptr) {
848 bb_cursor->InsertInstructionAfter(deopt_flag, cursor);
849 } else {
850 bb_cursor->InsertInstructionBefore(deopt_flag, bb_cursor->GetFirstInstruction());
851 }
Mingyao Yangb0b051a2016-11-17 09:04:53 -0800852 bb_cursor->InsertInstructionAfter(compare, deopt_flag);
853 bb_cursor->InsertInstructionAfter(deopt, compare);
854
855 // Add receiver as input to aid CHA guard optimization later.
856 deopt_flag->AddInput(invoke_instruction->InputAt(0));
857 DCHECK_EQ(deopt_flag->InputCount(), 1u);
Mingyao Yang063fc772016-08-02 11:02:54 -0700858 deopt->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
Mingyao Yangb0b051a2016-11-17 09:04:53 -0800859 outermost_graph_->IncrementNumberOfCHAGuards();
Mingyao Yang063fc772016-08-02 11:02:54 -0700860}
861
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000862HInstruction* HInliner::AddTypeGuard(HInstruction* receiver,
863 HInstruction* cursor,
864 HBasicBlock* bb_cursor,
Andreas Gampea5b09a62016-11-17 15:21:22 -0800865 dex::TypeIndex class_index,
Nicolas Geoffray5247c082017-01-13 14:17:29 +0000866 Handle<mirror::Class> klass,
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000867 HInstruction* invoke_instruction,
868 bool with_deoptimization) {
869 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
870 HInstanceFieldGet* receiver_class = BuildGetReceiverClass(
871 class_linker, receiver, invoke_instruction->GetDexPc());
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000872 if (cursor != nullptr) {
873 bb_cursor->InsertInstructionAfter(receiver_class, cursor);
874 } else {
875 bb_cursor->InsertInstructionBefore(receiver_class, bb_cursor->GetFirstInstruction());
876 }
Nicolas Geoffray56876342016-12-16 16:09:08 +0000877
878 const DexFile& caller_dex_file = *caller_compilation_unit_.GetDexFile();
Calin Juravle07f01df2017-04-28 19:58:01 -0700879 bool is_referrer;
880 ArtMethod* outermost_art_method = outermost_graph_->GetArtMethod();
881 if (outermost_art_method == nullptr) {
882 DCHECK(Runtime::Current()->IsAotCompiler());
883 // We are in AOT mode and we don't have an ART method to determine
884 // if the inlined method belongs to the referrer. Assume it doesn't.
885 is_referrer = false;
886 } else {
887 is_referrer = klass.Get() == outermost_art_method->GetDeclaringClass();
888 }
889
Nicolas Geoffray56876342016-12-16 16:09:08 +0000890 // Note that we will just compare the classes, so we don't need Java semantics access checks.
891 // Note that the type index and the dex file are relative to the method this type guard is
892 // inlined into.
Vladimir Markoca6fff82017-10-03 14:49:14 +0100893 HLoadClass* load_class = new (graph_->GetAllocator()) HLoadClass(graph_->GetCurrentMethod(),
894 class_index,
895 caller_dex_file,
896 klass,
897 is_referrer,
898 invoke_instruction->GetDexPc(),
Andreas Gampe3db70682018-12-26 15:12:03 -0800899 /* needs_access_check= */ false);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +0000900 HLoadClass::LoadKind kind = HSharpening::ComputeLoadClassKind(
Vladimir Markobb089b62018-06-28 17:30:16 +0100901 load_class, codegen_, caller_compilation_unit_);
Nicolas Geoffray83c8e272017-01-31 14:36:37 +0000902 DCHECK(kind != HLoadClass::LoadKind::kInvalid)
903 << "We should always be able to reference a class for inline caches";
Vladimir Marko28e012a2017-12-07 11:22:59 +0000904 // Load kind must be set before inserting the instruction into the graph.
Nicolas Geoffray83c8e272017-01-31 14:36:37 +0000905 load_class->SetLoadKind(kind);
Vladimir Marko28e012a2017-12-07 11:22:59 +0000906 bb_cursor->InsertInstructionAfter(load_class, receiver_class);
Calin Juravle13439f02017-02-21 01:17:21 -0800907 // In AOT mode, we will most likely load the class from BSS, which will involve a call
908 // to the runtime. In this case, the load instruction will need an environment so copy
909 // it from the invoke instruction.
910 if (load_class->NeedsEnvironment()) {
911 DCHECK(Runtime::Current()->IsAotCompiler());
912 load_class->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
913 }
Nicolas Geoffray56876342016-12-16 16:09:08 +0000914
Vladimir Markoca6fff82017-10-03 14:49:14 +0100915 HNotEqual* compare = new (graph_->GetAllocator()) HNotEqual(load_class, receiver_class);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000916 bb_cursor->InsertInstructionAfter(compare, load_class);
917 if (with_deoptimization) {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100918 HDeoptimize* deoptimize = new (graph_->GetAllocator()) HDeoptimize(
919 graph_->GetAllocator(),
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +0000920 compare,
921 receiver,
Nicolas Geoffray4e92c3c2017-05-08 09:34:26 +0100922 Runtime::Current()->IsAotCompiler()
923 ? DeoptimizationKind::kAotInlineCache
924 : DeoptimizationKind::kJitInlineCache,
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +0000925 invoke_instruction->GetDexPc());
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000926 bb_cursor->InsertInstructionAfter(deoptimize, compare);
927 deoptimize->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +0000928 DCHECK_EQ(invoke_instruction->InputAt(0), receiver);
929 receiver->ReplaceUsesDominatedBy(deoptimize, deoptimize);
930 deoptimize->SetReferenceTypeInfo(receiver->GetReferenceTypeInfo());
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000931 }
932 return compare;
933}
934
Nicolas Geoffrayb8958022021-04-15 15:12:31 +0100935static void MaybeReplaceAndRemove(HInstruction* new_instruction, HInstruction* old_instruction) {
936 DCHECK(new_instruction != old_instruction);
937 if (new_instruction != nullptr) {
938 old_instruction->ReplaceWith(new_instruction);
939 }
940 old_instruction->GetBlock()->RemoveInstruction(old_instruction);
941}
942
Vladimir Markoe9fb3dc2021-03-10 12:17:53 +0000943bool HInliner::TryInlinePolymorphicCall(
944 HInvoke* invoke_instruction,
945 const StackHandleScope<InlineCache::kIndividualCacheSize>& classes) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000946 DCHECK(invoke_instruction->IsInvokeVirtual() || invoke_instruction->IsInvokeInterface())
947 << invoke_instruction->DebugName();
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000948
Nicolas Geoffraye6c0f2a2020-09-07 08:30:52 +0100949 if (TryInlinePolymorphicCallToSameTarget(invoke_instruction, classes)) {
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000950 return true;
951 }
952
953 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
Andreas Gampe542451c2016-07-26 09:02:02 -0700954 PointerSize pointer_size = class_linker->GetImagePointerSize();
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000955
956 bool all_targets_inlined = true;
957 bool one_target_inlined = false;
Vladimir Markoe9fb3dc2021-03-10 12:17:53 +0000958 DCHECK_EQ(classes.NumberOfReferences(), InlineCache::kIndividualCacheSize);
959 uint8_t number_of_types = InlineCache::kIndividualCacheSize - classes.RemainingSlots();
960 for (size_t i = 0; i != number_of_types; ++i) {
961 DCHECK(classes.GetReference(i) != nullptr);
962 Handle<mirror::Class> handle =
963 graph_->GetHandleCache()->NewHandle(classes.GetReference(i)->AsClass());
964 ArtMethod* method = ResolveMethodFromInlineCache(handle, invoke_instruction, pointer_size);
Nicolas Geoffray4c0b4bc2017-03-17 13:08:26 +0000965 if (method == nullptr) {
966 DCHECK(Runtime::Current()->IsAotCompiler());
967 // AOT profile is bogus. This loop expects to iterate over all entries,
968 // so just just continue.
969 all_targets_inlined = false;
970 continue;
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000971 }
972
973 HInstruction* receiver = invoke_instruction->InputAt(0);
974 HInstruction* cursor = invoke_instruction->GetPrevious();
975 HBasicBlock* bb_cursor = invoke_instruction->GetBlock();
976
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000977 dex::TypeIndex class_index = FindClassIndexIn(handle.Get(), caller_compilation_unit_);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000978 HInstruction* return_replacement = nullptr;
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000979 LOG_NOTE() << "Try inline polymorphic call to " << method->PrettyMethod();
Andreas Gampea5b09a62016-11-17 15:21:22 -0800980 if (!class_index.IsValid() ||
Nicolas Geoffray0f001b72017-01-04 16:46:23 +0000981 !TryBuildAndInline(invoke_instruction,
982 method,
Andreas Gampe3db70682018-12-26 15:12:03 -0800983 ReferenceTypeInfo::Create(handle, /* is_exact= */ true),
Nicolas Geoffray0f001b72017-01-04 16:46:23 +0000984 &return_replacement)) {
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000985 all_targets_inlined = false;
986 } else {
987 one_target_inlined = true;
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000988
Nicolas Geoffraye6c0f2a2020-09-07 08:30:52 +0100989 LOG_SUCCESS() << "Polymorphic call to "
990 << invoke_instruction->GetMethodReference().PrettyMethod()
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000991 << " has inlined " << ArtMethod::PrettyMethod(method);
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +0000992
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000993 // If we have inlined all targets before, and this receiver is the last seen,
994 // we deoptimize instead of keeping the original invoke instruction.
Calin Juravleaf44e6c2017-05-23 14:24:55 -0700995 bool deoptimize = !UseOnlyPolymorphicInliningWithNoDeopt() &&
996 all_targets_inlined &&
Vladimir Markoe9fb3dc2021-03-10 12:17:53 +0000997 (i + 1 == number_of_types);
Nicolas Geoffray93a18c52016-04-22 13:16:14 +0100998
Nicolas Geoffray56876342016-12-16 16:09:08 +0000999 HInstruction* compare = AddTypeGuard(receiver,
1000 cursor,
1001 bb_cursor,
1002 class_index,
Nicolas Geoffray5247c082017-01-13 14:17:29 +00001003 handle,
Nicolas Geoffray56876342016-12-16 16:09:08 +00001004 invoke_instruction,
1005 deoptimize);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001006 if (deoptimize) {
Nicolas Geoffrayb8958022021-04-15 15:12:31 +01001007 MaybeReplaceAndRemove(return_replacement, invoke_instruction);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001008 } else {
1009 CreateDiamondPatternForPolymorphicInline(compare, return_replacement, invoke_instruction);
1010 }
1011 }
1012 }
1013
1014 if (!one_target_inlined) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001015 LOG_FAIL_NO_STAT()
Nicolas Geoffraye6c0f2a2020-09-07 08:30:52 +01001016 << "Call to " << invoke_instruction->GetMethodReference().PrettyMethod()
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001017 << " from inline cache is not inlined because none"
1018 << " of its targets could be inlined";
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001019 return false;
1020 }
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00001021
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001022 MaybeRecordStat(stats_, MethodCompilationStat::kInlinedPolymorphicCall);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001023
1024 // Run type propagation to get the guards typed.
Vladimir Marko456307a2016-04-19 14:12:13 +00001025 ReferenceTypePropagation rtp_fixup(graph_,
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001026 outer_compilation_unit_.GetClassLoader(),
Vladimir Marko456307a2016-04-19 14:12:13 +00001027 outer_compilation_unit_.GetDexCache(),
Andreas Gampe3db70682018-12-26 15:12:03 -08001028 /* is_first_run= */ false);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001029 rtp_fixup.Run();
1030 return true;
1031}
1032
1033void HInliner::CreateDiamondPatternForPolymorphicInline(HInstruction* compare,
1034 HInstruction* return_replacement,
1035 HInstruction* invoke_instruction) {
1036 uint32_t dex_pc = invoke_instruction->GetDexPc();
1037 HBasicBlock* cursor_block = compare->GetBlock();
1038 HBasicBlock* original_invoke_block = invoke_instruction->GetBlock();
Vladimir Markoca6fff82017-10-03 14:49:14 +01001039 ArenaAllocator* allocator = graph_->GetAllocator();
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001040
1041 // Spit the block after the compare: `cursor_block` will now be the start of the diamond,
1042 // and the returned block is the start of the then branch (that could contain multiple blocks).
1043 HBasicBlock* then = cursor_block->SplitAfterForInlining(compare);
1044
1045 // Split the block containing the invoke before and after the invoke. The returned block
1046 // of the split before will contain the invoke and will be the otherwise branch of
1047 // the diamond. The returned block of the split after will be the merge block
1048 // of the diamond.
1049 HBasicBlock* end_then = invoke_instruction->GetBlock();
1050 HBasicBlock* otherwise = end_then->SplitBeforeForInlining(invoke_instruction);
1051 HBasicBlock* merge = otherwise->SplitAfterForInlining(invoke_instruction);
1052
1053 // If the methods we are inlining return a value, we create a phi in the merge block
1054 // that will have the `invoke_instruction and the `return_replacement` as inputs.
1055 if (return_replacement != nullptr) {
1056 HPhi* phi = new (allocator) HPhi(
1057 allocator, kNoRegNumber, 0, HPhi::ToPhiType(invoke_instruction->GetType()), dex_pc);
1058 merge->AddPhi(phi);
1059 invoke_instruction->ReplaceWith(phi);
1060 phi->AddInput(return_replacement);
1061 phi->AddInput(invoke_instruction);
1062 }
1063
1064 // Add the control flow instructions.
1065 otherwise->AddInstruction(new (allocator) HGoto(dex_pc));
1066 end_then->AddInstruction(new (allocator) HGoto(dex_pc));
1067 cursor_block->AddInstruction(new (allocator) HIf(compare, dex_pc));
1068
1069 // Add the newly created blocks to the graph.
1070 graph_->AddBlock(then);
1071 graph_->AddBlock(otherwise);
1072 graph_->AddBlock(merge);
1073
1074 // Set up successor (and implictly predecessor) relations.
1075 cursor_block->AddSuccessor(otherwise);
1076 cursor_block->AddSuccessor(then);
1077 end_then->AddSuccessor(merge);
1078 otherwise->AddSuccessor(merge);
1079
1080 // Set up dominance information.
1081 then->SetDominator(cursor_block);
1082 cursor_block->AddDominatedBlock(then);
1083 otherwise->SetDominator(cursor_block);
1084 cursor_block->AddDominatedBlock(otherwise);
1085 merge->SetDominator(cursor_block);
1086 cursor_block->AddDominatedBlock(merge);
1087
1088 // Update the revert post order.
1089 size_t index = IndexOfElement(graph_->reverse_post_order_, cursor_block);
1090 MakeRoomFor(&graph_->reverse_post_order_, 1, index);
1091 graph_->reverse_post_order_[++index] = then;
1092 index = IndexOfElement(graph_->reverse_post_order_, end_then);
1093 MakeRoomFor(&graph_->reverse_post_order_, 2, index);
1094 graph_->reverse_post_order_[++index] = otherwise;
1095 graph_->reverse_post_order_[++index] = merge;
1096
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001097
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00001098 graph_->UpdateLoopAndTryInformationOfNewBlock(
Andreas Gampe3db70682018-12-26 15:12:03 -08001099 then, original_invoke_block, /* replace_if_back_edge= */ false);
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00001100 graph_->UpdateLoopAndTryInformationOfNewBlock(
Andreas Gampe3db70682018-12-26 15:12:03 -08001101 otherwise, original_invoke_block, /* replace_if_back_edge= */ false);
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00001102
1103 // In case the original invoke location was a back edge, we need to update
1104 // the loop to now have the merge block as a back edge.
1105 graph_->UpdateLoopAndTryInformationOfNewBlock(
Andreas Gampe3db70682018-12-26 15:12:03 -08001106 merge, original_invoke_block, /* replace_if_back_edge= */ true);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001107}
1108
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +00001109bool HInliner::TryInlinePolymorphicCallToSameTarget(
1110 HInvoke* invoke_instruction,
Vladimir Markoe9fb3dc2021-03-10 12:17:53 +00001111 const StackHandleScope<InlineCache::kIndividualCacheSize>& classes) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001112 // This optimization only works under JIT for now.
Vladimir Marko695348f2020-05-19 14:42:02 +01001113 if (!codegen_->GetCompilerOptions().IsJitCompiler()) {
Calin Juravle13439f02017-02-21 01:17:21 -08001114 return false;
1115 }
1116
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001117 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
Andreas Gampe542451c2016-07-26 09:02:02 -07001118 PointerSize pointer_size = class_linker->GetImagePointerSize();
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001119
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001120 ArtMethod* actual_method = nullptr;
Nicolas Geoffray4f97a212016-02-25 16:17:54 +00001121 size_t method_index = invoke_instruction->IsInvokeVirtual()
1122 ? invoke_instruction->AsInvokeVirtual()->GetVTableIndex()
1123 : invoke_instruction->AsInvokeInterface()->GetImtIndex();
1124
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001125 // Check whether we are actually calling the same method among
1126 // the different types seen.
Vladimir Markoe9fb3dc2021-03-10 12:17:53 +00001127 DCHECK_EQ(classes.NumberOfReferences(), InlineCache::kIndividualCacheSize);
1128 uint8_t number_of_types = InlineCache::kIndividualCacheSize - classes.RemainingSlots();
1129 for (size_t i = 0; i != number_of_types; ++i) {
1130 DCHECK(classes.GetReference(i) != nullptr);
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001131 ArtMethod* new_method = nullptr;
1132 if (invoke_instruction->IsInvokeInterface()) {
Vladimir Markoe9fb3dc2021-03-10 12:17:53 +00001133 new_method = classes.GetReference(i)->AsClass()->GetImt(pointer_size)->Get(
Matthew Gharrity465ecc82016-07-19 21:32:52 +00001134 method_index, pointer_size);
Nicolas Geoffray4f97a212016-02-25 16:17:54 +00001135 if (new_method->IsRuntimeMethod()) {
1136 // Bail out as soon as we see a conflict trampoline in one of the target's
1137 // interface table.
1138 return false;
1139 }
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001140 } else {
1141 DCHECK(invoke_instruction->IsInvokeVirtual());
Vladimir Markoe9fb3dc2021-03-10 12:17:53 +00001142 new_method =
1143 classes.GetReference(i)->AsClass()->GetEmbeddedVTableEntry(method_index, pointer_size);
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001144 }
Nicolas Geoffray4f97a212016-02-25 16:17:54 +00001145 DCHECK(new_method != nullptr);
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001146 if (actual_method == nullptr) {
1147 actual_method = new_method;
1148 } else if (actual_method != new_method) {
1149 // Different methods, bailout.
1150 return false;
1151 }
1152 }
1153
1154 HInstruction* receiver = invoke_instruction->InputAt(0);
1155 HInstruction* cursor = invoke_instruction->GetPrevious();
1156 HBasicBlock* bb_cursor = invoke_instruction->GetBlock();
1157
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01001158 HInstruction* return_replacement = nullptr;
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001159 if (!TryBuildAndInline(invoke_instruction,
1160 actual_method,
1161 ReferenceTypeInfo::CreateInvalid(),
1162 &return_replacement)) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001163 return false;
1164 }
1165
1166 // We successfully inlined, now add a guard.
1167 HInstanceFieldGet* receiver_class = BuildGetReceiverClass(
1168 class_linker, receiver, invoke_instruction->GetDexPc());
1169
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001170 DataType::Type type = Is64BitInstructionSet(graph_->GetInstructionSet())
1171 ? DataType::Type::kInt64
1172 : DataType::Type::kInt32;
Vladimir Markoca6fff82017-10-03 14:49:14 +01001173 HClassTableGet* class_table_get = new (graph_->GetAllocator()) HClassTableGet(
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001174 receiver_class,
1175 type,
Vladimir Markoa1de9182016-02-25 11:37:38 +00001176 invoke_instruction->IsInvokeVirtual() ? HClassTableGet::TableKind::kVTable
1177 : HClassTableGet::TableKind::kIMTable,
Nicolas Geoffray4f97a212016-02-25 16:17:54 +00001178 method_index,
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001179 invoke_instruction->GetDexPc());
1180
1181 HConstant* constant;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001182 if (type == DataType::Type::kInt64) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001183 constant = graph_->GetLongConstant(
1184 reinterpret_cast<intptr_t>(actual_method), invoke_instruction->GetDexPc());
1185 } else {
1186 constant = graph_->GetIntConstant(
1187 reinterpret_cast<intptr_t>(actual_method), invoke_instruction->GetDexPc());
1188 }
1189
Vladimir Markoca6fff82017-10-03 14:49:14 +01001190 HNotEqual* compare = new (graph_->GetAllocator()) HNotEqual(class_table_get, constant);
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001191 if (cursor != nullptr) {
1192 bb_cursor->InsertInstructionAfter(receiver_class, cursor);
1193 } else {
1194 bb_cursor->InsertInstructionBefore(receiver_class, bb_cursor->GetFirstInstruction());
1195 }
1196 bb_cursor->InsertInstructionAfter(class_table_get, receiver_class);
1197 bb_cursor->InsertInstructionAfter(compare, class_table_get);
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01001198
1199 if (outermost_graph_->IsCompilingOsr()) {
1200 CreateDiamondPatternForPolymorphicInline(compare, return_replacement, invoke_instruction);
1201 } else {
Vladimir Markoca6fff82017-10-03 14:49:14 +01001202 HDeoptimize* deoptimize = new (graph_->GetAllocator()) HDeoptimize(
1203 graph_->GetAllocator(),
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +00001204 compare,
1205 receiver,
Nicolas Geoffray4e92c3c2017-05-08 09:34:26 +01001206 DeoptimizationKind::kJitSameTarget,
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +00001207 invoke_instruction->GetDexPc());
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01001208 bb_cursor->InsertInstructionAfter(deoptimize, compare);
1209 deoptimize->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
Nicolas Geoffrayb8958022021-04-15 15:12:31 +01001210 MaybeReplaceAndRemove(return_replacement, invoke_instruction);
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +00001211 receiver->ReplaceUsesDominatedBy(deoptimize, deoptimize);
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +00001212 deoptimize->SetReferenceTypeInfo(receiver->GetReferenceTypeInfo());
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01001213 }
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001214
1215 // Run type propagation to get the guard typed.
Vladimir Marko456307a2016-04-19 14:12:13 +00001216 ReferenceTypePropagation rtp_fixup(graph_,
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001217 outer_compilation_unit_.GetClassLoader(),
Vladimir Marko456307a2016-04-19 14:12:13 +00001218 outer_compilation_unit_.GetDexCache(),
Andreas Gampe3db70682018-12-26 15:12:03 -08001219 /* is_first_run= */ false);
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001220 rtp_fixup.Run();
1221
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001222 MaybeRecordStat(stats_, MethodCompilationStat::kInlinedPolymorphicCall);
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001223
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001224 LOG_SUCCESS() << "Inlined same polymorphic target " << actual_method->PrettyMethod();
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001225 return true;
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001226}
1227
Nicolas Geoffraye1e0e0f2021-04-29 08:57:13 +00001228void HInliner::MaybeRunReferenceTypePropagation(HInstruction* replacement,
1229 HInvoke* invoke_instruction) {
1230 if (ReturnTypeMoreSpecific(replacement, invoke_instruction)) {
David Brazdil94ab38f2016-06-21 17:48:19 +01001231 // Actual return value has a more specific type than the method's declared
1232 // return type. Run RTP again on the outer graph to propagate it.
1233 ReferenceTypePropagation(graph_,
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001234 outer_compilation_unit_.GetClassLoader(),
David Brazdil94ab38f2016-06-21 17:48:19 +01001235 outer_compilation_unit_.GetDexCache(),
Andreas Gampe3db70682018-12-26 15:12:03 -08001236 /* is_first_run= */ false).Run();
David Brazdil94ab38f2016-06-21 17:48:19 +01001237 }
Nicolas Geoffraye1e0e0f2021-04-29 08:57:13 +00001238}
1239
1240bool HInliner::TryDevirtualize(HInvoke* invoke_instruction,
1241 ArtMethod* method,
1242 HInvoke** replacement) {
Nicolas Geoffraye1e0e0f2021-04-29 08:57:13 +00001243 DCHECK(invoke_instruction != *replacement);
Nicolas Geoffrayec068092021-05-10 17:28:32 +00001244 if (!invoke_instruction->IsInvokeInterface() && !invoke_instruction->IsInvokeVirtual()) {
Nicolas Geoffraye1e0e0f2021-04-29 08:57:13 +00001245 return false;
1246 }
Nicolas Geoffray39d4df62021-05-07 12:22:47 +00001247
Nicolas Geoffrayec068092021-05-10 17:28:32 +00001248 // Don't bother trying to call directly a default conflict method. It
1249 // doesn't have a proper MethodReference, but also `GetCanonicalMethod`
1250 // will return an actual default implementation.
1251 if (method->IsDefaultConflicting()) {
1252 return false;
Nicolas Geoffray39d4df62021-05-07 12:22:47 +00001253 }
Nicolas Geoffrayec068092021-05-10 17:28:32 +00001254 DCHECK(!method->IsProxyMethod());
1255 ClassLinker* cl = Runtime::Current()->GetClassLinker();
1256 PointerSize pointer_size = cl->GetImagePointerSize();
1257 // The sharpening logic assumes the caller isn't passing a copied method.
1258 method = method->GetCanonicalMethod(pointer_size);
Nicolas Geoffraye1e0e0f2021-04-29 08:57:13 +00001259 uint32_t dex_method_index = FindMethodIndexIn(
1260 method,
1261 *invoke_instruction->GetMethodReference().dex_file,
1262 invoke_instruction->GetMethodReference().index);
1263 if (dex_method_index == dex::kDexNoIndex) {
1264 return false;
1265 }
Nicolas Geoffrayec068092021-05-10 17:28:32 +00001266 HInvokeStaticOrDirect::DispatchInfo dispatch_info =
1267 HSharpening::SharpenLoadMethod(method,
1268 /* has_method_id= */ true,
1269 /* for_interface_call= */ false,
1270 codegen_);
1271 DCHECK_NE(dispatch_info.code_ptr_location, CodePtrLocation::kCallCriticalNative);
1272 if (dispatch_info.method_load_kind == MethodLoadKind::kRuntimeCall) {
1273 // If sharpening returns that we need to load the method at runtime, keep
1274 // the virtual/interface call which will be faster.
1275 // Also, the entrypoints for runtime calls do not handle devirtualized
1276 // calls.
1277 return false;
1278 }
1279
1280 HInvokeStaticOrDirect* new_invoke = new (graph_->GetAllocator()) HInvokeStaticOrDirect(
Nicolas Geoffraye1e0e0f2021-04-29 08:57:13 +00001281 graph_->GetAllocator(),
1282 invoke_instruction->GetNumberOfArguments(),
1283 invoke_instruction->GetType(),
1284 invoke_instruction->GetDexPc(),
1285 MethodReference(invoke_instruction->GetMethodReference().dex_file, dex_method_index),
1286 method,
Nicolas Geoffrayec068092021-05-10 17:28:32 +00001287 dispatch_info,
1288 kDirect,
Nicolas Geoffraye1e0e0f2021-04-29 08:57:13 +00001289 MethodReference(method->GetDexFile(), method->GetDexMethodIndex()),
Nicolas Geoffrayec068092021-05-10 17:28:32 +00001290 HInvokeStaticOrDirect::ClinitCheckRequirement::kNone);
Nicolas Geoffraye1e0e0f2021-04-29 08:57:13 +00001291 HInputsRef inputs = invoke_instruction->GetInputs();
Nicolas Geoffrayec068092021-05-10 17:28:32 +00001292 DCHECK_EQ(inputs.size(), invoke_instruction->GetNumberOfArguments());
Nicolas Geoffraye1e0e0f2021-04-29 08:57:13 +00001293 for (size_t index = 0; index != inputs.size(); ++index) {
1294 new_invoke->SetArgumentAt(index, inputs[index]);
1295 }
Nicolas Geoffrayec068092021-05-10 17:28:32 +00001296 if (HInvokeStaticOrDirect::NeedsCurrentMethodInput(dispatch_info)) {
1297 new_invoke->SetRawInputAt(new_invoke->GetCurrentMethodIndexUnchecked(),
1298 graph_->GetCurrentMethod());
1299 }
Nicolas Geoffraye1e0e0f2021-04-29 08:57:13 +00001300 invoke_instruction->GetBlock()->InsertInstructionBefore(new_invoke, invoke_instruction);
1301 new_invoke->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
1302 if (invoke_instruction->GetType() == DataType::Type::kReference) {
1303 new_invoke->SetReferenceTypeInfo(invoke_instruction->GetReferenceTypeInfo());
1304 }
1305 *replacement = new_invoke;
1306
1307 MaybeReplaceAndRemove(*replacement, invoke_instruction);
1308 // No need to call MaybeRunReferenceTypePropagation, as we know the return type
1309 // cannot be more specific.
1310 DCHECK(!ReturnTypeMoreSpecific(*replacement, invoke_instruction));
1311 return true;
1312}
1313
1314
1315bool HInliner::TryInlineAndReplace(HInvoke* invoke_instruction,
1316 ArtMethod* method,
1317 ReferenceTypeInfo receiver_type,
1318 bool do_rtp) {
1319 DCHECK(!invoke_instruction->IsIntrinsic());
1320 HInstruction* return_replacement = nullptr;
1321
1322 if (!TryBuildAndInline(invoke_instruction, method, receiver_type, &return_replacement)) {
1323 return false;
1324 }
1325
1326 MaybeReplaceAndRemove(return_replacement, invoke_instruction);
1327 FixUpReturnReferenceType(method, return_replacement);
1328 if (do_rtp) {
1329 MaybeRunReferenceTypePropagation(return_replacement, invoke_instruction);
1330 }
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001331 return true;
1332}
1333
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001334size_t HInliner::CountRecursiveCallsOf(ArtMethod* method) const {
1335 const HInliner* current = this;
1336 size_t count = 0;
1337 do {
1338 if (current->graph_->GetArtMethod() == method) {
1339 ++count;
1340 }
1341 current = current->parent_;
1342 } while (current != nullptr);
1343 return count;
1344}
1345
Vladimir Marko213ee2d2018-06-22 11:56:34 +01001346static inline bool MayInline(const CompilerOptions& compiler_options,
1347 const DexFile& inlined_from,
1348 const DexFile& inlined_into) {
Vladimir Marko213ee2d2018-06-22 11:56:34 +01001349 // We're not allowed to inline across dex files if we're the no-inline-from dex file.
1350 if (!IsSameDexFile(inlined_from, inlined_into) &&
1351 ContainsElement(compiler_options.GetNoInlineFromDexFile(), &inlined_from)) {
1352 return false;
1353 }
1354
1355 return true;
1356}
1357
Eric Holk1868de92020-02-12 09:10:21 -08001358// Returns whether inlining is allowed based on ART semantics.
1359bool HInliner::IsInliningAllowed(ArtMethod* method, const CodeItemDataAccessor& accessor) const {
Mathieu Chartier808c7a52017-12-15 11:19:33 -08001360 if (!accessor.HasCodeItem()) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001361 LOG_FAIL_NO_STAT()
1362 << "Method " << method->PrettyMethod() << " is not inlined because it is native";
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001363 return false;
1364 }
1365
Nicolas Geoffray250a3782016-04-20 16:27:53 +01001366 if (!method->IsCompilable()) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001367 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedNotVerified)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001368 << "Method " << method->PrettyMethod()
1369 << " has soft failures un-handled by the compiler, so it cannot be inlined";
Aart Bik897df032018-02-07 13:29:11 -08001370 return false;
Nicolas Geoffray250a3782016-04-20 16:27:53 +01001371 }
1372
Vladimir Marko2afaff72018-11-30 17:01:50 +00001373 if (IsMethodUnverified(codegen_->GetCompilerOptions(), method)) {
Aart Bik2c148f02018-02-02 14:30:35 -08001374 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedNotVerified)
1375 << "Method " << method->PrettyMethod()
1376 << " couldn't be verified, so it cannot be inlined";
1377 return false;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001378 }
1379
Eric Holk1868de92020-02-12 09:10:21 -08001380 return true;
1381}
1382
1383// Returns whether ART supports inlining this method.
1384//
1385// Some methods are not supported because they have features for which inlining
1386// is not implemented. For example, we do not currently support inlining throw
1387// instructions into a try block.
1388bool HInliner::IsInliningSupported(const HInvoke* invoke_instruction,
1389 ArtMethod* method,
1390 const CodeItemDataAccessor& accessor) const {
1391 if (method->IsProxyMethod()) {
1392 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedProxy)
1393 << "Method " << method->PrettyMethod()
1394 << " is not inlined because of unimplemented inline support for proxy methods.";
1395 return false;
1396 }
1397
1398 if (accessor.TriesSize() != 0) {
1399 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedTryCatch)
1400 << "Method " << method->PrettyMethod() << " is not inlined because of try block";
1401 return false;
1402 }
1403
Roland Levillain4c0eb422015-04-24 16:43:49 +01001404 if (invoke_instruction->IsInvokeStaticOrDirect() &&
1405 invoke_instruction->AsInvokeStaticOrDirect()->IsStaticWithImplicitClinitCheck()) {
1406 // Case of a static method that cannot be inlined because it implicitly
1407 // requires an initialization check of its declaring class.
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001408 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedDexCache)
1409 << "Method " << method->PrettyMethod()
1410 << " is not inlined because it is static and requires a clinit"
1411 << " check that cannot be emitted due to Dex cache limitations";
Roland Levillain4c0eb422015-04-24 16:43:49 +01001412 return false;
1413 }
1414
Eric Holk1868de92020-02-12 09:10:21 -08001415 return true;
1416}
1417
1418// Returns whether our resource limits allow inlining this method.
1419bool HInliner::IsInliningBudgetAvailable(ArtMethod* method,
1420 const CodeItemDataAccessor& accessor) const {
1421 if (CountRecursiveCallsOf(method) > kMaximumNumberOfRecursiveCalls) {
1422 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedRecursiveBudget)
1423 << "Method "
1424 << method->PrettyMethod()
1425 << " is not inlined because it has reached its recursive call budget.";
1426 return false;
1427 }
1428
1429 size_t inline_max_code_units = codegen_->GetCompilerOptions().GetInlineMaxCodeUnits();
1430 if (accessor.InsnsSizeInCodeUnits() > inline_max_code_units) {
1431 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedCodeItem)
1432 << "Method " << method->PrettyMethod()
1433 << " is not inlined because its code item is too big: "
1434 << accessor.InsnsSizeInCodeUnits()
1435 << " > "
1436 << inline_max_code_units;
1437 return false;
1438 }
1439
1440 return true;
1441}
1442
1443bool HInliner::TryBuildAndInline(HInvoke* invoke_instruction,
1444 ArtMethod* method,
1445 ReferenceTypeInfo receiver_type,
1446 HInstruction** return_replacement) {
Nicolas Geoffrayb8958022021-04-15 15:12:31 +01001447 // If invoke_instruction is devirtualized to a different method, give intrinsics
1448 // another chance before we try to inline it.
1449 if (invoke_instruction->GetResolvedMethod() != method && method->IsIntrinsic()) {
1450 MaybeRecordStat(stats_, MethodCompilationStat::kIntrinsicRecognized);
1451 // For simplicity, always create a new instruction to replace the existing
1452 // invoke.
1453 HInvokeVirtual* new_invoke = new (graph_->GetAllocator()) HInvokeVirtual(
1454 graph_->GetAllocator(),
1455 invoke_instruction->GetNumberOfArguments(),
1456 invoke_instruction->GetType(),
1457 invoke_instruction->GetDexPc(),
1458 invoke_instruction->GetMethodReference(), // Use existing invoke's method's reference.
1459 method,
1460 MethodReference(method->GetDexFile(), method->GetDexMethodIndex()),
1461 method->GetMethodIndex());
1462 DCHECK_NE(new_invoke->GetIntrinsic(), Intrinsics::kNone);
1463 HInputsRef inputs = invoke_instruction->GetInputs();
1464 for (size_t index = 0; index != inputs.size(); ++index) {
1465 new_invoke->SetArgumentAt(index, inputs[index]);
1466 }
1467 invoke_instruction->GetBlock()->InsertInstructionBefore(new_invoke, invoke_instruction);
1468 new_invoke->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
1469 if (invoke_instruction->GetType() == DataType::Type::kReference) {
1470 new_invoke->SetReferenceTypeInfo(invoke_instruction->GetReferenceTypeInfo());
1471 }
1472 *return_replacement = new_invoke;
1473 return true;
1474 }
1475
Eric Holk1868de92020-02-12 09:10:21 -08001476 // Check whether we're allowed to inline. The outermost compilation unit is the relevant
1477 // dex file here (though the transitivity of an inline chain would allow checking the caller).
1478 if (!MayInline(codegen_->GetCompilerOptions(),
1479 *method->GetDexFile(),
1480 *outer_compilation_unit_.GetDexFile())) {
1481 if (TryPatternSubstitution(invoke_instruction, method, return_replacement)) {
1482 LOG_SUCCESS() << "Successfully replaced pattern of invoke "
1483 << method->PrettyMethod();
1484 MaybeRecordStat(stats_, MethodCompilationStat::kReplacedInvokeWithSimplePattern);
1485 return true;
1486 }
1487 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedWont)
1488 << "Won't inline " << method->PrettyMethod() << " in "
1489 << outer_compilation_unit_.GetDexFile()->GetLocation() << " ("
1490 << caller_compilation_unit_.GetDexFile()->GetLocation() << ") from "
1491 << method->GetDexFile()->GetLocation();
1492 return false;
1493 }
1494
1495 CodeItemDataAccessor accessor(method->DexInstructionData());
1496
1497 if (!IsInliningAllowed(method, accessor)) {
1498 return false;
1499 }
1500
1501 if (!IsInliningSupported(invoke_instruction, method, accessor)) {
1502 return false;
1503 }
1504
1505 if (!IsInliningBudgetAvailable(method, accessor)) {
1506 return false;
1507 }
1508
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001509 if (!TryBuildAndInlineHelper(
Eric Holk1868de92020-02-12 09:10:21 -08001510 invoke_instruction, method, receiver_type, return_replacement)) {
Nicolas Geoffrayc0365b12015-03-18 18:31:52 +00001511 return false;
1512 }
1513
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001514 LOG_SUCCESS() << method->PrettyMethod();
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001515 MaybeRecordStat(stats_, MethodCompilationStat::kInlinedInvoke);
Nicolas Geoffrayc0365b12015-03-18 18:31:52 +00001516 return true;
1517}
1518
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001519static HInstruction* GetInvokeInputForArgVRegIndex(HInvoke* invoke_instruction,
1520 size_t arg_vreg_index)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001521 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001522 size_t input_index = 0;
1523 for (size_t i = 0; i < arg_vreg_index; ++i, ++input_index) {
1524 DCHECK_LT(input_index, invoke_instruction->GetNumberOfArguments());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001525 if (DataType::Is64BitType(invoke_instruction->InputAt(input_index)->GetType())) {
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001526 ++i;
1527 DCHECK_NE(i, arg_vreg_index);
1528 }
1529 }
1530 DCHECK_LT(input_index, invoke_instruction->GetNumberOfArguments());
1531 return invoke_instruction->InputAt(input_index);
1532}
1533
1534// Try to recognize known simple patterns and replace invoke call with appropriate instructions.
1535bool HInliner::TryPatternSubstitution(HInvoke* invoke_instruction,
Nicolas Geoffraye6c0f2a2020-09-07 08:30:52 +01001536 ArtMethod* method,
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001537 HInstruction** return_replacement) {
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001538 InlineMethod inline_method;
Nicolas Geoffraye6c0f2a2020-09-07 08:30:52 +01001539 if (!InlineMethodAnalyser::AnalyseMethodCode(method, &inline_method)) {
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001540 return false;
1541 }
1542
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001543 switch (inline_method.opcode) {
1544 case kInlineOpNop:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001545 DCHECK_EQ(invoke_instruction->GetType(), DataType::Type::kVoid);
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001546 *return_replacement = nullptr;
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001547 break;
1548 case kInlineOpReturnArg:
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001549 *return_replacement = GetInvokeInputForArgVRegIndex(invoke_instruction,
1550 inline_method.d.return_data.arg);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001551 break;
1552 case kInlineOpNonWideConst:
Nicolas Geoffraye6c0f2a2020-09-07 08:30:52 +01001553 if (method->GetShorty()[0] == 'L') {
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001554 DCHECK_EQ(inline_method.d.data, 0u);
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001555 *return_replacement = graph_->GetNullConstant();
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001556 } else {
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001557 *return_replacement = graph_->GetIntConstant(static_cast<int32_t>(inline_method.d.data));
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001558 }
1559 break;
1560 case kInlineOpIGet: {
1561 const InlineIGetIPutData& data = inline_method.d.ifield_data;
1562 if (data.method_is_static || data.object_arg != 0u) {
1563 // TODO: Needs null check.
1564 return false;
1565 }
1566 HInstruction* obj = GetInvokeInputForArgVRegIndex(invoke_instruction, data.object_arg);
Nicolas Geoffraye6c0f2a2020-09-07 08:30:52 +01001567 HInstanceFieldGet* iget = CreateInstanceFieldGet(data.field_idx, method, obj);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001568 DCHECK_EQ(iget->GetFieldOffset().Uint32Value(), data.field_offset);
1569 DCHECK_EQ(iget->IsVolatile() ? 1u : 0u, data.is_volatile);
1570 invoke_instruction->GetBlock()->InsertInstructionBefore(iget, invoke_instruction);
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001571 *return_replacement = iget;
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001572 break;
1573 }
1574 case kInlineOpIPut: {
1575 const InlineIGetIPutData& data = inline_method.d.ifield_data;
1576 if (data.method_is_static || data.object_arg != 0u) {
1577 // TODO: Needs null check.
1578 return false;
1579 }
1580 HInstruction* obj = GetInvokeInputForArgVRegIndex(invoke_instruction, data.object_arg);
1581 HInstruction* value = GetInvokeInputForArgVRegIndex(invoke_instruction, data.src_arg);
Nicolas Geoffraye6c0f2a2020-09-07 08:30:52 +01001582 HInstanceFieldSet* iput = CreateInstanceFieldSet(data.field_idx, method, obj, value);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001583 DCHECK_EQ(iput->GetFieldOffset().Uint32Value(), data.field_offset);
1584 DCHECK_EQ(iput->IsVolatile() ? 1u : 0u, data.is_volatile);
1585 invoke_instruction->GetBlock()->InsertInstructionBefore(iput, invoke_instruction);
1586 if (data.return_arg_plus1 != 0u) {
1587 size_t return_arg = data.return_arg_plus1 - 1u;
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001588 *return_replacement = GetInvokeInputForArgVRegIndex(invoke_instruction, return_arg);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001589 }
1590 break;
1591 }
Vladimir Marko354efa62016-02-04 19:46:56 +00001592 case kInlineOpConstructor: {
1593 const InlineConstructorData& data = inline_method.d.constructor_data;
1594 // Get the indexes to arrays for easier processing.
1595 uint16_t iput_field_indexes[] = {
1596 data.iput0_field_index, data.iput1_field_index, data.iput2_field_index
1597 };
1598 uint16_t iput_args[] = { data.iput0_arg, data.iput1_arg, data.iput2_arg };
1599 static_assert(arraysize(iput_args) == arraysize(iput_field_indexes), "Size mismatch");
1600 // Count valid field indexes.
1601 size_t number_of_iputs = 0u;
1602 while (number_of_iputs != arraysize(iput_field_indexes) &&
1603 iput_field_indexes[number_of_iputs] != DexFile::kDexNoIndex16) {
1604 // Check that there are no duplicate valid field indexes.
1605 DCHECK_EQ(0, std::count(iput_field_indexes + number_of_iputs + 1,
1606 iput_field_indexes + arraysize(iput_field_indexes),
1607 iput_field_indexes[number_of_iputs]));
1608 ++number_of_iputs;
1609 }
1610 // Check that there are no valid field indexes in the rest of the array.
1611 DCHECK_EQ(0, std::count_if(iput_field_indexes + number_of_iputs,
1612 iput_field_indexes + arraysize(iput_field_indexes),
1613 [](uint16_t index) { return index != DexFile::kDexNoIndex16; }));
1614
1615 // Create HInstanceFieldSet for each IPUT that stores non-zero data.
Andreas Gampe3db70682018-12-26 15:12:03 -08001616 HInstruction* obj = GetInvokeInputForArgVRegIndex(invoke_instruction,
1617 /* arg_vreg_index= */ 0u);
Vladimir Marko354efa62016-02-04 19:46:56 +00001618 bool needs_constructor_barrier = false;
1619 for (size_t i = 0; i != number_of_iputs; ++i) {
1620 HInstruction* value = GetInvokeInputForArgVRegIndex(invoke_instruction, iput_args[i]);
Roland Levillain1a653882016-03-18 18:05:57 +00001621 if (!value->IsConstant() || !value->AsConstant()->IsZeroBitPattern()) {
Vladimir Marko354efa62016-02-04 19:46:56 +00001622 uint16_t field_index = iput_field_indexes[i];
Vladimir Markof44d36c2017-03-14 14:18:46 +00001623 bool is_final;
1624 HInstanceFieldSet* iput =
Nicolas Geoffraye6c0f2a2020-09-07 08:30:52 +01001625 CreateInstanceFieldSet(field_index, method, obj, value, &is_final);
Vladimir Marko354efa62016-02-04 19:46:56 +00001626 invoke_instruction->GetBlock()->InsertInstructionBefore(iput, invoke_instruction);
1627
1628 // Check whether the field is final. If it is, we need to add a barrier.
Vladimir Markof44d36c2017-03-14 14:18:46 +00001629 if (is_final) {
Vladimir Marko354efa62016-02-04 19:46:56 +00001630 needs_constructor_barrier = true;
1631 }
1632 }
1633 }
1634 if (needs_constructor_barrier) {
Vladimir Marko1a2a5cd2018-11-07 15:39:48 +00001635 // See DexCompilationUnit::RequiresConstructorBarrier for more details.
Igor Murashkind01745e2017-04-05 16:40:31 -07001636 DCHECK(obj != nullptr) << "only non-static methods can have a constructor fence";
1637
1638 HConstructorFence* constructor_fence =
Vladimir Markoca6fff82017-10-03 14:49:14 +01001639 new (graph_->GetAllocator()) HConstructorFence(obj, kNoDexPc, graph_->GetAllocator());
Igor Murashkind01745e2017-04-05 16:40:31 -07001640 invoke_instruction->GetBlock()->InsertInstructionBefore(constructor_fence,
1641 invoke_instruction);
Vladimir Marko354efa62016-02-04 19:46:56 +00001642 }
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001643 *return_replacement = nullptr;
Vladimir Marko354efa62016-02-04 19:46:56 +00001644 break;
1645 }
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001646 default:
1647 LOG(FATAL) << "UNREACHABLE";
1648 UNREACHABLE();
1649 }
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001650 return true;
1651}
1652
Vladimir Markof44d36c2017-03-14 14:18:46 +00001653HInstanceFieldGet* HInliner::CreateInstanceFieldGet(uint32_t field_index,
1654 ArtMethod* referrer,
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001655 HInstruction* obj)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001656 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markof44d36c2017-03-14 14:18:46 +00001657 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1658 ArtField* resolved_field =
Andreas Gampe3db70682018-12-26 15:12:03 -08001659 class_linker->LookupResolvedField(field_index, referrer, /* is_static= */ false);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001660 DCHECK(resolved_field != nullptr);
Vladimir Markoca6fff82017-10-03 14:49:14 +01001661 HInstanceFieldGet* iget = new (graph_->GetAllocator()) HInstanceFieldGet(
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001662 obj,
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00001663 resolved_field,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001664 DataType::FromShorty(resolved_field->GetTypeDescriptor()[0]),
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001665 resolved_field->GetOffset(),
1666 resolved_field->IsVolatile(),
1667 field_index,
1668 resolved_field->GetDeclaringClass()->GetDexClassDefIndex(),
Vladimir Markof44d36c2017-03-14 14:18:46 +00001669 *referrer->GetDexFile(),
Vladimir Markoadda4352016-01-29 10:24:41 +00001670 // Read barrier generates a runtime call in slow path and we need a valid
1671 // dex pc for the associated stack map. 0 is bogus but valid. Bug: 26854537.
Andreas Gampe3db70682018-12-26 15:12:03 -08001672 /* dex_pc= */ 0);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001673 if (iget->GetType() == DataType::Type::kReference) {
Vladimir Marko456307a2016-04-19 14:12:13 +00001674 // Use the same dex_cache that we used for field lookup as the hint_dex_cache.
Vladimir Marko02ca05a2020-05-12 13:58:51 +01001675 Handle<mirror::DexCache> dex_cache =
1676 graph_->GetHandleCache()->NewHandle(referrer->GetDexCache());
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001677 ReferenceTypePropagation rtp(graph_,
1678 outer_compilation_unit_.GetClassLoader(),
1679 dex_cache,
Andreas Gampe3db70682018-12-26 15:12:03 -08001680 /* is_first_run= */ false);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001681 rtp.Visit(iget);
1682 }
1683 return iget;
1684}
1685
Vladimir Markof44d36c2017-03-14 14:18:46 +00001686HInstanceFieldSet* HInliner::CreateInstanceFieldSet(uint32_t field_index,
1687 ArtMethod* referrer,
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001688 HInstruction* obj,
Vladimir Markof44d36c2017-03-14 14:18:46 +00001689 HInstruction* value,
1690 bool* is_final)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001691 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markof44d36c2017-03-14 14:18:46 +00001692 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1693 ArtField* resolved_field =
Andreas Gampe3db70682018-12-26 15:12:03 -08001694 class_linker->LookupResolvedField(field_index, referrer, /* is_static= */ false);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001695 DCHECK(resolved_field != nullptr);
Vladimir Markof44d36c2017-03-14 14:18:46 +00001696 if (is_final != nullptr) {
1697 // This information is needed only for constructors.
1698 DCHECK(referrer->IsConstructor());
1699 *is_final = resolved_field->IsFinal();
1700 }
Vladimir Markoca6fff82017-10-03 14:49:14 +01001701 HInstanceFieldSet* iput = new (graph_->GetAllocator()) HInstanceFieldSet(
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001702 obj,
1703 value,
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00001704 resolved_field,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001705 DataType::FromShorty(resolved_field->GetTypeDescriptor()[0]),
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001706 resolved_field->GetOffset(),
1707 resolved_field->IsVolatile(),
1708 field_index,
1709 resolved_field->GetDeclaringClass()->GetDexClassDefIndex(),
Vladimir Markof44d36c2017-03-14 14:18:46 +00001710 *referrer->GetDexFile(),
Vladimir Markoadda4352016-01-29 10:24:41 +00001711 // Read barrier generates a runtime call in slow path and we need a valid
1712 // dex pc for the associated stack map. 0 is bogus but valid. Bug: 26854537.
Andreas Gampe3db70682018-12-26 15:12:03 -08001713 /* dex_pc= */ 0);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001714 return iput;
1715}
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +00001716
Vladimir Markob1d0ee12017-04-20 19:50:32 +01001717template <typename T>
Vladimir Marko02ca05a2020-05-12 13:58:51 +01001718static inline Handle<T> NewHandleIfDifferent(ObjPtr<T> object, Handle<T> hint, HGraph* graph)
Vladimir Markob1d0ee12017-04-20 19:50:32 +01001719 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko02ca05a2020-05-12 13:58:51 +01001720 return (object != hint.Get()) ? graph->GetHandleCache()->NewHandle(object) : hint;
Vladimir Markob1d0ee12017-04-20 19:50:32 +01001721}
1722
Vladimir Marko6be1dbd2018-11-13 13:09:51 +00001723static bool CanEncodeInlinedMethodInStackMap(const DexFile& caller_dex_file, ArtMethod* callee)
1724 REQUIRES_SHARED(Locks::mutator_lock_) {
1725 if (!Runtime::Current()->IsAotCompiler()) {
1726 // JIT can always encode methods in stack maps.
1727 return true;
1728 }
1729 if (IsSameDexFile(caller_dex_file, *callee->GetDexFile())) {
1730 return true;
1731 }
1732 // TODO(ngeoffray): Support more AOT cases for inlining:
1733 // - methods in multidex
1734 // - methods in boot image for on-device non-PIC compilation.
1735 return false;
1736}
1737
Eric Holk1868de92020-02-12 09:10:21 -08001738 // Substitutes parameters in the callee graph with their values from the caller.
1739void HInliner::SubstituteArguments(HGraph* callee_graph,
1740 HInvoke* invoke_instruction,
1741 ReferenceTypeInfo receiver_type,
1742 const DexCompilationUnit& dex_compilation_unit) {
1743 ArtMethod* const resolved_method = callee_graph->GetArtMethod();
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001744 size_t parameter_index = 0;
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001745 bool run_rtp = false;
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001746 for (HInstructionIterator instructions(callee_graph->GetEntryBlock()->GetInstructions());
1747 !instructions.Done();
1748 instructions.Advance()) {
1749 HInstruction* current = instructions.Current();
1750 if (current->IsParameterValue()) {
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001751 HInstruction* argument = invoke_instruction->InputAt(parameter_index);
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001752 if (argument->IsNullConstant()) {
1753 current->ReplaceWith(callee_graph->GetNullConstant());
1754 } else if (argument->IsIntConstant()) {
1755 current->ReplaceWith(callee_graph->GetIntConstant(argument->AsIntConstant()->GetValue()));
1756 } else if (argument->IsLongConstant()) {
1757 current->ReplaceWith(callee_graph->GetLongConstant(argument->AsLongConstant()->GetValue()));
1758 } else if (argument->IsFloatConstant()) {
1759 current->ReplaceWith(
1760 callee_graph->GetFloatConstant(argument->AsFloatConstant()->GetValue()));
1761 } else if (argument->IsDoubleConstant()) {
1762 current->ReplaceWith(
1763 callee_graph->GetDoubleConstant(argument->AsDoubleConstant()->GetValue()));
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001764 } else if (argument->GetType() == DataType::Type::kReference) {
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001765 if (!resolved_method->IsStatic() && parameter_index == 0 && receiver_type.IsValid()) {
1766 run_rtp = true;
1767 current->SetReferenceTypeInfo(receiver_type);
1768 } else {
1769 current->SetReferenceTypeInfo(argument->GetReferenceTypeInfo());
1770 }
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001771 current->AsParameterValue()->SetCanBeNull(argument->CanBeNull());
1772 }
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001773 ++parameter_index;
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001774 }
1775 }
1776
David Brazdil94ab38f2016-06-21 17:48:19 +01001777 // We have replaced formal arguments with actual arguments. If actual types
1778 // are more specific than the declared ones, run RTP again on the inner graph.
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001779 if (run_rtp || ArgumentTypesMoreSpecific(invoke_instruction, resolved_method)) {
David Brazdil94ab38f2016-06-21 17:48:19 +01001780 ReferenceTypePropagation(callee_graph,
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001781 outer_compilation_unit_.GetClassLoader(),
David Brazdil94ab38f2016-06-21 17:48:19 +01001782 dex_compilation_unit.GetDexCache(),
Andreas Gampe3db70682018-12-26 15:12:03 -08001783 /* is_first_run= */ false).Run();
David Brazdil94ab38f2016-06-21 17:48:19 +01001784 }
Eric Holk1868de92020-02-12 09:10:21 -08001785}
David Brazdil94ab38f2016-06-21 17:48:19 +01001786
Eric Holk1868de92020-02-12 09:10:21 -08001787// Returns whether we can inline the callee_graph into the target_block.
1788//
1789// This performs a combination of semantics checks, compiler support checks, and
1790// resource limit checks.
1791//
1792// If this function returns true, it will also set out_number_of_instructions to
1793// the number of instructions in the inlined body.
1794bool HInliner::CanInlineBody(const HGraph* callee_graph,
1795 const HBasicBlock* target_block,
1796 size_t* out_number_of_instructions) const {
Eric Holk1868de92020-02-12 09:10:21 -08001797 ArtMethod* const resolved_method = callee_graph->GetArtMethod();
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +00001798
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001799 HBasicBlock* exit_block = callee_graph->GetExitBlock();
1800 if (exit_block == nullptr) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001801 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedInfiniteLoop)
Nicolas Geoffray8731e702021-04-06 12:11:59 +01001802 << "Method " << resolved_method->PrettyMethod()
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001803 << " could not be inlined because it has an infinite loop";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001804 return false;
1805 }
1806
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00001807 bool has_one_return = false;
Vladimir Marko60584552015-09-03 13:35:12 +00001808 for (HBasicBlock* predecessor : exit_block->GetPredecessors()) {
1809 if (predecessor->GetLastInstruction()->IsThrow()) {
Eric Holk1868de92020-02-12 09:10:21 -08001810 if (target_block->IsTryBlock()) {
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00001811 // TODO(ngeoffray): Support adding HTryBoundary in Hgraph::InlineInto.
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001812 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedTryCatch)
Nicolas Geoffray8731e702021-04-06 12:11:59 +01001813 << "Method " << resolved_method->PrettyMethod()
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001814 << " could not be inlined because one branch always throws and"
1815 << " caller is in a try/catch block";
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00001816 return false;
1817 } else if (graph_->GetExitBlock() == nullptr) {
1818 // TODO(ngeoffray): Support adding HExit in the caller graph.
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001819 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedInfiniteLoop)
Nicolas Geoffray8731e702021-04-06 12:11:59 +01001820 << "Method " << resolved_method->PrettyMethod()
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001821 << " could not be inlined because one branch always throws and"
1822 << " caller does not have an exit block";
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00001823 return false;
Nicolas Geoffray1eede6a2017-03-02 16:14:53 +00001824 } else if (graph_->HasIrreducibleLoops()) {
1825 // TODO(ngeoffray): Support re-computing loop information to graphs with
1826 // irreducible loops?
Nicolas Geoffray8731e702021-04-06 12:11:59 +01001827 VLOG(compiler) << "Method " << resolved_method->PrettyMethod()
Nicolas Geoffray1eede6a2017-03-02 16:14:53 +00001828 << " could not be inlined because one branch always throws and"
1829 << " caller has irreducible loops";
1830 return false;
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00001831 }
1832 } else {
1833 has_one_return = true;
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001834 }
1835 }
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00001836
1837 if (!has_one_return) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001838 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedAlwaysThrows)
Nicolas Geoffray8731e702021-04-06 12:11:59 +01001839 << "Method " << resolved_method->PrettyMethod()
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001840 << " could not be inlined because it always throws";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001841 return false;
1842 }
1843
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001844 size_t number_of_instructions = 0;
Vladimir Marko2c45bc92016-10-25 16:54:12 +01001845 // Skip the entry block, it does not contain instructions that prevent inlining.
1846 for (HBasicBlock* block : callee_graph->GetReversePostOrderSkipEntryBlock()) {
David Sehrc757dec2016-11-04 15:48:34 -07001847 if (block->IsLoopHeader()) {
1848 if (block->GetLoopInformation()->IsIrreducible()) {
1849 // Don't inline methods with irreducible loops, they could prevent some
1850 // optimizations to run.
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001851 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedIrreducibleLoop)
Nicolas Geoffray8731e702021-04-06 12:11:59 +01001852 << "Method " << resolved_method->PrettyMethod()
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001853 << " could not be inlined because it contains an irreducible loop";
David Sehrc757dec2016-11-04 15:48:34 -07001854 return false;
1855 }
1856 if (!block->GetLoopInformation()->HasExitEdge()) {
1857 // Don't inline methods with loops without exit, since they cause the
1858 // loop information to be computed incorrectly when updating after
1859 // inlining.
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001860 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedLoopWithoutExit)
Nicolas Geoffray8731e702021-04-06 12:11:59 +01001861 << "Method " << resolved_method->PrettyMethod()
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001862 << " could not be inlined because it contains a loop with no exit";
David Sehrc757dec2016-11-04 15:48:34 -07001863 return false;
1864 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001865 }
1866
1867 for (HInstructionIterator instr_it(block->GetInstructions());
1868 !instr_it.Done();
1869 instr_it.Advance()) {
Tim Murray674e8be2021-04-12 12:30:28 -07001870 if (++number_of_instructions > inlining_budget_) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001871 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedInstructionBudget)
Nicolas Geoffray8731e702021-04-06 12:11:59 +01001872 << "Method " << resolved_method->PrettyMethod()
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001873 << " is not inlined because the outer method has reached"
1874 << " its instruction budget limit.";
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001875 return false;
1876 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001877 HInstruction* current = instr_it.Current();
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001878 if (current->NeedsEnvironment() &&
Tim Murray674e8be2021-04-12 12:30:28 -07001879 (total_number_of_dex_registers_ > kMaximumNumberOfCumulatedDexRegisters)) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001880 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedEnvironmentBudget)
Nicolas Geoffray8731e702021-04-06 12:11:59 +01001881 << "Method " << resolved_method->PrettyMethod()
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001882 << " is not inlined because its caller has reached"
1883 << " its environment budget limit.";
Nicolas Geoffray5949fa02015-12-18 10:57:10 +00001884 return false;
1885 }
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001886
Nicolas Geoffrayfbdfa6d2017-02-03 10:43:13 +00001887 if (current->NeedsEnvironment() &&
1888 !CanEncodeInlinedMethodInStackMap(*caller_compilation_unit_.GetDexFile(),
1889 resolved_method)) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001890 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedStackMaps)
Nicolas Geoffray8731e702021-04-06 12:11:59 +01001891 << "Method " << resolved_method->PrettyMethod()
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001892 << " could not be inlined because " << current->DebugName()
1893 << " needs an environment, is in a different dex file"
1894 << ", and cannot be encoded in the stack maps.";
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001895 return false;
1896 }
Nicolas Geoffray9437b782015-03-25 10:08:51 +00001897
Nicolas Geoffrayd9309292015-10-31 22:21:31 +00001898 if (current->IsUnresolvedStaticFieldGet() ||
1899 current->IsUnresolvedInstanceFieldGet() ||
1900 current->IsUnresolvedStaticFieldSet() ||
1901 current->IsUnresolvedInstanceFieldSet()) {
1902 // Entrypoint for unresolved fields does not handle inlined frames.
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001903 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedUnresolvedEntrypoint)
Nicolas Geoffray8731e702021-04-06 12:11:59 +01001904 << "Method " << resolved_method->PrettyMethod()
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001905 << " could not be inlined because it is using an unresolved"
1906 << " entrypoint";
Nicolas Geoffrayd9309292015-10-31 22:21:31 +00001907 return false;
1908 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001909 }
1910 }
Eric Holk1868de92020-02-12 09:10:21 -08001911
1912 *out_number_of_instructions = number_of_instructions;
1913 return true;
1914}
1915
1916bool HInliner::TryBuildAndInlineHelper(HInvoke* invoke_instruction,
1917 ArtMethod* resolved_method,
1918 ReferenceTypeInfo receiver_type,
1919 HInstruction** return_replacement) {
1920 DCHECK(!(resolved_method->IsStatic() && receiver_type.IsValid()));
1921 const dex::CodeItem* code_item = resolved_method->GetCodeItem();
1922 const DexFile& callee_dex_file = *resolved_method->GetDexFile();
1923 uint32_t method_index = resolved_method->GetDexMethodIndex();
1924 CodeItemDebugInfoAccessor code_item_accessor(resolved_method->DexInstructionDebugInfo());
1925 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
1926 Handle<mirror::DexCache> dex_cache = NewHandleIfDifferent(resolved_method->GetDexCache(),
1927 caller_compilation_unit_.GetDexCache(),
Vladimir Marko02ca05a2020-05-12 13:58:51 +01001928 graph_);
Eric Holk1868de92020-02-12 09:10:21 -08001929 Handle<mirror::ClassLoader> class_loader =
1930 NewHandleIfDifferent(resolved_method->GetDeclaringClass()->GetClassLoader(),
1931 caller_compilation_unit_.GetClassLoader(),
Vladimir Marko02ca05a2020-05-12 13:58:51 +01001932 graph_);
Eric Holk1868de92020-02-12 09:10:21 -08001933
Vladimir Marko02ca05a2020-05-12 13:58:51 +01001934 Handle<mirror::Class> compiling_class =
1935 graph_->GetHandleCache()->NewHandle(resolved_method->GetDeclaringClass());
Eric Holk1868de92020-02-12 09:10:21 -08001936 DexCompilationUnit dex_compilation_unit(
1937 class_loader,
1938 class_linker,
1939 callee_dex_file,
1940 code_item,
1941 resolved_method->GetDeclaringClass()->GetDexClassDefIndex(),
1942 method_index,
1943 resolved_method->GetAccessFlags(),
1944 /* verified_method= */ nullptr,
1945 dex_cache,
1946 compiling_class);
1947
1948 InvokeType invoke_type = invoke_instruction->GetInvokeType();
1949 if (invoke_type == kInterface) {
1950 // We have statically resolved the dispatch. To please the class linker
1951 // at runtime, we change this call as if it was a virtual call.
1952 invoke_type = kVirtual;
1953 }
1954
1955 bool caller_dead_reference_safe = graph_->IsDeadReferenceSafe();
1956 const dex::ClassDef& callee_class = resolved_method->GetClassDef();
1957 // MethodContainsRSensitiveAccess is currently slow, but HasDeadReferenceSafeAnnotation()
1958 // is currently rarely true.
1959 bool callee_dead_reference_safe =
1960 annotations::HasDeadReferenceSafeAnnotation(callee_dex_file, callee_class)
1961 && !annotations::MethodContainsRSensitiveAccess(callee_dex_file, callee_class, method_index);
1962
1963 const int32_t caller_instruction_counter = graph_->GetCurrentInstructionId();
1964 HGraph* callee_graph = new (graph_->GetAllocator()) HGraph(
1965 graph_->GetAllocator(),
1966 graph_->GetArenaStack(),
Vladimir Marko02ca05a2020-05-12 13:58:51 +01001967 graph_->GetHandleCache()->GetHandles(),
Eric Holk1868de92020-02-12 09:10:21 -08001968 callee_dex_file,
1969 method_index,
1970 codegen_->GetCompilerOptions().GetInstructionSet(),
1971 invoke_type,
1972 callee_dead_reference_safe,
1973 graph_->IsDebuggable(),
Nicolas Geoffray0d60a2b2020-06-17 14:31:56 +01001974 graph_->GetCompilationKind(),
Eric Holk1868de92020-02-12 09:10:21 -08001975 /* start_instruction_id= */ caller_instruction_counter);
1976 callee_graph->SetArtMethod(resolved_method);
1977
1978 // When they are needed, allocate `inline_stats_` on the Arena instead
1979 // of on the stack, as Clang might produce a stack frame too large
1980 // for this function, that would not fit the requirements of the
1981 // `-Wframe-larger-than` option.
1982 if (stats_ != nullptr) {
1983 // Reuse one object for all inline attempts from this caller to keep Arena memory usage low.
1984 if (inline_stats_ == nullptr) {
1985 void* storage = graph_->GetAllocator()->Alloc<OptimizingCompilerStats>(kArenaAllocMisc);
1986 inline_stats_ = new (storage) OptimizingCompilerStats;
1987 } else {
1988 inline_stats_->Reset();
1989 }
1990 }
1991 HGraphBuilder builder(callee_graph,
1992 code_item_accessor,
1993 &dex_compilation_unit,
1994 &outer_compilation_unit_,
1995 codegen_,
Nicolas Geoffray4924ea92021-03-23 08:25:31 +00001996 inline_stats_);
Eric Holk1868de92020-02-12 09:10:21 -08001997
1998 if (builder.BuildGraph() != kAnalysisSuccess) {
1999 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedCannotBuild)
2000 << "Method " << callee_dex_file.PrettyMethod(method_index)
2001 << " could not be built, so cannot be inlined";
2002 return false;
2003 }
2004
2005 SubstituteArguments(callee_graph, invoke_instruction, receiver_type, dex_compilation_unit);
2006
2007 RunOptimizations(callee_graph, code_item, dex_compilation_unit);
2008
2009 size_t number_of_instructions = 0;
2010 if (!CanInlineBody(callee_graph, invoke_instruction->GetBlock(), &number_of_instructions)) {
2011 return false;
2012 }
2013
David Brazdil3f523062016-02-29 16:53:33 +00002014 DCHECK_EQ(caller_instruction_counter, graph_->GetCurrentInstructionId())
2015 << "No instructions can be added to the outer graph while inner graph is being built";
2016
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00002017 // Inline the callee graph inside the caller graph.
David Brazdil3f523062016-02-29 16:53:33 +00002018 const int32_t callee_instruction_counter = callee_graph->GetCurrentInstructionId();
2019 graph_->SetCurrentInstructionId(callee_instruction_counter);
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00002020 *return_replacement = callee_graph->InlineInto(graph_, invoke_instruction);
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00002021 // Update our budget for other inlining attempts in `caller_graph`.
2022 total_number_of_instructions_ += number_of_instructions;
2023 UpdateInliningBudget();
David Brazdil3f523062016-02-29 16:53:33 +00002024
2025 DCHECK_EQ(callee_instruction_counter, callee_graph->GetCurrentInstructionId())
2026 << "No instructions can be added to the inner graph during inlining into the outer graph";
2027
Vladimir Marko438709f2017-02-23 18:56:13 +00002028 if (stats_ != nullptr) {
2029 DCHECK(inline_stats_ != nullptr);
2030 inline_stats_->AddTo(stats_);
2031 }
2032
Hans Boehm206348c2018-12-05 11:11:33 -08002033 if (caller_dead_reference_safe && !callee_dead_reference_safe) {
2034 // Caller was dead reference safe, but is not anymore, since we inlined dead
2035 // reference unsafe code. Prior transformations remain valid, since they did not
2036 // affect the inlined code.
2037 graph_->MarkDeadReferenceUnsafe();
2038 }
2039
Vladimir Markobe10e8e2016-01-22 12:09:44 +00002040 return true;
2041}
Calin Juravle2e768302015-07-28 14:41:11 +00002042
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00002043void HInliner::RunOptimizations(HGraph* callee_graph,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08002044 const dex::CodeItem* code_item,
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00002045 const DexCompilationUnit& dex_compilation_unit) {
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01002046 // Note: if the outermost_graph_ is being compiled OSR, we should not run any
2047 // optimization that could lead to a HDeoptimize. The following optimizations do not.
Vladimir Marko438709f2017-02-23 18:56:13 +00002048 HDeadCodeElimination dce(callee_graph, inline_stats_, "dead_code_elimination$inliner");
Andreas Gampeca620d72016-11-08 08:09:33 -08002049 HConstantFolding fold(callee_graph, "constant_folding$inliner");
Vladimir Markobb089b62018-06-28 17:30:16 +01002050 InstructionSimplifier simplify(callee_graph, codegen_, inline_stats_);
Roland Levillaina3aef2e2016-04-06 17:45:58 +01002051
2052 HOptimization* optimizations[] = {
Roland Levillaina3aef2e2016-04-06 17:45:58 +01002053 &simplify,
2054 &fold,
2055 &dce,
2056 };
2057
2058 for (size_t i = 0; i < arraysize(optimizations); ++i) {
2059 HOptimization* optimization = optimizations[i];
2060 optimization->Run();
2061 }
2062
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00002063 // Bail early for pathological cases on the environment (for example recursive calls,
2064 // or too large environment).
Tim Murray674e8be2021-04-12 12:30:28 -07002065 if (total_number_of_dex_registers_ > kMaximumNumberOfCumulatedDexRegisters) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00002066 LOG_NOTE() << "Calls in " << callee_graph->GetArtMethod()->PrettyMethod()
2067 << " will not be inlined because the outer method has reached"
2068 << " its environment budget limit.";
2069 return;
Roland Levillaina3aef2e2016-04-06 17:45:58 +01002070 }
2071
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00002072 // Bail early if we know we already are over the limit.
2073 size_t number_of_instructions = CountNumberOfInstructions(callee_graph);
2074 if (number_of_instructions > inlining_budget_) {
2075 LOG_NOTE() << "Calls in " << callee_graph->GetArtMethod()->PrettyMethod()
2076 << " will not be inlined because the outer method has reached"
2077 << " its instruction budget limit. " << number_of_instructions;
2078 return;
2079 }
2080
Mathieu Chartier698ebbc2018-01-05 11:00:42 -08002081 CodeItemDataAccessor accessor(callee_graph->GetDexFile(), code_item);
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00002082 HInliner inliner(callee_graph,
2083 outermost_graph_,
2084 codegen_,
2085 outer_compilation_unit_,
2086 dex_compilation_unit,
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00002087 inline_stats_,
Mathieu Chartier808c7a52017-12-15 11:19:33 -08002088 total_number_of_dex_registers_ + accessor.RegistersSize(),
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00002089 total_number_of_instructions_ + number_of_instructions,
2090 this,
2091 depth_ + 1);
2092 inliner.Run();
Roland Levillaina3aef2e2016-04-06 17:45:58 +01002093}
2094
Vladimir Marko5a62af52020-05-11 15:16:24 +01002095static bool IsReferenceTypeRefinement(ObjPtr<mirror::Class> declared_class,
2096 bool declared_is_exact,
David Brazdil94ab38f2016-06-21 17:48:19 +01002097 bool declared_can_be_null,
2098 HInstruction* actual_obj)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002099 REQUIRES_SHARED(Locks::mutator_lock_) {
David Brazdil94ab38f2016-06-21 17:48:19 +01002100 if (declared_can_be_null && !actual_obj->CanBeNull()) {
2101 return true;
2102 }
2103
2104 ReferenceTypeInfo actual_rti = actual_obj->GetReferenceTypeInfo();
Vladimir Marko5a62af52020-05-11 15:16:24 +01002105 ObjPtr<mirror::Class> actual_class = actual_rti.GetTypeHandle().Get();
2106 return (actual_rti.IsExact() && !declared_is_exact) ||
2107 (declared_class != actual_class && declared_class->IsAssignableFrom(actual_class));
David Brazdil94ab38f2016-06-21 17:48:19 +01002108}
2109
Vladimir Marko5a62af52020-05-11 15:16:24 +01002110static bool IsReferenceTypeRefinement(ObjPtr<mirror::Class> declared_class,
2111 bool declared_can_be_null,
2112 HInstruction* actual_obj)
2113 REQUIRES_SHARED(Locks::mutator_lock_) {
2114 bool admissible = ReferenceTypePropagation::IsAdmissible(declared_class);
2115 return IsReferenceTypeRefinement(
2116 admissible ? declared_class : GetClassRoot<mirror::Class>(),
2117 /*declared_is_exact=*/ admissible && declared_class->CannotBeAssignedFromOtherTypes(),
2118 declared_can_be_null,
2119 actual_obj);
David Brazdil94ab38f2016-06-21 17:48:19 +01002120}
2121
2122bool HInliner::ArgumentTypesMoreSpecific(HInvoke* invoke_instruction, ArtMethod* resolved_method) {
2123 // If this is an instance call, test whether the type of the `this` argument
2124 // is more specific than the class which declares the method.
2125 if (!resolved_method->IsStatic()) {
Vladimir Marko5a62af52020-05-11 15:16:24 +01002126 if (IsReferenceTypeRefinement(resolved_method->GetDeclaringClass(),
2127 /*declared_can_be_null=*/ false,
David Brazdil94ab38f2016-06-21 17:48:19 +01002128 invoke_instruction->InputAt(0u))) {
2129 return true;
2130 }
2131 }
2132
David Brazdil94ab38f2016-06-21 17:48:19 +01002133 // Iterate over the list of parameter types and test whether any of the
2134 // actual inputs has a more specific reference type than the type declared in
2135 // the signature.
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08002136 const dex::TypeList* param_list = resolved_method->GetParameterTypeList();
David Brazdil94ab38f2016-06-21 17:48:19 +01002137 for (size_t param_idx = 0,
2138 input_idx = resolved_method->IsStatic() ? 0 : 1,
2139 e = (param_list == nullptr ? 0 : param_list->Size());
2140 param_idx < e;
2141 ++param_idx, ++input_idx) {
2142 HInstruction* input = invoke_instruction->InputAt(input_idx);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002143 if (input->GetType() == DataType::Type::kReference) {
Vladimir Markob45528c2017-07-27 14:14:28 +01002144 ObjPtr<mirror::Class> param_cls = resolved_method->LookupResolvedClassFromTypeIndex(
2145 param_list->GetTypeItem(param_idx).type_idx_);
Vladimir Marko5a62af52020-05-11 15:16:24 +01002146 if (IsReferenceTypeRefinement(param_cls, /*declared_can_be_null=*/ true, input)) {
David Brazdil94ab38f2016-06-21 17:48:19 +01002147 return true;
2148 }
2149 }
2150 }
2151
2152 return false;
2153}
2154
Nicolas Geoffraye1e0e0f2021-04-29 08:57:13 +00002155bool HInliner::ReturnTypeMoreSpecific(HInstruction* return_replacement,
2156 HInvoke* invoke_instruction) {
Alex Light68289a52015-12-15 17:30:30 -08002157 // Check the integrity of reference types and run another type propagation if needed.
David Brazdil4833f5a2015-12-16 10:37:39 +00002158 if (return_replacement != nullptr) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002159 if (return_replacement->GetType() == DataType::Type::kReference) {
David Brazdil94ab38f2016-06-21 17:48:19 +01002160 // Test if the return type is a refinement of the declared return type.
Vladimir Marko5a62af52020-05-11 15:16:24 +01002161 ReferenceTypeInfo invoke_rti = invoke_instruction->GetReferenceTypeInfo();
2162 if (IsReferenceTypeRefinement(invoke_rti.GetTypeHandle().Get(),
2163 invoke_rti.IsExact(),
2164 /*declared_can_be_null=*/ true,
David Brazdil94ab38f2016-06-21 17:48:19 +01002165 return_replacement)) {
2166 return true;
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00002167 } else if (return_replacement->IsInstanceFieldGet()) {
2168 HInstanceFieldGet* field_get = return_replacement->AsInstanceFieldGet();
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00002169 if (field_get->GetFieldInfo().GetField() ==
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002170 GetClassRoot<mirror::Object>()->GetInstanceField(0)) {
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00002171 return true;
2172 }
David Brazdil94ab38f2016-06-21 17:48:19 +01002173 }
2174 } else if (return_replacement->IsInstanceOf()) {
2175 // Inlining InstanceOf into an If may put a tighter bound on reference types.
2176 return true;
2177 }
2178 }
2179
2180 return false;
2181}
2182
2183void HInliner::FixUpReturnReferenceType(ArtMethod* resolved_method,
2184 HInstruction* return_replacement) {
2185 if (return_replacement != nullptr) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002186 if (return_replacement->GetType() == DataType::Type::kReference) {
David Brazdil4833f5a2015-12-16 10:37:39 +00002187 if (!return_replacement->GetReferenceTypeInfo().IsValid()) {
2188 // Make sure that we have a valid type for the return. We may get an invalid one when
2189 // we inline invokes with multiple branches and create a Phi for the result.
2190 // TODO: we could be more precise by merging the phi inputs but that requires
2191 // some functionality from the reference type propagation.
2192 DCHECK(return_replacement->IsPhi());
Vladimir Markob45528c2017-07-27 14:14:28 +01002193 ObjPtr<mirror::Class> cls = resolved_method->LookupResolvedReturnType();
Vladimir Marko5a62af52020-05-11 15:16:24 +01002194 ReferenceTypeInfo rti = ReferenceTypePropagation::IsAdmissible(cls)
Vladimir Marko02ca05a2020-05-12 13:58:51 +01002195 ? ReferenceTypeInfo::Create(graph_->GetHandleCache()->NewHandle(cls))
Vladimir Marko5a62af52020-05-11 15:16:24 +01002196 : graph_->GetInexactObjectRti();
2197 return_replacement->SetReferenceTypeInfo(rti);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01002198 }
Calin Juravlecdfed3d2015-10-26 14:05:01 +00002199 }
Calin Juravle2e768302015-07-28 14:41:11 +00002200 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002201}
2202
2203} // namespace art