blob: cdd8fb26384eb41cabca18c17bb5c37d0c1770ca [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
Santiago Aboy Solanes4f5b7cb2022-02-10 10:25:15 +000067// Limit recursive polymorphic call inlining to prevent code bloat, since it can quickly get out of
68// hand in the presence of multiple Wrapper classes. We set this to 0 to disallow polymorphic
69// recursive calls at all.
70static constexpr size_t kMaximumNumberOfPolymorphicRecursiveCalls = 0;
71
Calin Juravlee2492d42017-03-20 11:42:13 -070072// Controls the use of inline caches in AOT mode.
Calin Juravle8af70892017-03-28 15:31:44 -070073static constexpr bool kUseAOTInlineCaches = true;
Calin Juravlee2492d42017-03-20 11:42:13 -070074
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +000075// We check for line numbers to make sure the DepthString implementation
76// aligns the output nicely.
77#define LOG_INTERNAL(msg) \
78 static_assert(__LINE__ > 10, "Unhandled line number"); \
79 static_assert(__LINE__ < 10000, "Unhandled line number"); \
80 VLOG(compiler) << DepthString(__LINE__) << msg
81
82#define LOG_TRY() LOG_INTERNAL("Try inlinining call: ")
83#define LOG_NOTE() LOG_INTERNAL("Note: ")
84#define LOG_SUCCESS() LOG_INTERNAL("Success: ")
Igor Murashkin1e065a52017-08-09 13:20:34 -070085#define LOG_FAIL(stats_ptr, stat) MaybeRecordStat(stats_ptr, stat); LOG_INTERNAL("Fail: ")
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +000086#define LOG_FAIL_NO_STAT() LOG_INTERNAL("Fail: ")
87
88std::string HInliner::DepthString(int line) const {
89 std::string value;
90 // Indent according to the inlining depth.
91 size_t count = depth_;
92 // Line numbers get printed in the log, so add a space if the log's line is less
93 // than 1000, and two if less than 100. 10 cannot be reached as it's the copyright.
94 if (!kIsTargetBuild) {
95 if (line < 100) {
96 value += " ";
97 }
98 if (line < 1000) {
99 value += " ";
100 }
101 // Safeguard if this file reaches more than 10000 lines.
102 DCHECK_LT(line, 10000);
103 }
104 for (size_t i = 0; i < count; ++i) {
105 value += " ";
106 }
107 return value;
108}
109
110static size_t CountNumberOfInstructions(HGraph* graph) {
111 size_t number_of_instructions = 0;
112 for (HBasicBlock* block : graph->GetReversePostOrderSkipEntryBlock()) {
113 for (HInstructionIterator instr_it(block->GetInstructions());
114 !instr_it.Done();
115 instr_it.Advance()) {
116 ++number_of_instructions;
117 }
118 }
119 return number_of_instructions;
120}
121
122void HInliner::UpdateInliningBudget() {
123 if (total_number_of_instructions_ >= kMaximumNumberOfTotalInstructions) {
124 // Always try to inline small methods.
125 inlining_budget_ = kMaximumNumberOfInstructionsForSmallMethod;
126 } else {
127 inlining_budget_ = std::max(
128 kMaximumNumberOfInstructionsForSmallMethod,
129 kMaximumNumberOfTotalInstructions - total_number_of_instructions_);
130 }
131}
132
Aart Bik24773202018-04-26 10:28:51 -0700133bool HInliner::Run() {
Vladimir Marko213ee2d2018-06-22 11:56:34 +0100134 if (codegen_->GetCompilerOptions().GetInlineMaxCodeUnits() == 0) {
Aart Bik24773202018-04-26 10:28:51 -0700135 // Inlining effectively disabled.
136 return false;
137 } else if (graph_->IsDebuggable()) {
Nicolas Geoffraye50b8d22015-03-13 08:57:42 +0000138 // For simplicity, we currently never inline when the graph is debuggable. This avoids
139 // doing some logic in the runtime to discover if a method could have been inlined.
Aart Bik24773202018-04-26 10:28:51 -0700140 return false;
Nicolas Geoffraye50b8d22015-03-13 08:57:42 +0000141 }
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000142
Santiago Aboy Solanes8e92a612022-04-06 15:11:28 +0100143 bool did_inline = false;
Santiago Aboy Solanes8ed39492022-07-20 11:13:39 +0100144 // The inliner is the only phase that sets invokes as `always throwing`, and since we only run the
145 // inliner once per graph this value should always be false at the beginning of the inlining
146 // phase. This is important since we use `HasAlwaysThrowingInvokes` to know whether the inliner
147 // phase performed a relevant change in the graph.
148 DCHECK(!graph_->HasAlwaysThrowingInvokes());
Aart Bik24773202018-04-26 10:28:51 -0700149
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000150 // Initialize the number of instructions for the method being compiled. Recursive calls
151 // to HInliner::Run have already updated the instruction count.
152 if (outermost_graph_ == graph_) {
153 total_number_of_instructions_ = CountNumberOfInstructions(graph_);
154 }
155
156 UpdateInliningBudget();
157 DCHECK_NE(total_number_of_instructions_, 0u);
158 DCHECK_NE(inlining_budget_, 0u);
159
David Srbecky4fa07a52020-03-31 20:52:09 +0100160 // If we're compiling tests, honor inlining directives in method names:
Roland Levillain6c3af162017-04-27 11:18:56 +0100161 // - if a method's name contains the substring "$noinline$", do not
Vladimir Marko6be1dbd2018-11-13 13:09:51 +0000162 // inline that method;
163 // - if a method's name contains the substring "$inline$", ensure
164 // that this method is actually inlined.
Vladimir Markobe0c7cf2018-03-19 13:40:56 +0000165 // We limit the latter to AOT compilation, as the JIT may or may not inline
Nicolas Geoffray08490b82017-07-18 12:58:10 +0100166 // depending on the state of classes at runtime.
David Srbecky4fa07a52020-03-31 20:52:09 +0100167 const bool honor_noinline_directives = codegen_->GetCompilerOptions().CompileArtTest();
Vladimir Markobe0c7cf2018-03-19 13:40:56 +0000168 const bool honor_inline_directives =
169 honor_noinline_directives && Runtime::Current()->IsAotCompiler();
Roland Levillain6c3af162017-04-27 11:18:56 +0100170
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +0000171 // Keep a copy of all blocks when starting the visit.
172 ArenaVector<HBasicBlock*> blocks = graph_->GetReversePostOrder();
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100173 DCHECK(!blocks.empty());
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +0000174 // Because we are changing the graph when inlining,
175 // we just iterate over the blocks of the outer method.
176 // This avoids doing the inlining work again on the inlined blocks.
177 for (HBasicBlock* block : blocks) {
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +0000178 for (HInstruction* instruction = block->GetFirstInstruction(); instruction != nullptr;) {
179 HInstruction* next = instruction->GetNext();
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100180 HInvoke* call = instruction->AsInvoke();
Razvan A Lupusoru3e90a962015-03-27 13:44:44 -0700181 // As long as the call is not intrinsified, it is worth trying to inline.
182 if (call != nullptr && call->GetIntrinsic() == Intrinsics::kNone) {
Vladimir Markobe0c7cf2018-03-19 13:40:56 +0000183 if (honor_noinline_directives) {
Nicolas Geoffrayb703d182017-02-14 18:05:28 +0000184 // Debugging case: directives in method names control or assert on inlining.
Nicolas Geoffraye6c0f2a2020-09-07 08:30:52 +0100185 std::string callee_name =
186 call->GetMethodReference().PrettyMethod(/* with_signature= */ false);
Nicolas Geoffrayb703d182017-02-14 18:05:28 +0000187 // Tests prevent inlining by having $noinline$ in their method names.
188 if (callee_name.find("$noinline$") == std::string::npos) {
Santiago Aboy Solanes8ed39492022-07-20 11:13:39 +0100189 if (TryInline(call)) {
Santiago Aboy Solanes8e92a612022-04-06 15:11:28 +0100190 did_inline = true;
Aart Bik54e45c52018-04-27 13:57:21 -0700191 } else if (honor_inline_directives) {
Nicolas Geoffray1949baf2017-10-17 12:14:53 +0000192 bool should_have_inlined = (callee_name.find("$inline$") != std::string::npos);
193 CHECK(!should_have_inlined) << "Could not inline " << callee_name;
Nicolas Geoffrayb703d182017-02-14 18:05:28 +0000194 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000195 }
Guillaume "Vermeille" Sancheze918d382015-06-03 15:32:41 +0100196 } else {
Vladimir Markobe0c7cf2018-03-19 13:40:56 +0000197 DCHECK(!honor_inline_directives);
Nicolas Geoffrayb703d182017-02-14 18:05:28 +0000198 // Normal case: try to inline.
Santiago Aboy Solanes8ed39492022-07-20 11:13:39 +0100199 if (TryInline(call)) {
Santiago Aboy Solanes8e92a612022-04-06 15:11:28 +0100200 did_inline = true;
Aart Bik24773202018-04-26 10:28:51 -0700201 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000202 }
203 }
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +0000204 instruction = next;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000205 }
206 }
Aart Bik24773202018-04-26 10:28:51 -0700207
Santiago Aboy Solanes8ed39492022-07-20 11:13:39 +0100208 // We return true if we either inlined at least one method, or we marked one of our methods as
209 // always throwing.
210 return did_inline || graph_->HasAlwaysThrowingInvokes();
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000211}
212
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100213static bool IsMethodOrDeclaringClassFinal(ArtMethod* method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700214 REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100215 return method->IsFinal() || method->GetDeclaringClass()->IsFinal();
216}
217
218/**
219 * Given the `resolved_method` looked up in the dex cache, try to find
220 * the actual runtime target of an interface or virtual call.
221 * Return nullptr if the runtime target cannot be proven.
222 */
Nicolas Geoffraye6c0f2a2020-09-07 08:30:52 +0100223static ArtMethod* FindVirtualOrInterfaceTarget(HInvoke* invoke)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700224 REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffraye6c0f2a2020-09-07 08:30:52 +0100225 ArtMethod* resolved_method = invoke->GetResolvedMethod();
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100226 if (IsMethodOrDeclaringClassFinal(resolved_method)) {
227 // No need to lookup further, the resolved method will be the target.
228 return resolved_method;
229 }
230
231 HInstruction* receiver = invoke->InputAt(0);
232 if (receiver->IsNullCheck()) {
233 // Due to multiple levels of inlining within the same pass, it might be that
234 // null check does not have the reference type of the actual receiver.
235 receiver = receiver->InputAt(0);
236 }
237 ReferenceTypeInfo info = receiver->GetReferenceTypeInfo();
Calin Juravle2e768302015-07-28 14:41:11 +0000238 DCHECK(info.IsValid()) << "Invalid RTI for " << receiver->DebugName();
239 if (!info.IsExact()) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100240 // We currently only support inlining with known receivers.
241 // TODO: Remove this check, we should be able to inline final methods
242 // on unknown receivers.
243 return nullptr;
244 } else if (info.GetTypeHandle()->IsInterface()) {
245 // Statically knowing that the receiver has an interface type cannot
246 // help us find what is the target method.
247 return nullptr;
248 } else if (!resolved_method->GetDeclaringClass()->IsAssignableFrom(info.GetTypeHandle().Get())) {
249 // The method that we're trying to call is not in the receiver's class or super classes.
250 return nullptr;
Nicolas Geoffrayab5327d2016-03-18 11:36:20 +0000251 } else if (info.GetTypeHandle()->IsErroneous()) {
252 // If the type is erroneous, do not go further, as we are going to query the vtable or
253 // imt table, that we can only safely do on non-erroneous classes.
254 return nullptr;
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100255 }
256
257 ClassLinker* cl = Runtime::Current()->GetClassLinker();
Andreas Gampe542451c2016-07-26 09:02:02 -0700258 PointerSize pointer_size = cl->GetImagePointerSize();
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100259 if (invoke->IsInvokeInterface()) {
260 resolved_method = info.GetTypeHandle()->FindVirtualMethodForInterface(
261 resolved_method, pointer_size);
262 } else {
263 DCHECK(invoke->IsInvokeVirtual());
264 resolved_method = info.GetTypeHandle()->FindVirtualMethodForVirtual(
265 resolved_method, pointer_size);
266 }
267
268 if (resolved_method == nullptr) {
269 // The information we had on the receiver was not enough to find
270 // the target method. Since we check above the exact type of the receiver,
271 // the only reason this can happen is an IncompatibleClassChangeError.
272 return nullptr;
Alex Light9139e002015-10-09 15:59:48 -0700273 } else if (!resolved_method->IsInvokable()) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100274 // The information we had on the receiver was not enough to find
275 // the target method. Since we check above the exact type of the receiver,
276 // the only reason this can happen is an IncompatibleClassChangeError.
277 return nullptr;
278 } else if (IsMethodOrDeclaringClassFinal(resolved_method)) {
279 // A final method has to be the target method.
280 return resolved_method;
281 } else if (info.IsExact()) {
282 // If we found a method and the receiver's concrete type is statically
283 // known, we know for sure the target.
284 return resolved_method;
285 } else {
286 // Even if we did find a method, the receiver type was not enough to
287 // statically find the runtime target.
288 return nullptr;
289 }
290}
291
292static uint32_t FindMethodIndexIn(ArtMethod* method,
293 const DexFile& dex_file,
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +0000294 uint32_t name_and_signature_index)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700295 REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100296 if (IsSameDexFile(*method->GetDexFile(), dex_file)) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100297 return method->GetDexMethodIndex();
298 } else {
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +0000299 return method->FindDexMethodIndexInOtherDexFile(dex_file, name_and_signature_index);
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100300 }
301}
302
Vladimir Marko423bebb2019-03-26 15:17:21 +0000303static dex::TypeIndex FindClassIndexIn(ObjPtr<mirror::Class> cls,
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000304 const DexCompilationUnit& compilation_unit)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700305 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000306 const DexFile& dex_file = *compilation_unit.GetDexFile();
Andreas Gampea5b09a62016-11-17 15:21:22 -0800307 dex::TypeIndex index;
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100308 if (cls->GetDexCache() == nullptr) {
David Sehr709b0702016-10-13 09:12:37 -0700309 DCHECK(cls->IsArrayClass()) << cls->PrettyClass();
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000310 index = cls->FindTypeIndexInOtherDexFile(dex_file);
Andreas Gampea5b09a62016-11-17 15:21:22 -0800311 } else if (!cls->GetDexTypeIndex().IsValid()) {
David Sehr709b0702016-10-13 09:12:37 -0700312 DCHECK(cls->IsProxyClass()) << cls->PrettyClass();
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100313 // TODO: deal with proxy classes.
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100314 } else if (IsSameDexFile(cls->GetDexFile(), dex_file)) {
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000315 DCHECK_EQ(cls->GetDexCache(), compilation_unit.GetDexCache().Get());
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000316 index = cls->GetDexTypeIndex();
Nicolas Geoffray491617a2016-07-19 17:06:23 +0100317 } else {
318 index = cls->FindTypeIndexInOtherDexFile(dex_file);
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000319 // We cannot guarantee the entry will resolve to the same class,
Nicolas Geoffray491617a2016-07-19 17:06:23 +0100320 // as there may be different class loaders. So only return the index if it's
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000321 // the right class already resolved with the class loader.
322 if (index.IsValid()) {
Vladimir Marko666ee3d2017-12-11 18:37:36 +0000323 ObjPtr<mirror::Class> resolved = compilation_unit.GetClassLinker()->LookupResolvedType(
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000324 index, compilation_unit.GetDexCache().Get(), compilation_unit.GetClassLoader().Get());
325 if (resolved != cls) {
326 index = dex::TypeIndex::Invalid();
327 }
Nicolas Geoffray491617a2016-07-19 17:06:23 +0100328 }
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100329 }
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000330
331 return index;
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100332}
333
Calin Juravle13439f02017-02-21 01:17:21 -0800334HInliner::InlineCacheType HInliner::GetInlineCacheType(
Vladimir Markoe9fb3dc2021-03-10 12:17:53 +0000335 const StackHandleScope<InlineCache::kIndividualCacheSize>& classes) {
336 DCHECK_EQ(classes.NumberOfReferences(), InlineCache::kIndividualCacheSize);
337 uint8_t number_of_types = InlineCache::kIndividualCacheSize - classes.RemainingSlots();
Calin Juravle13439f02017-02-21 01:17:21 -0800338 if (number_of_types == 0) {
339 return kInlineCacheUninitialized;
340 } else if (number_of_types == 1) {
341 return kInlineCacheMonomorphic;
342 } else if (number_of_types == InlineCache::kIndividualCacheSize) {
343 return kInlineCacheMegamorphic;
344 } else {
345 return kInlineCachePolymorphic;
346 }
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000347}
348
Vladimir Markoe9fb3dc2021-03-10 12:17:53 +0000349static inline ObjPtr<mirror::Class> GetMonomorphicType(
350 const StackHandleScope<InlineCache::kIndividualCacheSize>& classes)
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000351 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markoe9fb3dc2021-03-10 12:17:53 +0000352 DCHECK(classes.GetReference(0) != nullptr);
353 return classes.GetReference(0)->AsClass();
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000354}
355
Nicolas Geoffraye1e0e0f2021-04-29 08:57:13 +0000356ArtMethod* HInliner::FindMethodFromCHA(ArtMethod* resolved_method) {
Mingyao Yang063fc772016-08-02 11:02:54 -0700357 if (!resolved_method->HasSingleImplementation()) {
358 return nullptr;
359 }
360 if (Runtime::Current()->IsAotCompiler()) {
361 // No CHA-based devirtulization for AOT compiler (yet).
362 return nullptr;
363 }
Nicolas Geoffray141b63c2019-02-27 14:28:46 +0000364 if (Runtime::Current()->IsZygote()) {
365 // No CHA-based devirtulization for Zygote, as it compiles with
366 // offline information.
367 return nullptr;
368 }
Mingyao Yang063fc772016-08-02 11:02:54 -0700369 if (outermost_graph_->IsCompilingOsr()) {
370 // We do not support HDeoptimize in OSR methods.
371 return nullptr;
372 }
Mingyao Yange8fcd012017-01-20 10:43:30 -0800373 PointerSize pointer_size = caller_compilation_unit_.GetClassLinker()->GetImagePointerSize();
Nicolas Geoffray18ea1c92017-03-27 08:00:18 +0000374 ArtMethod* single_impl = resolved_method->GetSingleImplementation(pointer_size);
375 if (single_impl == nullptr) {
376 return nullptr;
377 }
378 if (single_impl->IsProxyMethod()) {
379 // Proxy method is a generic invoker that's not worth
380 // devirtualizing/inlining. It also causes issues when the proxy
381 // method is in another dex file if we try to rewrite invoke-interface to
382 // invoke-virtual because a proxy method doesn't have a real dex file.
383 return nullptr;
384 }
Nicolas Geoffray8e33e842017-04-03 16:55:16 +0100385 if (!single_impl->GetDeclaringClass()->IsResolved()) {
386 // There's a race with the class loading, which updates the CHA info
387 // before setting the class to resolved. So we just bail for this
388 // rare occurence.
389 return nullptr;
390 }
Nicolas Geoffray18ea1c92017-03-27 08:00:18 +0000391 return single_impl;
Mingyao Yang063fc772016-08-02 11:02:54 -0700392}
393
Nicolas Geoffraycf74ae72021-07-15 10:37:28 +0100394static bool IsMethodVerified(ArtMethod* method)
David Sehr0225f8e2018-01-31 08:52:24 +0000395 REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffraycf74ae72021-07-15 10:37:28 +0100396 if (method->GetDeclaringClass()->IsVerified()) {
397 return true;
398 }
399 // For AOT, we check if the class has a verification status that allows us to
400 // inline / analyze.
401 // At runtime, we know this is cold code if the class is not verified, so don't
402 // bother analyzing.
403 if (Runtime::Current()->IsAotCompiler()) {
404 if (method->GetDeclaringClass()->IsVerifiedNeedsAccessChecks() ||
405 method->GetDeclaringClass()->ShouldVerifyAtRuntime()) {
Nicolas Geoffray5da05072021-06-18 15:51:12 +0100406 return true;
407 }
Aart Bik2c148f02018-02-02 14:30:35 -0800408 }
409 return false;
410}
411
Nicolas Geoffraycf74ae72021-07-15 10:37:28 +0100412static bool AlwaysThrows(ArtMethod* method)
Aart Bik2c148f02018-02-02 14:30:35 -0800413 REQUIRES_SHARED(Locks::mutator_lock_) {
414 DCHECK(method != nullptr);
415 // Skip non-compilable and unverified methods.
Nicolas Geoffraycf74ae72021-07-15 10:37:28 +0100416 if (!method->IsCompilable() || !IsMethodVerified(method)) {
Aart Bik2c148f02018-02-02 14:30:35 -0800417 return false;
418 }
Aart Bika8b8e9b2018-01-09 11:01:02 -0800419 // Skip native methods, methods with try blocks, and methods that are too large.
Aart Bik2c148f02018-02-02 14:30:35 -0800420 CodeItemDataAccessor accessor(method->DexInstructionData());
Aart Bika8b8e9b2018-01-09 11:01:02 -0800421 if (!accessor.HasCodeItem() ||
422 accessor.TriesSize() != 0 ||
423 accessor.InsnsSizeInCodeUnits() > kMaximumNumberOfTotalInstructions) {
424 return false;
425 }
426 // Scan for exits.
427 bool throw_seen = false;
428 for (const DexInstructionPcPair& pair : accessor) {
429 switch (pair.Inst().Opcode()) {
430 case Instruction::RETURN:
431 case Instruction::RETURN_VOID:
432 case Instruction::RETURN_WIDE:
433 case Instruction::RETURN_OBJECT:
Aart Bika8b8e9b2018-01-09 11:01:02 -0800434 return false; // found regular control flow back
435 case Instruction::THROW:
436 throw_seen = true;
437 break;
438 default:
439 break;
440 }
441 }
442 return throw_seen;
443}
444
Santiago Aboy Solanes8ed39492022-07-20 11:13:39 +0100445bool HInliner::TryInline(HInvoke* invoke_instruction) {
Mathieu Chartier8284e9a2020-05-15 17:14:33 -0700446 MaybeRecordStat(stats_, MethodCompilationStat::kTryInline);
447
448 // Don't bother to move further if we know the method is unresolved or the invocation is
449 // polymorphic (invoke-{polymorphic,custom}).
450 if (invoke_instruction->IsInvokeUnresolved()) {
451 MaybeRecordStat(stats_, MethodCompilationStat::kNotInlinedUnresolved);
452 return false;
453 } else if (invoke_instruction->IsInvokePolymorphic()) {
454 MaybeRecordStat(stats_, MethodCompilationStat::kNotInlinedPolymorphic);
455 return false;
456 } else if (invoke_instruction->IsInvokeCustom()) {
457 MaybeRecordStat(stats_, MethodCompilationStat::kNotInlinedCustom);
458 return false;
Calin Juravle175dc732015-08-25 15:42:32 +0100459 }
460
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000461 ScopedObjectAccess soa(Thread::Current());
Nicolas Geoffraye6c0f2a2020-09-07 08:30:52 +0100462 LOG_TRY() << invoke_instruction->GetMethodReference().PrettyMethod();
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000463
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +0100464 ArtMethod* resolved_method = invoke_instruction->GetResolvedMethod();
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +0100465 if (resolved_method == nullptr) {
466 DCHECK(invoke_instruction->IsInvokeStaticOrDirect());
467 DCHECK(invoke_instruction->AsInvokeStaticOrDirect()->IsStringInit());
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000468 LOG_FAIL_NO_STAT() << "Not inlining a String.<init> method";
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +0100469 return false;
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000470 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000471
Nicolas Geoffraye1e0e0f2021-04-29 08:57:13 +0000472 ArtMethod* actual_method = invoke_instruction->IsInvokeStaticOrDirect()
473 ? invoke_instruction->GetResolvedMethod()
474 : FindVirtualOrInterfaceTarget(invoke_instruction);
Eric Holk1868de92020-02-12 09:10:21 -0800475
Nicolas Geoffraye1e0e0f2021-04-29 08:57:13 +0000476 if (actual_method != nullptr) {
477 // Single target.
478 bool result = TryInlineAndReplace(invoke_instruction,
479 actual_method,
480 ReferenceTypeInfo::CreateInvalid(),
481 /* do_rtp= */ true);
482 if (result) {
483 MaybeRecordStat(stats_, MethodCompilationStat::kInlinedInvokeVirtualOrInterface);
Santiago Aboy Solanes15580482021-10-12 13:11:29 +0100484 if (outermost_graph_ == graph_) {
485 MaybeRecordStat(stats_, MethodCompilationStat::kInlinedLastInvokeVirtualOrInterface);
486 }
Nicolas Geoffraye1e0e0f2021-04-29 08:57:13 +0000487 } else {
488 HInvoke* invoke_to_analyze = nullptr;
489 if (TryDevirtualize(invoke_instruction, actual_method, &invoke_to_analyze)) {
490 // Consider devirtualization as inlining.
491 result = true;
492 MaybeRecordStat(stats_, MethodCompilationStat::kDevirtualized);
Eric Holk1868de92020-02-12 09:10:21 -0800493 } else {
Nicolas Geoffraye1e0e0f2021-04-29 08:57:13 +0000494 invoke_to_analyze = invoke_instruction;
495 }
Santiago Aboy Solanes8ed39492022-07-20 11:13:39 +0100496 // Set always throws property for non-inlined method call with single target.
Nicolas Geoffraycf74ae72021-07-15 10:37:28 +0100497 if (AlwaysThrows(actual_method)) {
Santiago Aboy Solanes8ed39492022-07-20 11:13:39 +0100498 invoke_to_analyze->SetAlwaysThrows(/* always_throws= */ true);
499 graph_->SetHasAlwaysThrowingInvokes(/* value= */ true);
Mingyao Yang063fc772016-08-02 11:02:54 -0700500 }
Calin Juravle69158982016-03-16 11:53:41 +0000501 }
Nicolas Geoffraye1e0e0f2021-04-29 08:57:13 +0000502 return result;
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100503 }
Nicolas Geoffraye1e0e0f2021-04-29 08:57:13 +0000504
505 DCHECK(!invoke_instruction->IsInvokeStaticOrDirect());
506
507 if (TryInlineFromCHA(invoke_instruction)) {
508 return true;
509 }
510 return TryInlineFromInlineCache(invoke_instruction);
511}
512
513bool HInliner::TryInlineFromCHA(HInvoke* invoke_instruction) {
514 ArtMethod* method = FindMethodFromCHA(invoke_instruction->GetResolvedMethod());
515 if (method == nullptr) {
516 return false;
517 }
518 LOG_NOTE() << "Try CHA-based inlining of " << method->PrettyMethod();
519
520 uint32_t dex_pc = invoke_instruction->GetDexPc();
521 HInstruction* cursor = invoke_instruction->GetPrevious();
522 HBasicBlock* bb_cursor = invoke_instruction->GetBlock();
523 if (!TryInlineAndReplace(invoke_instruction,
524 method,
525 ReferenceTypeInfo::CreateInvalid(),
526 /* do_rtp= */ true)) {
527 return false;
528 }
529 AddCHAGuard(invoke_instruction, dex_pc, cursor, bb_cursor);
530 // Add dependency due to devirtualization: we are assuming the resolved method
531 // has a single implementation.
532 outermost_graph_->AddCHASingleImplementationDependency(invoke_instruction->GetResolvedMethod());
533 MaybeRecordStat(stats_, MethodCompilationStat::kCHAInline);
534 return true;
Calin Juravle13439f02017-02-21 01:17:21 -0800535}
536
Calin Juravleaf44e6c2017-05-23 14:24:55 -0700537bool HInliner::UseOnlyPolymorphicInliningWithNoDeopt() {
538 // If we are compiling AOT or OSR, pretend the call using inline caches is polymorphic and
539 // do not generate a deopt.
540 //
541 // For AOT:
542 // Generating a deopt does not ensure that we will actually capture the new types;
543 // and the danger is that we could be stuck in a loop with "forever" deoptimizations.
544 // Take for example the following scenario:
545 // - we capture the inline cache in one run
546 // - the next run, we deoptimize because we miss a type check, but the method
547 // never becomes hot again
548 // In this case, the inline cache will not be updated in the profile and the AOT code
549 // will keep deoptimizing.
550 // Another scenario is if we use profile compilation for a process which is not allowed
551 // to JIT (e.g. system server). If we deoptimize we will run interpreted code for the
552 // rest of the lifetime.
553 // TODO(calin):
554 // This is a compromise because we will most likely never update the inline cache
555 // in the profile (unless there's another reason to deopt). So we might be stuck with
556 // a sub-optimal inline cache.
557 // We could be smarter when capturing inline caches to mitigate this.
558 // (e.g. by having different thresholds for new and old methods).
559 //
560 // For OSR:
561 // We may come from the interpreter and it may have seen different receiver types.
562 return Runtime::Current()->IsAotCompiler() || outermost_graph_->IsCompilingOsr();
563}
Nicolas Geoffraye6c0f2a2020-09-07 08:30:52 +0100564bool HInliner::TryInlineFromInlineCache(HInvoke* invoke_instruction)
Calin Juravle13439f02017-02-21 01:17:21 -0800565 REQUIRES_SHARED(Locks::mutator_lock_) {
Calin Juravlee2492d42017-03-20 11:42:13 -0700566 if (Runtime::Current()->IsAotCompiler() && !kUseAOTInlineCaches) {
567 return false;
568 }
569
Vladimir Markoe9fb3dc2021-03-10 12:17:53 +0000570 StackHandleScope<InlineCache::kIndividualCacheSize> classes(Thread::Current());
Nicolas Geoffrayde1b2a22019-02-27 09:10:57 +0000571 // The Zygote JIT compiles based on a profile, so we shouldn't use runtime inline caches
572 // for it.
573 InlineCacheType inline_cache_type =
574 (Runtime::Current()->IsAotCompiler() || Runtime::Current()->IsZygote())
Vladimir Markoe9fb3dc2021-03-10 12:17:53 +0000575 ? GetInlineCacheAOT(invoke_instruction, &classes)
576 : GetInlineCacheJIT(invoke_instruction, &classes);
Calin Juravle13439f02017-02-21 01:17:21 -0800577
578 switch (inline_cache_type) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000579 case kInlineCacheNoData: {
580 LOG_FAIL_NO_STAT()
Nicolas Geoffrayd2f13ba2019-06-04 16:48:58 +0100581 << "No inline cache information for call to "
Nicolas Geoffraye6c0f2a2020-09-07 08:30:52 +0100582 << invoke_instruction->GetMethodReference().PrettyMethod();
Calin Juravle13439f02017-02-21 01:17:21 -0800583 return false;
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000584 }
Calin Juravle13439f02017-02-21 01:17:21 -0800585
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000586 case kInlineCacheUninitialized: {
587 LOG_FAIL_NO_STAT()
588 << "Interface or virtual call to "
Nicolas Geoffraye6c0f2a2020-09-07 08:30:52 +0100589 << invoke_instruction->GetMethodReference().PrettyMethod()
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000590 << " is not hit and not inlined";
591 return false;
592 }
593
594 case kInlineCacheMonomorphic: {
Vladimir Markocd09e1f2017-11-24 15:02:40 +0000595 MaybeRecordStat(stats_, MethodCompilationStat::kMonomorphicCall);
Calin Juravleaf44e6c2017-05-23 14:24:55 -0700596 if (UseOnlyPolymorphicInliningWithNoDeopt()) {
Vladimir Markoe9fb3dc2021-03-10 12:17:53 +0000597 return TryInlinePolymorphicCall(invoke_instruction, classes);
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000598 } else {
Vladimir Markoe9fb3dc2021-03-10 12:17:53 +0000599 return TryInlineMonomorphicCall(invoke_instruction, classes);
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000600 }
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000601 }
Calin Juravle13439f02017-02-21 01:17:21 -0800602
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000603 case kInlineCachePolymorphic: {
Vladimir Markocd09e1f2017-11-24 15:02:40 +0000604 MaybeRecordStat(stats_, MethodCompilationStat::kPolymorphicCall);
Vladimir Markoe9fb3dc2021-03-10 12:17:53 +0000605 return TryInlinePolymorphicCall(invoke_instruction, classes);
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000606 }
Calin Juravle13439f02017-02-21 01:17:21 -0800607
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000608 case kInlineCacheMegamorphic: {
609 LOG_FAIL_NO_STAT()
610 << "Interface or virtual call to "
Nicolas Geoffraye6c0f2a2020-09-07 08:30:52 +0100611 << invoke_instruction->GetMethodReference().PrettyMethod()
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000612 << " is megamorphic and not inlined";
Vladimir Markocd09e1f2017-11-24 15:02:40 +0000613 MaybeRecordStat(stats_, MethodCompilationStat::kMegamorphicCall);
Calin Juravle13439f02017-02-21 01:17:21 -0800614 return false;
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000615 }
Calin Juravle13439f02017-02-21 01:17:21 -0800616
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000617 case kInlineCacheMissingTypes: {
618 LOG_FAIL_NO_STAT()
619 << "Interface or virtual call to "
Nicolas Geoffraye6c0f2a2020-09-07 08:30:52 +0100620 << invoke_instruction->GetMethodReference().PrettyMethod()
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000621 << " is missing types and not inlined";
Calin Juravle13439f02017-02-21 01:17:21 -0800622 return false;
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000623 }
Calin Juravle13439f02017-02-21 01:17:21 -0800624 }
625 UNREACHABLE();
626}
627
628HInliner::InlineCacheType HInliner::GetInlineCacheJIT(
629 HInvoke* invoke_instruction,
Vladimir Markoe9fb3dc2021-03-10 12:17:53 +0000630 /*out*/StackHandleScope<InlineCache::kIndividualCacheSize>* classes) {
Vladimir Marko695348f2020-05-19 14:42:02 +0100631 DCHECK(codegen_->GetCompilerOptions().IsJitCompiler());
Calin Juravle13439f02017-02-21 01:17:21 -0800632
633 ArtMethod* caller = graph_->GetArtMethod();
634 // Under JIT, we should always know the caller.
635 DCHECK(caller != nullptr);
Nicolas Geoffray9e598902021-11-19 14:53:07 +0000636 ProfilingInfo* profiling_info = graph_->GetProfilingInfo();
Calin Juravle13439f02017-02-21 01:17:21 -0800637 if (profiling_info == nullptr) {
638 return kInlineCacheNoData;
639 }
640
Vladimir Markoe9fb3dc2021-03-10 12:17:53 +0000641 Runtime::Current()->GetJit()->GetCodeCache()->CopyInlineCacheInto(
642 *profiling_info->GetInlineCache(invoke_instruction->GetDexPc()),
643 classes);
644 return GetInlineCacheType(*classes);
Calin Juravle13439f02017-02-21 01:17:21 -0800645}
646
647HInliner::InlineCacheType HInliner::GetInlineCacheAOT(
Calin Juravle13439f02017-02-21 01:17:21 -0800648 HInvoke* invoke_instruction,
Vladimir Markoe9fb3dc2021-03-10 12:17:53 +0000649 /*out*/StackHandleScope<InlineCache::kIndividualCacheSize>* classes) {
650 DCHECK_EQ(classes->NumberOfReferences(), InlineCache::kIndividualCacheSize);
651 DCHECK_EQ(classes->RemainingSlots(), InlineCache::kIndividualCacheSize);
652
Vladimir Marko1a2a5cd2018-11-07 15:39:48 +0000653 const ProfileCompilationInfo* pci = codegen_->GetCompilerOptions().GetProfileCompilationInfo();
Calin Juravle13439f02017-02-21 01:17:21 -0800654 if (pci == nullptr) {
655 return kInlineCacheNoData;
656 }
657
Vladimir Markoa64c1ad2021-03-08 14:27:05 +0000658 ProfileCompilationInfo::MethodHotness hotness = pci->GetMethodHotness(MethodReference(
659 caller_compilation_unit_.GetDexFile(), caller_compilation_unit_.GetDexMethodIndex()));
660 if (!hotness.IsHot()) {
Calin Juravle13439f02017-02-21 01:17:21 -0800661 return kInlineCacheNoData; // no profile information for this invocation.
662 }
663
Vladimir Markoa64c1ad2021-03-08 14:27:05 +0000664 const ProfileCompilationInfo::InlineCacheMap* inline_caches = hotness.GetInlineCacheMap();
665 DCHECK(inline_caches != nullptr);
666 const auto it = inline_caches->find(invoke_instruction->GetDexPc());
667 if (it == inline_caches->end()) {
Calin Juravle13439f02017-02-21 01:17:21 -0800668 return kInlineCacheUninitialized;
669 }
670
671 const ProfileCompilationInfo::DexPcData& dex_pc_data = it->second;
Calin Juravle13439f02017-02-21 01:17:21 -0800672 if (dex_pc_data.is_missing_types) {
673 return kInlineCacheMissingTypes;
674 }
675 if (dex_pc_data.is_megamorphic) {
676 return kInlineCacheMegamorphic;
677 }
Calin Juravle13439f02017-02-21 01:17:21 -0800678 DCHECK_LE(dex_pc_data.classes.size(), InlineCache::kIndividualCacheSize);
Vladimir Markoa64c1ad2021-03-08 14:27:05 +0000679
Vladimir Markoc63d9672021-03-31 15:50:39 +0100680 // Walk over the class descriptors and look up the actual classes.
681 // If we cannot find a type we return kInlineCacheMissingTypes.
682 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
683 for (const dex::TypeIndex& type_index : dex_pc_data.classes) {
684 const DexFile* dex_file = caller_compilation_unit_.GetDexFile();
685 const char* descriptor = pci->GetTypeDescriptor(dex_file, type_index);
686 ObjPtr<mirror::ClassLoader> class_loader = caller_compilation_unit_.GetClassLoader().Get();
687 ObjPtr<mirror::Class> clazz = class_linker->LookupResolvedType(descriptor, class_loader);
688 if (clazz == nullptr) {
689 VLOG(compiler) << "Could not find class from inline cache in AOT mode "
Nicolas Geoffraye6c0f2a2020-09-07 08:30:52 +0100690 << invoke_instruction->GetMethodReference().PrettyMethod()
691 << " : "
Vladimir Markoc63d9672021-03-31 15:50:39 +0100692 << descriptor;
Calin Juravle13439f02017-02-21 01:17:21 -0800693 return kInlineCacheMissingTypes;
694 }
Vladimir Markoc63d9672021-03-31 15:50:39 +0100695 DCHECK_NE(classes->RemainingSlots(), 0u);
696 classes->NewHandle(clazz);
Calin Juravle13439f02017-02-21 01:17:21 -0800697 }
Vladimir Markoa64c1ad2021-03-08 14:27:05 +0000698
Vladimir Markoe9fb3dc2021-03-10 12:17:53 +0000699 return GetInlineCacheType(*classes);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100700}
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000701
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000702HInstanceFieldGet* HInliner::BuildGetReceiverClass(ClassLinker* class_linker,
703 HInstruction* receiver,
704 uint32_t dex_pc) const {
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100705 ArtField* field = GetClassRoot<mirror::Object>(class_linker)->GetInstanceField(0);
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000706 DCHECK_EQ(std::string(field->GetName()), "shadow$_klass_");
Vladimir Markoca6fff82017-10-03 14:49:14 +0100707 HInstanceFieldGet* result = new (graph_->GetAllocator()) HInstanceFieldGet(
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000708 receiver,
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +0000709 field,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100710 DataType::Type::kReference,
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000711 field->GetOffset(),
712 field->IsVolatile(),
713 field->GetDexFieldIndex(),
714 field->GetDeclaringClass()->GetDexClassDefIndex(),
715 *field->GetDexFile(),
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000716 dex_pc);
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000717 // The class of a field is effectively final, and does not have any memory dependencies.
718 result->SetSideEffects(SideEffects::None());
719 return result;
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000720}
721
Nicolas Geoffray4c0b4bc2017-03-17 13:08:26 +0000722static ArtMethod* ResolveMethodFromInlineCache(Handle<mirror::Class> klass,
Nicolas Geoffraye6c0f2a2020-09-07 08:30:52 +0100723 HInvoke* invoke_instruction,
Nicolas Geoffray4c0b4bc2017-03-17 13:08:26 +0000724 PointerSize pointer_size)
725 REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffraye6c0f2a2020-09-07 08:30:52 +0100726 ArtMethod* resolved_method = invoke_instruction->GetResolvedMethod();
Nicolas Geoffray4c0b4bc2017-03-17 13:08:26 +0000727 if (Runtime::Current()->IsAotCompiler()) {
728 // We can get unrelated types when working with profiles (corruption,
729 // systme updates, or anyone can write to it). So first check if the class
730 // actually implements the declaring class of the method that is being
731 // called in bytecode.
732 // Note: the lookup methods used below require to have assignable types.
733 if (!resolved_method->GetDeclaringClass()->IsAssignableFrom(klass.Get())) {
734 return nullptr;
735 }
Nicolas Geoffray4fba66c2021-08-26 18:49:04 +0100736
737 // Also check whether the type in the inline cache is an interface or an
738 // abstract class. We only expect concrete classes in inline caches, so this
739 // means the class was changed.
740 if (klass->IsAbstract() || klass->IsInterface()) {
741 return nullptr;
742 }
Nicolas Geoffray4c0b4bc2017-03-17 13:08:26 +0000743 }
744
745 if (invoke_instruction->IsInvokeInterface()) {
746 resolved_method = klass->FindVirtualMethodForInterface(resolved_method, pointer_size);
747 } else {
748 DCHECK(invoke_instruction->IsInvokeVirtual());
749 resolved_method = klass->FindVirtualMethodForVirtual(resolved_method, pointer_size);
750 }
Alex Light2769f012021-03-23 11:58:58 -0700751 // Even if the class exists we can still not have the function the
752 // inline-cache targets if the profile is from far enough in the past/future.
753 // We need to allow this since we don't update boot-profiles very often. This
754 // can occur in boot-profiles with inline-caches.
755 DCHECK(Runtime::Current()->IsAotCompiler() || resolved_method != nullptr);
Nicolas Geoffray4c0b4bc2017-03-17 13:08:26 +0000756 return resolved_method;
757}
758
Vladimir Markoe9fb3dc2021-03-10 12:17:53 +0000759bool HInliner::TryInlineMonomorphicCall(
760 HInvoke* invoke_instruction,
761 const StackHandleScope<InlineCache::kIndividualCacheSize>& classes) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000762 DCHECK(invoke_instruction->IsInvokeVirtual() || invoke_instruction->IsInvokeInterface())
763 << invoke_instruction->DebugName();
764
Andreas Gampea5b09a62016-11-17 15:21:22 -0800765 dex::TypeIndex class_index = FindClassIndexIn(
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000766 GetMonomorphicType(classes), caller_compilation_unit_);
Andreas Gampea5b09a62016-11-17 15:21:22 -0800767 if (!class_index.IsValid()) {
Santiago Aboy Solanesfa73acc2021-11-12 14:23:27 +0000768 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedDexCacheInaccessibleToCaller)
Nicolas Geoffraye6c0f2a2020-09-07 08:30:52 +0100769 << "Call to " << ArtMethod::PrettyMethod(invoke_instruction->GetResolvedMethod())
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000770 << " from inline cache is not inlined because its class is not"
771 << " accessible to the caller";
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100772 return false;
773 }
774
775 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
Andreas Gampe542451c2016-07-26 09:02:02 -0700776 PointerSize pointer_size = class_linker->GetImagePointerSize();
Vladimir Marko02ca05a2020-05-12 13:58:51 +0100777 Handle<mirror::Class> monomorphic_type =
778 graph_->GetHandleCache()->NewHandle(GetMonomorphicType(classes));
Nicolas Geoffraye6c0f2a2020-09-07 08:30:52 +0100779 ArtMethod* resolved_method = ResolveMethodFromInlineCache(
780 monomorphic_type, invoke_instruction, pointer_size);
Nicolas Geoffray4c0b4bc2017-03-17 13:08:26 +0000781 if (resolved_method == nullptr) {
782 // Bogus AOT profile, bail.
783 DCHECK(Runtime::Current()->IsAotCompiler());
784 return false;
785 }
786
Vladimir Markoe9fb3dc2021-03-10 12:17:53 +0000787 LOG_NOTE() << "Try inline monomorphic call to " << resolved_method->PrettyMethod();
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100788 HInstruction* receiver = invoke_instruction->InputAt(0);
789 HInstruction* cursor = invoke_instruction->GetPrevious();
790 HBasicBlock* bb_cursor = invoke_instruction->GetBlock();
Mingyao Yang063fc772016-08-02 11:02:54 -0700791 if (!TryInlineAndReplace(invoke_instruction,
792 resolved_method,
Andreas Gampe3db70682018-12-26 15:12:03 -0800793 ReferenceTypeInfo::Create(monomorphic_type, /* is_exact= */ true),
Nicolas Geoffraye1e0e0f2021-04-29 08:57:13 +0000794 /* do_rtp= */ false)) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100795 return false;
796 }
797
798 // We successfully inlined, now add a guard.
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000799 AddTypeGuard(receiver,
800 cursor,
801 bb_cursor,
802 class_index,
Nicolas Geoffray5247c082017-01-13 14:17:29 +0000803 monomorphic_type,
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000804 invoke_instruction,
Andreas Gampe3db70682018-12-26 15:12:03 -0800805 /* with_deoptimization= */ true);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100806
807 // Run type propagation to get the guard typed, and eventually propagate the
808 // type of the receiver.
Vladimir Marko456307a2016-04-19 14:12:13 +0000809 ReferenceTypePropagation rtp_fixup(graph_,
810 outer_compilation_unit_.GetDexCache(),
Andreas Gampe3db70682018-12-26 15:12:03 -0800811 /* is_first_run= */ false);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100812 rtp_fixup.Run();
813
Vladimir Markocd09e1f2017-11-24 15:02:40 +0000814 MaybeRecordStat(stats_, MethodCompilationStat::kInlinedMonomorphicCall);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100815 return true;
816}
817
Mingyao Yang063fc772016-08-02 11:02:54 -0700818void HInliner::AddCHAGuard(HInstruction* invoke_instruction,
819 uint32_t dex_pc,
820 HInstruction* cursor,
821 HBasicBlock* bb_cursor) {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100822 HShouldDeoptimizeFlag* deopt_flag = new (graph_->GetAllocator())
823 HShouldDeoptimizeFlag(graph_->GetAllocator(), dex_pc);
Mythri Alle5097f832021-11-02 14:52:30 +0000824 // ShouldDeoptimizeFlag is used to perform a deoptimization because of a CHA
825 // invalidation or for debugging reasons. It is OK to just check for non-zero
826 // value here instead of the specific CHA value. When a debugging deopt is
827 // requested we deoptimize before we execute any code and hence we shouldn't
828 // see that case here.
Vladimir Markoca6fff82017-10-03 14:49:14 +0100829 HInstruction* compare = new (graph_->GetAllocator()) HNotEqual(
Mingyao Yang063fc772016-08-02 11:02:54 -0700830 deopt_flag, graph_->GetIntConstant(0, dex_pc));
Vladimir Markoca6fff82017-10-03 14:49:14 +0100831 HInstruction* deopt = new (graph_->GetAllocator()) HDeoptimize(
832 graph_->GetAllocator(), compare, DeoptimizationKind::kCHA, dex_pc);
Mingyao Yang063fc772016-08-02 11:02:54 -0700833
834 if (cursor != nullptr) {
835 bb_cursor->InsertInstructionAfter(deopt_flag, cursor);
836 } else {
837 bb_cursor->InsertInstructionBefore(deopt_flag, bb_cursor->GetFirstInstruction());
838 }
Mingyao Yangb0b051a2016-11-17 09:04:53 -0800839 bb_cursor->InsertInstructionAfter(compare, deopt_flag);
840 bb_cursor->InsertInstructionAfter(deopt, compare);
841
842 // Add receiver as input to aid CHA guard optimization later.
843 deopt_flag->AddInput(invoke_instruction->InputAt(0));
844 DCHECK_EQ(deopt_flag->InputCount(), 1u);
Mingyao Yang063fc772016-08-02 11:02:54 -0700845 deopt->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
Mingyao Yangb0b051a2016-11-17 09:04:53 -0800846 outermost_graph_->IncrementNumberOfCHAGuards();
Mingyao Yang063fc772016-08-02 11:02:54 -0700847}
848
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000849HInstruction* HInliner::AddTypeGuard(HInstruction* receiver,
850 HInstruction* cursor,
851 HBasicBlock* bb_cursor,
Andreas Gampea5b09a62016-11-17 15:21:22 -0800852 dex::TypeIndex class_index,
Nicolas Geoffray5247c082017-01-13 14:17:29 +0000853 Handle<mirror::Class> klass,
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000854 HInstruction* invoke_instruction,
855 bool with_deoptimization) {
856 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
857 HInstanceFieldGet* receiver_class = BuildGetReceiverClass(
858 class_linker, receiver, invoke_instruction->GetDexPc());
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000859 if (cursor != nullptr) {
860 bb_cursor->InsertInstructionAfter(receiver_class, cursor);
861 } else {
862 bb_cursor->InsertInstructionBefore(receiver_class, bb_cursor->GetFirstInstruction());
863 }
Nicolas Geoffray56876342016-12-16 16:09:08 +0000864
865 const DexFile& caller_dex_file = *caller_compilation_unit_.GetDexFile();
Calin Juravle07f01df2017-04-28 19:58:01 -0700866 bool is_referrer;
867 ArtMethod* outermost_art_method = outermost_graph_->GetArtMethod();
868 if (outermost_art_method == nullptr) {
869 DCHECK(Runtime::Current()->IsAotCompiler());
870 // We are in AOT mode and we don't have an ART method to determine
871 // if the inlined method belongs to the referrer. Assume it doesn't.
872 is_referrer = false;
873 } else {
874 is_referrer = klass.Get() == outermost_art_method->GetDeclaringClass();
875 }
876
Nicolas Geoffray56876342016-12-16 16:09:08 +0000877 // Note that we will just compare the classes, so we don't need Java semantics access checks.
878 // Note that the type index and the dex file are relative to the method this type guard is
879 // inlined into.
Vladimir Markoca6fff82017-10-03 14:49:14 +0100880 HLoadClass* load_class = new (graph_->GetAllocator()) HLoadClass(graph_->GetCurrentMethod(),
881 class_index,
882 caller_dex_file,
883 klass,
884 is_referrer,
885 invoke_instruction->GetDexPc(),
Andreas Gampe3db70682018-12-26 15:12:03 -0800886 /* needs_access_check= */ false);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +0000887 HLoadClass::LoadKind kind = HSharpening::ComputeLoadClassKind(
Vladimir Markobb089b62018-06-28 17:30:16 +0100888 load_class, codegen_, caller_compilation_unit_);
Nicolas Geoffray83c8e272017-01-31 14:36:37 +0000889 DCHECK(kind != HLoadClass::LoadKind::kInvalid)
890 << "We should always be able to reference a class for inline caches";
Vladimir Marko28e012a2017-12-07 11:22:59 +0000891 // Load kind must be set before inserting the instruction into the graph.
Nicolas Geoffray83c8e272017-01-31 14:36:37 +0000892 load_class->SetLoadKind(kind);
Vladimir Marko28e012a2017-12-07 11:22:59 +0000893 bb_cursor->InsertInstructionAfter(load_class, receiver_class);
Calin Juravle13439f02017-02-21 01:17:21 -0800894 // In AOT mode, we will most likely load the class from BSS, which will involve a call
895 // to the runtime. In this case, the load instruction will need an environment so copy
896 // it from the invoke instruction.
897 if (load_class->NeedsEnvironment()) {
898 DCHECK(Runtime::Current()->IsAotCompiler());
899 load_class->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
900 }
Nicolas Geoffray56876342016-12-16 16:09:08 +0000901
Vladimir Markoca6fff82017-10-03 14:49:14 +0100902 HNotEqual* compare = new (graph_->GetAllocator()) HNotEqual(load_class, receiver_class);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000903 bb_cursor->InsertInstructionAfter(compare, load_class);
904 if (with_deoptimization) {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100905 HDeoptimize* deoptimize = new (graph_->GetAllocator()) HDeoptimize(
906 graph_->GetAllocator(),
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +0000907 compare,
908 receiver,
Nicolas Geoffray4e92c3c2017-05-08 09:34:26 +0100909 Runtime::Current()->IsAotCompiler()
910 ? DeoptimizationKind::kAotInlineCache
911 : DeoptimizationKind::kJitInlineCache,
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +0000912 invoke_instruction->GetDexPc());
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000913 bb_cursor->InsertInstructionAfter(deoptimize, compare);
914 deoptimize->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +0000915 DCHECK_EQ(invoke_instruction->InputAt(0), receiver);
916 receiver->ReplaceUsesDominatedBy(deoptimize, deoptimize);
917 deoptimize->SetReferenceTypeInfo(receiver->GetReferenceTypeInfo());
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000918 }
919 return compare;
920}
921
Nicolas Geoffrayb8958022021-04-15 15:12:31 +0100922static void MaybeReplaceAndRemove(HInstruction* new_instruction, HInstruction* old_instruction) {
923 DCHECK(new_instruction != old_instruction);
924 if (new_instruction != nullptr) {
925 old_instruction->ReplaceWith(new_instruction);
926 }
927 old_instruction->GetBlock()->RemoveInstruction(old_instruction);
928}
929
Vladimir Markoe9fb3dc2021-03-10 12:17:53 +0000930bool HInliner::TryInlinePolymorphicCall(
931 HInvoke* invoke_instruction,
932 const StackHandleScope<InlineCache::kIndividualCacheSize>& classes) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000933 DCHECK(invoke_instruction->IsInvokeVirtual() || invoke_instruction->IsInvokeInterface())
934 << invoke_instruction->DebugName();
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000935
Nicolas Geoffraye6c0f2a2020-09-07 08:30:52 +0100936 if (TryInlinePolymorphicCallToSameTarget(invoke_instruction, classes)) {
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000937 return true;
938 }
939
940 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
Andreas Gampe542451c2016-07-26 09:02:02 -0700941 PointerSize pointer_size = class_linker->GetImagePointerSize();
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000942
943 bool all_targets_inlined = true;
944 bool one_target_inlined = false;
Vladimir Markoe9fb3dc2021-03-10 12:17:53 +0000945 DCHECK_EQ(classes.NumberOfReferences(), InlineCache::kIndividualCacheSize);
946 uint8_t number_of_types = InlineCache::kIndividualCacheSize - classes.RemainingSlots();
947 for (size_t i = 0; i != number_of_types; ++i) {
948 DCHECK(classes.GetReference(i) != nullptr);
949 Handle<mirror::Class> handle =
950 graph_->GetHandleCache()->NewHandle(classes.GetReference(i)->AsClass());
951 ArtMethod* method = ResolveMethodFromInlineCache(handle, invoke_instruction, pointer_size);
Nicolas Geoffray4c0b4bc2017-03-17 13:08:26 +0000952 if (method == nullptr) {
953 DCHECK(Runtime::Current()->IsAotCompiler());
954 // AOT profile is bogus. This loop expects to iterate over all entries,
955 // so just just continue.
956 all_targets_inlined = false;
957 continue;
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000958 }
959
960 HInstruction* receiver = invoke_instruction->InputAt(0);
961 HInstruction* cursor = invoke_instruction->GetPrevious();
962 HBasicBlock* bb_cursor = invoke_instruction->GetBlock();
963
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000964 dex::TypeIndex class_index = FindClassIndexIn(handle.Get(), caller_compilation_unit_);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000965 HInstruction* return_replacement = nullptr;
Santiago Aboy Solanes4f5b7cb2022-02-10 10:25:15 +0000966
Santiago Aboy Solanesac875152022-02-16 11:13:42 +0000967 // In monomorphic cases when UseOnlyPolymorphicInliningWithNoDeopt() is true, we call
968 // `TryInlinePolymorphicCall` even though we are monomorphic.
969 const bool actually_monomorphic = number_of_types == 1;
Santiago Aboy Solanes872ec722022-02-18 14:10:25 +0000970 DCHECK_IMPLIES(actually_monomorphic, UseOnlyPolymorphicInliningWithNoDeopt());
Santiago Aboy Solanesac875152022-02-16 11:13:42 +0000971
972 // We only want to limit recursive polymorphic cases, not monomorphic ones.
Santiago Aboy Solanes4f5b7cb2022-02-10 10:25:15 +0000973 const bool too_many_polymorphic_recursive_calls =
Santiago Aboy Solanesac875152022-02-16 11:13:42 +0000974 !actually_monomorphic &&
Santiago Aboy Solanes4f5b7cb2022-02-10 10:25:15 +0000975 CountRecursiveCallsOf(method) > kMaximumNumberOfPolymorphicRecursiveCalls;
976 if (too_many_polymorphic_recursive_calls) {
977 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedPolymorphicRecursiveBudget)
978 << "Method " << method->PrettyMethod()
979 << " is not inlined because it has reached its polymorphic recursive call budget.";
980 } else if (class_index.IsValid()) {
981 LOG_NOTE() << "Try inline polymorphic call to " << method->PrettyMethod();
982 }
983
984 if (too_many_polymorphic_recursive_calls ||
985 !class_index.IsValid() ||
Nicolas Geoffray0f001b72017-01-04 16:46:23 +0000986 !TryBuildAndInline(invoke_instruction,
987 method,
Andreas Gampe3db70682018-12-26 15:12:03 -0800988 ReferenceTypeInfo::Create(handle, /* is_exact= */ true),
Nicolas Geoffray0f001b72017-01-04 16:46:23 +0000989 &return_replacement)) {
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000990 all_targets_inlined = false;
991 } else {
992 one_target_inlined = true;
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000993
Nicolas Geoffraye6c0f2a2020-09-07 08:30:52 +0100994 LOG_SUCCESS() << "Polymorphic call to "
995 << invoke_instruction->GetMethodReference().PrettyMethod()
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000996 << " has inlined " << ArtMethod::PrettyMethod(method);
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +0000997
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000998 // If we have inlined all targets before, and this receiver is the last seen,
999 // we deoptimize instead of keeping the original invoke instruction.
Calin Juravleaf44e6c2017-05-23 14:24:55 -07001000 bool deoptimize = !UseOnlyPolymorphicInliningWithNoDeopt() &&
1001 all_targets_inlined &&
Vladimir Markoe9fb3dc2021-03-10 12:17:53 +00001002 (i + 1 == number_of_types);
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01001003
Nicolas Geoffray56876342016-12-16 16:09:08 +00001004 HInstruction* compare = AddTypeGuard(receiver,
1005 cursor,
1006 bb_cursor,
1007 class_index,
Nicolas Geoffray5247c082017-01-13 14:17:29 +00001008 handle,
Nicolas Geoffray56876342016-12-16 16:09:08 +00001009 invoke_instruction,
1010 deoptimize);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001011 if (deoptimize) {
Nicolas Geoffrayb8958022021-04-15 15:12:31 +01001012 MaybeReplaceAndRemove(return_replacement, invoke_instruction);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001013 } else {
1014 CreateDiamondPatternForPolymorphicInline(compare, return_replacement, invoke_instruction);
1015 }
1016 }
1017 }
1018
1019 if (!one_target_inlined) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001020 LOG_FAIL_NO_STAT()
Nicolas Geoffraye6c0f2a2020-09-07 08:30:52 +01001021 << "Call to " << invoke_instruction->GetMethodReference().PrettyMethod()
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001022 << " from inline cache is not inlined because none"
1023 << " of its targets could be inlined";
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001024 return false;
1025 }
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00001026
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001027 MaybeRecordStat(stats_, MethodCompilationStat::kInlinedPolymorphicCall);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001028
1029 // Run type propagation to get the guards typed.
Vladimir Marko456307a2016-04-19 14:12:13 +00001030 ReferenceTypePropagation rtp_fixup(graph_,
1031 outer_compilation_unit_.GetDexCache(),
Andreas Gampe3db70682018-12-26 15:12:03 -08001032 /* is_first_run= */ false);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001033 rtp_fixup.Run();
1034 return true;
1035}
1036
1037void HInliner::CreateDiamondPatternForPolymorphicInline(HInstruction* compare,
1038 HInstruction* return_replacement,
1039 HInstruction* invoke_instruction) {
1040 uint32_t dex_pc = invoke_instruction->GetDexPc();
1041 HBasicBlock* cursor_block = compare->GetBlock();
1042 HBasicBlock* original_invoke_block = invoke_instruction->GetBlock();
Vladimir Markoca6fff82017-10-03 14:49:14 +01001043 ArenaAllocator* allocator = graph_->GetAllocator();
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001044
1045 // Spit the block after the compare: `cursor_block` will now be the start of the diamond,
1046 // and the returned block is the start of the then branch (that could contain multiple blocks).
1047 HBasicBlock* then = cursor_block->SplitAfterForInlining(compare);
1048
1049 // Split the block containing the invoke before and after the invoke. The returned block
1050 // of the split before will contain the invoke and will be the otherwise branch of
1051 // the diamond. The returned block of the split after will be the merge block
1052 // of the diamond.
1053 HBasicBlock* end_then = invoke_instruction->GetBlock();
1054 HBasicBlock* otherwise = end_then->SplitBeforeForInlining(invoke_instruction);
1055 HBasicBlock* merge = otherwise->SplitAfterForInlining(invoke_instruction);
1056
1057 // If the methods we are inlining return a value, we create a phi in the merge block
1058 // that will have the `invoke_instruction and the `return_replacement` as inputs.
1059 if (return_replacement != nullptr) {
1060 HPhi* phi = new (allocator) HPhi(
1061 allocator, kNoRegNumber, 0, HPhi::ToPhiType(invoke_instruction->GetType()), dex_pc);
1062 merge->AddPhi(phi);
1063 invoke_instruction->ReplaceWith(phi);
1064 phi->AddInput(return_replacement);
1065 phi->AddInput(invoke_instruction);
1066 }
1067
1068 // Add the control flow instructions.
1069 otherwise->AddInstruction(new (allocator) HGoto(dex_pc));
1070 end_then->AddInstruction(new (allocator) HGoto(dex_pc));
1071 cursor_block->AddInstruction(new (allocator) HIf(compare, dex_pc));
1072
1073 // Add the newly created blocks to the graph.
1074 graph_->AddBlock(then);
1075 graph_->AddBlock(otherwise);
1076 graph_->AddBlock(merge);
1077
1078 // Set up successor (and implictly predecessor) relations.
1079 cursor_block->AddSuccessor(otherwise);
1080 cursor_block->AddSuccessor(then);
1081 end_then->AddSuccessor(merge);
1082 otherwise->AddSuccessor(merge);
1083
1084 // Set up dominance information.
1085 then->SetDominator(cursor_block);
1086 cursor_block->AddDominatedBlock(then);
1087 otherwise->SetDominator(cursor_block);
1088 cursor_block->AddDominatedBlock(otherwise);
1089 merge->SetDominator(cursor_block);
1090 cursor_block->AddDominatedBlock(merge);
1091
1092 // Update the revert post order.
1093 size_t index = IndexOfElement(graph_->reverse_post_order_, cursor_block);
1094 MakeRoomFor(&graph_->reverse_post_order_, 1, index);
1095 graph_->reverse_post_order_[++index] = then;
1096 index = IndexOfElement(graph_->reverse_post_order_, end_then);
1097 MakeRoomFor(&graph_->reverse_post_order_, 2, index);
1098 graph_->reverse_post_order_[++index] = otherwise;
1099 graph_->reverse_post_order_[++index] = merge;
1100
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001101
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00001102 graph_->UpdateLoopAndTryInformationOfNewBlock(
Andreas Gampe3db70682018-12-26 15:12:03 -08001103 then, original_invoke_block, /* replace_if_back_edge= */ false);
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00001104 graph_->UpdateLoopAndTryInformationOfNewBlock(
Andreas Gampe3db70682018-12-26 15:12:03 -08001105 otherwise, original_invoke_block, /* replace_if_back_edge= */ false);
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00001106
1107 // In case the original invoke location was a back edge, we need to update
1108 // the loop to now have the merge block as a back edge.
1109 graph_->UpdateLoopAndTryInformationOfNewBlock(
Andreas Gampe3db70682018-12-26 15:12:03 -08001110 merge, original_invoke_block, /* replace_if_back_edge= */ true);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001111}
1112
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +00001113bool HInliner::TryInlinePolymorphicCallToSameTarget(
1114 HInvoke* invoke_instruction,
Vladimir Markoe9fb3dc2021-03-10 12:17:53 +00001115 const StackHandleScope<InlineCache::kIndividualCacheSize>& classes) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001116 // This optimization only works under JIT for now.
Vladimir Marko695348f2020-05-19 14:42:02 +01001117 if (!codegen_->GetCompilerOptions().IsJitCompiler()) {
Calin Juravle13439f02017-02-21 01:17:21 -08001118 return false;
1119 }
1120
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001121 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
Andreas Gampe542451c2016-07-26 09:02:02 -07001122 PointerSize pointer_size = class_linker->GetImagePointerSize();
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001123
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001124 ArtMethod* actual_method = nullptr;
Nicolas Geoffray4f97a212016-02-25 16:17:54 +00001125 size_t method_index = invoke_instruction->IsInvokeVirtual()
1126 ? invoke_instruction->AsInvokeVirtual()->GetVTableIndex()
1127 : invoke_instruction->AsInvokeInterface()->GetImtIndex();
1128
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001129 // Check whether we are actually calling the same method among
1130 // the different types seen.
Vladimir Markoe9fb3dc2021-03-10 12:17:53 +00001131 DCHECK_EQ(classes.NumberOfReferences(), InlineCache::kIndividualCacheSize);
1132 uint8_t number_of_types = InlineCache::kIndividualCacheSize - classes.RemainingSlots();
1133 for (size_t i = 0; i != number_of_types; ++i) {
1134 DCHECK(classes.GetReference(i) != nullptr);
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001135 ArtMethod* new_method = nullptr;
1136 if (invoke_instruction->IsInvokeInterface()) {
Vladimir Markoe9fb3dc2021-03-10 12:17:53 +00001137 new_method = classes.GetReference(i)->AsClass()->GetImt(pointer_size)->Get(
Matthew Gharrity465ecc82016-07-19 21:32:52 +00001138 method_index, pointer_size);
Nicolas Geoffray4f97a212016-02-25 16:17:54 +00001139 if (new_method->IsRuntimeMethod()) {
1140 // Bail out as soon as we see a conflict trampoline in one of the target's
1141 // interface table.
1142 return false;
1143 }
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001144 } else {
1145 DCHECK(invoke_instruction->IsInvokeVirtual());
Vladimir Markoe9fb3dc2021-03-10 12:17:53 +00001146 new_method =
1147 classes.GetReference(i)->AsClass()->GetEmbeddedVTableEntry(method_index, pointer_size);
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001148 }
Nicolas Geoffray4f97a212016-02-25 16:17:54 +00001149 DCHECK(new_method != nullptr);
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001150 if (actual_method == nullptr) {
1151 actual_method = new_method;
1152 } else if (actual_method != new_method) {
1153 // Different methods, bailout.
1154 return false;
1155 }
1156 }
1157
1158 HInstruction* receiver = invoke_instruction->InputAt(0);
1159 HInstruction* cursor = invoke_instruction->GetPrevious();
1160 HBasicBlock* bb_cursor = invoke_instruction->GetBlock();
1161
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01001162 HInstruction* return_replacement = nullptr;
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001163 if (!TryBuildAndInline(invoke_instruction,
1164 actual_method,
1165 ReferenceTypeInfo::CreateInvalid(),
1166 &return_replacement)) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001167 return false;
1168 }
1169
1170 // We successfully inlined, now add a guard.
1171 HInstanceFieldGet* receiver_class = BuildGetReceiverClass(
1172 class_linker, receiver, invoke_instruction->GetDexPc());
1173
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001174 DataType::Type type = Is64BitInstructionSet(graph_->GetInstructionSet())
1175 ? DataType::Type::kInt64
1176 : DataType::Type::kInt32;
Vladimir Markoca6fff82017-10-03 14:49:14 +01001177 HClassTableGet* class_table_get = new (graph_->GetAllocator()) HClassTableGet(
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001178 receiver_class,
1179 type,
Vladimir Markoa1de9182016-02-25 11:37:38 +00001180 invoke_instruction->IsInvokeVirtual() ? HClassTableGet::TableKind::kVTable
1181 : HClassTableGet::TableKind::kIMTable,
Nicolas Geoffray4f97a212016-02-25 16:17:54 +00001182 method_index,
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001183 invoke_instruction->GetDexPc());
1184
1185 HConstant* constant;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001186 if (type == DataType::Type::kInt64) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001187 constant = graph_->GetLongConstant(
1188 reinterpret_cast<intptr_t>(actual_method), invoke_instruction->GetDexPc());
1189 } else {
1190 constant = graph_->GetIntConstant(
1191 reinterpret_cast<intptr_t>(actual_method), invoke_instruction->GetDexPc());
1192 }
1193
Vladimir Markoca6fff82017-10-03 14:49:14 +01001194 HNotEqual* compare = new (graph_->GetAllocator()) HNotEqual(class_table_get, constant);
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001195 if (cursor != nullptr) {
1196 bb_cursor->InsertInstructionAfter(receiver_class, cursor);
1197 } else {
1198 bb_cursor->InsertInstructionBefore(receiver_class, bb_cursor->GetFirstInstruction());
1199 }
1200 bb_cursor->InsertInstructionAfter(class_table_get, receiver_class);
1201 bb_cursor->InsertInstructionAfter(compare, class_table_get);
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01001202
1203 if (outermost_graph_->IsCompilingOsr()) {
1204 CreateDiamondPatternForPolymorphicInline(compare, return_replacement, invoke_instruction);
1205 } else {
Vladimir Markoca6fff82017-10-03 14:49:14 +01001206 HDeoptimize* deoptimize = new (graph_->GetAllocator()) HDeoptimize(
1207 graph_->GetAllocator(),
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +00001208 compare,
1209 receiver,
Nicolas Geoffray4e92c3c2017-05-08 09:34:26 +01001210 DeoptimizationKind::kJitSameTarget,
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +00001211 invoke_instruction->GetDexPc());
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01001212 bb_cursor->InsertInstructionAfter(deoptimize, compare);
1213 deoptimize->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
Nicolas Geoffrayb8958022021-04-15 15:12:31 +01001214 MaybeReplaceAndRemove(return_replacement, invoke_instruction);
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +00001215 receiver->ReplaceUsesDominatedBy(deoptimize, deoptimize);
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +00001216 deoptimize->SetReferenceTypeInfo(receiver->GetReferenceTypeInfo());
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01001217 }
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001218
1219 // Run type propagation to get the guard typed.
Vladimir Marko456307a2016-04-19 14:12:13 +00001220 ReferenceTypePropagation rtp_fixup(graph_,
1221 outer_compilation_unit_.GetDexCache(),
Andreas Gampe3db70682018-12-26 15:12:03 -08001222 /* is_first_run= */ false);
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001223 rtp_fixup.Run();
1224
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001225 MaybeRecordStat(stats_, MethodCompilationStat::kInlinedPolymorphicCall);
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001226
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001227 LOG_SUCCESS() << "Inlined same polymorphic target " << actual_method->PrettyMethod();
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001228 return true;
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001229}
1230
Nicolas Geoffraye1e0e0f2021-04-29 08:57:13 +00001231void HInliner::MaybeRunReferenceTypePropagation(HInstruction* replacement,
1232 HInvoke* invoke_instruction) {
1233 if (ReturnTypeMoreSpecific(replacement, invoke_instruction)) {
David Brazdil94ab38f2016-06-21 17:48:19 +01001234 // Actual return value has a more specific type than the method's declared
1235 // return type. Run RTP again on the outer graph to propagate it.
1236 ReferenceTypePropagation(graph_,
1237 outer_compilation_unit_.GetDexCache(),
Andreas Gampe3db70682018-12-26 15:12:03 -08001238 /* is_first_run= */ false).Run();
David Brazdil94ab38f2016-06-21 17:48:19 +01001239 }
Nicolas Geoffraye1e0e0f2021-04-29 08:57:13 +00001240}
1241
1242bool HInliner::TryDevirtualize(HInvoke* invoke_instruction,
1243 ArtMethod* method,
1244 HInvoke** replacement) {
Nicolas Geoffraye1e0e0f2021-04-29 08:57:13 +00001245 DCHECK(invoke_instruction != *replacement);
Nicolas Geoffrayec068092021-05-10 17:28:32 +00001246 if (!invoke_instruction->IsInvokeInterface() && !invoke_instruction->IsInvokeVirtual()) {
Nicolas Geoffraye1e0e0f2021-04-29 08:57:13 +00001247 return false;
1248 }
Nicolas Geoffray39d4df62021-05-07 12:22:47 +00001249
Nicolas Geoffrayec068092021-05-10 17:28:32 +00001250 // Don't bother trying to call directly a default conflict method. It
1251 // doesn't have a proper MethodReference, but also `GetCanonicalMethod`
1252 // will return an actual default implementation.
1253 if (method->IsDefaultConflicting()) {
1254 return false;
Nicolas Geoffray39d4df62021-05-07 12:22:47 +00001255 }
Nicolas Geoffrayec068092021-05-10 17:28:32 +00001256 DCHECK(!method->IsProxyMethod());
1257 ClassLinker* cl = Runtime::Current()->GetClassLinker();
1258 PointerSize pointer_size = cl->GetImagePointerSize();
1259 // The sharpening logic assumes the caller isn't passing a copied method.
1260 method = method->GetCanonicalMethod(pointer_size);
Nicolas Geoffraye1e0e0f2021-04-29 08:57:13 +00001261 uint32_t dex_method_index = FindMethodIndexIn(
1262 method,
1263 *invoke_instruction->GetMethodReference().dex_file,
1264 invoke_instruction->GetMethodReference().index);
1265 if (dex_method_index == dex::kDexNoIndex) {
1266 return false;
1267 }
Nicolas Geoffrayec068092021-05-10 17:28:32 +00001268 HInvokeStaticOrDirect::DispatchInfo dispatch_info =
1269 HSharpening::SharpenLoadMethod(method,
1270 /* has_method_id= */ true,
1271 /* for_interface_call= */ false,
1272 codegen_);
1273 DCHECK_NE(dispatch_info.code_ptr_location, CodePtrLocation::kCallCriticalNative);
1274 if (dispatch_info.method_load_kind == MethodLoadKind::kRuntimeCall) {
1275 // If sharpening returns that we need to load the method at runtime, keep
1276 // the virtual/interface call which will be faster.
1277 // Also, the entrypoints for runtime calls do not handle devirtualized
1278 // calls.
1279 return false;
1280 }
1281
1282 HInvokeStaticOrDirect* new_invoke = new (graph_->GetAllocator()) HInvokeStaticOrDirect(
Nicolas Geoffraye1e0e0f2021-04-29 08:57:13 +00001283 graph_->GetAllocator(),
1284 invoke_instruction->GetNumberOfArguments(),
1285 invoke_instruction->GetType(),
1286 invoke_instruction->GetDexPc(),
1287 MethodReference(invoke_instruction->GetMethodReference().dex_file, dex_method_index),
1288 method,
Nicolas Geoffrayec068092021-05-10 17:28:32 +00001289 dispatch_info,
1290 kDirect,
Nicolas Geoffraye1e0e0f2021-04-29 08:57:13 +00001291 MethodReference(method->GetDexFile(), method->GetDexMethodIndex()),
Nicolas Geoffrayec068092021-05-10 17:28:32 +00001292 HInvokeStaticOrDirect::ClinitCheckRequirement::kNone);
Nicolas Geoffraye1e0e0f2021-04-29 08:57:13 +00001293 HInputsRef inputs = invoke_instruction->GetInputs();
Nicolas Geoffrayec068092021-05-10 17:28:32 +00001294 DCHECK_EQ(inputs.size(), invoke_instruction->GetNumberOfArguments());
Nicolas Geoffraye1e0e0f2021-04-29 08:57:13 +00001295 for (size_t index = 0; index != inputs.size(); ++index) {
1296 new_invoke->SetArgumentAt(index, inputs[index]);
1297 }
Nicolas Geoffrayec068092021-05-10 17:28:32 +00001298 if (HInvokeStaticOrDirect::NeedsCurrentMethodInput(dispatch_info)) {
1299 new_invoke->SetRawInputAt(new_invoke->GetCurrentMethodIndexUnchecked(),
1300 graph_->GetCurrentMethod());
1301 }
Nicolas Geoffraye1e0e0f2021-04-29 08:57:13 +00001302 invoke_instruction->GetBlock()->InsertInstructionBefore(new_invoke, invoke_instruction);
1303 new_invoke->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
1304 if (invoke_instruction->GetType() == DataType::Type::kReference) {
1305 new_invoke->SetReferenceTypeInfo(invoke_instruction->GetReferenceTypeInfo());
1306 }
1307 *replacement = new_invoke;
1308
1309 MaybeReplaceAndRemove(*replacement, invoke_instruction);
1310 // No need to call MaybeRunReferenceTypePropagation, as we know the return type
1311 // cannot be more specific.
1312 DCHECK(!ReturnTypeMoreSpecific(*replacement, invoke_instruction));
1313 return true;
1314}
1315
1316
1317bool HInliner::TryInlineAndReplace(HInvoke* invoke_instruction,
1318 ArtMethod* method,
1319 ReferenceTypeInfo receiver_type,
1320 bool do_rtp) {
1321 DCHECK(!invoke_instruction->IsIntrinsic());
1322 HInstruction* return_replacement = nullptr;
1323
1324 if (!TryBuildAndInline(invoke_instruction, method, receiver_type, &return_replacement)) {
1325 return false;
1326 }
1327
1328 MaybeReplaceAndRemove(return_replacement, invoke_instruction);
1329 FixUpReturnReferenceType(method, return_replacement);
1330 if (do_rtp) {
1331 MaybeRunReferenceTypePropagation(return_replacement, invoke_instruction);
1332 }
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001333 return true;
1334}
1335
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001336size_t HInliner::CountRecursiveCallsOf(ArtMethod* method) const {
1337 const HInliner* current = this;
1338 size_t count = 0;
1339 do {
1340 if (current->graph_->GetArtMethod() == method) {
1341 ++count;
1342 }
1343 current = current->parent_;
1344 } while (current != nullptr);
1345 return count;
1346}
1347
Vladimir Marko213ee2d2018-06-22 11:56:34 +01001348static inline bool MayInline(const CompilerOptions& compiler_options,
1349 const DexFile& inlined_from,
1350 const DexFile& inlined_into) {
Vladimir Marko213ee2d2018-06-22 11:56:34 +01001351 // We're not allowed to inline across dex files if we're the no-inline-from dex file.
1352 if (!IsSameDexFile(inlined_from, inlined_into) &&
1353 ContainsElement(compiler_options.GetNoInlineFromDexFile(), &inlined_from)) {
1354 return false;
1355 }
1356
1357 return true;
1358}
1359
Eric Holk1868de92020-02-12 09:10:21 -08001360// Returns whether inlining is allowed based on ART semantics.
1361bool HInliner::IsInliningAllowed(ArtMethod* method, const CodeItemDataAccessor& accessor) const {
Mathieu Chartier808c7a52017-12-15 11:19:33 -08001362 if (!accessor.HasCodeItem()) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001363 LOG_FAIL_NO_STAT()
1364 << "Method " << method->PrettyMethod() << " is not inlined because it is native";
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001365 return false;
1366 }
1367
Nicolas Geoffray250a3782016-04-20 16:27:53 +01001368 if (!method->IsCompilable()) {
Santiago Aboy Solanesfa73acc2021-11-12 14:23:27 +00001369 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedNotCompilable)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001370 << "Method " << method->PrettyMethod()
1371 << " has soft failures un-handled by the compiler, so it cannot be inlined";
Aart Bik897df032018-02-07 13:29:11 -08001372 return false;
Nicolas Geoffray250a3782016-04-20 16:27:53 +01001373 }
1374
Nicolas Geoffraycf74ae72021-07-15 10:37:28 +01001375 if (!IsMethodVerified(method)) {
Aart Bik2c148f02018-02-02 14:30:35 -08001376 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedNotVerified)
1377 << "Method " << method->PrettyMethod()
1378 << " couldn't be verified, so it cannot be inlined";
1379 return false;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001380 }
1381
Eric Holk1868de92020-02-12 09:10:21 -08001382 return true;
1383}
1384
1385// Returns whether ART supports inlining this method.
1386//
1387// Some methods are not supported because they have features for which inlining
1388// is not implemented. For example, we do not currently support inlining throw
1389// instructions into a try block.
1390bool HInliner::IsInliningSupported(const HInvoke* invoke_instruction,
1391 ArtMethod* method,
1392 const CodeItemDataAccessor& accessor) const {
1393 if (method->IsProxyMethod()) {
1394 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedProxy)
1395 << "Method " << method->PrettyMethod()
1396 << " is not inlined because of unimplemented inline support for proxy methods.";
1397 return false;
1398 }
1399
1400 if (accessor.TriesSize() != 0) {
Santiago Aboy Solanesfa73acc2021-11-12 14:23:27 +00001401 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedTryCatchCallee)
Eric Holk1868de92020-02-12 09:10:21 -08001402 << "Method " << method->PrettyMethod() << " is not inlined because of try block";
1403 return false;
1404 }
1405
Roland Levillain4c0eb422015-04-24 16:43:49 +01001406 if (invoke_instruction->IsInvokeStaticOrDirect() &&
1407 invoke_instruction->AsInvokeStaticOrDirect()->IsStaticWithImplicitClinitCheck()) {
1408 // Case of a static method that cannot be inlined because it implicitly
1409 // requires an initialization check of its declaring class.
Santiago Aboy Solanesfa73acc2021-11-12 14:23:27 +00001410 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedDexCacheClinitCheck)
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001411 << "Method " << method->PrettyMethod()
1412 << " is not inlined because it is static and requires a clinit"
1413 << " check that cannot be emitted due to Dex cache limitations";
Roland Levillain4c0eb422015-04-24 16:43:49 +01001414 return false;
1415 }
1416
Eric Holk1868de92020-02-12 09:10:21 -08001417 return true;
1418}
1419
1420// Returns whether our resource limits allow inlining this method.
1421bool HInliner::IsInliningBudgetAvailable(ArtMethod* method,
1422 const CodeItemDataAccessor& accessor) const {
1423 if (CountRecursiveCallsOf(method) > kMaximumNumberOfRecursiveCalls) {
1424 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedRecursiveBudget)
1425 << "Method "
1426 << method->PrettyMethod()
1427 << " is not inlined because it has reached its recursive call budget.";
1428 return false;
1429 }
1430
1431 size_t inline_max_code_units = codegen_->GetCompilerOptions().GetInlineMaxCodeUnits();
1432 if (accessor.InsnsSizeInCodeUnits() > inline_max_code_units) {
1433 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedCodeItem)
1434 << "Method " << method->PrettyMethod()
1435 << " is not inlined because its code item is too big: "
1436 << accessor.InsnsSizeInCodeUnits()
1437 << " > "
1438 << inline_max_code_units;
1439 return false;
1440 }
1441
1442 return true;
1443}
1444
1445bool HInliner::TryBuildAndInline(HInvoke* invoke_instruction,
1446 ArtMethod* method,
1447 ReferenceTypeInfo receiver_type,
1448 HInstruction** return_replacement) {
Nicolas Geoffrayb8958022021-04-15 15:12:31 +01001449 // If invoke_instruction is devirtualized to a different method, give intrinsics
1450 // another chance before we try to inline it.
1451 if (invoke_instruction->GetResolvedMethod() != method && method->IsIntrinsic()) {
1452 MaybeRecordStat(stats_, MethodCompilationStat::kIntrinsicRecognized);
1453 // For simplicity, always create a new instruction to replace the existing
1454 // invoke.
1455 HInvokeVirtual* new_invoke = new (graph_->GetAllocator()) HInvokeVirtual(
1456 graph_->GetAllocator(),
1457 invoke_instruction->GetNumberOfArguments(),
1458 invoke_instruction->GetType(),
1459 invoke_instruction->GetDexPc(),
1460 invoke_instruction->GetMethodReference(), // Use existing invoke's method's reference.
1461 method,
1462 MethodReference(method->GetDexFile(), method->GetDexMethodIndex()),
1463 method->GetMethodIndex());
1464 DCHECK_NE(new_invoke->GetIntrinsic(), Intrinsics::kNone);
1465 HInputsRef inputs = invoke_instruction->GetInputs();
1466 for (size_t index = 0; index != inputs.size(); ++index) {
1467 new_invoke->SetArgumentAt(index, inputs[index]);
1468 }
1469 invoke_instruction->GetBlock()->InsertInstructionBefore(new_invoke, invoke_instruction);
1470 new_invoke->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
1471 if (invoke_instruction->GetType() == DataType::Type::kReference) {
1472 new_invoke->SetReferenceTypeInfo(invoke_instruction->GetReferenceTypeInfo());
1473 }
1474 *return_replacement = new_invoke;
1475 return true;
1476 }
1477
Eric Holk1868de92020-02-12 09:10:21 -08001478 // Check whether we're allowed to inline. The outermost compilation unit is the relevant
1479 // dex file here (though the transitivity of an inline chain would allow checking the caller).
1480 if (!MayInline(codegen_->GetCompilerOptions(),
1481 *method->GetDexFile(),
1482 *outer_compilation_unit_.GetDexFile())) {
1483 if (TryPatternSubstitution(invoke_instruction, method, return_replacement)) {
1484 LOG_SUCCESS() << "Successfully replaced pattern of invoke "
1485 << method->PrettyMethod();
1486 MaybeRecordStat(stats_, MethodCompilationStat::kReplacedInvokeWithSimplePattern);
1487 return true;
1488 }
1489 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedWont)
1490 << "Won't inline " << method->PrettyMethod() << " in "
1491 << outer_compilation_unit_.GetDexFile()->GetLocation() << " ("
1492 << caller_compilation_unit_.GetDexFile()->GetLocation() << ") from "
1493 << method->GetDexFile()->GetLocation();
1494 return false;
1495 }
1496
1497 CodeItemDataAccessor accessor(method->DexInstructionData());
1498
1499 if (!IsInliningAllowed(method, accessor)) {
1500 return false;
1501 }
1502
1503 if (!IsInliningSupported(invoke_instruction, method, accessor)) {
1504 return false;
1505 }
1506
1507 if (!IsInliningBudgetAvailable(method, accessor)) {
1508 return false;
1509 }
1510
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001511 if (!TryBuildAndInlineHelper(
Eric Holk1868de92020-02-12 09:10:21 -08001512 invoke_instruction, method, receiver_type, return_replacement)) {
Nicolas Geoffrayc0365b12015-03-18 18:31:52 +00001513 return false;
1514 }
1515
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001516 LOG_SUCCESS() << method->PrettyMethod();
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001517 MaybeRecordStat(stats_, MethodCompilationStat::kInlinedInvoke);
Santiago Aboy Solanes15580482021-10-12 13:11:29 +01001518 if (outermost_graph_ == graph_) {
1519 MaybeRecordStat(stats_, MethodCompilationStat::kInlinedLastInvoke);
1520 }
Nicolas Geoffrayc0365b12015-03-18 18:31:52 +00001521 return true;
1522}
1523
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001524static HInstruction* GetInvokeInputForArgVRegIndex(HInvoke* invoke_instruction,
1525 size_t arg_vreg_index)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001526 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001527 size_t input_index = 0;
1528 for (size_t i = 0; i < arg_vreg_index; ++i, ++input_index) {
1529 DCHECK_LT(input_index, invoke_instruction->GetNumberOfArguments());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001530 if (DataType::Is64BitType(invoke_instruction->InputAt(input_index)->GetType())) {
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001531 ++i;
1532 DCHECK_NE(i, arg_vreg_index);
1533 }
1534 }
1535 DCHECK_LT(input_index, invoke_instruction->GetNumberOfArguments());
1536 return invoke_instruction->InputAt(input_index);
1537}
1538
1539// Try to recognize known simple patterns and replace invoke call with appropriate instructions.
1540bool HInliner::TryPatternSubstitution(HInvoke* invoke_instruction,
Nicolas Geoffraye6c0f2a2020-09-07 08:30:52 +01001541 ArtMethod* method,
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001542 HInstruction** return_replacement) {
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001543 InlineMethod inline_method;
Nicolas Geoffraye6c0f2a2020-09-07 08:30:52 +01001544 if (!InlineMethodAnalyser::AnalyseMethodCode(method, &inline_method)) {
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001545 return false;
1546 }
1547
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001548 switch (inline_method.opcode) {
1549 case kInlineOpNop:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001550 DCHECK_EQ(invoke_instruction->GetType(), DataType::Type::kVoid);
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001551 *return_replacement = nullptr;
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001552 break;
1553 case kInlineOpReturnArg:
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001554 *return_replacement = GetInvokeInputForArgVRegIndex(invoke_instruction,
1555 inline_method.d.return_data.arg);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001556 break;
Vladimir Marko103e56a2022-03-08 13:46:59 +00001557 case kInlineOpNonWideConst: {
1558 char shorty0 = method->GetShorty()[0];
1559 if (shorty0 == 'L') {
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001560 DCHECK_EQ(inline_method.d.data, 0u);
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001561 *return_replacement = graph_->GetNullConstant();
Vladimir Marko103e56a2022-03-08 13:46:59 +00001562 } else if (shorty0 == 'F') {
1563 *return_replacement = graph_->GetFloatConstant(
1564 bit_cast<float, int32_t>(static_cast<int32_t>(inline_method.d.data)));
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001565 } else {
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001566 *return_replacement = graph_->GetIntConstant(static_cast<int32_t>(inline_method.d.data));
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001567 }
1568 break;
Vladimir Marko103e56a2022-03-08 13:46:59 +00001569 }
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001570 case kInlineOpIGet: {
1571 const InlineIGetIPutData& data = inline_method.d.ifield_data;
1572 if (data.method_is_static || data.object_arg != 0u) {
1573 // TODO: Needs null check.
1574 return false;
1575 }
1576 HInstruction* obj = GetInvokeInputForArgVRegIndex(invoke_instruction, data.object_arg);
Nicolas Geoffraye6c0f2a2020-09-07 08:30:52 +01001577 HInstanceFieldGet* iget = CreateInstanceFieldGet(data.field_idx, method, obj);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001578 DCHECK_EQ(iget->GetFieldOffset().Uint32Value(), data.field_offset);
1579 DCHECK_EQ(iget->IsVolatile() ? 1u : 0u, data.is_volatile);
1580 invoke_instruction->GetBlock()->InsertInstructionBefore(iget, invoke_instruction);
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001581 *return_replacement = iget;
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001582 break;
1583 }
1584 case kInlineOpIPut: {
1585 const InlineIGetIPutData& data = inline_method.d.ifield_data;
1586 if (data.method_is_static || data.object_arg != 0u) {
1587 // TODO: Needs null check.
1588 return false;
1589 }
1590 HInstruction* obj = GetInvokeInputForArgVRegIndex(invoke_instruction, data.object_arg);
1591 HInstruction* value = GetInvokeInputForArgVRegIndex(invoke_instruction, data.src_arg);
Nicolas Geoffraye6c0f2a2020-09-07 08:30:52 +01001592 HInstanceFieldSet* iput = CreateInstanceFieldSet(data.field_idx, method, obj, value);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001593 DCHECK_EQ(iput->GetFieldOffset().Uint32Value(), data.field_offset);
1594 DCHECK_EQ(iput->IsVolatile() ? 1u : 0u, data.is_volatile);
1595 invoke_instruction->GetBlock()->InsertInstructionBefore(iput, invoke_instruction);
1596 if (data.return_arg_plus1 != 0u) {
1597 size_t return_arg = data.return_arg_plus1 - 1u;
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001598 *return_replacement = GetInvokeInputForArgVRegIndex(invoke_instruction, return_arg);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001599 }
1600 break;
1601 }
Vladimir Marko354efa62016-02-04 19:46:56 +00001602 case kInlineOpConstructor: {
1603 const InlineConstructorData& data = inline_method.d.constructor_data;
1604 // Get the indexes to arrays for easier processing.
1605 uint16_t iput_field_indexes[] = {
1606 data.iput0_field_index, data.iput1_field_index, data.iput2_field_index
1607 };
1608 uint16_t iput_args[] = { data.iput0_arg, data.iput1_arg, data.iput2_arg };
1609 static_assert(arraysize(iput_args) == arraysize(iput_field_indexes), "Size mismatch");
1610 // Count valid field indexes.
1611 size_t number_of_iputs = 0u;
1612 while (number_of_iputs != arraysize(iput_field_indexes) &&
1613 iput_field_indexes[number_of_iputs] != DexFile::kDexNoIndex16) {
1614 // Check that there are no duplicate valid field indexes.
1615 DCHECK_EQ(0, std::count(iput_field_indexes + number_of_iputs + 1,
1616 iput_field_indexes + arraysize(iput_field_indexes),
1617 iput_field_indexes[number_of_iputs]));
1618 ++number_of_iputs;
1619 }
1620 // Check that there are no valid field indexes in the rest of the array.
1621 DCHECK_EQ(0, std::count_if(iput_field_indexes + number_of_iputs,
1622 iput_field_indexes + arraysize(iput_field_indexes),
1623 [](uint16_t index) { return index != DexFile::kDexNoIndex16; }));
1624
1625 // Create HInstanceFieldSet for each IPUT that stores non-zero data.
Andreas Gampe3db70682018-12-26 15:12:03 -08001626 HInstruction* obj = GetInvokeInputForArgVRegIndex(invoke_instruction,
1627 /* arg_vreg_index= */ 0u);
Vladimir Marko354efa62016-02-04 19:46:56 +00001628 bool needs_constructor_barrier = false;
1629 for (size_t i = 0; i != number_of_iputs; ++i) {
1630 HInstruction* value = GetInvokeInputForArgVRegIndex(invoke_instruction, iput_args[i]);
Roland Levillain1a653882016-03-18 18:05:57 +00001631 if (!value->IsConstant() || !value->AsConstant()->IsZeroBitPattern()) {
Vladimir Marko354efa62016-02-04 19:46:56 +00001632 uint16_t field_index = iput_field_indexes[i];
Vladimir Markof44d36c2017-03-14 14:18:46 +00001633 bool is_final;
1634 HInstanceFieldSet* iput =
Nicolas Geoffraye6c0f2a2020-09-07 08:30:52 +01001635 CreateInstanceFieldSet(field_index, method, obj, value, &is_final);
Vladimir Marko354efa62016-02-04 19:46:56 +00001636 invoke_instruction->GetBlock()->InsertInstructionBefore(iput, invoke_instruction);
1637
1638 // Check whether the field is final. If it is, we need to add a barrier.
Vladimir Markof44d36c2017-03-14 14:18:46 +00001639 if (is_final) {
Vladimir Marko354efa62016-02-04 19:46:56 +00001640 needs_constructor_barrier = true;
1641 }
1642 }
1643 }
1644 if (needs_constructor_barrier) {
Vladimir Marko1a2a5cd2018-11-07 15:39:48 +00001645 // See DexCompilationUnit::RequiresConstructorBarrier for more details.
Igor Murashkind01745e2017-04-05 16:40:31 -07001646 DCHECK(obj != nullptr) << "only non-static methods can have a constructor fence";
1647
1648 HConstructorFence* constructor_fence =
Vladimir Markoca6fff82017-10-03 14:49:14 +01001649 new (graph_->GetAllocator()) HConstructorFence(obj, kNoDexPc, graph_->GetAllocator());
Igor Murashkind01745e2017-04-05 16:40:31 -07001650 invoke_instruction->GetBlock()->InsertInstructionBefore(constructor_fence,
1651 invoke_instruction);
Vladimir Marko354efa62016-02-04 19:46:56 +00001652 }
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001653 *return_replacement = nullptr;
Vladimir Marko354efa62016-02-04 19:46:56 +00001654 break;
1655 }
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001656 default:
1657 LOG(FATAL) << "UNREACHABLE";
1658 UNREACHABLE();
1659 }
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001660 return true;
1661}
1662
Vladimir Markof44d36c2017-03-14 14:18:46 +00001663HInstanceFieldGet* HInliner::CreateInstanceFieldGet(uint32_t field_index,
1664 ArtMethod* referrer,
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001665 HInstruction* obj)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001666 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markof44d36c2017-03-14 14:18:46 +00001667 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1668 ArtField* resolved_field =
Andreas Gampe3db70682018-12-26 15:12:03 -08001669 class_linker->LookupResolvedField(field_index, referrer, /* is_static= */ false);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001670 DCHECK(resolved_field != nullptr);
Vladimir Markoca6fff82017-10-03 14:49:14 +01001671 HInstanceFieldGet* iget = new (graph_->GetAllocator()) HInstanceFieldGet(
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001672 obj,
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00001673 resolved_field,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001674 DataType::FromShorty(resolved_field->GetTypeDescriptor()[0]),
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001675 resolved_field->GetOffset(),
1676 resolved_field->IsVolatile(),
1677 field_index,
1678 resolved_field->GetDeclaringClass()->GetDexClassDefIndex(),
Vladimir Markof44d36c2017-03-14 14:18:46 +00001679 *referrer->GetDexFile(),
Vladimir Markoadda4352016-01-29 10:24:41 +00001680 // Read barrier generates a runtime call in slow path and we need a valid
1681 // dex pc for the associated stack map. 0 is bogus but valid. Bug: 26854537.
Andreas Gampe3db70682018-12-26 15:12:03 -08001682 /* dex_pc= */ 0);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001683 if (iget->GetType() == DataType::Type::kReference) {
Vladimir Marko456307a2016-04-19 14:12:13 +00001684 // Use the same dex_cache that we used for field lookup as the hint_dex_cache.
Vladimir Marko02ca05a2020-05-12 13:58:51 +01001685 Handle<mirror::DexCache> dex_cache =
1686 graph_->GetHandleCache()->NewHandle(referrer->GetDexCache());
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001687 ReferenceTypePropagation rtp(graph_,
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001688 dex_cache,
Andreas Gampe3db70682018-12-26 15:12:03 -08001689 /* is_first_run= */ false);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001690 rtp.Visit(iget);
1691 }
1692 return iget;
1693}
1694
Vladimir Markof44d36c2017-03-14 14:18:46 +00001695HInstanceFieldSet* HInliner::CreateInstanceFieldSet(uint32_t field_index,
1696 ArtMethod* referrer,
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001697 HInstruction* obj,
Vladimir Markof44d36c2017-03-14 14:18:46 +00001698 HInstruction* value,
1699 bool* is_final)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001700 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markof44d36c2017-03-14 14:18:46 +00001701 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1702 ArtField* resolved_field =
Andreas Gampe3db70682018-12-26 15:12:03 -08001703 class_linker->LookupResolvedField(field_index, referrer, /* is_static= */ false);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001704 DCHECK(resolved_field != nullptr);
Vladimir Markof44d36c2017-03-14 14:18:46 +00001705 if (is_final != nullptr) {
1706 // This information is needed only for constructors.
1707 DCHECK(referrer->IsConstructor());
1708 *is_final = resolved_field->IsFinal();
1709 }
Vladimir Markoca6fff82017-10-03 14:49:14 +01001710 HInstanceFieldSet* iput = new (graph_->GetAllocator()) HInstanceFieldSet(
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001711 obj,
1712 value,
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00001713 resolved_field,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001714 DataType::FromShorty(resolved_field->GetTypeDescriptor()[0]),
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001715 resolved_field->GetOffset(),
1716 resolved_field->IsVolatile(),
1717 field_index,
1718 resolved_field->GetDeclaringClass()->GetDexClassDefIndex(),
Vladimir Markof44d36c2017-03-14 14:18:46 +00001719 *referrer->GetDexFile(),
Vladimir Markoadda4352016-01-29 10:24:41 +00001720 // Read barrier generates a runtime call in slow path and we need a valid
1721 // dex pc for the associated stack map. 0 is bogus but valid. Bug: 26854537.
Andreas Gampe3db70682018-12-26 15:12:03 -08001722 /* dex_pc= */ 0);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001723 return iput;
1724}
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +00001725
Vladimir Markob1d0ee12017-04-20 19:50:32 +01001726template <typename T>
Vladimir Marko02ca05a2020-05-12 13:58:51 +01001727static inline Handle<T> NewHandleIfDifferent(ObjPtr<T> object, Handle<T> hint, HGraph* graph)
Vladimir Markob1d0ee12017-04-20 19:50:32 +01001728 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko02ca05a2020-05-12 13:58:51 +01001729 return (object != hint.Get()) ? graph->GetHandleCache()->NewHandle(object) : hint;
Vladimir Markob1d0ee12017-04-20 19:50:32 +01001730}
1731
Santiago Aboy Solanese43aa3f2021-11-01 09:02:09 +00001732static bool CanEncodeInlinedMethodInStackMap(const DexFile& outer_dex_file,
1733 ArtMethod* callee,
Santiago Aboy Solanes970ba212021-10-21 10:52:47 +01001734 const CodeGenerator* codegen,
Santiago Aboy Solanese43aa3f2021-11-01 09:02:09 +00001735 bool* out_needs_bss_check)
Vladimir Marko6be1dbd2018-11-13 13:09:51 +00001736 REQUIRES_SHARED(Locks::mutator_lock_) {
1737 if (!Runtime::Current()->IsAotCompiler()) {
1738 // JIT can always encode methods in stack maps.
1739 return true;
1740 }
Santiago Aboy Solanesa0232ad2021-11-08 17:00:06 +00001741
Santiago Aboy Solanes970ba212021-10-21 10:52:47 +01001742 const DexFile* dex_file = callee->GetDexFile();
1743 if (IsSameDexFile(outer_dex_file, *dex_file)) {
Vladimir Marko6be1dbd2018-11-13 13:09:51 +00001744 return true;
1745 }
Santiago Aboy Solanese43aa3f2021-11-01 09:02:09 +00001746
Santiago Aboy Solanes970ba212021-10-21 10:52:47 +01001747 // Inline across dexfiles if the callee's DexFile is:
1748 // 1) in the bootclasspath, or
Santiago Aboy Solanesf4bd5de2022-03-23 08:25:33 +00001749 if (callee->GetDeclaringClass()->IsBootStrapClassLoaded()) {
Santiago Aboy Solanes69a87e32022-03-08 16:43:54 +00001750 // In multi-image, each BCP DexFile has their own OatWriter. Since they don't cooperate with
1751 // each other, we request the BSS check for them.
Santiago Aboy Solanesf4bd5de2022-03-23 08:25:33 +00001752 // TODO(solanes, 154012332): Add .bss support for BCP multi-image.
1753 *out_needs_bss_check = codegen->GetCompilerOptions().IsMultiImage();
Santiago Aboy Solanese43aa3f2021-11-01 09:02:09 +00001754 return true;
1755 }
1756
Santiago Aboy Solanesa0232ad2021-11-08 17:00:06 +00001757 // 2) is a non-BCP dexfile with the OatFile we are compiling.
1758 if (codegen->GetCompilerOptions().WithinOatFile(dex_file)) {
Santiago Aboy Solanes970ba212021-10-21 10:52:47 +01001759 return true;
1760 }
1761
1762 // TODO(solanes): Support more AOT cases for inlining:
1763 // - methods in class loader context's DexFiles
Vladimir Marko6be1dbd2018-11-13 13:09:51 +00001764 return false;
1765}
1766
Eric Holk1868de92020-02-12 09:10:21 -08001767 // Substitutes parameters in the callee graph with their values from the caller.
1768void HInliner::SubstituteArguments(HGraph* callee_graph,
1769 HInvoke* invoke_instruction,
1770 ReferenceTypeInfo receiver_type,
1771 const DexCompilationUnit& dex_compilation_unit) {
1772 ArtMethod* const resolved_method = callee_graph->GetArtMethod();
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001773 size_t parameter_index = 0;
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001774 bool run_rtp = false;
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001775 for (HInstructionIterator instructions(callee_graph->GetEntryBlock()->GetInstructions());
1776 !instructions.Done();
1777 instructions.Advance()) {
1778 HInstruction* current = instructions.Current();
1779 if (current->IsParameterValue()) {
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001780 HInstruction* argument = invoke_instruction->InputAt(parameter_index);
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001781 if (argument->IsNullConstant()) {
1782 current->ReplaceWith(callee_graph->GetNullConstant());
1783 } else if (argument->IsIntConstant()) {
1784 current->ReplaceWith(callee_graph->GetIntConstant(argument->AsIntConstant()->GetValue()));
1785 } else if (argument->IsLongConstant()) {
1786 current->ReplaceWith(callee_graph->GetLongConstant(argument->AsLongConstant()->GetValue()));
1787 } else if (argument->IsFloatConstant()) {
1788 current->ReplaceWith(
1789 callee_graph->GetFloatConstant(argument->AsFloatConstant()->GetValue()));
1790 } else if (argument->IsDoubleConstant()) {
1791 current->ReplaceWith(
1792 callee_graph->GetDoubleConstant(argument->AsDoubleConstant()->GetValue()));
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001793 } else if (argument->GetType() == DataType::Type::kReference) {
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001794 if (!resolved_method->IsStatic() && parameter_index == 0 && receiver_type.IsValid()) {
1795 run_rtp = true;
1796 current->SetReferenceTypeInfo(receiver_type);
1797 } else {
1798 current->SetReferenceTypeInfo(argument->GetReferenceTypeInfo());
1799 }
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001800 current->AsParameterValue()->SetCanBeNull(argument->CanBeNull());
1801 }
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001802 ++parameter_index;
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001803 }
1804 }
1805
David Brazdil94ab38f2016-06-21 17:48:19 +01001806 // We have replaced formal arguments with actual arguments. If actual types
1807 // are more specific than the declared ones, run RTP again on the inner graph.
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001808 if (run_rtp || ArgumentTypesMoreSpecific(invoke_instruction, resolved_method)) {
David Brazdil94ab38f2016-06-21 17:48:19 +01001809 ReferenceTypePropagation(callee_graph,
1810 dex_compilation_unit.GetDexCache(),
Andreas Gampe3db70682018-12-26 15:12:03 -08001811 /* is_first_run= */ false).Run();
David Brazdil94ab38f2016-06-21 17:48:19 +01001812 }
Eric Holk1868de92020-02-12 09:10:21 -08001813}
David Brazdil94ab38f2016-06-21 17:48:19 +01001814
Eric Holk1868de92020-02-12 09:10:21 -08001815// Returns whether we can inline the callee_graph into the target_block.
1816//
1817// This performs a combination of semantics checks, compiler support checks, and
1818// resource limit checks.
1819//
1820// If this function returns true, it will also set out_number_of_instructions to
1821// the number of instructions in the inlined body.
1822bool HInliner::CanInlineBody(const HGraph* callee_graph,
Santiago Aboy Solanes8ed39492022-07-20 11:13:39 +01001823 HInvoke* invoke,
Eric Holk1868de92020-02-12 09:10:21 -08001824 size_t* out_number_of_instructions) const {
Santiago Aboy Solanes8ed39492022-07-20 11:13:39 +01001825 const HBasicBlock* target_block = invoke->GetBlock();
Eric Holk1868de92020-02-12 09:10:21 -08001826 ArtMethod* const resolved_method = callee_graph->GetArtMethod();
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +00001827
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001828 HBasicBlock* exit_block = callee_graph->GetExitBlock();
1829 if (exit_block == nullptr) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001830 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedInfiniteLoop)
Nicolas Geoffray8731e702021-04-06 12:11:59 +01001831 << "Method " << resolved_method->PrettyMethod()
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001832 << " could not be inlined because it has an infinite loop";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001833 return false;
1834 }
1835
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00001836 bool has_one_return = false;
Vladimir Marko60584552015-09-03 13:35:12 +00001837 for (HBasicBlock* predecessor : exit_block->GetPredecessors()) {
1838 if (predecessor->GetLastInstruction()->IsThrow()) {
Eric Holk1868de92020-02-12 09:10:21 -08001839 if (target_block->IsTryBlock()) {
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00001840 // TODO(ngeoffray): Support adding HTryBoundary in Hgraph::InlineInto.
Santiago Aboy Solanesfa73acc2021-11-12 14:23:27 +00001841 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedTryCatchCaller)
Nicolas Geoffray8731e702021-04-06 12:11:59 +01001842 << "Method " << resolved_method->PrettyMethod()
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001843 << " could not be inlined because one branch always throws and"
1844 << " caller is in a try/catch block";
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00001845 return false;
1846 } else if (graph_->GetExitBlock() == nullptr) {
1847 // TODO(ngeoffray): Support adding HExit in the caller graph.
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001848 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedInfiniteLoop)
Nicolas Geoffray8731e702021-04-06 12:11:59 +01001849 << "Method " << resolved_method->PrettyMethod()
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001850 << " could not be inlined because one branch always throws and"
1851 << " caller does not have an exit block";
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00001852 return false;
Nicolas Geoffray1eede6a2017-03-02 16:14:53 +00001853 } else if (graph_->HasIrreducibleLoops()) {
1854 // TODO(ngeoffray): Support re-computing loop information to graphs with
1855 // irreducible loops?
Nicolas Geoffray8731e702021-04-06 12:11:59 +01001856 VLOG(compiler) << "Method " << resolved_method->PrettyMethod()
Nicolas Geoffray1eede6a2017-03-02 16:14:53 +00001857 << " could not be inlined because one branch always throws and"
1858 << " caller has irreducible loops";
1859 return false;
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00001860 }
1861 } else {
1862 has_one_return = true;
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001863 }
1864 }
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00001865
1866 if (!has_one_return) {
Santiago Aboy Solanes8ed39492022-07-20 11:13:39 +01001867 // If we know that the method always throws with the particular parameters, set it as such. This
1868 // is better than using the dex instructions as we have more information about this particular
1869 // call.
1870 invoke->SetAlwaysThrows(/* always_throws= */ true);
1871 graph_->SetHasAlwaysThrowingInvokes(/* value= */ true);
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001872 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedAlwaysThrows)
Nicolas Geoffray8731e702021-04-06 12:11:59 +01001873 << "Method " << resolved_method->PrettyMethod()
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001874 << " could not be inlined because it always throws";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001875 return false;
1876 }
1877
Santiago Aboy Solanese43aa3f2021-11-01 09:02:09 +00001878 const bool too_many_registers =
1879 total_number_of_dex_registers_ > kMaximumNumberOfCumulatedDexRegisters;
1880 bool needs_bss_check = false;
1881 const bool can_encode_in_stack_map = CanEncodeInlinedMethodInStackMap(
Santiago Aboy Solanes970ba212021-10-21 10:52:47 +01001882 *outer_compilation_unit_.GetDexFile(), resolved_method, codegen_, &needs_bss_check);
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001883 size_t number_of_instructions = 0;
Vladimir Marko2c45bc92016-10-25 16:54:12 +01001884 // Skip the entry block, it does not contain instructions that prevent inlining.
1885 for (HBasicBlock* block : callee_graph->GetReversePostOrderSkipEntryBlock()) {
David Sehrc757dec2016-11-04 15:48:34 -07001886 if (block->IsLoopHeader()) {
1887 if (block->GetLoopInformation()->IsIrreducible()) {
1888 // Don't inline methods with irreducible loops, they could prevent some
1889 // optimizations to run.
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001890 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedIrreducibleLoop)
Nicolas Geoffray8731e702021-04-06 12:11:59 +01001891 << "Method " << resolved_method->PrettyMethod()
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001892 << " could not be inlined because it contains an irreducible loop";
David Sehrc757dec2016-11-04 15:48:34 -07001893 return false;
1894 }
1895 if (!block->GetLoopInformation()->HasExitEdge()) {
1896 // Don't inline methods with loops without exit, since they cause the
1897 // loop information to be computed incorrectly when updating after
1898 // inlining.
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001899 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedLoopWithoutExit)
Nicolas Geoffray8731e702021-04-06 12:11:59 +01001900 << "Method " << resolved_method->PrettyMethod()
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001901 << " could not be inlined because it contains a loop with no exit";
David Sehrc757dec2016-11-04 15:48:34 -07001902 return false;
1903 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001904 }
1905
1906 for (HInstructionIterator instr_it(block->GetInstructions());
1907 !instr_it.Done();
1908 instr_it.Advance()) {
Tim Murray674e8be2021-04-12 12:30:28 -07001909 if (++number_of_instructions > inlining_budget_) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001910 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedInstructionBudget)
Nicolas Geoffray8731e702021-04-06 12:11:59 +01001911 << "Method " << resolved_method->PrettyMethod()
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001912 << " is not inlined because the outer method has reached"
1913 << " its instruction budget limit.";
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001914 return false;
1915 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001916 HInstruction* current = instr_it.Current();
Santiago Aboy Solanese43aa3f2021-11-01 09:02:09 +00001917 if (current->NeedsEnvironment()) {
1918 if (too_many_registers) {
1919 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedEnvironmentBudget)
1920 << "Method " << resolved_method->PrettyMethod()
1921 << " is not inlined because its caller has reached"
1922 << " its environment budget limit.";
1923 return false;
1924 }
Santiago Aboy Solanes33a31292021-09-24 08:50:06 +00001925
Santiago Aboy Solanese43aa3f2021-11-01 09:02:09 +00001926 if (!can_encode_in_stack_map) {
1927 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedStackMaps)
1928 << "Method " << resolved_method->PrettyMethod() << " could not be inlined because "
1929 << current->DebugName() << " needs an environment, is in a different dex file"
1930 << ", and cannot be encoded in the stack maps.";
1931 return false;
1932 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001933 }
Nicolas Geoffray9437b782015-03-25 10:08:51 +00001934
Nicolas Geoffrayd9309292015-10-31 22:21:31 +00001935 if (current->IsUnresolvedStaticFieldGet() ||
1936 current->IsUnresolvedInstanceFieldGet() ||
1937 current->IsUnresolvedStaticFieldSet() ||
1938 current->IsUnresolvedInstanceFieldSet()) {
1939 // Entrypoint for unresolved fields does not handle inlined frames.
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001940 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedUnresolvedEntrypoint)
Nicolas Geoffray8731e702021-04-06 12:11:59 +01001941 << "Method " << resolved_method->PrettyMethod()
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001942 << " could not be inlined because it is using an unresolved"
1943 << " entrypoint";
Nicolas Geoffrayd9309292015-10-31 22:21:31 +00001944 return false;
1945 }
Santiago Aboy Solanese43aa3f2021-11-01 09:02:09 +00001946
Santiago Aboy Solanesf4bd5de2022-03-23 08:25:33 +00001947 // We currently don't have support for inlining across dex files if we are:
Santiago Aboy Solanese43aa3f2021-11-01 09:02:09 +00001948 // 1) In AoT,
Santiago Aboy Solanesf4bd5de2022-03-23 08:25:33 +00001949 // 2) cross-dex inlining,
1950 // 3) the callee is a BCP DexFile,
1951 // 4) we are compiling multi image, and
1952 // 5) have an instruction that needs a bss entry, which will always be
1953 // 5)b) an instruction that needs an environment.
1954 // 1) - 4) are encoded in `needs_bss_check` (see CanEncodeInlinedMethodInStackMap).
Santiago Aboy Solanese43aa3f2021-11-01 09:02:09 +00001955 if (needs_bss_check && current->NeedsBss()) {
1956 DCHECK(current->NeedsEnvironment());
1957 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedBss)
1958 << "Method " << resolved_method->PrettyMethod()
1959 << " could not be inlined because it needs a BSS check";
1960 return false;
1961 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001962 }
1963 }
Eric Holk1868de92020-02-12 09:10:21 -08001964
1965 *out_number_of_instructions = number_of_instructions;
1966 return true;
1967}
1968
1969bool HInliner::TryBuildAndInlineHelper(HInvoke* invoke_instruction,
1970 ArtMethod* resolved_method,
1971 ReferenceTypeInfo receiver_type,
1972 HInstruction** return_replacement) {
1973 DCHECK(!(resolved_method->IsStatic() && receiver_type.IsValid()));
1974 const dex::CodeItem* code_item = resolved_method->GetCodeItem();
1975 const DexFile& callee_dex_file = *resolved_method->GetDexFile();
1976 uint32_t method_index = resolved_method->GetDexMethodIndex();
1977 CodeItemDebugInfoAccessor code_item_accessor(resolved_method->DexInstructionDebugInfo());
1978 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
1979 Handle<mirror::DexCache> dex_cache = NewHandleIfDifferent(resolved_method->GetDexCache(),
1980 caller_compilation_unit_.GetDexCache(),
Vladimir Marko02ca05a2020-05-12 13:58:51 +01001981 graph_);
Eric Holk1868de92020-02-12 09:10:21 -08001982 Handle<mirror::ClassLoader> class_loader =
1983 NewHandleIfDifferent(resolved_method->GetDeclaringClass()->GetClassLoader(),
1984 caller_compilation_unit_.GetClassLoader(),
Vladimir Marko02ca05a2020-05-12 13:58:51 +01001985 graph_);
Eric Holk1868de92020-02-12 09:10:21 -08001986
Vladimir Marko02ca05a2020-05-12 13:58:51 +01001987 Handle<mirror::Class> compiling_class =
1988 graph_->GetHandleCache()->NewHandle(resolved_method->GetDeclaringClass());
Eric Holk1868de92020-02-12 09:10:21 -08001989 DexCompilationUnit dex_compilation_unit(
1990 class_loader,
1991 class_linker,
1992 callee_dex_file,
1993 code_item,
1994 resolved_method->GetDeclaringClass()->GetDexClassDefIndex(),
1995 method_index,
1996 resolved_method->GetAccessFlags(),
1997 /* verified_method= */ nullptr,
1998 dex_cache,
1999 compiling_class);
2000
2001 InvokeType invoke_type = invoke_instruction->GetInvokeType();
2002 if (invoke_type == kInterface) {
2003 // We have statically resolved the dispatch. To please the class linker
2004 // at runtime, we change this call as if it was a virtual call.
2005 invoke_type = kVirtual;
2006 }
2007
2008 bool caller_dead_reference_safe = graph_->IsDeadReferenceSafe();
2009 const dex::ClassDef& callee_class = resolved_method->GetClassDef();
2010 // MethodContainsRSensitiveAccess is currently slow, but HasDeadReferenceSafeAnnotation()
2011 // is currently rarely true.
2012 bool callee_dead_reference_safe =
2013 annotations::HasDeadReferenceSafeAnnotation(callee_dex_file, callee_class)
2014 && !annotations::MethodContainsRSensitiveAccess(callee_dex_file, callee_class, method_index);
2015
2016 const int32_t caller_instruction_counter = graph_->GetCurrentInstructionId();
2017 HGraph* callee_graph = new (graph_->GetAllocator()) HGraph(
2018 graph_->GetAllocator(),
2019 graph_->GetArenaStack(),
Vladimir Marko02ca05a2020-05-12 13:58:51 +01002020 graph_->GetHandleCache()->GetHandles(),
Eric Holk1868de92020-02-12 09:10:21 -08002021 callee_dex_file,
2022 method_index,
2023 codegen_->GetCompilerOptions().GetInstructionSet(),
2024 invoke_type,
2025 callee_dead_reference_safe,
2026 graph_->IsDebuggable(),
Nicolas Geoffray0d60a2b2020-06-17 14:31:56 +01002027 graph_->GetCompilationKind(),
Eric Holk1868de92020-02-12 09:10:21 -08002028 /* start_instruction_id= */ caller_instruction_counter);
2029 callee_graph->SetArtMethod(resolved_method);
2030
Nicolas Geoffray9e598902021-11-19 14:53:07 +00002031 ScopedProfilingInfoUse spiu(Runtime::Current()->GetJit(), resolved_method, Thread::Current());
2032 if (Runtime::Current()->GetJit() != nullptr) {
2033 callee_graph->SetProfilingInfo(spiu.GetProfilingInfo());
2034 }
2035
Eric Holk1868de92020-02-12 09:10:21 -08002036 // When they are needed, allocate `inline_stats_` on the Arena instead
2037 // of on the stack, as Clang might produce a stack frame too large
2038 // for this function, that would not fit the requirements of the
2039 // `-Wframe-larger-than` option.
2040 if (stats_ != nullptr) {
2041 // Reuse one object for all inline attempts from this caller to keep Arena memory usage low.
2042 if (inline_stats_ == nullptr) {
2043 void* storage = graph_->GetAllocator()->Alloc<OptimizingCompilerStats>(kArenaAllocMisc);
2044 inline_stats_ = new (storage) OptimizingCompilerStats;
2045 } else {
2046 inline_stats_->Reset();
2047 }
2048 }
2049 HGraphBuilder builder(callee_graph,
2050 code_item_accessor,
2051 &dex_compilation_unit,
2052 &outer_compilation_unit_,
2053 codegen_,
Nicolas Geoffray4924ea92021-03-23 08:25:31 +00002054 inline_stats_);
Eric Holk1868de92020-02-12 09:10:21 -08002055
2056 if (builder.BuildGraph() != kAnalysisSuccess) {
2057 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedCannotBuild)
2058 << "Method " << callee_dex_file.PrettyMethod(method_index)
2059 << " could not be built, so cannot be inlined";
2060 return false;
2061 }
2062
2063 SubstituteArguments(callee_graph, invoke_instruction, receiver_type, dex_compilation_unit);
2064
2065 RunOptimizations(callee_graph, code_item, dex_compilation_unit);
2066
2067 size_t number_of_instructions = 0;
Santiago Aboy Solanes8ed39492022-07-20 11:13:39 +01002068 if (!CanInlineBody(callee_graph, invoke_instruction, &number_of_instructions)) {
Eric Holk1868de92020-02-12 09:10:21 -08002069 return false;
2070 }
2071
David Brazdil3f523062016-02-29 16:53:33 +00002072 DCHECK_EQ(caller_instruction_counter, graph_->GetCurrentInstructionId())
2073 << "No instructions can be added to the outer graph while inner graph is being built";
2074
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00002075 // Inline the callee graph inside the caller graph.
David Brazdil3f523062016-02-29 16:53:33 +00002076 const int32_t callee_instruction_counter = callee_graph->GetCurrentInstructionId();
2077 graph_->SetCurrentInstructionId(callee_instruction_counter);
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00002078 *return_replacement = callee_graph->InlineInto(graph_, invoke_instruction);
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00002079 // Update our budget for other inlining attempts in `caller_graph`.
2080 total_number_of_instructions_ += number_of_instructions;
2081 UpdateInliningBudget();
David Brazdil3f523062016-02-29 16:53:33 +00002082
2083 DCHECK_EQ(callee_instruction_counter, callee_graph->GetCurrentInstructionId())
2084 << "No instructions can be added to the inner graph during inlining into the outer graph";
2085
Vladimir Marko438709f2017-02-23 18:56:13 +00002086 if (stats_ != nullptr) {
2087 DCHECK(inline_stats_ != nullptr);
2088 inline_stats_->AddTo(stats_);
2089 }
2090
Hans Boehm206348c2018-12-05 11:11:33 -08002091 if (caller_dead_reference_safe && !callee_dead_reference_safe) {
2092 // Caller was dead reference safe, but is not anymore, since we inlined dead
2093 // reference unsafe code. Prior transformations remain valid, since they did not
2094 // affect the inlined code.
2095 graph_->MarkDeadReferenceUnsafe();
2096 }
2097
Vladimir Markobe10e8e2016-01-22 12:09:44 +00002098 return true;
2099}
Calin Juravle2e768302015-07-28 14:41:11 +00002100
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00002101void HInliner::RunOptimizations(HGraph* callee_graph,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08002102 const dex::CodeItem* code_item,
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00002103 const DexCompilationUnit& dex_compilation_unit) {
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01002104 // Note: if the outermost_graph_ is being compiled OSR, we should not run any
2105 // optimization that could lead to a HDeoptimize. The following optimizations do not.
Vladimir Marko438709f2017-02-23 18:56:13 +00002106 HDeadCodeElimination dce(callee_graph, inline_stats_, "dead_code_elimination$inliner");
Santiago Aboy Solanes8c3b58a2022-08-15 13:21:59 +00002107 HConstantFolding fold(callee_graph, inline_stats_, "constant_folding$inliner");
Vladimir Markobb089b62018-06-28 17:30:16 +01002108 InstructionSimplifier simplify(callee_graph, codegen_, inline_stats_);
Roland Levillaina3aef2e2016-04-06 17:45:58 +01002109
2110 HOptimization* optimizations[] = {
Roland Levillaina3aef2e2016-04-06 17:45:58 +01002111 &simplify,
2112 &fold,
2113 &dce,
2114 };
2115
2116 for (size_t i = 0; i < arraysize(optimizations); ++i) {
2117 HOptimization* optimization = optimizations[i];
2118 optimization->Run();
2119 }
2120
Santiago Aboy Solanes33a31292021-09-24 08:50:06 +00002121 // Bail early for pathological cases on the environment (for example recursive calls,
2122 // or too large environment).
2123 if (total_number_of_dex_registers_ > kMaximumNumberOfCumulatedDexRegisters) {
2124 LOG_NOTE() << "Calls in " << callee_graph->GetArtMethod()->PrettyMethod()
2125 << " will not be inlined because the outer method has reached"
2126 << " its environment budget limit.";
2127 return;
2128 }
2129
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00002130 // Bail early if we know we already are over the limit.
2131 size_t number_of_instructions = CountNumberOfInstructions(callee_graph);
2132 if (number_of_instructions > inlining_budget_) {
2133 LOG_NOTE() << "Calls in " << callee_graph->GetArtMethod()->PrettyMethod()
2134 << " will not be inlined because the outer method has reached"
2135 << " its instruction budget limit. " << number_of_instructions;
2136 return;
2137 }
2138
Mathieu Chartier698ebbc2018-01-05 11:00:42 -08002139 CodeItemDataAccessor accessor(callee_graph->GetDexFile(), code_item);
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00002140 HInliner inliner(callee_graph,
2141 outermost_graph_,
2142 codegen_,
2143 outer_compilation_unit_,
2144 dex_compilation_unit,
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00002145 inline_stats_,
Mathieu Chartier808c7a52017-12-15 11:19:33 -08002146 total_number_of_dex_registers_ + accessor.RegistersSize(),
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00002147 total_number_of_instructions_ + number_of_instructions,
2148 this,
2149 depth_ + 1);
2150 inliner.Run();
Roland Levillaina3aef2e2016-04-06 17:45:58 +01002151}
2152
Vladimir Marko5a62af52020-05-11 15:16:24 +01002153static bool IsReferenceTypeRefinement(ObjPtr<mirror::Class> declared_class,
2154 bool declared_is_exact,
David Brazdil94ab38f2016-06-21 17:48:19 +01002155 bool declared_can_be_null,
2156 HInstruction* actual_obj)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002157 REQUIRES_SHARED(Locks::mutator_lock_) {
David Brazdil94ab38f2016-06-21 17:48:19 +01002158 if (declared_can_be_null && !actual_obj->CanBeNull()) {
2159 return true;
2160 }
2161
2162 ReferenceTypeInfo actual_rti = actual_obj->GetReferenceTypeInfo();
Vladimir Marko5a62af52020-05-11 15:16:24 +01002163 ObjPtr<mirror::Class> actual_class = actual_rti.GetTypeHandle().Get();
2164 return (actual_rti.IsExact() && !declared_is_exact) ||
2165 (declared_class != actual_class && declared_class->IsAssignableFrom(actual_class));
David Brazdil94ab38f2016-06-21 17:48:19 +01002166}
2167
Vladimir Marko5a62af52020-05-11 15:16:24 +01002168static bool IsReferenceTypeRefinement(ObjPtr<mirror::Class> declared_class,
2169 bool declared_can_be_null,
2170 HInstruction* actual_obj)
2171 REQUIRES_SHARED(Locks::mutator_lock_) {
2172 bool admissible = ReferenceTypePropagation::IsAdmissible(declared_class);
2173 return IsReferenceTypeRefinement(
2174 admissible ? declared_class : GetClassRoot<mirror::Class>(),
2175 /*declared_is_exact=*/ admissible && declared_class->CannotBeAssignedFromOtherTypes(),
2176 declared_can_be_null,
2177 actual_obj);
David Brazdil94ab38f2016-06-21 17:48:19 +01002178}
2179
2180bool HInliner::ArgumentTypesMoreSpecific(HInvoke* invoke_instruction, ArtMethod* resolved_method) {
2181 // If this is an instance call, test whether the type of the `this` argument
2182 // is more specific than the class which declares the method.
2183 if (!resolved_method->IsStatic()) {
Vladimir Marko5a62af52020-05-11 15:16:24 +01002184 if (IsReferenceTypeRefinement(resolved_method->GetDeclaringClass(),
2185 /*declared_can_be_null=*/ false,
David Brazdil94ab38f2016-06-21 17:48:19 +01002186 invoke_instruction->InputAt(0u))) {
2187 return true;
2188 }
2189 }
2190
David Brazdil94ab38f2016-06-21 17:48:19 +01002191 // Iterate over the list of parameter types and test whether any of the
2192 // actual inputs has a more specific reference type than the type declared in
2193 // the signature.
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08002194 const dex::TypeList* param_list = resolved_method->GetParameterTypeList();
David Brazdil94ab38f2016-06-21 17:48:19 +01002195 for (size_t param_idx = 0,
2196 input_idx = resolved_method->IsStatic() ? 0 : 1,
2197 e = (param_list == nullptr ? 0 : param_list->Size());
2198 param_idx < e;
2199 ++param_idx, ++input_idx) {
2200 HInstruction* input = invoke_instruction->InputAt(input_idx);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002201 if (input->GetType() == DataType::Type::kReference) {
Vladimir Markob45528c2017-07-27 14:14:28 +01002202 ObjPtr<mirror::Class> param_cls = resolved_method->LookupResolvedClassFromTypeIndex(
2203 param_list->GetTypeItem(param_idx).type_idx_);
Vladimir Marko5a62af52020-05-11 15:16:24 +01002204 if (IsReferenceTypeRefinement(param_cls, /*declared_can_be_null=*/ true, input)) {
David Brazdil94ab38f2016-06-21 17:48:19 +01002205 return true;
2206 }
2207 }
2208 }
2209
2210 return false;
2211}
2212
Nicolas Geoffraye1e0e0f2021-04-29 08:57:13 +00002213bool HInliner::ReturnTypeMoreSpecific(HInstruction* return_replacement,
2214 HInvoke* invoke_instruction) {
Alex Light68289a52015-12-15 17:30:30 -08002215 // Check the integrity of reference types and run another type propagation if needed.
David Brazdil4833f5a2015-12-16 10:37:39 +00002216 if (return_replacement != nullptr) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002217 if (return_replacement->GetType() == DataType::Type::kReference) {
David Brazdil94ab38f2016-06-21 17:48:19 +01002218 // Test if the return type is a refinement of the declared return type.
Vladimir Marko5a62af52020-05-11 15:16:24 +01002219 ReferenceTypeInfo invoke_rti = invoke_instruction->GetReferenceTypeInfo();
2220 if (IsReferenceTypeRefinement(invoke_rti.GetTypeHandle().Get(),
2221 invoke_rti.IsExact(),
2222 /*declared_can_be_null=*/ true,
David Brazdil94ab38f2016-06-21 17:48:19 +01002223 return_replacement)) {
2224 return true;
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00002225 } else if (return_replacement->IsInstanceFieldGet()) {
2226 HInstanceFieldGet* field_get = return_replacement->AsInstanceFieldGet();
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00002227 if (field_get->GetFieldInfo().GetField() ==
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002228 GetClassRoot<mirror::Object>()->GetInstanceField(0)) {
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00002229 return true;
2230 }
David Brazdil94ab38f2016-06-21 17:48:19 +01002231 }
2232 } else if (return_replacement->IsInstanceOf()) {
2233 // Inlining InstanceOf into an If may put a tighter bound on reference types.
2234 return true;
2235 }
2236 }
2237
2238 return false;
2239}
2240
2241void HInliner::FixUpReturnReferenceType(ArtMethod* resolved_method,
2242 HInstruction* return_replacement) {
2243 if (return_replacement != nullptr) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002244 if (return_replacement->GetType() == DataType::Type::kReference) {
David Brazdil4833f5a2015-12-16 10:37:39 +00002245 if (!return_replacement->GetReferenceTypeInfo().IsValid()) {
2246 // Make sure that we have a valid type for the return. We may get an invalid one when
2247 // we inline invokes with multiple branches and create a Phi for the result.
2248 // TODO: we could be more precise by merging the phi inputs but that requires
2249 // some functionality from the reference type propagation.
2250 DCHECK(return_replacement->IsPhi());
Vladimir Markob45528c2017-07-27 14:14:28 +01002251 ObjPtr<mirror::Class> cls = resolved_method->LookupResolvedReturnType();
Vladimir Marko5a62af52020-05-11 15:16:24 +01002252 ReferenceTypeInfo rti = ReferenceTypePropagation::IsAdmissible(cls)
Vladimir Marko02ca05a2020-05-12 13:58:51 +01002253 ? ReferenceTypeInfo::Create(graph_->GetHandleCache()->NewHandle(cls))
Vladimir Marko5a62af52020-05-11 15:16:24 +01002254 : graph_->GetInexactObjectRti();
2255 return_replacement->SetReferenceTypeInfo(rti);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01002256 }
Calin Juravlecdfed3d2015-10-26 14:05:01 +00002257 }
Calin Juravle2e768302015-07-28 14:41:11 +00002258 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002259}
2260
2261} // namespace art