blob: a40218d7a07edac066f4df02905018765a25c35b [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"
Calin Juravleec748352015-07-29 13:52:12 +010029#include "driver/compiler_options.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000030#include "driver/dex_compilation_unit.h"
31#include "instruction_simplifier.h"
Scott Wakelingd60a1af2015-07-22 14:32:44 +010032#include "intrinsics.h"
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +000033#include "jit/jit.h"
34#include "jit/jit_code_cache.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000035#include "mirror/class_loader.h"
36#include "mirror/dex_cache.h"
Andreas Gampe52ecb652018-10-24 15:18:21 -070037#include "mirror/object_array-alloc-inl.h"
38#include "mirror/object_array-inl.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000039#include "nodes.h"
Nicolas Geoffray454a4812015-06-09 10:37:32 +010040#include "reference_type_propagation.h"
Matthew Gharritye9288852016-07-14 14:08:16 -070041#include "register_allocator_linear_scan.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070042#include "scoped_thread_state_change-inl.h"
Vladimir Markodc151b22015-10-15 18:02:30 +010043#include "sharpening.h"
David Brazdil4833f5a2015-12-16 10:37:39 +000044#include "ssa_builder.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000045#include "ssa_phi_elimination.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000046#include "thread.h"
Nicolas Geoffray5da05072021-06-18 15:51:12 +010047#include "verifier/verifier_compiler_binding.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000048
Vladimir Marko0a516052019-10-14 13:00:44 +000049namespace art {
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000050
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +000051// Instruction limit to control memory.
52static constexpr size_t kMaximumNumberOfTotalInstructions = 1024;
53
54// Maximum number of instructions for considering a method small,
55// which we will always try to inline if the other non-instruction limits
56// are not reached.
57static constexpr size_t kMaximumNumberOfInstructionsForSmallMethod = 3;
Nicolas Geoffray5949fa02015-12-18 10:57:10 +000058
59// Limit the number of dex registers that we accumulate while inlining
60// to avoid creating large amount of nested environments.
Nicolas Geoffrayf81621e2017-06-07 13:18:03 +010061static constexpr size_t kMaximumNumberOfCumulatedDexRegisters = 32;
Nicolas Geoffray5949fa02015-12-18 10:57:10 +000062
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +000063// Limit recursive call inlining, which do not benefit from too
64// much inlining compared to code locality.
65static constexpr size_t kMaximumNumberOfRecursiveCalls = 4;
Nicolas Geoffraye418dda2015-08-11 20:03:09 -070066
Calin Juravlee2492d42017-03-20 11:42:13 -070067// Controls the use of inline caches in AOT mode.
Calin Juravle8af70892017-03-28 15:31:44 -070068static constexpr bool kUseAOTInlineCaches = true;
Calin Juravlee2492d42017-03-20 11:42:13 -070069
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +000070// We check for line numbers to make sure the DepthString implementation
71// aligns the output nicely.
72#define LOG_INTERNAL(msg) \
73 static_assert(__LINE__ > 10, "Unhandled line number"); \
74 static_assert(__LINE__ < 10000, "Unhandled line number"); \
75 VLOG(compiler) << DepthString(__LINE__) << msg
76
77#define LOG_TRY() LOG_INTERNAL("Try inlinining call: ")
78#define LOG_NOTE() LOG_INTERNAL("Note: ")
79#define LOG_SUCCESS() LOG_INTERNAL("Success: ")
Igor Murashkin1e065a52017-08-09 13:20:34 -070080#define LOG_FAIL(stats_ptr, stat) MaybeRecordStat(stats_ptr, stat); LOG_INTERNAL("Fail: ")
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +000081#define LOG_FAIL_NO_STAT() LOG_INTERNAL("Fail: ")
82
83std::string HInliner::DepthString(int line) const {
84 std::string value;
85 // Indent according to the inlining depth.
86 size_t count = depth_;
87 // Line numbers get printed in the log, so add a space if the log's line is less
88 // than 1000, and two if less than 100. 10 cannot be reached as it's the copyright.
89 if (!kIsTargetBuild) {
90 if (line < 100) {
91 value += " ";
92 }
93 if (line < 1000) {
94 value += " ";
95 }
96 // Safeguard if this file reaches more than 10000 lines.
97 DCHECK_LT(line, 10000);
98 }
99 for (size_t i = 0; i < count; ++i) {
100 value += " ";
101 }
102 return value;
103}
104
105static size_t CountNumberOfInstructions(HGraph* graph) {
106 size_t number_of_instructions = 0;
107 for (HBasicBlock* block : graph->GetReversePostOrderSkipEntryBlock()) {
108 for (HInstructionIterator instr_it(block->GetInstructions());
109 !instr_it.Done();
110 instr_it.Advance()) {
111 ++number_of_instructions;
112 }
113 }
114 return number_of_instructions;
115}
116
117void HInliner::UpdateInliningBudget() {
118 if (total_number_of_instructions_ >= kMaximumNumberOfTotalInstructions) {
119 // Always try to inline small methods.
120 inlining_budget_ = kMaximumNumberOfInstructionsForSmallMethod;
121 } else {
122 inlining_budget_ = std::max(
123 kMaximumNumberOfInstructionsForSmallMethod,
124 kMaximumNumberOfTotalInstructions - total_number_of_instructions_);
125 }
126}
127
Aart Bik24773202018-04-26 10:28:51 -0700128bool HInliner::Run() {
Vladimir Marko213ee2d2018-06-22 11:56:34 +0100129 if (codegen_->GetCompilerOptions().GetInlineMaxCodeUnits() == 0) {
Aart Bik24773202018-04-26 10:28:51 -0700130 // Inlining effectively disabled.
131 return false;
132 } else if (graph_->IsDebuggable()) {
Nicolas Geoffraye50b8d22015-03-13 08:57:42 +0000133 // For simplicity, we currently never inline when the graph is debuggable. This avoids
134 // doing some logic in the runtime to discover if a method could have been inlined.
Aart Bik24773202018-04-26 10:28:51 -0700135 return false;
Nicolas Geoffraye50b8d22015-03-13 08:57:42 +0000136 }
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000137
Aart Bik24773202018-04-26 10:28:51 -0700138 bool didInline = false;
139
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000140 // Initialize the number of instructions for the method being compiled. Recursive calls
141 // to HInliner::Run have already updated the instruction count.
142 if (outermost_graph_ == graph_) {
143 total_number_of_instructions_ = CountNumberOfInstructions(graph_);
144 }
145
146 UpdateInliningBudget();
147 DCHECK_NE(total_number_of_instructions_, 0u);
148 DCHECK_NE(inlining_budget_, 0u);
149
David Srbecky4fa07a52020-03-31 20:52:09 +0100150 // If we're compiling tests, honor inlining directives in method names:
Roland Levillain6c3af162017-04-27 11:18:56 +0100151 // - if a method's name contains the substring "$noinline$", do not
Vladimir Marko6be1dbd2018-11-13 13:09:51 +0000152 // inline that method;
153 // - if a method's name contains the substring "$inline$", ensure
154 // that this method is actually inlined.
Vladimir Markobe0c7cf2018-03-19 13:40:56 +0000155 // We limit the latter to AOT compilation, as the JIT may or may not inline
Nicolas Geoffray08490b82017-07-18 12:58:10 +0100156 // depending on the state of classes at runtime.
David Srbecky4fa07a52020-03-31 20:52:09 +0100157 const bool honor_noinline_directives = codegen_->GetCompilerOptions().CompileArtTest();
Vladimir Markobe0c7cf2018-03-19 13:40:56 +0000158 const bool honor_inline_directives =
159 honor_noinline_directives && Runtime::Current()->IsAotCompiler();
Roland Levillain6c3af162017-04-27 11:18:56 +0100160
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +0000161 // Keep a copy of all blocks when starting the visit.
162 ArenaVector<HBasicBlock*> blocks = graph_->GetReversePostOrder();
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100163 DCHECK(!blocks.empty());
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +0000164 // Because we are changing the graph when inlining,
165 // we just iterate over the blocks of the outer method.
166 // This avoids doing the inlining work again on the inlined blocks.
167 for (HBasicBlock* block : blocks) {
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +0000168 for (HInstruction* instruction = block->GetFirstInstruction(); instruction != nullptr;) {
169 HInstruction* next = instruction->GetNext();
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100170 HInvoke* call = instruction->AsInvoke();
Razvan A Lupusoru3e90a962015-03-27 13:44:44 -0700171 // As long as the call is not intrinsified, it is worth trying to inline.
172 if (call != nullptr && call->GetIntrinsic() == Intrinsics::kNone) {
Vladimir Markobe0c7cf2018-03-19 13:40:56 +0000173 if (honor_noinline_directives) {
Nicolas Geoffrayb703d182017-02-14 18:05:28 +0000174 // Debugging case: directives in method names control or assert on inlining.
Nicolas Geoffraye6c0f2a2020-09-07 08:30:52 +0100175 std::string callee_name =
176 call->GetMethodReference().PrettyMethod(/* with_signature= */ false);
Nicolas Geoffrayb703d182017-02-14 18:05:28 +0000177 // Tests prevent inlining by having $noinline$ in their method names.
178 if (callee_name.find("$noinline$") == std::string::npos) {
Aart Bik24773202018-04-26 10:28:51 -0700179 if (TryInline(call)) {
180 didInline = true;
Aart Bik54e45c52018-04-27 13:57:21 -0700181 } else if (honor_inline_directives) {
Nicolas Geoffray1949baf2017-10-17 12:14:53 +0000182 bool should_have_inlined = (callee_name.find("$inline$") != std::string::npos);
183 CHECK(!should_have_inlined) << "Could not inline " << callee_name;
Nicolas Geoffrayb703d182017-02-14 18:05:28 +0000184 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000185 }
Guillaume "Vermeille" Sancheze918d382015-06-03 15:32:41 +0100186 } else {
Vladimir Markobe0c7cf2018-03-19 13:40:56 +0000187 DCHECK(!honor_inline_directives);
Nicolas Geoffrayb703d182017-02-14 18:05:28 +0000188 // Normal case: try to inline.
Aart Bik24773202018-04-26 10:28:51 -0700189 if (TryInline(call)) {
190 didInline = true;
191 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000192 }
193 }
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +0000194 instruction = next;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000195 }
196 }
Aart Bik24773202018-04-26 10:28:51 -0700197
198 return didInline;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000199}
200
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100201static bool IsMethodOrDeclaringClassFinal(ArtMethod* method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700202 REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100203 return method->IsFinal() || method->GetDeclaringClass()->IsFinal();
204}
205
206/**
207 * Given the `resolved_method` looked up in the dex cache, try to find
208 * the actual runtime target of an interface or virtual call.
209 * Return nullptr if the runtime target cannot be proven.
210 */
Nicolas Geoffraye6c0f2a2020-09-07 08:30:52 +0100211static ArtMethod* FindVirtualOrInterfaceTarget(HInvoke* invoke)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700212 REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffraye6c0f2a2020-09-07 08:30:52 +0100213 ArtMethod* resolved_method = invoke->GetResolvedMethod();
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100214 if (IsMethodOrDeclaringClassFinal(resolved_method)) {
215 // No need to lookup further, the resolved method will be the target.
216 return resolved_method;
217 }
218
219 HInstruction* receiver = invoke->InputAt(0);
220 if (receiver->IsNullCheck()) {
221 // Due to multiple levels of inlining within the same pass, it might be that
222 // null check does not have the reference type of the actual receiver.
223 receiver = receiver->InputAt(0);
224 }
225 ReferenceTypeInfo info = receiver->GetReferenceTypeInfo();
Calin Juravle2e768302015-07-28 14:41:11 +0000226 DCHECK(info.IsValid()) << "Invalid RTI for " << receiver->DebugName();
227 if (!info.IsExact()) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100228 // We currently only support inlining with known receivers.
229 // TODO: Remove this check, we should be able to inline final methods
230 // on unknown receivers.
231 return nullptr;
232 } else if (info.GetTypeHandle()->IsInterface()) {
233 // Statically knowing that the receiver has an interface type cannot
234 // help us find what is the target method.
235 return nullptr;
236 } else if (!resolved_method->GetDeclaringClass()->IsAssignableFrom(info.GetTypeHandle().Get())) {
237 // The method that we're trying to call is not in the receiver's class or super classes.
238 return nullptr;
Nicolas Geoffrayab5327d2016-03-18 11:36:20 +0000239 } else if (info.GetTypeHandle()->IsErroneous()) {
240 // If the type is erroneous, do not go further, as we are going to query the vtable or
241 // imt table, that we can only safely do on non-erroneous classes.
242 return nullptr;
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100243 }
244
245 ClassLinker* cl = Runtime::Current()->GetClassLinker();
Andreas Gampe542451c2016-07-26 09:02:02 -0700246 PointerSize pointer_size = cl->GetImagePointerSize();
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100247 if (invoke->IsInvokeInterface()) {
248 resolved_method = info.GetTypeHandle()->FindVirtualMethodForInterface(
249 resolved_method, pointer_size);
250 } else {
251 DCHECK(invoke->IsInvokeVirtual());
252 resolved_method = info.GetTypeHandle()->FindVirtualMethodForVirtual(
253 resolved_method, pointer_size);
254 }
255
256 if (resolved_method == nullptr) {
257 // The information we had on the receiver was not enough to find
258 // the target method. Since we check above the exact type of the receiver,
259 // the only reason this can happen is an IncompatibleClassChangeError.
260 return nullptr;
Alex Light9139e002015-10-09 15:59:48 -0700261 } else if (!resolved_method->IsInvokable()) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100262 // The information we had on the receiver was not enough to find
263 // the target method. Since we check above the exact type of the receiver,
264 // the only reason this can happen is an IncompatibleClassChangeError.
265 return nullptr;
266 } else if (IsMethodOrDeclaringClassFinal(resolved_method)) {
267 // A final method has to be the target method.
268 return resolved_method;
269 } else if (info.IsExact()) {
270 // If we found a method and the receiver's concrete type is statically
271 // known, we know for sure the target.
272 return resolved_method;
273 } else {
274 // Even if we did find a method, the receiver type was not enough to
275 // statically find the runtime target.
276 return nullptr;
277 }
278}
279
280static uint32_t FindMethodIndexIn(ArtMethod* method,
281 const DexFile& dex_file,
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +0000282 uint32_t name_and_signature_index)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700283 REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100284 if (IsSameDexFile(*method->GetDexFile(), dex_file)) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100285 return method->GetDexMethodIndex();
286 } else {
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +0000287 return method->FindDexMethodIndexInOtherDexFile(dex_file, name_and_signature_index);
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100288 }
289}
290
Vladimir Marko423bebb2019-03-26 15:17:21 +0000291static dex::TypeIndex FindClassIndexIn(ObjPtr<mirror::Class> cls,
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000292 const DexCompilationUnit& compilation_unit)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700293 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000294 const DexFile& dex_file = *compilation_unit.GetDexFile();
Andreas Gampea5b09a62016-11-17 15:21:22 -0800295 dex::TypeIndex index;
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100296 if (cls->GetDexCache() == nullptr) {
David Sehr709b0702016-10-13 09:12:37 -0700297 DCHECK(cls->IsArrayClass()) << cls->PrettyClass();
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000298 index = cls->FindTypeIndexInOtherDexFile(dex_file);
Andreas Gampea5b09a62016-11-17 15:21:22 -0800299 } else if (!cls->GetDexTypeIndex().IsValid()) {
David Sehr709b0702016-10-13 09:12:37 -0700300 DCHECK(cls->IsProxyClass()) << cls->PrettyClass();
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100301 // TODO: deal with proxy classes.
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100302 } else if (IsSameDexFile(cls->GetDexFile(), dex_file)) {
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000303 DCHECK_EQ(cls->GetDexCache(), compilation_unit.GetDexCache().Get());
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000304 index = cls->GetDexTypeIndex();
Nicolas Geoffray491617a2016-07-19 17:06:23 +0100305 } else {
306 index = cls->FindTypeIndexInOtherDexFile(dex_file);
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000307 // We cannot guarantee the entry will resolve to the same class,
Nicolas Geoffray491617a2016-07-19 17:06:23 +0100308 // as there may be different class loaders. So only return the index if it's
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000309 // the right class already resolved with the class loader.
310 if (index.IsValid()) {
Vladimir Marko666ee3d2017-12-11 18:37:36 +0000311 ObjPtr<mirror::Class> resolved = compilation_unit.GetClassLinker()->LookupResolvedType(
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000312 index, compilation_unit.GetDexCache().Get(), compilation_unit.GetClassLoader().Get());
313 if (resolved != cls) {
314 index = dex::TypeIndex::Invalid();
315 }
Nicolas Geoffray491617a2016-07-19 17:06:23 +0100316 }
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100317 }
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000318
319 return index;
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100320}
321
Calin Juravle13439f02017-02-21 01:17:21 -0800322HInliner::InlineCacheType HInliner::GetInlineCacheType(
Vladimir Markoe9fb3dc2021-03-10 12:17:53 +0000323 const StackHandleScope<InlineCache::kIndividualCacheSize>& classes) {
324 DCHECK_EQ(classes.NumberOfReferences(), InlineCache::kIndividualCacheSize);
325 uint8_t number_of_types = InlineCache::kIndividualCacheSize - classes.RemainingSlots();
Calin Juravle13439f02017-02-21 01:17:21 -0800326 if (number_of_types == 0) {
327 return kInlineCacheUninitialized;
328 } else if (number_of_types == 1) {
329 return kInlineCacheMonomorphic;
330 } else if (number_of_types == InlineCache::kIndividualCacheSize) {
331 return kInlineCacheMegamorphic;
332 } else {
333 return kInlineCachePolymorphic;
334 }
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000335}
336
Vladimir Markoe9fb3dc2021-03-10 12:17:53 +0000337static inline ObjPtr<mirror::Class> GetMonomorphicType(
338 const StackHandleScope<InlineCache::kIndividualCacheSize>& classes)
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000339 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markoe9fb3dc2021-03-10 12:17:53 +0000340 DCHECK(classes.GetReference(0) != nullptr);
341 return classes.GetReference(0)->AsClass();
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000342}
343
Nicolas Geoffraye1e0e0f2021-04-29 08:57:13 +0000344ArtMethod* HInliner::FindMethodFromCHA(ArtMethod* resolved_method) {
Mingyao Yang063fc772016-08-02 11:02:54 -0700345 if (!resolved_method->HasSingleImplementation()) {
346 return nullptr;
347 }
348 if (Runtime::Current()->IsAotCompiler()) {
349 // No CHA-based devirtulization for AOT compiler (yet).
350 return nullptr;
351 }
Nicolas Geoffray141b63c2019-02-27 14:28:46 +0000352 if (Runtime::Current()->IsZygote()) {
353 // No CHA-based devirtulization for Zygote, as it compiles with
354 // offline information.
355 return nullptr;
356 }
Mingyao Yang063fc772016-08-02 11:02:54 -0700357 if (outermost_graph_->IsCompilingOsr()) {
358 // We do not support HDeoptimize in OSR methods.
359 return nullptr;
360 }
Mingyao Yange8fcd012017-01-20 10:43:30 -0800361 PointerSize pointer_size = caller_compilation_unit_.GetClassLinker()->GetImagePointerSize();
Nicolas Geoffray18ea1c92017-03-27 08:00:18 +0000362 ArtMethod* single_impl = resolved_method->GetSingleImplementation(pointer_size);
363 if (single_impl == nullptr) {
364 return nullptr;
365 }
366 if (single_impl->IsProxyMethod()) {
367 // Proxy method is a generic invoker that's not worth
368 // devirtualizing/inlining. It also causes issues when the proxy
369 // method is in another dex file if we try to rewrite invoke-interface to
370 // invoke-virtual because a proxy method doesn't have a real dex file.
371 return nullptr;
372 }
Nicolas Geoffray8e33e842017-04-03 16:55:16 +0100373 if (!single_impl->GetDeclaringClass()->IsResolved()) {
374 // There's a race with the class loading, which updates the CHA info
375 // before setting the class to resolved. So we just bail for this
376 // rare occurence.
377 return nullptr;
378 }
Nicolas Geoffray18ea1c92017-03-27 08:00:18 +0000379 return single_impl;
Mingyao Yang063fc772016-08-02 11:02:54 -0700380}
381
Nicolas Geoffraycf74ae72021-07-15 10:37:28 +0100382static bool IsMethodVerified(ArtMethod* method)
David Sehr0225f8e2018-01-31 08:52:24 +0000383 REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffraycf74ae72021-07-15 10:37:28 +0100384 if (method->GetDeclaringClass()->IsVerified()) {
385 return true;
386 }
387 // For AOT, we check if the class has a verification status that allows us to
388 // inline / analyze.
389 // At runtime, we know this is cold code if the class is not verified, so don't
390 // bother analyzing.
391 if (Runtime::Current()->IsAotCompiler()) {
392 if (method->GetDeclaringClass()->IsVerifiedNeedsAccessChecks() ||
393 method->GetDeclaringClass()->ShouldVerifyAtRuntime()) {
Nicolas Geoffray5da05072021-06-18 15:51:12 +0100394 return true;
395 }
Aart Bik2c148f02018-02-02 14:30:35 -0800396 }
397 return false;
398}
399
Nicolas Geoffraycf74ae72021-07-15 10:37:28 +0100400static bool AlwaysThrows(ArtMethod* method)
Aart Bik2c148f02018-02-02 14:30:35 -0800401 REQUIRES_SHARED(Locks::mutator_lock_) {
402 DCHECK(method != nullptr);
403 // Skip non-compilable and unverified methods.
Nicolas Geoffraycf74ae72021-07-15 10:37:28 +0100404 if (!method->IsCompilable() || !IsMethodVerified(method)) {
Aart Bik2c148f02018-02-02 14:30:35 -0800405 return false;
406 }
Aart Bika8b8e9b2018-01-09 11:01:02 -0800407 // Skip native methods, methods with try blocks, and methods that are too large.
Aart Bik2c148f02018-02-02 14:30:35 -0800408 CodeItemDataAccessor accessor(method->DexInstructionData());
Aart Bika8b8e9b2018-01-09 11:01:02 -0800409 if (!accessor.HasCodeItem() ||
410 accessor.TriesSize() != 0 ||
411 accessor.InsnsSizeInCodeUnits() > kMaximumNumberOfTotalInstructions) {
412 return false;
413 }
414 // Scan for exits.
415 bool throw_seen = false;
416 for (const DexInstructionPcPair& pair : accessor) {
417 switch (pair.Inst().Opcode()) {
418 case Instruction::RETURN:
419 case Instruction::RETURN_VOID:
420 case Instruction::RETURN_WIDE:
421 case Instruction::RETURN_OBJECT:
Aart Bika8b8e9b2018-01-09 11:01:02 -0800422 return false; // found regular control flow back
423 case Instruction::THROW:
424 throw_seen = true;
425 break;
426 default:
427 break;
428 }
429 }
430 return throw_seen;
431}
432
Nicolas Geoffraye418dda2015-08-11 20:03:09 -0700433bool HInliner::TryInline(HInvoke* invoke_instruction) {
Mathieu Chartier8284e9a2020-05-15 17:14:33 -0700434 MaybeRecordStat(stats_, MethodCompilationStat::kTryInline);
435
436 // Don't bother to move further if we know the method is unresolved or the invocation is
437 // polymorphic (invoke-{polymorphic,custom}).
438 if (invoke_instruction->IsInvokeUnresolved()) {
439 MaybeRecordStat(stats_, MethodCompilationStat::kNotInlinedUnresolved);
440 return false;
441 } else if (invoke_instruction->IsInvokePolymorphic()) {
442 MaybeRecordStat(stats_, MethodCompilationStat::kNotInlinedPolymorphic);
443 return false;
444 } else if (invoke_instruction->IsInvokeCustom()) {
445 MaybeRecordStat(stats_, MethodCompilationStat::kNotInlinedCustom);
446 return false;
Calin Juravle175dc732015-08-25 15:42:32 +0100447 }
448
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000449 ScopedObjectAccess soa(Thread::Current());
Nicolas Geoffraye6c0f2a2020-09-07 08:30:52 +0100450 LOG_TRY() << invoke_instruction->GetMethodReference().PrettyMethod();
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000451
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +0100452 ArtMethod* resolved_method = invoke_instruction->GetResolvedMethod();
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +0100453 if (resolved_method == nullptr) {
454 DCHECK(invoke_instruction->IsInvokeStaticOrDirect());
455 DCHECK(invoke_instruction->AsInvokeStaticOrDirect()->IsStringInit());
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000456 LOG_FAIL_NO_STAT() << "Not inlining a String.<init> method";
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +0100457 return false;
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000458 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000459
Nicolas Geoffraye1e0e0f2021-04-29 08:57:13 +0000460 ArtMethod* actual_method = invoke_instruction->IsInvokeStaticOrDirect()
461 ? invoke_instruction->GetResolvedMethod()
462 : FindVirtualOrInterfaceTarget(invoke_instruction);
Eric Holk1868de92020-02-12 09:10:21 -0800463
Nicolas Geoffraye1e0e0f2021-04-29 08:57:13 +0000464 if (actual_method != nullptr) {
465 // Single target.
466 bool result = TryInlineAndReplace(invoke_instruction,
467 actual_method,
468 ReferenceTypeInfo::CreateInvalid(),
469 /* do_rtp= */ true);
470 if (result) {
471 MaybeRecordStat(stats_, MethodCompilationStat::kInlinedInvokeVirtualOrInterface);
Santiago Aboy Solanes15580482021-10-12 13:11:29 +0100472 if (outermost_graph_ == graph_) {
473 MaybeRecordStat(stats_, MethodCompilationStat::kInlinedLastInvokeVirtualOrInterface);
474 }
Nicolas Geoffraye1e0e0f2021-04-29 08:57:13 +0000475 } else {
476 HInvoke* invoke_to_analyze = nullptr;
477 if (TryDevirtualize(invoke_instruction, actual_method, &invoke_to_analyze)) {
478 // Consider devirtualization as inlining.
479 result = true;
480 MaybeRecordStat(stats_, MethodCompilationStat::kDevirtualized);
Eric Holk1868de92020-02-12 09:10:21 -0800481 } else {
Nicolas Geoffraye1e0e0f2021-04-29 08:57:13 +0000482 invoke_to_analyze = invoke_instruction;
483 }
484 // Set always throws property for non-inlined method call with single
485 // target.
Nicolas Geoffraycf74ae72021-07-15 10:37:28 +0100486 if (AlwaysThrows(actual_method)) {
Nicolas Geoffraye1e0e0f2021-04-29 08:57:13 +0000487 invoke_to_analyze->SetAlwaysThrows(true);
Mingyao Yang063fc772016-08-02 11:02:54 -0700488 }
Calin Juravle69158982016-03-16 11:53:41 +0000489 }
Nicolas Geoffraye1e0e0f2021-04-29 08:57:13 +0000490 return result;
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100491 }
Nicolas Geoffraye1e0e0f2021-04-29 08:57:13 +0000492
493 DCHECK(!invoke_instruction->IsInvokeStaticOrDirect());
494
495 if (TryInlineFromCHA(invoke_instruction)) {
496 return true;
497 }
498 return TryInlineFromInlineCache(invoke_instruction);
499}
500
501bool HInliner::TryInlineFromCHA(HInvoke* invoke_instruction) {
502 ArtMethod* method = FindMethodFromCHA(invoke_instruction->GetResolvedMethod());
503 if (method == nullptr) {
504 return false;
505 }
506 LOG_NOTE() << "Try CHA-based inlining of " << method->PrettyMethod();
507
508 uint32_t dex_pc = invoke_instruction->GetDexPc();
509 HInstruction* cursor = invoke_instruction->GetPrevious();
510 HBasicBlock* bb_cursor = invoke_instruction->GetBlock();
511 if (!TryInlineAndReplace(invoke_instruction,
512 method,
513 ReferenceTypeInfo::CreateInvalid(),
514 /* do_rtp= */ true)) {
515 return false;
516 }
517 AddCHAGuard(invoke_instruction, dex_pc, cursor, bb_cursor);
518 // Add dependency due to devirtualization: we are assuming the resolved method
519 // has a single implementation.
520 outermost_graph_->AddCHASingleImplementationDependency(invoke_instruction->GetResolvedMethod());
521 MaybeRecordStat(stats_, MethodCompilationStat::kCHAInline);
522 return true;
Calin Juravle13439f02017-02-21 01:17:21 -0800523}
524
Calin Juravleaf44e6c2017-05-23 14:24:55 -0700525bool HInliner::UseOnlyPolymorphicInliningWithNoDeopt() {
526 // If we are compiling AOT or OSR, pretend the call using inline caches is polymorphic and
527 // do not generate a deopt.
528 //
529 // For AOT:
530 // Generating a deopt does not ensure that we will actually capture the new types;
531 // and the danger is that we could be stuck in a loop with "forever" deoptimizations.
532 // Take for example the following scenario:
533 // - we capture the inline cache in one run
534 // - the next run, we deoptimize because we miss a type check, but the method
535 // never becomes hot again
536 // In this case, the inline cache will not be updated in the profile and the AOT code
537 // will keep deoptimizing.
538 // Another scenario is if we use profile compilation for a process which is not allowed
539 // to JIT (e.g. system server). If we deoptimize we will run interpreted code for the
540 // rest of the lifetime.
541 // TODO(calin):
542 // This is a compromise because we will most likely never update the inline cache
543 // in the profile (unless there's another reason to deopt). So we might be stuck with
544 // a sub-optimal inline cache.
545 // We could be smarter when capturing inline caches to mitigate this.
546 // (e.g. by having different thresholds for new and old methods).
547 //
548 // For OSR:
549 // We may come from the interpreter and it may have seen different receiver types.
550 return Runtime::Current()->IsAotCompiler() || outermost_graph_->IsCompilingOsr();
551}
Nicolas Geoffraye6c0f2a2020-09-07 08:30:52 +0100552bool HInliner::TryInlineFromInlineCache(HInvoke* invoke_instruction)
Calin Juravle13439f02017-02-21 01:17:21 -0800553 REQUIRES_SHARED(Locks::mutator_lock_) {
Calin Juravlee2492d42017-03-20 11:42:13 -0700554 if (Runtime::Current()->IsAotCompiler() && !kUseAOTInlineCaches) {
555 return false;
556 }
557
Vladimir Markoe9fb3dc2021-03-10 12:17:53 +0000558 StackHandleScope<InlineCache::kIndividualCacheSize> classes(Thread::Current());
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +0000559 // The Zygote JIT compiles based on a profile, so we shouldn't use runtime inline caches
560 // for it.
561 InlineCacheType inline_cache_type =
562 (Runtime::Current()->IsAotCompiler() || Runtime::Current()->IsZygote())
Vladimir Markoe9fb3dc2021-03-10 12:17:53 +0000563 ? GetInlineCacheAOT(invoke_instruction, &classes)
564 : GetInlineCacheJIT(invoke_instruction, &classes);
Calin Juravle13439f02017-02-21 01:17:21 -0800565
566 switch (inline_cache_type) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000567 case kInlineCacheNoData: {
568 LOG_FAIL_NO_STAT()
Nicolas Geoffrayd2f13ba2019-06-04 16:48:58 +0100569 << "No inline cache information for call to "
Nicolas Geoffraye6c0f2a2020-09-07 08:30:52 +0100570 << invoke_instruction->GetMethodReference().PrettyMethod();
Calin Juravle13439f02017-02-21 01:17:21 -0800571 return false;
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000572 }
Calin Juravle13439f02017-02-21 01:17:21 -0800573
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000574 case kInlineCacheUninitialized: {
575 LOG_FAIL_NO_STAT()
576 << "Interface or virtual call to "
Nicolas Geoffraye6c0f2a2020-09-07 08:30:52 +0100577 << invoke_instruction->GetMethodReference().PrettyMethod()
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000578 << " is not hit and not inlined";
579 return false;
580 }
581
582 case kInlineCacheMonomorphic: {
Vladimir Markocd09e1f2017-11-24 15:02:40 +0000583 MaybeRecordStat(stats_, MethodCompilationStat::kMonomorphicCall);
Calin Juravleaf44e6c2017-05-23 14:24:55 -0700584 if (UseOnlyPolymorphicInliningWithNoDeopt()) {
Vladimir Markoe9fb3dc2021-03-10 12:17:53 +0000585 return TryInlinePolymorphicCall(invoke_instruction, classes);
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000586 } else {
Vladimir Markoe9fb3dc2021-03-10 12:17:53 +0000587 return TryInlineMonomorphicCall(invoke_instruction, classes);
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000588 }
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000589 }
Calin Juravle13439f02017-02-21 01:17:21 -0800590
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000591 case kInlineCachePolymorphic: {
Vladimir Markocd09e1f2017-11-24 15:02:40 +0000592 MaybeRecordStat(stats_, MethodCompilationStat::kPolymorphicCall);
Vladimir Markoe9fb3dc2021-03-10 12:17:53 +0000593 return TryInlinePolymorphicCall(invoke_instruction, classes);
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000594 }
Calin Juravle13439f02017-02-21 01:17:21 -0800595
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000596 case kInlineCacheMegamorphic: {
597 LOG_FAIL_NO_STAT()
598 << "Interface or virtual call to "
Nicolas Geoffraye6c0f2a2020-09-07 08:30:52 +0100599 << invoke_instruction->GetMethodReference().PrettyMethod()
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000600 << " is megamorphic and not inlined";
Vladimir Markocd09e1f2017-11-24 15:02:40 +0000601 MaybeRecordStat(stats_, MethodCompilationStat::kMegamorphicCall);
Calin Juravle13439f02017-02-21 01:17:21 -0800602 return false;
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000603 }
Calin Juravle13439f02017-02-21 01:17:21 -0800604
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000605 case kInlineCacheMissingTypes: {
606 LOG_FAIL_NO_STAT()
607 << "Interface or virtual call to "
Nicolas Geoffraye6c0f2a2020-09-07 08:30:52 +0100608 << invoke_instruction->GetMethodReference().PrettyMethod()
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000609 << " is missing types and not inlined";
Calin Juravle13439f02017-02-21 01:17:21 -0800610 return false;
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000611 }
Calin Juravle13439f02017-02-21 01:17:21 -0800612 }
613 UNREACHABLE();
614}
615
616HInliner::InlineCacheType HInliner::GetInlineCacheJIT(
617 HInvoke* invoke_instruction,
Vladimir Markoe9fb3dc2021-03-10 12:17:53 +0000618 /*out*/StackHandleScope<InlineCache::kIndividualCacheSize>* classes) {
Vladimir Marko695348f2020-05-19 14:42:02 +0100619 DCHECK(codegen_->GetCompilerOptions().IsJitCompiler());
Calin Juravle13439f02017-02-21 01:17:21 -0800620
621 ArtMethod* caller = graph_->GetArtMethod();
622 // Under JIT, we should always know the caller.
623 DCHECK(caller != nullptr);
Nicolas Geoffray095dc462020-08-17 16:40:28 +0100624 ScopedProfilingInfoUse spiu(Runtime::Current()->GetJit(), caller, Thread::Current());
625 ProfilingInfo* profiling_info = spiu.GetProfilingInfo();
Calin Juravle13439f02017-02-21 01:17:21 -0800626
627 if (profiling_info == nullptr) {
628 return kInlineCacheNoData;
629 }
630
Vladimir Markoe9fb3dc2021-03-10 12:17:53 +0000631 Runtime::Current()->GetJit()->GetCodeCache()->CopyInlineCacheInto(
632 *profiling_info->GetInlineCache(invoke_instruction->GetDexPc()),
633 classes);
634 return GetInlineCacheType(*classes);
Calin Juravle13439f02017-02-21 01:17:21 -0800635}
636
637HInliner::InlineCacheType HInliner::GetInlineCacheAOT(
Calin Juravle13439f02017-02-21 01:17:21 -0800638 HInvoke* invoke_instruction,
Vladimir Markoe9fb3dc2021-03-10 12:17:53 +0000639 /*out*/StackHandleScope<InlineCache::kIndividualCacheSize>* classes) {
640 DCHECK_EQ(classes->NumberOfReferences(), InlineCache::kIndividualCacheSize);
641 DCHECK_EQ(classes->RemainingSlots(), InlineCache::kIndividualCacheSize);
642
Vladimir Marko1a2a5cd2018-11-07 15:39:48 +0000643 const ProfileCompilationInfo* pci = codegen_->GetCompilerOptions().GetProfileCompilationInfo();
Calin Juravle13439f02017-02-21 01:17:21 -0800644 if (pci == nullptr) {
645 return kInlineCacheNoData;
646 }
647
Vladimir Markoa64c1ad2021-03-08 14:27:05 +0000648 ProfileCompilationInfo::MethodHotness hotness = pci->GetMethodHotness(MethodReference(
649 caller_compilation_unit_.GetDexFile(), caller_compilation_unit_.GetDexMethodIndex()));
650 if (!hotness.IsHot()) {
Calin Juravle13439f02017-02-21 01:17:21 -0800651 return kInlineCacheNoData; // no profile information for this invocation.
652 }
653
Vladimir Markoa64c1ad2021-03-08 14:27:05 +0000654 const ProfileCompilationInfo::InlineCacheMap* inline_caches = hotness.GetInlineCacheMap();
655 DCHECK(inline_caches != nullptr);
656 const auto it = inline_caches->find(invoke_instruction->GetDexPc());
657 if (it == inline_caches->end()) {
Calin Juravle13439f02017-02-21 01:17:21 -0800658 return kInlineCacheUninitialized;
659 }
660
661 const ProfileCompilationInfo::DexPcData& dex_pc_data = it->second;
Calin Juravle13439f02017-02-21 01:17:21 -0800662 if (dex_pc_data.is_missing_types) {
663 return kInlineCacheMissingTypes;
664 }
665 if (dex_pc_data.is_megamorphic) {
666 return kInlineCacheMegamorphic;
667 }
Calin Juravle13439f02017-02-21 01:17:21 -0800668 DCHECK_LE(dex_pc_data.classes.size(), InlineCache::kIndividualCacheSize);
Vladimir Markoa64c1ad2021-03-08 14:27:05 +0000669
Vladimir Markoc63d9672021-03-31 15:50:39 +0100670 // Walk over the class descriptors and look up the actual classes.
671 // If we cannot find a type we return kInlineCacheMissingTypes.
672 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
673 for (const dex::TypeIndex& type_index : dex_pc_data.classes) {
674 const DexFile* dex_file = caller_compilation_unit_.GetDexFile();
675 const char* descriptor = pci->GetTypeDescriptor(dex_file, type_index);
676 ObjPtr<mirror::ClassLoader> class_loader = caller_compilation_unit_.GetClassLoader().Get();
677 ObjPtr<mirror::Class> clazz = class_linker->LookupResolvedType(descriptor, class_loader);
678 if (clazz == nullptr) {
679 VLOG(compiler) << "Could not find class from inline cache in AOT mode "
Nicolas Geoffraye6c0f2a2020-09-07 08:30:52 +0100680 << invoke_instruction->GetMethodReference().PrettyMethod()
681 << " : "
Vladimir Markoc63d9672021-03-31 15:50:39 +0100682 << descriptor;
Calin Juravle13439f02017-02-21 01:17:21 -0800683 return kInlineCacheMissingTypes;
684 }
Vladimir Markoc63d9672021-03-31 15:50:39 +0100685 DCHECK_NE(classes->RemainingSlots(), 0u);
686 classes->NewHandle(clazz);
Calin Juravle13439f02017-02-21 01:17:21 -0800687 }
Vladimir Markoa64c1ad2021-03-08 14:27:05 +0000688
Vladimir Markoe9fb3dc2021-03-10 12:17:53 +0000689 return GetInlineCacheType(*classes);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100690}
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000691
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000692HInstanceFieldGet* HInliner::BuildGetReceiverClass(ClassLinker* class_linker,
693 HInstruction* receiver,
694 uint32_t dex_pc) const {
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100695 ArtField* field = GetClassRoot<mirror::Object>(class_linker)->GetInstanceField(0);
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000696 DCHECK_EQ(std::string(field->GetName()), "shadow$_klass_");
Vladimir Markoca6fff82017-10-03 14:49:14 +0100697 HInstanceFieldGet* result = new (graph_->GetAllocator()) HInstanceFieldGet(
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000698 receiver,
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +0000699 field,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100700 DataType::Type::kReference,
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000701 field->GetOffset(),
702 field->IsVolatile(),
703 field->GetDexFieldIndex(),
704 field->GetDeclaringClass()->GetDexClassDefIndex(),
705 *field->GetDexFile(),
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000706 dex_pc);
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000707 // The class of a field is effectively final, and does not have any memory dependencies.
708 result->SetSideEffects(SideEffects::None());
709 return result;
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000710}
711
Nicolas Geoffray4c0b4bc2017-03-17 13:08:26 +0000712static ArtMethod* ResolveMethodFromInlineCache(Handle<mirror::Class> klass,
Nicolas Geoffraye6c0f2a2020-09-07 08:30:52 +0100713 HInvoke* invoke_instruction,
Nicolas Geoffray4c0b4bc2017-03-17 13:08:26 +0000714 PointerSize pointer_size)
715 REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffraye6c0f2a2020-09-07 08:30:52 +0100716 ArtMethod* resolved_method = invoke_instruction->GetResolvedMethod();
Nicolas Geoffray4c0b4bc2017-03-17 13:08:26 +0000717 if (Runtime::Current()->IsAotCompiler()) {
718 // We can get unrelated types when working with profiles (corruption,
719 // systme updates, or anyone can write to it). So first check if the class
720 // actually implements the declaring class of the method that is being
721 // called in bytecode.
722 // Note: the lookup methods used below require to have assignable types.
723 if (!resolved_method->GetDeclaringClass()->IsAssignableFrom(klass.Get())) {
724 return nullptr;
725 }
Nicolas Geoffray4fba66c2021-08-26 18:49:04 +0100726
727 // Also check whether the type in the inline cache is an interface or an
728 // abstract class. We only expect concrete classes in inline caches, so this
729 // means the class was changed.
730 if (klass->IsAbstract() || klass->IsInterface()) {
731 return nullptr;
732 }
Nicolas Geoffray4c0b4bc2017-03-17 13:08:26 +0000733 }
734
735 if (invoke_instruction->IsInvokeInterface()) {
736 resolved_method = klass->FindVirtualMethodForInterface(resolved_method, pointer_size);
737 } else {
738 DCHECK(invoke_instruction->IsInvokeVirtual());
739 resolved_method = klass->FindVirtualMethodForVirtual(resolved_method, pointer_size);
740 }
Alex Light2769f012021-03-23 11:58:58 -0700741 // Even if the class exists we can still not have the function the
742 // inline-cache targets if the profile is from far enough in the past/future.
743 // We need to allow this since we don't update boot-profiles very often. This
744 // can occur in boot-profiles with inline-caches.
745 DCHECK(Runtime::Current()->IsAotCompiler() || resolved_method != nullptr);
Nicolas Geoffray4c0b4bc2017-03-17 13:08:26 +0000746 return resolved_method;
747}
748
Vladimir Markoe9fb3dc2021-03-10 12:17:53 +0000749bool HInliner::TryInlineMonomorphicCall(
750 HInvoke* invoke_instruction,
751 const StackHandleScope<InlineCache::kIndividualCacheSize>& classes) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000752 DCHECK(invoke_instruction->IsInvokeVirtual() || invoke_instruction->IsInvokeInterface())
753 << invoke_instruction->DebugName();
754
Andreas Gampea5b09a62016-11-17 15:21:22 -0800755 dex::TypeIndex class_index = FindClassIndexIn(
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000756 GetMonomorphicType(classes), caller_compilation_unit_);
Andreas Gampea5b09a62016-11-17 15:21:22 -0800757 if (!class_index.IsValid()) {
Santiago Aboy Solanesfa73acc2021-11-12 14:23:27 +0000758 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedDexCacheInaccessibleToCaller)
Nicolas Geoffraye6c0f2a2020-09-07 08:30:52 +0100759 << "Call to " << ArtMethod::PrettyMethod(invoke_instruction->GetResolvedMethod())
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000760 << " from inline cache is not inlined because its class is not"
761 << " accessible to the caller";
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100762 return false;
763 }
764
765 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
Andreas Gampe542451c2016-07-26 09:02:02 -0700766 PointerSize pointer_size = class_linker->GetImagePointerSize();
Vladimir Marko02ca05a2020-05-12 13:58:51 +0100767 Handle<mirror::Class> monomorphic_type =
768 graph_->GetHandleCache()->NewHandle(GetMonomorphicType(classes));
Nicolas Geoffraye6c0f2a2020-09-07 08:30:52 +0100769 ArtMethod* resolved_method = ResolveMethodFromInlineCache(
770 monomorphic_type, invoke_instruction, pointer_size);
Nicolas Geoffray4c0b4bc2017-03-17 13:08:26 +0000771 if (resolved_method == nullptr) {
772 // Bogus AOT profile, bail.
773 DCHECK(Runtime::Current()->IsAotCompiler());
774 return false;
775 }
776
Vladimir Markoe9fb3dc2021-03-10 12:17:53 +0000777 LOG_NOTE() << "Try inline monomorphic call to " << resolved_method->PrettyMethod();
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100778 HInstruction* receiver = invoke_instruction->InputAt(0);
779 HInstruction* cursor = invoke_instruction->GetPrevious();
780 HBasicBlock* bb_cursor = invoke_instruction->GetBlock();
Mingyao Yang063fc772016-08-02 11:02:54 -0700781 if (!TryInlineAndReplace(invoke_instruction,
782 resolved_method,
Andreas Gampe3db70682018-12-26 15:12:03 -0800783 ReferenceTypeInfo::Create(monomorphic_type, /* is_exact= */ true),
Nicolas Geoffraye1e0e0f2021-04-29 08:57:13 +0000784 /* do_rtp= */ false)) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100785 return false;
786 }
787
788 // We successfully inlined, now add a guard.
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000789 AddTypeGuard(receiver,
790 cursor,
791 bb_cursor,
792 class_index,
Nicolas Geoffray5247c082017-01-13 14:17:29 +0000793 monomorphic_type,
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000794 invoke_instruction,
Andreas Gampe3db70682018-12-26 15:12:03 -0800795 /* with_deoptimization= */ true);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100796
797 // Run type propagation to get the guard typed, and eventually propagate the
798 // type of the receiver.
Vladimir Marko456307a2016-04-19 14:12:13 +0000799 ReferenceTypePropagation rtp_fixup(graph_,
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000800 outer_compilation_unit_.GetClassLoader(),
Vladimir Marko456307a2016-04-19 14:12:13 +0000801 outer_compilation_unit_.GetDexCache(),
Andreas Gampe3db70682018-12-26 15:12:03 -0800802 /* is_first_run= */ false);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100803 rtp_fixup.Run();
804
Vladimir Markocd09e1f2017-11-24 15:02:40 +0000805 MaybeRecordStat(stats_, MethodCompilationStat::kInlinedMonomorphicCall);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100806 return true;
807}
808
Mingyao Yang063fc772016-08-02 11:02:54 -0700809void HInliner::AddCHAGuard(HInstruction* invoke_instruction,
810 uint32_t dex_pc,
811 HInstruction* cursor,
812 HBasicBlock* bb_cursor) {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100813 HShouldDeoptimizeFlag* deopt_flag = new (graph_->GetAllocator())
814 HShouldDeoptimizeFlag(graph_->GetAllocator(), dex_pc);
Mythri Alle5097f832021-11-02 14:52:30 +0000815 // ShouldDeoptimizeFlag is used to perform a deoptimization because of a CHA
816 // invalidation or for debugging reasons. It is OK to just check for non-zero
817 // value here instead of the specific CHA value. When a debugging deopt is
818 // requested we deoptimize before we execute any code and hence we shouldn't
819 // see that case here.
Vladimir Markoca6fff82017-10-03 14:49:14 +0100820 HInstruction* compare = new (graph_->GetAllocator()) HNotEqual(
Mingyao Yang063fc772016-08-02 11:02:54 -0700821 deopt_flag, graph_->GetIntConstant(0, dex_pc));
Vladimir Markoca6fff82017-10-03 14:49:14 +0100822 HInstruction* deopt = new (graph_->GetAllocator()) HDeoptimize(
823 graph_->GetAllocator(), compare, DeoptimizationKind::kCHA, dex_pc);
Mingyao Yang063fc772016-08-02 11:02:54 -0700824
825 if (cursor != nullptr) {
826 bb_cursor->InsertInstructionAfter(deopt_flag, cursor);
827 } else {
828 bb_cursor->InsertInstructionBefore(deopt_flag, bb_cursor->GetFirstInstruction());
829 }
Mingyao Yangb0b051a2016-11-17 09:04:53 -0800830 bb_cursor->InsertInstructionAfter(compare, deopt_flag);
831 bb_cursor->InsertInstructionAfter(deopt, compare);
832
833 // Add receiver as input to aid CHA guard optimization later.
834 deopt_flag->AddInput(invoke_instruction->InputAt(0));
835 DCHECK_EQ(deopt_flag->InputCount(), 1u);
Mingyao Yang063fc772016-08-02 11:02:54 -0700836 deopt->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
Mingyao Yangb0b051a2016-11-17 09:04:53 -0800837 outermost_graph_->IncrementNumberOfCHAGuards();
Mingyao Yang063fc772016-08-02 11:02:54 -0700838}
839
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000840HInstruction* HInliner::AddTypeGuard(HInstruction* receiver,
841 HInstruction* cursor,
842 HBasicBlock* bb_cursor,
Andreas Gampea5b09a62016-11-17 15:21:22 -0800843 dex::TypeIndex class_index,
Nicolas Geoffray5247c082017-01-13 14:17:29 +0000844 Handle<mirror::Class> klass,
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000845 HInstruction* invoke_instruction,
846 bool with_deoptimization) {
847 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
848 HInstanceFieldGet* receiver_class = BuildGetReceiverClass(
849 class_linker, receiver, invoke_instruction->GetDexPc());
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000850 if (cursor != nullptr) {
851 bb_cursor->InsertInstructionAfter(receiver_class, cursor);
852 } else {
853 bb_cursor->InsertInstructionBefore(receiver_class, bb_cursor->GetFirstInstruction());
854 }
Nicolas Geoffray56876342016-12-16 16:09:08 +0000855
856 const DexFile& caller_dex_file = *caller_compilation_unit_.GetDexFile();
Calin Juravle07f01df2017-04-28 19:58:01 -0700857 bool is_referrer;
858 ArtMethod* outermost_art_method = outermost_graph_->GetArtMethod();
859 if (outermost_art_method == nullptr) {
860 DCHECK(Runtime::Current()->IsAotCompiler());
861 // We are in AOT mode and we don't have an ART method to determine
862 // if the inlined method belongs to the referrer. Assume it doesn't.
863 is_referrer = false;
864 } else {
865 is_referrer = klass.Get() == outermost_art_method->GetDeclaringClass();
866 }
867
Nicolas Geoffray56876342016-12-16 16:09:08 +0000868 // Note that we will just compare the classes, so we don't need Java semantics access checks.
869 // Note that the type index and the dex file are relative to the method this type guard is
870 // inlined into.
Vladimir Markoca6fff82017-10-03 14:49:14 +0100871 HLoadClass* load_class = new (graph_->GetAllocator()) HLoadClass(graph_->GetCurrentMethod(),
872 class_index,
873 caller_dex_file,
874 klass,
875 is_referrer,
876 invoke_instruction->GetDexPc(),
Andreas Gampe3db70682018-12-26 15:12:03 -0800877 /* needs_access_check= */ false);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +0000878 HLoadClass::LoadKind kind = HSharpening::ComputeLoadClassKind(
Vladimir Markobb089b62018-06-28 17:30:16 +0100879 load_class, codegen_, caller_compilation_unit_);
Nicolas Geoffray83c8e272017-01-31 14:36:37 +0000880 DCHECK(kind != HLoadClass::LoadKind::kInvalid)
881 << "We should always be able to reference a class for inline caches";
Vladimir Marko28e012a2017-12-07 11:22:59 +0000882 // Load kind must be set before inserting the instruction into the graph.
Nicolas Geoffray83c8e272017-01-31 14:36:37 +0000883 load_class->SetLoadKind(kind);
Vladimir Marko28e012a2017-12-07 11:22:59 +0000884 bb_cursor->InsertInstructionAfter(load_class, receiver_class);
Calin Juravle13439f02017-02-21 01:17:21 -0800885 // In AOT mode, we will most likely load the class from BSS, which will involve a call
886 // to the runtime. In this case, the load instruction will need an environment so copy
887 // it from the invoke instruction.
888 if (load_class->NeedsEnvironment()) {
889 DCHECK(Runtime::Current()->IsAotCompiler());
890 load_class->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
891 }
Nicolas Geoffray56876342016-12-16 16:09:08 +0000892
Vladimir Markoca6fff82017-10-03 14:49:14 +0100893 HNotEqual* compare = new (graph_->GetAllocator()) HNotEqual(load_class, receiver_class);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000894 bb_cursor->InsertInstructionAfter(compare, load_class);
895 if (with_deoptimization) {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100896 HDeoptimize* deoptimize = new (graph_->GetAllocator()) HDeoptimize(
897 graph_->GetAllocator(),
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +0000898 compare,
899 receiver,
Nicolas Geoffray4e92c3c2017-05-08 09:34:26 +0100900 Runtime::Current()->IsAotCompiler()
901 ? DeoptimizationKind::kAotInlineCache
902 : DeoptimizationKind::kJitInlineCache,
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +0000903 invoke_instruction->GetDexPc());
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000904 bb_cursor->InsertInstructionAfter(deoptimize, compare);
905 deoptimize->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +0000906 DCHECK_EQ(invoke_instruction->InputAt(0), receiver);
907 receiver->ReplaceUsesDominatedBy(deoptimize, deoptimize);
908 deoptimize->SetReferenceTypeInfo(receiver->GetReferenceTypeInfo());
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000909 }
910 return compare;
911}
912
Nicolas Geoffrayb8958022021-04-15 15:12:31 +0100913static void MaybeReplaceAndRemove(HInstruction* new_instruction, HInstruction* old_instruction) {
914 DCHECK(new_instruction != old_instruction);
915 if (new_instruction != nullptr) {
916 old_instruction->ReplaceWith(new_instruction);
917 }
918 old_instruction->GetBlock()->RemoveInstruction(old_instruction);
919}
920
Vladimir Markoe9fb3dc2021-03-10 12:17:53 +0000921bool HInliner::TryInlinePolymorphicCall(
922 HInvoke* invoke_instruction,
923 const StackHandleScope<InlineCache::kIndividualCacheSize>& classes) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000924 DCHECK(invoke_instruction->IsInvokeVirtual() || invoke_instruction->IsInvokeInterface())
925 << invoke_instruction->DebugName();
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000926
Nicolas Geoffraye6c0f2a2020-09-07 08:30:52 +0100927 if (TryInlinePolymorphicCallToSameTarget(invoke_instruction, classes)) {
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000928 return true;
929 }
930
931 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
Andreas Gampe542451c2016-07-26 09:02:02 -0700932 PointerSize pointer_size = class_linker->GetImagePointerSize();
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000933
934 bool all_targets_inlined = true;
935 bool one_target_inlined = false;
Vladimir Markoe9fb3dc2021-03-10 12:17:53 +0000936 DCHECK_EQ(classes.NumberOfReferences(), InlineCache::kIndividualCacheSize);
937 uint8_t number_of_types = InlineCache::kIndividualCacheSize - classes.RemainingSlots();
938 for (size_t i = 0; i != number_of_types; ++i) {
939 DCHECK(classes.GetReference(i) != nullptr);
940 Handle<mirror::Class> handle =
941 graph_->GetHandleCache()->NewHandle(classes.GetReference(i)->AsClass());
942 ArtMethod* method = ResolveMethodFromInlineCache(handle, invoke_instruction, pointer_size);
Nicolas Geoffray4c0b4bc2017-03-17 13:08:26 +0000943 if (method == nullptr) {
944 DCHECK(Runtime::Current()->IsAotCompiler());
945 // AOT profile is bogus. This loop expects to iterate over all entries,
946 // so just just continue.
947 all_targets_inlined = false;
948 continue;
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000949 }
950
951 HInstruction* receiver = invoke_instruction->InputAt(0);
952 HInstruction* cursor = invoke_instruction->GetPrevious();
953 HBasicBlock* bb_cursor = invoke_instruction->GetBlock();
954
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000955 dex::TypeIndex class_index = FindClassIndexIn(handle.Get(), caller_compilation_unit_);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000956 HInstruction* return_replacement = nullptr;
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000957 LOG_NOTE() << "Try inline polymorphic call to " << method->PrettyMethod();
Andreas Gampea5b09a62016-11-17 15:21:22 -0800958 if (!class_index.IsValid() ||
Nicolas Geoffray0f001b72017-01-04 16:46:23 +0000959 !TryBuildAndInline(invoke_instruction,
960 method,
Andreas Gampe3db70682018-12-26 15:12:03 -0800961 ReferenceTypeInfo::Create(handle, /* is_exact= */ true),
Nicolas Geoffray0f001b72017-01-04 16:46:23 +0000962 &return_replacement)) {
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000963 all_targets_inlined = false;
964 } else {
965 one_target_inlined = true;
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000966
Nicolas Geoffraye6c0f2a2020-09-07 08:30:52 +0100967 LOG_SUCCESS() << "Polymorphic call to "
968 << invoke_instruction->GetMethodReference().PrettyMethod()
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000969 << " has inlined " << ArtMethod::PrettyMethod(method);
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +0000970
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000971 // If we have inlined all targets before, and this receiver is the last seen,
972 // we deoptimize instead of keeping the original invoke instruction.
Calin Juravleaf44e6c2017-05-23 14:24:55 -0700973 bool deoptimize = !UseOnlyPolymorphicInliningWithNoDeopt() &&
974 all_targets_inlined &&
Vladimir Markoe9fb3dc2021-03-10 12:17:53 +0000975 (i + 1 == number_of_types);
Nicolas Geoffray93a18c52016-04-22 13:16:14 +0100976
Nicolas Geoffray56876342016-12-16 16:09:08 +0000977 HInstruction* compare = AddTypeGuard(receiver,
978 cursor,
979 bb_cursor,
980 class_index,
Nicolas Geoffray5247c082017-01-13 14:17:29 +0000981 handle,
Nicolas Geoffray56876342016-12-16 16:09:08 +0000982 invoke_instruction,
983 deoptimize);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000984 if (deoptimize) {
Nicolas Geoffrayb8958022021-04-15 15:12:31 +0100985 MaybeReplaceAndRemove(return_replacement, invoke_instruction);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000986 } else {
987 CreateDiamondPatternForPolymorphicInline(compare, return_replacement, invoke_instruction);
988 }
989 }
990 }
991
992 if (!one_target_inlined) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000993 LOG_FAIL_NO_STAT()
Nicolas Geoffraye6c0f2a2020-09-07 08:30:52 +0100994 << "Call to " << invoke_instruction->GetMethodReference().PrettyMethod()
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000995 << " from inline cache is not inlined because none"
996 << " of its targets could be inlined";
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000997 return false;
998 }
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +0000999
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001000 MaybeRecordStat(stats_, MethodCompilationStat::kInlinedPolymorphicCall);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001001
1002 // Run type propagation to get the guards typed.
Vladimir Marko456307a2016-04-19 14:12:13 +00001003 ReferenceTypePropagation rtp_fixup(graph_,
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001004 outer_compilation_unit_.GetClassLoader(),
Vladimir Marko456307a2016-04-19 14:12:13 +00001005 outer_compilation_unit_.GetDexCache(),
Andreas Gampe3db70682018-12-26 15:12:03 -08001006 /* is_first_run= */ false);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001007 rtp_fixup.Run();
1008 return true;
1009}
1010
1011void HInliner::CreateDiamondPatternForPolymorphicInline(HInstruction* compare,
1012 HInstruction* return_replacement,
1013 HInstruction* invoke_instruction) {
1014 uint32_t dex_pc = invoke_instruction->GetDexPc();
1015 HBasicBlock* cursor_block = compare->GetBlock();
1016 HBasicBlock* original_invoke_block = invoke_instruction->GetBlock();
Vladimir Markoca6fff82017-10-03 14:49:14 +01001017 ArenaAllocator* allocator = graph_->GetAllocator();
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001018
1019 // Spit the block after the compare: `cursor_block` will now be the start of the diamond,
1020 // and the returned block is the start of the then branch (that could contain multiple blocks).
1021 HBasicBlock* then = cursor_block->SplitAfterForInlining(compare);
1022
1023 // Split the block containing the invoke before and after the invoke. The returned block
1024 // of the split before will contain the invoke and will be the otherwise branch of
1025 // the diamond. The returned block of the split after will be the merge block
1026 // of the diamond.
1027 HBasicBlock* end_then = invoke_instruction->GetBlock();
1028 HBasicBlock* otherwise = end_then->SplitBeforeForInlining(invoke_instruction);
1029 HBasicBlock* merge = otherwise->SplitAfterForInlining(invoke_instruction);
1030
1031 // If the methods we are inlining return a value, we create a phi in the merge block
1032 // that will have the `invoke_instruction and the `return_replacement` as inputs.
1033 if (return_replacement != nullptr) {
1034 HPhi* phi = new (allocator) HPhi(
1035 allocator, kNoRegNumber, 0, HPhi::ToPhiType(invoke_instruction->GetType()), dex_pc);
1036 merge->AddPhi(phi);
1037 invoke_instruction->ReplaceWith(phi);
1038 phi->AddInput(return_replacement);
1039 phi->AddInput(invoke_instruction);
1040 }
1041
1042 // Add the control flow instructions.
1043 otherwise->AddInstruction(new (allocator) HGoto(dex_pc));
1044 end_then->AddInstruction(new (allocator) HGoto(dex_pc));
1045 cursor_block->AddInstruction(new (allocator) HIf(compare, dex_pc));
1046
1047 // Add the newly created blocks to the graph.
1048 graph_->AddBlock(then);
1049 graph_->AddBlock(otherwise);
1050 graph_->AddBlock(merge);
1051
1052 // Set up successor (and implictly predecessor) relations.
1053 cursor_block->AddSuccessor(otherwise);
1054 cursor_block->AddSuccessor(then);
1055 end_then->AddSuccessor(merge);
1056 otherwise->AddSuccessor(merge);
1057
1058 // Set up dominance information.
1059 then->SetDominator(cursor_block);
1060 cursor_block->AddDominatedBlock(then);
1061 otherwise->SetDominator(cursor_block);
1062 cursor_block->AddDominatedBlock(otherwise);
1063 merge->SetDominator(cursor_block);
1064 cursor_block->AddDominatedBlock(merge);
1065
1066 // Update the revert post order.
1067 size_t index = IndexOfElement(graph_->reverse_post_order_, cursor_block);
1068 MakeRoomFor(&graph_->reverse_post_order_, 1, index);
1069 graph_->reverse_post_order_[++index] = then;
1070 index = IndexOfElement(graph_->reverse_post_order_, end_then);
1071 MakeRoomFor(&graph_->reverse_post_order_, 2, index);
1072 graph_->reverse_post_order_[++index] = otherwise;
1073 graph_->reverse_post_order_[++index] = merge;
1074
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001075
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00001076 graph_->UpdateLoopAndTryInformationOfNewBlock(
Andreas Gampe3db70682018-12-26 15:12:03 -08001077 then, original_invoke_block, /* replace_if_back_edge= */ false);
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00001078 graph_->UpdateLoopAndTryInformationOfNewBlock(
Andreas Gampe3db70682018-12-26 15:12:03 -08001079 otherwise, original_invoke_block, /* replace_if_back_edge= */ false);
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00001080
1081 // In case the original invoke location was a back edge, we need to update
1082 // the loop to now have the merge block as a back edge.
1083 graph_->UpdateLoopAndTryInformationOfNewBlock(
Andreas Gampe3db70682018-12-26 15:12:03 -08001084 merge, original_invoke_block, /* replace_if_back_edge= */ true);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001085}
1086
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +00001087bool HInliner::TryInlinePolymorphicCallToSameTarget(
1088 HInvoke* invoke_instruction,
Vladimir Markoe9fb3dc2021-03-10 12:17:53 +00001089 const StackHandleScope<InlineCache::kIndividualCacheSize>& classes) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001090 // This optimization only works under JIT for now.
Vladimir Marko695348f2020-05-19 14:42:02 +01001091 if (!codegen_->GetCompilerOptions().IsJitCompiler()) {
Calin Juravle13439f02017-02-21 01:17:21 -08001092 return false;
1093 }
1094
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001095 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
Andreas Gampe542451c2016-07-26 09:02:02 -07001096 PointerSize pointer_size = class_linker->GetImagePointerSize();
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001097
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001098 ArtMethod* actual_method = nullptr;
Nicolas Geoffray4f97a212016-02-25 16:17:54 +00001099 size_t method_index = invoke_instruction->IsInvokeVirtual()
1100 ? invoke_instruction->AsInvokeVirtual()->GetVTableIndex()
1101 : invoke_instruction->AsInvokeInterface()->GetImtIndex();
1102
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001103 // Check whether we are actually calling the same method among
1104 // the different types seen.
Vladimir Markoe9fb3dc2021-03-10 12:17:53 +00001105 DCHECK_EQ(classes.NumberOfReferences(), InlineCache::kIndividualCacheSize);
1106 uint8_t number_of_types = InlineCache::kIndividualCacheSize - classes.RemainingSlots();
1107 for (size_t i = 0; i != number_of_types; ++i) {
1108 DCHECK(classes.GetReference(i) != nullptr);
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001109 ArtMethod* new_method = nullptr;
1110 if (invoke_instruction->IsInvokeInterface()) {
Vladimir Markoe9fb3dc2021-03-10 12:17:53 +00001111 new_method = classes.GetReference(i)->AsClass()->GetImt(pointer_size)->Get(
Matthew Gharrity465ecc82016-07-19 21:32:52 +00001112 method_index, pointer_size);
Nicolas Geoffray4f97a212016-02-25 16:17:54 +00001113 if (new_method->IsRuntimeMethod()) {
1114 // Bail out as soon as we see a conflict trampoline in one of the target's
1115 // interface table.
1116 return false;
1117 }
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001118 } else {
1119 DCHECK(invoke_instruction->IsInvokeVirtual());
Vladimir Markoe9fb3dc2021-03-10 12:17:53 +00001120 new_method =
1121 classes.GetReference(i)->AsClass()->GetEmbeddedVTableEntry(method_index, pointer_size);
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001122 }
Nicolas Geoffray4f97a212016-02-25 16:17:54 +00001123 DCHECK(new_method != nullptr);
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001124 if (actual_method == nullptr) {
1125 actual_method = new_method;
1126 } else if (actual_method != new_method) {
1127 // Different methods, bailout.
1128 return false;
1129 }
1130 }
1131
1132 HInstruction* receiver = invoke_instruction->InputAt(0);
1133 HInstruction* cursor = invoke_instruction->GetPrevious();
1134 HBasicBlock* bb_cursor = invoke_instruction->GetBlock();
1135
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01001136 HInstruction* return_replacement = nullptr;
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001137 if (!TryBuildAndInline(invoke_instruction,
1138 actual_method,
1139 ReferenceTypeInfo::CreateInvalid(),
1140 &return_replacement)) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001141 return false;
1142 }
1143
1144 // We successfully inlined, now add a guard.
1145 HInstanceFieldGet* receiver_class = BuildGetReceiverClass(
1146 class_linker, receiver, invoke_instruction->GetDexPc());
1147
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001148 DataType::Type type = Is64BitInstructionSet(graph_->GetInstructionSet())
1149 ? DataType::Type::kInt64
1150 : DataType::Type::kInt32;
Vladimir Markoca6fff82017-10-03 14:49:14 +01001151 HClassTableGet* class_table_get = new (graph_->GetAllocator()) HClassTableGet(
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001152 receiver_class,
1153 type,
Vladimir Markoa1de9182016-02-25 11:37:38 +00001154 invoke_instruction->IsInvokeVirtual() ? HClassTableGet::TableKind::kVTable
1155 : HClassTableGet::TableKind::kIMTable,
Nicolas Geoffray4f97a212016-02-25 16:17:54 +00001156 method_index,
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001157 invoke_instruction->GetDexPc());
1158
1159 HConstant* constant;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001160 if (type == DataType::Type::kInt64) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001161 constant = graph_->GetLongConstant(
1162 reinterpret_cast<intptr_t>(actual_method), invoke_instruction->GetDexPc());
1163 } else {
1164 constant = graph_->GetIntConstant(
1165 reinterpret_cast<intptr_t>(actual_method), invoke_instruction->GetDexPc());
1166 }
1167
Vladimir Markoca6fff82017-10-03 14:49:14 +01001168 HNotEqual* compare = new (graph_->GetAllocator()) HNotEqual(class_table_get, constant);
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001169 if (cursor != nullptr) {
1170 bb_cursor->InsertInstructionAfter(receiver_class, cursor);
1171 } else {
1172 bb_cursor->InsertInstructionBefore(receiver_class, bb_cursor->GetFirstInstruction());
1173 }
1174 bb_cursor->InsertInstructionAfter(class_table_get, receiver_class);
1175 bb_cursor->InsertInstructionAfter(compare, class_table_get);
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01001176
1177 if (outermost_graph_->IsCompilingOsr()) {
1178 CreateDiamondPatternForPolymorphicInline(compare, return_replacement, invoke_instruction);
1179 } else {
Vladimir Markoca6fff82017-10-03 14:49:14 +01001180 HDeoptimize* deoptimize = new (graph_->GetAllocator()) HDeoptimize(
1181 graph_->GetAllocator(),
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +00001182 compare,
1183 receiver,
Nicolas Geoffray4e92c3c2017-05-08 09:34:26 +01001184 DeoptimizationKind::kJitSameTarget,
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +00001185 invoke_instruction->GetDexPc());
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01001186 bb_cursor->InsertInstructionAfter(deoptimize, compare);
1187 deoptimize->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
Nicolas Geoffrayb8958022021-04-15 15:12:31 +01001188 MaybeReplaceAndRemove(return_replacement, invoke_instruction);
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +00001189 receiver->ReplaceUsesDominatedBy(deoptimize, deoptimize);
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +00001190 deoptimize->SetReferenceTypeInfo(receiver->GetReferenceTypeInfo());
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01001191 }
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001192
1193 // Run type propagation to get the guard typed.
Vladimir Marko456307a2016-04-19 14:12:13 +00001194 ReferenceTypePropagation rtp_fixup(graph_,
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001195 outer_compilation_unit_.GetClassLoader(),
Vladimir Marko456307a2016-04-19 14:12:13 +00001196 outer_compilation_unit_.GetDexCache(),
Andreas Gampe3db70682018-12-26 15:12:03 -08001197 /* is_first_run= */ false);
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001198 rtp_fixup.Run();
1199
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001200 MaybeRecordStat(stats_, MethodCompilationStat::kInlinedPolymorphicCall);
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001201
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001202 LOG_SUCCESS() << "Inlined same polymorphic target " << actual_method->PrettyMethod();
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001203 return true;
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001204}
1205
Nicolas Geoffraye1e0e0f2021-04-29 08:57:13 +00001206void HInliner::MaybeRunReferenceTypePropagation(HInstruction* replacement,
1207 HInvoke* invoke_instruction) {
1208 if (ReturnTypeMoreSpecific(replacement, invoke_instruction)) {
David Brazdil94ab38f2016-06-21 17:48:19 +01001209 // Actual return value has a more specific type than the method's declared
1210 // return type. Run RTP again on the outer graph to propagate it.
1211 ReferenceTypePropagation(graph_,
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001212 outer_compilation_unit_.GetClassLoader(),
David Brazdil94ab38f2016-06-21 17:48:19 +01001213 outer_compilation_unit_.GetDexCache(),
Andreas Gampe3db70682018-12-26 15:12:03 -08001214 /* is_first_run= */ false).Run();
David Brazdil94ab38f2016-06-21 17:48:19 +01001215 }
Nicolas Geoffraye1e0e0f2021-04-29 08:57:13 +00001216}
1217
1218bool HInliner::TryDevirtualize(HInvoke* invoke_instruction,
1219 ArtMethod* method,
1220 HInvoke** replacement) {
Nicolas Geoffraye1e0e0f2021-04-29 08:57:13 +00001221 DCHECK(invoke_instruction != *replacement);
Nicolas Geoffrayec068092021-05-10 17:28:32 +00001222 if (!invoke_instruction->IsInvokeInterface() && !invoke_instruction->IsInvokeVirtual()) {
Nicolas Geoffraye1e0e0f2021-04-29 08:57:13 +00001223 return false;
1224 }
Nicolas Geoffray39d4df62021-05-07 12:22:47 +00001225
Nicolas Geoffrayec068092021-05-10 17:28:32 +00001226 // Don't bother trying to call directly a default conflict method. It
1227 // doesn't have a proper MethodReference, but also `GetCanonicalMethod`
1228 // will return an actual default implementation.
1229 if (method->IsDefaultConflicting()) {
1230 return false;
Nicolas Geoffray39d4df62021-05-07 12:22:47 +00001231 }
Nicolas Geoffrayec068092021-05-10 17:28:32 +00001232 DCHECK(!method->IsProxyMethod());
1233 ClassLinker* cl = Runtime::Current()->GetClassLinker();
1234 PointerSize pointer_size = cl->GetImagePointerSize();
1235 // The sharpening logic assumes the caller isn't passing a copied method.
1236 method = method->GetCanonicalMethod(pointer_size);
Nicolas Geoffraye1e0e0f2021-04-29 08:57:13 +00001237 uint32_t dex_method_index = FindMethodIndexIn(
1238 method,
1239 *invoke_instruction->GetMethodReference().dex_file,
1240 invoke_instruction->GetMethodReference().index);
1241 if (dex_method_index == dex::kDexNoIndex) {
1242 return false;
1243 }
Nicolas Geoffrayec068092021-05-10 17:28:32 +00001244 HInvokeStaticOrDirect::DispatchInfo dispatch_info =
1245 HSharpening::SharpenLoadMethod(method,
1246 /* has_method_id= */ true,
1247 /* for_interface_call= */ false,
1248 codegen_);
1249 DCHECK_NE(dispatch_info.code_ptr_location, CodePtrLocation::kCallCriticalNative);
1250 if (dispatch_info.method_load_kind == MethodLoadKind::kRuntimeCall) {
1251 // If sharpening returns that we need to load the method at runtime, keep
1252 // the virtual/interface call which will be faster.
1253 // Also, the entrypoints for runtime calls do not handle devirtualized
1254 // calls.
1255 return false;
1256 }
1257
1258 HInvokeStaticOrDirect* new_invoke = new (graph_->GetAllocator()) HInvokeStaticOrDirect(
Nicolas Geoffraye1e0e0f2021-04-29 08:57:13 +00001259 graph_->GetAllocator(),
1260 invoke_instruction->GetNumberOfArguments(),
1261 invoke_instruction->GetType(),
1262 invoke_instruction->GetDexPc(),
1263 MethodReference(invoke_instruction->GetMethodReference().dex_file, dex_method_index),
1264 method,
Nicolas Geoffrayec068092021-05-10 17:28:32 +00001265 dispatch_info,
1266 kDirect,
Nicolas Geoffraye1e0e0f2021-04-29 08:57:13 +00001267 MethodReference(method->GetDexFile(), method->GetDexMethodIndex()),
Nicolas Geoffrayec068092021-05-10 17:28:32 +00001268 HInvokeStaticOrDirect::ClinitCheckRequirement::kNone);
Nicolas Geoffraye1e0e0f2021-04-29 08:57:13 +00001269 HInputsRef inputs = invoke_instruction->GetInputs();
Nicolas Geoffrayec068092021-05-10 17:28:32 +00001270 DCHECK_EQ(inputs.size(), invoke_instruction->GetNumberOfArguments());
Nicolas Geoffraye1e0e0f2021-04-29 08:57:13 +00001271 for (size_t index = 0; index != inputs.size(); ++index) {
1272 new_invoke->SetArgumentAt(index, inputs[index]);
1273 }
Nicolas Geoffrayec068092021-05-10 17:28:32 +00001274 if (HInvokeStaticOrDirect::NeedsCurrentMethodInput(dispatch_info)) {
1275 new_invoke->SetRawInputAt(new_invoke->GetCurrentMethodIndexUnchecked(),
1276 graph_->GetCurrentMethod());
1277 }
Nicolas Geoffraye1e0e0f2021-04-29 08:57:13 +00001278 invoke_instruction->GetBlock()->InsertInstructionBefore(new_invoke, invoke_instruction);
1279 new_invoke->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
1280 if (invoke_instruction->GetType() == DataType::Type::kReference) {
1281 new_invoke->SetReferenceTypeInfo(invoke_instruction->GetReferenceTypeInfo());
1282 }
1283 *replacement = new_invoke;
1284
1285 MaybeReplaceAndRemove(*replacement, invoke_instruction);
1286 // No need to call MaybeRunReferenceTypePropagation, as we know the return type
1287 // cannot be more specific.
1288 DCHECK(!ReturnTypeMoreSpecific(*replacement, invoke_instruction));
1289 return true;
1290}
1291
1292
1293bool HInliner::TryInlineAndReplace(HInvoke* invoke_instruction,
1294 ArtMethod* method,
1295 ReferenceTypeInfo receiver_type,
1296 bool do_rtp) {
1297 DCHECK(!invoke_instruction->IsIntrinsic());
1298 HInstruction* return_replacement = nullptr;
1299
1300 if (!TryBuildAndInline(invoke_instruction, method, receiver_type, &return_replacement)) {
1301 return false;
1302 }
1303
1304 MaybeReplaceAndRemove(return_replacement, invoke_instruction);
1305 FixUpReturnReferenceType(method, return_replacement);
1306 if (do_rtp) {
1307 MaybeRunReferenceTypePropagation(return_replacement, invoke_instruction);
1308 }
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001309 return true;
1310}
1311
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001312size_t HInliner::CountRecursiveCallsOf(ArtMethod* method) const {
1313 const HInliner* current = this;
1314 size_t count = 0;
1315 do {
1316 if (current->graph_->GetArtMethod() == method) {
1317 ++count;
1318 }
1319 current = current->parent_;
1320 } while (current != nullptr);
1321 return count;
1322}
1323
Vladimir Marko213ee2d2018-06-22 11:56:34 +01001324static inline bool MayInline(const CompilerOptions& compiler_options,
1325 const DexFile& inlined_from,
1326 const DexFile& inlined_into) {
Vladimir Marko213ee2d2018-06-22 11:56:34 +01001327 // We're not allowed to inline across dex files if we're the no-inline-from dex file.
1328 if (!IsSameDexFile(inlined_from, inlined_into) &&
1329 ContainsElement(compiler_options.GetNoInlineFromDexFile(), &inlined_from)) {
1330 return false;
1331 }
1332
1333 return true;
1334}
1335
Eric Holk1868de92020-02-12 09:10:21 -08001336// Returns whether inlining is allowed based on ART semantics.
1337bool HInliner::IsInliningAllowed(ArtMethod* method, const CodeItemDataAccessor& accessor) const {
Mathieu Chartier808c7a52017-12-15 11:19:33 -08001338 if (!accessor.HasCodeItem()) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001339 LOG_FAIL_NO_STAT()
1340 << "Method " << method->PrettyMethod() << " is not inlined because it is native";
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001341 return false;
1342 }
1343
Nicolas Geoffray250a3782016-04-20 16:27:53 +01001344 if (!method->IsCompilable()) {
Santiago Aboy Solanesfa73acc2021-11-12 14:23:27 +00001345 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedNotCompilable)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001346 << "Method " << method->PrettyMethod()
1347 << " has soft failures un-handled by the compiler, so it cannot be inlined";
Aart Bik897df032018-02-07 13:29:11 -08001348 return false;
Nicolas Geoffray250a3782016-04-20 16:27:53 +01001349 }
1350
Nicolas Geoffraycf74ae72021-07-15 10:37:28 +01001351 if (!IsMethodVerified(method)) {
Aart Bik2c148f02018-02-02 14:30:35 -08001352 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedNotVerified)
1353 << "Method " << method->PrettyMethod()
1354 << " couldn't be verified, so it cannot be inlined";
1355 return false;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001356 }
1357
Eric Holk1868de92020-02-12 09:10:21 -08001358 return true;
1359}
1360
1361// Returns whether ART supports inlining this method.
1362//
1363// Some methods are not supported because they have features for which inlining
1364// is not implemented. For example, we do not currently support inlining throw
1365// instructions into a try block.
1366bool HInliner::IsInliningSupported(const HInvoke* invoke_instruction,
1367 ArtMethod* method,
1368 const CodeItemDataAccessor& accessor) const {
1369 if (method->IsProxyMethod()) {
1370 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedProxy)
1371 << "Method " << method->PrettyMethod()
1372 << " is not inlined because of unimplemented inline support for proxy methods.";
1373 return false;
1374 }
1375
1376 if (accessor.TriesSize() != 0) {
Santiago Aboy Solanesfa73acc2021-11-12 14:23:27 +00001377 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedTryCatchCallee)
Eric Holk1868de92020-02-12 09:10:21 -08001378 << "Method " << method->PrettyMethod() << " is not inlined because of try block";
1379 return false;
1380 }
1381
Roland Levillain4c0eb422015-04-24 16:43:49 +01001382 if (invoke_instruction->IsInvokeStaticOrDirect() &&
1383 invoke_instruction->AsInvokeStaticOrDirect()->IsStaticWithImplicitClinitCheck()) {
1384 // Case of a static method that cannot be inlined because it implicitly
1385 // requires an initialization check of its declaring class.
Santiago Aboy Solanesfa73acc2021-11-12 14:23:27 +00001386 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedDexCacheClinitCheck)
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001387 << "Method " << method->PrettyMethod()
1388 << " is not inlined because it is static and requires a clinit"
1389 << " check that cannot be emitted due to Dex cache limitations";
Roland Levillain4c0eb422015-04-24 16:43:49 +01001390 return false;
1391 }
1392
Eric Holk1868de92020-02-12 09:10:21 -08001393 return true;
1394}
1395
1396// Returns whether our resource limits allow inlining this method.
1397bool HInliner::IsInliningBudgetAvailable(ArtMethod* method,
1398 const CodeItemDataAccessor& accessor) const {
1399 if (CountRecursiveCallsOf(method) > kMaximumNumberOfRecursiveCalls) {
1400 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedRecursiveBudget)
1401 << "Method "
1402 << method->PrettyMethod()
1403 << " is not inlined because it has reached its recursive call budget.";
1404 return false;
1405 }
1406
1407 size_t inline_max_code_units = codegen_->GetCompilerOptions().GetInlineMaxCodeUnits();
1408 if (accessor.InsnsSizeInCodeUnits() > inline_max_code_units) {
1409 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedCodeItem)
1410 << "Method " << method->PrettyMethod()
1411 << " is not inlined because its code item is too big: "
1412 << accessor.InsnsSizeInCodeUnits()
1413 << " > "
1414 << inline_max_code_units;
1415 return false;
1416 }
1417
1418 return true;
1419}
1420
1421bool HInliner::TryBuildAndInline(HInvoke* invoke_instruction,
1422 ArtMethod* method,
1423 ReferenceTypeInfo receiver_type,
1424 HInstruction** return_replacement) {
Nicolas Geoffrayb8958022021-04-15 15:12:31 +01001425 // If invoke_instruction is devirtualized to a different method, give intrinsics
1426 // another chance before we try to inline it.
1427 if (invoke_instruction->GetResolvedMethod() != method && method->IsIntrinsic()) {
1428 MaybeRecordStat(stats_, MethodCompilationStat::kIntrinsicRecognized);
1429 // For simplicity, always create a new instruction to replace the existing
1430 // invoke.
1431 HInvokeVirtual* new_invoke = new (graph_->GetAllocator()) HInvokeVirtual(
1432 graph_->GetAllocator(),
1433 invoke_instruction->GetNumberOfArguments(),
1434 invoke_instruction->GetType(),
1435 invoke_instruction->GetDexPc(),
1436 invoke_instruction->GetMethodReference(), // Use existing invoke's method's reference.
1437 method,
1438 MethodReference(method->GetDexFile(), method->GetDexMethodIndex()),
1439 method->GetMethodIndex());
1440 DCHECK_NE(new_invoke->GetIntrinsic(), Intrinsics::kNone);
1441 HInputsRef inputs = invoke_instruction->GetInputs();
1442 for (size_t index = 0; index != inputs.size(); ++index) {
1443 new_invoke->SetArgumentAt(index, inputs[index]);
1444 }
1445 invoke_instruction->GetBlock()->InsertInstructionBefore(new_invoke, invoke_instruction);
1446 new_invoke->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
1447 if (invoke_instruction->GetType() == DataType::Type::kReference) {
1448 new_invoke->SetReferenceTypeInfo(invoke_instruction->GetReferenceTypeInfo());
1449 }
1450 *return_replacement = new_invoke;
1451 return true;
1452 }
1453
Eric Holk1868de92020-02-12 09:10:21 -08001454 // Check whether we're allowed to inline. The outermost compilation unit is the relevant
1455 // dex file here (though the transitivity of an inline chain would allow checking the caller).
1456 if (!MayInline(codegen_->GetCompilerOptions(),
1457 *method->GetDexFile(),
1458 *outer_compilation_unit_.GetDexFile())) {
1459 if (TryPatternSubstitution(invoke_instruction, method, return_replacement)) {
1460 LOG_SUCCESS() << "Successfully replaced pattern of invoke "
1461 << method->PrettyMethod();
1462 MaybeRecordStat(stats_, MethodCompilationStat::kReplacedInvokeWithSimplePattern);
1463 return true;
1464 }
1465 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedWont)
1466 << "Won't inline " << method->PrettyMethod() << " in "
1467 << outer_compilation_unit_.GetDexFile()->GetLocation() << " ("
1468 << caller_compilation_unit_.GetDexFile()->GetLocation() << ") from "
1469 << method->GetDexFile()->GetLocation();
1470 return false;
1471 }
1472
1473 CodeItemDataAccessor accessor(method->DexInstructionData());
1474
1475 if (!IsInliningAllowed(method, accessor)) {
1476 return false;
1477 }
1478
1479 if (!IsInliningSupported(invoke_instruction, method, accessor)) {
1480 return false;
1481 }
1482
1483 if (!IsInliningBudgetAvailable(method, accessor)) {
1484 return false;
1485 }
1486
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001487 if (!TryBuildAndInlineHelper(
Eric Holk1868de92020-02-12 09:10:21 -08001488 invoke_instruction, method, receiver_type, return_replacement)) {
Nicolas Geoffrayc0365b12015-03-18 18:31:52 +00001489 return false;
1490 }
1491
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001492 LOG_SUCCESS() << method->PrettyMethod();
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001493 MaybeRecordStat(stats_, MethodCompilationStat::kInlinedInvoke);
Santiago Aboy Solanes15580482021-10-12 13:11:29 +01001494 if (outermost_graph_ == graph_) {
1495 MaybeRecordStat(stats_, MethodCompilationStat::kInlinedLastInvoke);
1496 }
Nicolas Geoffrayc0365b12015-03-18 18:31:52 +00001497 return true;
1498}
1499
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001500static HInstruction* GetInvokeInputForArgVRegIndex(HInvoke* invoke_instruction,
1501 size_t arg_vreg_index)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001502 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001503 size_t input_index = 0;
1504 for (size_t i = 0; i < arg_vreg_index; ++i, ++input_index) {
1505 DCHECK_LT(input_index, invoke_instruction->GetNumberOfArguments());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001506 if (DataType::Is64BitType(invoke_instruction->InputAt(input_index)->GetType())) {
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001507 ++i;
1508 DCHECK_NE(i, arg_vreg_index);
1509 }
1510 }
1511 DCHECK_LT(input_index, invoke_instruction->GetNumberOfArguments());
1512 return invoke_instruction->InputAt(input_index);
1513}
1514
1515// Try to recognize known simple patterns and replace invoke call with appropriate instructions.
1516bool HInliner::TryPatternSubstitution(HInvoke* invoke_instruction,
Nicolas Geoffraye6c0f2a2020-09-07 08:30:52 +01001517 ArtMethod* method,
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001518 HInstruction** return_replacement) {
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001519 InlineMethod inline_method;
Nicolas Geoffraye6c0f2a2020-09-07 08:30:52 +01001520 if (!InlineMethodAnalyser::AnalyseMethodCode(method, &inline_method)) {
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001521 return false;
1522 }
1523
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001524 switch (inline_method.opcode) {
1525 case kInlineOpNop:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001526 DCHECK_EQ(invoke_instruction->GetType(), DataType::Type::kVoid);
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001527 *return_replacement = nullptr;
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001528 break;
1529 case kInlineOpReturnArg:
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001530 *return_replacement = GetInvokeInputForArgVRegIndex(invoke_instruction,
1531 inline_method.d.return_data.arg);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001532 break;
1533 case kInlineOpNonWideConst:
Nicolas Geoffraye6c0f2a2020-09-07 08:30:52 +01001534 if (method->GetShorty()[0] == 'L') {
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001535 DCHECK_EQ(inline_method.d.data, 0u);
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001536 *return_replacement = graph_->GetNullConstant();
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001537 } else {
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001538 *return_replacement = graph_->GetIntConstant(static_cast<int32_t>(inline_method.d.data));
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001539 }
1540 break;
1541 case kInlineOpIGet: {
1542 const InlineIGetIPutData& data = inline_method.d.ifield_data;
1543 if (data.method_is_static || data.object_arg != 0u) {
1544 // TODO: Needs null check.
1545 return false;
1546 }
1547 HInstruction* obj = GetInvokeInputForArgVRegIndex(invoke_instruction, data.object_arg);
Nicolas Geoffraye6c0f2a2020-09-07 08:30:52 +01001548 HInstanceFieldGet* iget = CreateInstanceFieldGet(data.field_idx, method, obj);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001549 DCHECK_EQ(iget->GetFieldOffset().Uint32Value(), data.field_offset);
1550 DCHECK_EQ(iget->IsVolatile() ? 1u : 0u, data.is_volatile);
1551 invoke_instruction->GetBlock()->InsertInstructionBefore(iget, invoke_instruction);
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001552 *return_replacement = iget;
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001553 break;
1554 }
1555 case kInlineOpIPut: {
1556 const InlineIGetIPutData& data = inline_method.d.ifield_data;
1557 if (data.method_is_static || data.object_arg != 0u) {
1558 // TODO: Needs null check.
1559 return false;
1560 }
1561 HInstruction* obj = GetInvokeInputForArgVRegIndex(invoke_instruction, data.object_arg);
1562 HInstruction* value = GetInvokeInputForArgVRegIndex(invoke_instruction, data.src_arg);
Nicolas Geoffraye6c0f2a2020-09-07 08:30:52 +01001563 HInstanceFieldSet* iput = CreateInstanceFieldSet(data.field_idx, method, obj, value);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001564 DCHECK_EQ(iput->GetFieldOffset().Uint32Value(), data.field_offset);
1565 DCHECK_EQ(iput->IsVolatile() ? 1u : 0u, data.is_volatile);
1566 invoke_instruction->GetBlock()->InsertInstructionBefore(iput, invoke_instruction);
1567 if (data.return_arg_plus1 != 0u) {
1568 size_t return_arg = data.return_arg_plus1 - 1u;
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001569 *return_replacement = GetInvokeInputForArgVRegIndex(invoke_instruction, return_arg);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001570 }
1571 break;
1572 }
Vladimir Marko354efa62016-02-04 19:46:56 +00001573 case kInlineOpConstructor: {
1574 const InlineConstructorData& data = inline_method.d.constructor_data;
1575 // Get the indexes to arrays for easier processing.
1576 uint16_t iput_field_indexes[] = {
1577 data.iput0_field_index, data.iput1_field_index, data.iput2_field_index
1578 };
1579 uint16_t iput_args[] = { data.iput0_arg, data.iput1_arg, data.iput2_arg };
1580 static_assert(arraysize(iput_args) == arraysize(iput_field_indexes), "Size mismatch");
1581 // Count valid field indexes.
1582 size_t number_of_iputs = 0u;
1583 while (number_of_iputs != arraysize(iput_field_indexes) &&
1584 iput_field_indexes[number_of_iputs] != DexFile::kDexNoIndex16) {
1585 // Check that there are no duplicate valid field indexes.
1586 DCHECK_EQ(0, std::count(iput_field_indexes + number_of_iputs + 1,
1587 iput_field_indexes + arraysize(iput_field_indexes),
1588 iput_field_indexes[number_of_iputs]));
1589 ++number_of_iputs;
1590 }
1591 // Check that there are no valid field indexes in the rest of the array.
1592 DCHECK_EQ(0, std::count_if(iput_field_indexes + number_of_iputs,
1593 iput_field_indexes + arraysize(iput_field_indexes),
1594 [](uint16_t index) { return index != DexFile::kDexNoIndex16; }));
1595
1596 // Create HInstanceFieldSet for each IPUT that stores non-zero data.
Andreas Gampe3db70682018-12-26 15:12:03 -08001597 HInstruction* obj = GetInvokeInputForArgVRegIndex(invoke_instruction,
1598 /* arg_vreg_index= */ 0u);
Vladimir Marko354efa62016-02-04 19:46:56 +00001599 bool needs_constructor_barrier = false;
1600 for (size_t i = 0; i != number_of_iputs; ++i) {
1601 HInstruction* value = GetInvokeInputForArgVRegIndex(invoke_instruction, iput_args[i]);
Roland Levillain1a653882016-03-18 18:05:57 +00001602 if (!value->IsConstant() || !value->AsConstant()->IsZeroBitPattern()) {
Vladimir Marko354efa62016-02-04 19:46:56 +00001603 uint16_t field_index = iput_field_indexes[i];
Vladimir Markof44d36c2017-03-14 14:18:46 +00001604 bool is_final;
1605 HInstanceFieldSet* iput =
Nicolas Geoffraye6c0f2a2020-09-07 08:30:52 +01001606 CreateInstanceFieldSet(field_index, method, obj, value, &is_final);
Vladimir Marko354efa62016-02-04 19:46:56 +00001607 invoke_instruction->GetBlock()->InsertInstructionBefore(iput, invoke_instruction);
1608
1609 // Check whether the field is final. If it is, we need to add a barrier.
Vladimir Markof44d36c2017-03-14 14:18:46 +00001610 if (is_final) {
Vladimir Marko354efa62016-02-04 19:46:56 +00001611 needs_constructor_barrier = true;
1612 }
1613 }
1614 }
1615 if (needs_constructor_barrier) {
Vladimir Marko1a2a5cd2018-11-07 15:39:48 +00001616 // See DexCompilationUnit::RequiresConstructorBarrier for more details.
Igor Murashkind01745e2017-04-05 16:40:31 -07001617 DCHECK(obj != nullptr) << "only non-static methods can have a constructor fence";
1618
1619 HConstructorFence* constructor_fence =
Vladimir Markoca6fff82017-10-03 14:49:14 +01001620 new (graph_->GetAllocator()) HConstructorFence(obj, kNoDexPc, graph_->GetAllocator());
Igor Murashkind01745e2017-04-05 16:40:31 -07001621 invoke_instruction->GetBlock()->InsertInstructionBefore(constructor_fence,
1622 invoke_instruction);
Vladimir Marko354efa62016-02-04 19:46:56 +00001623 }
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001624 *return_replacement = nullptr;
Vladimir Marko354efa62016-02-04 19:46:56 +00001625 break;
1626 }
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001627 default:
1628 LOG(FATAL) << "UNREACHABLE";
1629 UNREACHABLE();
1630 }
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001631 return true;
1632}
1633
Vladimir Markof44d36c2017-03-14 14:18:46 +00001634HInstanceFieldGet* HInliner::CreateInstanceFieldGet(uint32_t field_index,
1635 ArtMethod* referrer,
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001636 HInstruction* obj)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001637 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markof44d36c2017-03-14 14:18:46 +00001638 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1639 ArtField* resolved_field =
Andreas Gampe3db70682018-12-26 15:12:03 -08001640 class_linker->LookupResolvedField(field_index, referrer, /* is_static= */ false);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001641 DCHECK(resolved_field != nullptr);
Vladimir Markoca6fff82017-10-03 14:49:14 +01001642 HInstanceFieldGet* iget = new (graph_->GetAllocator()) HInstanceFieldGet(
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001643 obj,
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00001644 resolved_field,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001645 DataType::FromShorty(resolved_field->GetTypeDescriptor()[0]),
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001646 resolved_field->GetOffset(),
1647 resolved_field->IsVolatile(),
1648 field_index,
1649 resolved_field->GetDeclaringClass()->GetDexClassDefIndex(),
Vladimir Markof44d36c2017-03-14 14:18:46 +00001650 *referrer->GetDexFile(),
Vladimir Markoadda4352016-01-29 10:24:41 +00001651 // Read barrier generates a runtime call in slow path and we need a valid
1652 // dex pc for the associated stack map. 0 is bogus but valid. Bug: 26854537.
Andreas Gampe3db70682018-12-26 15:12:03 -08001653 /* dex_pc= */ 0);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001654 if (iget->GetType() == DataType::Type::kReference) {
Vladimir Marko456307a2016-04-19 14:12:13 +00001655 // Use the same dex_cache that we used for field lookup as the hint_dex_cache.
Vladimir Marko02ca05a2020-05-12 13:58:51 +01001656 Handle<mirror::DexCache> dex_cache =
1657 graph_->GetHandleCache()->NewHandle(referrer->GetDexCache());
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001658 ReferenceTypePropagation rtp(graph_,
1659 outer_compilation_unit_.GetClassLoader(),
1660 dex_cache,
Andreas Gampe3db70682018-12-26 15:12:03 -08001661 /* is_first_run= */ false);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001662 rtp.Visit(iget);
1663 }
1664 return iget;
1665}
1666
Vladimir Markof44d36c2017-03-14 14:18:46 +00001667HInstanceFieldSet* HInliner::CreateInstanceFieldSet(uint32_t field_index,
1668 ArtMethod* referrer,
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001669 HInstruction* obj,
Vladimir Markof44d36c2017-03-14 14:18:46 +00001670 HInstruction* value,
1671 bool* is_final)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001672 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markof44d36c2017-03-14 14:18:46 +00001673 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1674 ArtField* resolved_field =
Andreas Gampe3db70682018-12-26 15:12:03 -08001675 class_linker->LookupResolvedField(field_index, referrer, /* is_static= */ false);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001676 DCHECK(resolved_field != nullptr);
Vladimir Markof44d36c2017-03-14 14:18:46 +00001677 if (is_final != nullptr) {
1678 // This information is needed only for constructors.
1679 DCHECK(referrer->IsConstructor());
1680 *is_final = resolved_field->IsFinal();
1681 }
Vladimir Markoca6fff82017-10-03 14:49:14 +01001682 HInstanceFieldSet* iput = new (graph_->GetAllocator()) HInstanceFieldSet(
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001683 obj,
1684 value,
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00001685 resolved_field,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001686 DataType::FromShorty(resolved_field->GetTypeDescriptor()[0]),
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001687 resolved_field->GetOffset(),
1688 resolved_field->IsVolatile(),
1689 field_index,
1690 resolved_field->GetDeclaringClass()->GetDexClassDefIndex(),
Vladimir Markof44d36c2017-03-14 14:18:46 +00001691 *referrer->GetDexFile(),
Vladimir Markoadda4352016-01-29 10:24:41 +00001692 // Read barrier generates a runtime call in slow path and we need a valid
1693 // dex pc for the associated stack map. 0 is bogus but valid. Bug: 26854537.
Andreas Gampe3db70682018-12-26 15:12:03 -08001694 /* dex_pc= */ 0);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001695 return iput;
1696}
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +00001697
Vladimir Markob1d0ee12017-04-20 19:50:32 +01001698template <typename T>
Vladimir Marko02ca05a2020-05-12 13:58:51 +01001699static inline Handle<T> NewHandleIfDifferent(ObjPtr<T> object, Handle<T> hint, HGraph* graph)
Vladimir Markob1d0ee12017-04-20 19:50:32 +01001700 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko02ca05a2020-05-12 13:58:51 +01001701 return (object != hint.Get()) ? graph->GetHandleCache()->NewHandle(object) : hint;
Vladimir Markob1d0ee12017-04-20 19:50:32 +01001702}
1703
Santiago Aboy Solanese43aa3f2021-11-01 09:02:09 +00001704static bool CanEncodeInlinedMethodInStackMap(const DexFile& outer_dex_file,
1705 ArtMethod* callee,
Santiago Aboy Solanes970ba212021-10-21 10:52:47 +01001706 const CodeGenerator* codegen,
Santiago Aboy Solanese43aa3f2021-11-01 09:02:09 +00001707 bool* out_needs_bss_check)
Vladimir Marko6be1dbd2018-11-13 13:09:51 +00001708 REQUIRES_SHARED(Locks::mutator_lock_) {
1709 if (!Runtime::Current()->IsAotCompiler()) {
1710 // JIT can always encode methods in stack maps.
1711 return true;
1712 }
Santiago Aboy Solanesa0232ad2021-11-08 17:00:06 +00001713
Santiago Aboy Solanes970ba212021-10-21 10:52:47 +01001714 const DexFile* dex_file = callee->GetDexFile();
1715 if (IsSameDexFile(outer_dex_file, *dex_file)) {
Vladimir Marko6be1dbd2018-11-13 13:09:51 +00001716 return true;
1717 }
Santiago Aboy Solanese43aa3f2021-11-01 09:02:09 +00001718
Santiago Aboy Solanes970ba212021-10-21 10:52:47 +01001719 // Inline across dexfiles if the callee's DexFile is:
1720 // 1) in the bootclasspath, or
Santiago Aboy Solanese43aa3f2021-11-01 09:02:09 +00001721 if (callee->GetDeclaringClass()->GetClassLoader() == nullptr) {
Santiago Aboy Solanesa0232ad2021-11-08 17:00:06 +00001722 // There are cases in which the BCP DexFiles are within the OatFile as far as the compiler
1723 // options are concerned, but they have their own OatWriter (and therefore not in the same
1724 // OatFile). Then, we request the BSS check for all BCP DexFiles.
1725 // TODO(solanes): Add .bss support for BCP.
Santiago Aboy Solanese43aa3f2021-11-01 09:02:09 +00001726 *out_needs_bss_check = true;
1727 return true;
1728 }
1729
Santiago Aboy Solanesa0232ad2021-11-08 17:00:06 +00001730 // 2) is a non-BCP dexfile with the OatFile we are compiling.
1731 if (codegen->GetCompilerOptions().WithinOatFile(dex_file)) {
Santiago Aboy Solanes970ba212021-10-21 10:52:47 +01001732 return true;
1733 }
1734
1735 // TODO(solanes): Support more AOT cases for inlining:
1736 // - methods in class loader context's DexFiles
Vladimir Marko6be1dbd2018-11-13 13:09:51 +00001737 return false;
1738}
1739
Eric Holk1868de92020-02-12 09:10:21 -08001740 // Substitutes parameters in the callee graph with their values from the caller.
1741void HInliner::SubstituteArguments(HGraph* callee_graph,
1742 HInvoke* invoke_instruction,
1743 ReferenceTypeInfo receiver_type,
1744 const DexCompilationUnit& dex_compilation_unit) {
1745 ArtMethod* const resolved_method = callee_graph->GetArtMethod();
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001746 size_t parameter_index = 0;
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001747 bool run_rtp = false;
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001748 for (HInstructionIterator instructions(callee_graph->GetEntryBlock()->GetInstructions());
1749 !instructions.Done();
1750 instructions.Advance()) {
1751 HInstruction* current = instructions.Current();
1752 if (current->IsParameterValue()) {
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001753 HInstruction* argument = invoke_instruction->InputAt(parameter_index);
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001754 if (argument->IsNullConstant()) {
1755 current->ReplaceWith(callee_graph->GetNullConstant());
1756 } else if (argument->IsIntConstant()) {
1757 current->ReplaceWith(callee_graph->GetIntConstant(argument->AsIntConstant()->GetValue()));
1758 } else if (argument->IsLongConstant()) {
1759 current->ReplaceWith(callee_graph->GetLongConstant(argument->AsLongConstant()->GetValue()));
1760 } else if (argument->IsFloatConstant()) {
1761 current->ReplaceWith(
1762 callee_graph->GetFloatConstant(argument->AsFloatConstant()->GetValue()));
1763 } else if (argument->IsDoubleConstant()) {
1764 current->ReplaceWith(
1765 callee_graph->GetDoubleConstant(argument->AsDoubleConstant()->GetValue()));
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001766 } else if (argument->GetType() == DataType::Type::kReference) {
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001767 if (!resolved_method->IsStatic() && parameter_index == 0 && receiver_type.IsValid()) {
1768 run_rtp = true;
1769 current->SetReferenceTypeInfo(receiver_type);
1770 } else {
1771 current->SetReferenceTypeInfo(argument->GetReferenceTypeInfo());
1772 }
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001773 current->AsParameterValue()->SetCanBeNull(argument->CanBeNull());
1774 }
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001775 ++parameter_index;
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001776 }
1777 }
1778
David Brazdil94ab38f2016-06-21 17:48:19 +01001779 // We have replaced formal arguments with actual arguments. If actual types
1780 // are more specific than the declared ones, run RTP again on the inner graph.
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001781 if (run_rtp || ArgumentTypesMoreSpecific(invoke_instruction, resolved_method)) {
David Brazdil94ab38f2016-06-21 17:48:19 +01001782 ReferenceTypePropagation(callee_graph,
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001783 outer_compilation_unit_.GetClassLoader(),
David Brazdil94ab38f2016-06-21 17:48:19 +01001784 dex_compilation_unit.GetDexCache(),
Andreas Gampe3db70682018-12-26 15:12:03 -08001785 /* is_first_run= */ false).Run();
David Brazdil94ab38f2016-06-21 17:48:19 +01001786 }
Eric Holk1868de92020-02-12 09:10:21 -08001787}
David Brazdil94ab38f2016-06-21 17:48:19 +01001788
Eric Holk1868de92020-02-12 09:10:21 -08001789// Returns whether we can inline the callee_graph into the target_block.
1790//
1791// This performs a combination of semantics checks, compiler support checks, and
1792// resource limit checks.
1793//
1794// If this function returns true, it will also set out_number_of_instructions to
1795// the number of instructions in the inlined body.
1796bool HInliner::CanInlineBody(const HGraph* callee_graph,
1797 const HBasicBlock* target_block,
1798 size_t* out_number_of_instructions) const {
Eric Holk1868de92020-02-12 09:10:21 -08001799 ArtMethod* const resolved_method = callee_graph->GetArtMethod();
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +00001800
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001801 HBasicBlock* exit_block = callee_graph->GetExitBlock();
1802 if (exit_block == nullptr) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001803 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedInfiniteLoop)
Nicolas Geoffray8731e702021-04-06 12:11:59 +01001804 << "Method " << resolved_method->PrettyMethod()
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001805 << " could not be inlined because it has an infinite loop";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001806 return false;
1807 }
1808
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00001809 bool has_one_return = false;
Vladimir Marko60584552015-09-03 13:35:12 +00001810 for (HBasicBlock* predecessor : exit_block->GetPredecessors()) {
1811 if (predecessor->GetLastInstruction()->IsThrow()) {
Eric Holk1868de92020-02-12 09:10:21 -08001812 if (target_block->IsTryBlock()) {
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00001813 // TODO(ngeoffray): Support adding HTryBoundary in Hgraph::InlineInto.
Santiago Aboy Solanesfa73acc2021-11-12 14:23:27 +00001814 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedTryCatchCaller)
Nicolas Geoffray8731e702021-04-06 12:11:59 +01001815 << "Method " << resolved_method->PrettyMethod()
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001816 << " could not be inlined because one branch always throws and"
1817 << " caller is in a try/catch block";
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00001818 return false;
1819 } else if (graph_->GetExitBlock() == nullptr) {
1820 // TODO(ngeoffray): Support adding HExit in the caller graph.
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001821 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedInfiniteLoop)
Nicolas Geoffray8731e702021-04-06 12:11:59 +01001822 << "Method " << resolved_method->PrettyMethod()
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001823 << " could not be inlined because one branch always throws and"
1824 << " caller does not have an exit block";
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00001825 return false;
Nicolas Geoffray1eede6a2017-03-02 16:14:53 +00001826 } else if (graph_->HasIrreducibleLoops()) {
1827 // TODO(ngeoffray): Support re-computing loop information to graphs with
1828 // irreducible loops?
Nicolas Geoffray8731e702021-04-06 12:11:59 +01001829 VLOG(compiler) << "Method " << resolved_method->PrettyMethod()
Nicolas Geoffray1eede6a2017-03-02 16:14:53 +00001830 << " could not be inlined because one branch always throws and"
1831 << " caller has irreducible loops";
1832 return false;
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00001833 }
1834 } else {
1835 has_one_return = true;
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001836 }
1837 }
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00001838
1839 if (!has_one_return) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001840 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedAlwaysThrows)
Nicolas Geoffray8731e702021-04-06 12:11:59 +01001841 << "Method " << resolved_method->PrettyMethod()
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001842 << " could not be inlined because it always throws";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001843 return false;
1844 }
1845
Santiago Aboy Solanese43aa3f2021-11-01 09:02:09 +00001846 const bool too_many_registers =
1847 total_number_of_dex_registers_ > kMaximumNumberOfCumulatedDexRegisters;
1848 bool needs_bss_check = false;
1849 const bool can_encode_in_stack_map = CanEncodeInlinedMethodInStackMap(
Santiago Aboy Solanes970ba212021-10-21 10:52:47 +01001850 *outer_compilation_unit_.GetDexFile(), resolved_method, codegen_, &needs_bss_check);
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001851 size_t number_of_instructions = 0;
Vladimir Marko2c45bc92016-10-25 16:54:12 +01001852 // Skip the entry block, it does not contain instructions that prevent inlining.
1853 for (HBasicBlock* block : callee_graph->GetReversePostOrderSkipEntryBlock()) {
David Sehrc757dec2016-11-04 15:48:34 -07001854 if (block->IsLoopHeader()) {
1855 if (block->GetLoopInformation()->IsIrreducible()) {
1856 // Don't inline methods with irreducible loops, they could prevent some
1857 // optimizations to run.
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001858 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedIrreducibleLoop)
Nicolas Geoffray8731e702021-04-06 12:11:59 +01001859 << "Method " << resolved_method->PrettyMethod()
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001860 << " could not be inlined because it contains an irreducible loop";
David Sehrc757dec2016-11-04 15:48:34 -07001861 return false;
1862 }
1863 if (!block->GetLoopInformation()->HasExitEdge()) {
1864 // Don't inline methods with loops without exit, since they cause the
1865 // loop information to be computed incorrectly when updating after
1866 // inlining.
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001867 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedLoopWithoutExit)
Nicolas Geoffray8731e702021-04-06 12:11:59 +01001868 << "Method " << resolved_method->PrettyMethod()
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001869 << " could not be inlined because it contains a loop with no exit";
David Sehrc757dec2016-11-04 15:48:34 -07001870 return false;
1871 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001872 }
1873
1874 for (HInstructionIterator instr_it(block->GetInstructions());
1875 !instr_it.Done();
1876 instr_it.Advance()) {
Tim Murray674e8be2021-04-12 12:30:28 -07001877 if (++number_of_instructions > inlining_budget_) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001878 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedInstructionBudget)
Nicolas Geoffray8731e702021-04-06 12:11:59 +01001879 << "Method " << resolved_method->PrettyMethod()
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001880 << " is not inlined because the outer method has reached"
1881 << " its instruction budget limit.";
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001882 return false;
1883 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001884 HInstruction* current = instr_it.Current();
Santiago Aboy Solanese43aa3f2021-11-01 09:02:09 +00001885 if (current->NeedsEnvironment()) {
1886 if (too_many_registers) {
1887 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedEnvironmentBudget)
1888 << "Method " << resolved_method->PrettyMethod()
1889 << " is not inlined because its caller has reached"
1890 << " its environment budget limit.";
1891 return false;
1892 }
Santiago Aboy Solanes33a31292021-09-24 08:50:06 +00001893
Santiago Aboy Solanese43aa3f2021-11-01 09:02:09 +00001894 if (!can_encode_in_stack_map) {
1895 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedStackMaps)
1896 << "Method " << resolved_method->PrettyMethod() << " could not be inlined because "
1897 << current->DebugName() << " needs an environment, is in a different dex file"
1898 << ", and cannot be encoded in the stack maps.";
1899 return false;
1900 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001901 }
Nicolas Geoffray9437b782015-03-25 10:08:51 +00001902
Nicolas Geoffrayd9309292015-10-31 22:21:31 +00001903 if (current->IsUnresolvedStaticFieldGet() ||
1904 current->IsUnresolvedInstanceFieldGet() ||
1905 current->IsUnresolvedStaticFieldSet() ||
1906 current->IsUnresolvedInstanceFieldSet()) {
1907 // Entrypoint for unresolved fields does not handle inlined frames.
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001908 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedUnresolvedEntrypoint)
Nicolas Geoffray8731e702021-04-06 12:11:59 +01001909 << "Method " << resolved_method->PrettyMethod()
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001910 << " could not be inlined because it is using an unresolved"
1911 << " entrypoint";
Nicolas Geoffrayd9309292015-10-31 22:21:31 +00001912 return false;
1913 }
Santiago Aboy Solanese43aa3f2021-11-01 09:02:09 +00001914
1915 // We currently don't have support for inlining across dex files if the inlined method needs a
1916 // .bss entry. This only happens when we are:
1917 // 1) In AoT,
1918 // 2) cross-dex inlining, and
1919 // 3) have an instruction that needs a bss entry, which will always be
1920 // 3)b) an instruction that needs an environment.
1921 // TODO(solanes, 154012332): Add this support.
1922 if (needs_bss_check && current->NeedsBss()) {
1923 DCHECK(current->NeedsEnvironment());
1924 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedBss)
1925 << "Method " << resolved_method->PrettyMethod()
1926 << " could not be inlined because it needs a BSS check";
1927 return false;
1928 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001929 }
1930 }
Eric Holk1868de92020-02-12 09:10:21 -08001931
1932 *out_number_of_instructions = number_of_instructions;
1933 return true;
1934}
1935
1936bool HInliner::TryBuildAndInlineHelper(HInvoke* invoke_instruction,
1937 ArtMethod* resolved_method,
1938 ReferenceTypeInfo receiver_type,
1939 HInstruction** return_replacement) {
1940 DCHECK(!(resolved_method->IsStatic() && receiver_type.IsValid()));
1941 const dex::CodeItem* code_item = resolved_method->GetCodeItem();
1942 const DexFile& callee_dex_file = *resolved_method->GetDexFile();
1943 uint32_t method_index = resolved_method->GetDexMethodIndex();
1944 CodeItemDebugInfoAccessor code_item_accessor(resolved_method->DexInstructionDebugInfo());
1945 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
1946 Handle<mirror::DexCache> dex_cache = NewHandleIfDifferent(resolved_method->GetDexCache(),
1947 caller_compilation_unit_.GetDexCache(),
Vladimir Marko02ca05a2020-05-12 13:58:51 +01001948 graph_);
Eric Holk1868de92020-02-12 09:10:21 -08001949 Handle<mirror::ClassLoader> class_loader =
1950 NewHandleIfDifferent(resolved_method->GetDeclaringClass()->GetClassLoader(),
1951 caller_compilation_unit_.GetClassLoader(),
Vladimir Marko02ca05a2020-05-12 13:58:51 +01001952 graph_);
Eric Holk1868de92020-02-12 09:10:21 -08001953
Vladimir Marko02ca05a2020-05-12 13:58:51 +01001954 Handle<mirror::Class> compiling_class =
1955 graph_->GetHandleCache()->NewHandle(resolved_method->GetDeclaringClass());
Eric Holk1868de92020-02-12 09:10:21 -08001956 DexCompilationUnit dex_compilation_unit(
1957 class_loader,
1958 class_linker,
1959 callee_dex_file,
1960 code_item,
1961 resolved_method->GetDeclaringClass()->GetDexClassDefIndex(),
1962 method_index,
1963 resolved_method->GetAccessFlags(),
1964 /* verified_method= */ nullptr,
1965 dex_cache,
1966 compiling_class);
1967
1968 InvokeType invoke_type = invoke_instruction->GetInvokeType();
1969 if (invoke_type == kInterface) {
1970 // We have statically resolved the dispatch. To please the class linker
1971 // at runtime, we change this call as if it was a virtual call.
1972 invoke_type = kVirtual;
1973 }
1974
1975 bool caller_dead_reference_safe = graph_->IsDeadReferenceSafe();
1976 const dex::ClassDef& callee_class = resolved_method->GetClassDef();
1977 // MethodContainsRSensitiveAccess is currently slow, but HasDeadReferenceSafeAnnotation()
1978 // is currently rarely true.
1979 bool callee_dead_reference_safe =
1980 annotations::HasDeadReferenceSafeAnnotation(callee_dex_file, callee_class)
1981 && !annotations::MethodContainsRSensitiveAccess(callee_dex_file, callee_class, method_index);
1982
1983 const int32_t caller_instruction_counter = graph_->GetCurrentInstructionId();
1984 HGraph* callee_graph = new (graph_->GetAllocator()) HGraph(
1985 graph_->GetAllocator(),
1986 graph_->GetArenaStack(),
Vladimir Marko02ca05a2020-05-12 13:58:51 +01001987 graph_->GetHandleCache()->GetHandles(),
Eric Holk1868de92020-02-12 09:10:21 -08001988 callee_dex_file,
1989 method_index,
1990 codegen_->GetCompilerOptions().GetInstructionSet(),
1991 invoke_type,
1992 callee_dead_reference_safe,
1993 graph_->IsDebuggable(),
Nicolas Geoffray0d60a2b2020-06-17 14:31:56 +01001994 graph_->GetCompilationKind(),
Eric Holk1868de92020-02-12 09:10:21 -08001995 /* start_instruction_id= */ caller_instruction_counter);
1996 callee_graph->SetArtMethod(resolved_method);
1997
1998 // When they are needed, allocate `inline_stats_` on the Arena instead
1999 // of on the stack, as Clang might produce a stack frame too large
2000 // for this function, that would not fit the requirements of the
2001 // `-Wframe-larger-than` option.
2002 if (stats_ != nullptr) {
2003 // Reuse one object for all inline attempts from this caller to keep Arena memory usage low.
2004 if (inline_stats_ == nullptr) {
2005 void* storage = graph_->GetAllocator()->Alloc<OptimizingCompilerStats>(kArenaAllocMisc);
2006 inline_stats_ = new (storage) OptimizingCompilerStats;
2007 } else {
2008 inline_stats_->Reset();
2009 }
2010 }
2011 HGraphBuilder builder(callee_graph,
2012 code_item_accessor,
2013 &dex_compilation_unit,
2014 &outer_compilation_unit_,
2015 codegen_,
Nicolas Geoffray4924ea92021-03-23 08:25:31 +00002016 inline_stats_);
Eric Holk1868de92020-02-12 09:10:21 -08002017
2018 if (builder.BuildGraph() != kAnalysisSuccess) {
2019 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedCannotBuild)
2020 << "Method " << callee_dex_file.PrettyMethod(method_index)
2021 << " could not be built, so cannot be inlined";
2022 return false;
2023 }
2024
2025 SubstituteArguments(callee_graph, invoke_instruction, receiver_type, dex_compilation_unit);
2026
2027 RunOptimizations(callee_graph, code_item, dex_compilation_unit);
2028
2029 size_t number_of_instructions = 0;
2030 if (!CanInlineBody(callee_graph, invoke_instruction->GetBlock(), &number_of_instructions)) {
2031 return false;
2032 }
2033
David Brazdil3f523062016-02-29 16:53:33 +00002034 DCHECK_EQ(caller_instruction_counter, graph_->GetCurrentInstructionId())
2035 << "No instructions can be added to the outer graph while inner graph is being built";
2036
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00002037 // Inline the callee graph inside the caller graph.
David Brazdil3f523062016-02-29 16:53:33 +00002038 const int32_t callee_instruction_counter = callee_graph->GetCurrentInstructionId();
2039 graph_->SetCurrentInstructionId(callee_instruction_counter);
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00002040 *return_replacement = callee_graph->InlineInto(graph_, invoke_instruction);
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00002041 // Update our budget for other inlining attempts in `caller_graph`.
2042 total_number_of_instructions_ += number_of_instructions;
2043 UpdateInliningBudget();
David Brazdil3f523062016-02-29 16:53:33 +00002044
2045 DCHECK_EQ(callee_instruction_counter, callee_graph->GetCurrentInstructionId())
2046 << "No instructions can be added to the inner graph during inlining into the outer graph";
2047
Vladimir Marko438709f2017-02-23 18:56:13 +00002048 if (stats_ != nullptr) {
2049 DCHECK(inline_stats_ != nullptr);
2050 inline_stats_->AddTo(stats_);
2051 }
2052
Hans Boehm206348c2018-12-05 11:11:33 -08002053 if (caller_dead_reference_safe && !callee_dead_reference_safe) {
2054 // Caller was dead reference safe, but is not anymore, since we inlined dead
2055 // reference unsafe code. Prior transformations remain valid, since they did not
2056 // affect the inlined code.
2057 graph_->MarkDeadReferenceUnsafe();
2058 }
2059
Vladimir Markobe10e8e2016-01-22 12:09:44 +00002060 return true;
2061}
Calin Juravle2e768302015-07-28 14:41:11 +00002062
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00002063void HInliner::RunOptimizations(HGraph* callee_graph,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08002064 const dex::CodeItem* code_item,
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00002065 const DexCompilationUnit& dex_compilation_unit) {
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01002066 // Note: if the outermost_graph_ is being compiled OSR, we should not run any
2067 // optimization that could lead to a HDeoptimize. The following optimizations do not.
Vladimir Marko438709f2017-02-23 18:56:13 +00002068 HDeadCodeElimination dce(callee_graph, inline_stats_, "dead_code_elimination$inliner");
Andreas Gampeca620d72016-11-08 08:09:33 -08002069 HConstantFolding fold(callee_graph, "constant_folding$inliner");
Vladimir Markobb089b62018-06-28 17:30:16 +01002070 InstructionSimplifier simplify(callee_graph, codegen_, inline_stats_);
Roland Levillaina3aef2e2016-04-06 17:45:58 +01002071
2072 HOptimization* optimizations[] = {
Roland Levillaina3aef2e2016-04-06 17:45:58 +01002073 &simplify,
2074 &fold,
2075 &dce,
2076 };
2077
2078 for (size_t i = 0; i < arraysize(optimizations); ++i) {
2079 HOptimization* optimization = optimizations[i];
2080 optimization->Run();
2081 }
2082
Santiago Aboy Solanes33a31292021-09-24 08:50:06 +00002083 // Bail early for pathological cases on the environment (for example recursive calls,
2084 // or too large environment).
2085 if (total_number_of_dex_registers_ > kMaximumNumberOfCumulatedDexRegisters) {
2086 LOG_NOTE() << "Calls in " << callee_graph->GetArtMethod()->PrettyMethod()
2087 << " will not be inlined because the outer method has reached"
2088 << " its environment budget limit.";
2089 return;
2090 }
2091
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00002092 // Bail early if we know we already are over the limit.
2093 size_t number_of_instructions = CountNumberOfInstructions(callee_graph);
2094 if (number_of_instructions > inlining_budget_) {
2095 LOG_NOTE() << "Calls in " << callee_graph->GetArtMethod()->PrettyMethod()
2096 << " will not be inlined because the outer method has reached"
2097 << " its instruction budget limit. " << number_of_instructions;
2098 return;
2099 }
2100
Mathieu Chartier698ebbc2018-01-05 11:00:42 -08002101 CodeItemDataAccessor accessor(callee_graph->GetDexFile(), code_item);
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00002102 HInliner inliner(callee_graph,
2103 outermost_graph_,
2104 codegen_,
2105 outer_compilation_unit_,
2106 dex_compilation_unit,
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00002107 inline_stats_,
Mathieu Chartier808c7a52017-12-15 11:19:33 -08002108 total_number_of_dex_registers_ + accessor.RegistersSize(),
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00002109 total_number_of_instructions_ + number_of_instructions,
2110 this,
2111 depth_ + 1);
2112 inliner.Run();
Roland Levillaina3aef2e2016-04-06 17:45:58 +01002113}
2114
Vladimir Marko5a62af52020-05-11 15:16:24 +01002115static bool IsReferenceTypeRefinement(ObjPtr<mirror::Class> declared_class,
2116 bool declared_is_exact,
David Brazdil94ab38f2016-06-21 17:48:19 +01002117 bool declared_can_be_null,
2118 HInstruction* actual_obj)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002119 REQUIRES_SHARED(Locks::mutator_lock_) {
David Brazdil94ab38f2016-06-21 17:48:19 +01002120 if (declared_can_be_null && !actual_obj->CanBeNull()) {
2121 return true;
2122 }
2123
2124 ReferenceTypeInfo actual_rti = actual_obj->GetReferenceTypeInfo();
Vladimir Marko5a62af52020-05-11 15:16:24 +01002125 ObjPtr<mirror::Class> actual_class = actual_rti.GetTypeHandle().Get();
2126 return (actual_rti.IsExact() && !declared_is_exact) ||
2127 (declared_class != actual_class && declared_class->IsAssignableFrom(actual_class));
David Brazdil94ab38f2016-06-21 17:48:19 +01002128}
2129
Vladimir Marko5a62af52020-05-11 15:16:24 +01002130static bool IsReferenceTypeRefinement(ObjPtr<mirror::Class> declared_class,
2131 bool declared_can_be_null,
2132 HInstruction* actual_obj)
2133 REQUIRES_SHARED(Locks::mutator_lock_) {
2134 bool admissible = ReferenceTypePropagation::IsAdmissible(declared_class);
2135 return IsReferenceTypeRefinement(
2136 admissible ? declared_class : GetClassRoot<mirror::Class>(),
2137 /*declared_is_exact=*/ admissible && declared_class->CannotBeAssignedFromOtherTypes(),
2138 declared_can_be_null,
2139 actual_obj);
David Brazdil94ab38f2016-06-21 17:48:19 +01002140}
2141
2142bool HInliner::ArgumentTypesMoreSpecific(HInvoke* invoke_instruction, ArtMethod* resolved_method) {
2143 // If this is an instance call, test whether the type of the `this` argument
2144 // is more specific than the class which declares the method.
2145 if (!resolved_method->IsStatic()) {
Vladimir Marko5a62af52020-05-11 15:16:24 +01002146 if (IsReferenceTypeRefinement(resolved_method->GetDeclaringClass(),
2147 /*declared_can_be_null=*/ false,
David Brazdil94ab38f2016-06-21 17:48:19 +01002148 invoke_instruction->InputAt(0u))) {
2149 return true;
2150 }
2151 }
2152
David Brazdil94ab38f2016-06-21 17:48:19 +01002153 // Iterate over the list of parameter types and test whether any of the
2154 // actual inputs has a more specific reference type than the type declared in
2155 // the signature.
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08002156 const dex::TypeList* param_list = resolved_method->GetParameterTypeList();
David Brazdil94ab38f2016-06-21 17:48:19 +01002157 for (size_t param_idx = 0,
2158 input_idx = resolved_method->IsStatic() ? 0 : 1,
2159 e = (param_list == nullptr ? 0 : param_list->Size());
2160 param_idx < e;
2161 ++param_idx, ++input_idx) {
2162 HInstruction* input = invoke_instruction->InputAt(input_idx);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002163 if (input->GetType() == DataType::Type::kReference) {
Vladimir Markob45528c2017-07-27 14:14:28 +01002164 ObjPtr<mirror::Class> param_cls = resolved_method->LookupResolvedClassFromTypeIndex(
2165 param_list->GetTypeItem(param_idx).type_idx_);
Vladimir Marko5a62af52020-05-11 15:16:24 +01002166 if (IsReferenceTypeRefinement(param_cls, /*declared_can_be_null=*/ true, input)) {
David Brazdil94ab38f2016-06-21 17:48:19 +01002167 return true;
2168 }
2169 }
2170 }
2171
2172 return false;
2173}
2174
Nicolas Geoffraye1e0e0f2021-04-29 08:57:13 +00002175bool HInliner::ReturnTypeMoreSpecific(HInstruction* return_replacement,
2176 HInvoke* invoke_instruction) {
Alex Light68289a52015-12-15 17:30:30 -08002177 // Check the integrity of reference types and run another type propagation if needed.
David Brazdil4833f5a2015-12-16 10:37:39 +00002178 if (return_replacement != nullptr) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002179 if (return_replacement->GetType() == DataType::Type::kReference) {
David Brazdil94ab38f2016-06-21 17:48:19 +01002180 // Test if the return type is a refinement of the declared return type.
Vladimir Marko5a62af52020-05-11 15:16:24 +01002181 ReferenceTypeInfo invoke_rti = invoke_instruction->GetReferenceTypeInfo();
2182 if (IsReferenceTypeRefinement(invoke_rti.GetTypeHandle().Get(),
2183 invoke_rti.IsExact(),
2184 /*declared_can_be_null=*/ true,
David Brazdil94ab38f2016-06-21 17:48:19 +01002185 return_replacement)) {
2186 return true;
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00002187 } else if (return_replacement->IsInstanceFieldGet()) {
2188 HInstanceFieldGet* field_get = return_replacement->AsInstanceFieldGet();
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00002189 if (field_get->GetFieldInfo().GetField() ==
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002190 GetClassRoot<mirror::Object>()->GetInstanceField(0)) {
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00002191 return true;
2192 }
David Brazdil94ab38f2016-06-21 17:48:19 +01002193 }
2194 } else if (return_replacement->IsInstanceOf()) {
2195 // Inlining InstanceOf into an If may put a tighter bound on reference types.
2196 return true;
2197 }
2198 }
2199
2200 return false;
2201}
2202
2203void HInliner::FixUpReturnReferenceType(ArtMethod* resolved_method,
2204 HInstruction* return_replacement) {
2205 if (return_replacement != nullptr) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002206 if (return_replacement->GetType() == DataType::Type::kReference) {
David Brazdil4833f5a2015-12-16 10:37:39 +00002207 if (!return_replacement->GetReferenceTypeInfo().IsValid()) {
2208 // Make sure that we have a valid type for the return. We may get an invalid one when
2209 // we inline invokes with multiple branches and create a Phi for the result.
2210 // TODO: we could be more precise by merging the phi inputs but that requires
2211 // some functionality from the reference type propagation.
2212 DCHECK(return_replacement->IsPhi());
Vladimir Markob45528c2017-07-27 14:14:28 +01002213 ObjPtr<mirror::Class> cls = resolved_method->LookupResolvedReturnType();
Vladimir Marko5a62af52020-05-11 15:16:24 +01002214 ReferenceTypeInfo rti = ReferenceTypePropagation::IsAdmissible(cls)
Vladimir Marko02ca05a2020-05-12 13:58:51 +01002215 ? ReferenceTypeInfo::Create(graph_->GetHandleCache()->NewHandle(cls))
Vladimir Marko5a62af52020-05-11 15:16:24 +01002216 : graph_->GetInexactObjectRti();
2217 return_replacement->SetReferenceTypeInfo(rti);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01002218 }
Calin Juravlecdfed3d2015-10-26 14:05:01 +00002219 }
Calin Juravle2e768302015-07-28 14:41:11 +00002220 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002221}
2222
2223} // namespace art