blob: 7f94a298eb8515221cc3193d13a604f37b6baa17 [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"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000021#include "builder.h"
22#include "class_linker.h"
Vladimir Markob4eb1b12018-05-24 11:09:38 +010023#include "class_root.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000024#include "constant_folding.h"
Vladimir Marko0ebe0d82017-09-21 22:50:39 +010025#include "data_type-inl.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000026#include "dead_code_elimination.h"
Andreas Gampeb95c74b2017-04-20 19:43:21 -070027#include "dex/inline_method_analyser.h"
Vladimir Markobe10e8e2016-01-22 12:09:44 +000028#include "dex/verification_results.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070029#include "dex/verified_method.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000030#include "driver/compiler_driver-inl.h"
Calin Juravleec748352015-07-29 13:52:12 +010031#include "driver/compiler_options.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000032#include "driver/dex_compilation_unit.h"
33#include "instruction_simplifier.h"
Scott Wakelingd60a1af2015-07-22 14:32:44 +010034#include "intrinsics.h"
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +000035#include "jit/jit.h"
36#include "jit/jit_code_cache.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000037#include "mirror/class_loader.h"
38#include "mirror/dex_cache.h"
39#include "nodes.h"
Nicolas Geoffray335005e2015-06-25 10:01:47 +010040#include "optimizing_compiler.h"
Nicolas Geoffray454a4812015-06-09 10:37:32 +010041#include "reference_type_propagation.h"
Matthew Gharritye9288852016-07-14 14:08:16 -070042#include "register_allocator_linear_scan.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070043#include "scoped_thread_state_change-inl.h"
Vladimir Markodc151b22015-10-15 18:02:30 +010044#include "sharpening.h"
David Brazdil4833f5a2015-12-16 10:37:39 +000045#include "ssa_builder.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000046#include "ssa_phi_elimination.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000047#include "thread.h"
48
49namespace art {
50
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +000051// Instruction limit to control memory.
52static constexpr size_t kMaximumNumberOfTotalInstructions = 1024;
53
54// Maximum number of instructions for considering a method small,
55// which we will always try to inline if the other non-instruction limits
56// are not reached.
57static constexpr size_t kMaximumNumberOfInstructionsForSmallMethod = 3;
Nicolas Geoffray5949fa02015-12-18 10:57:10 +000058
59// Limit the number of dex registers that we accumulate while inlining
60// to avoid creating large amount of nested environments.
Nicolas Geoffrayf81621e2017-06-07 13:18:03 +010061static constexpr size_t kMaximumNumberOfCumulatedDexRegisters = 32;
Nicolas Geoffray5949fa02015-12-18 10:57:10 +000062
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +000063// Limit recursive call inlining, which do not benefit from too
64// much inlining compared to code locality.
65static constexpr size_t kMaximumNumberOfRecursiveCalls = 4;
Nicolas Geoffraye418dda2015-08-11 20:03:09 -070066
Calin Juravlee2492d42017-03-20 11:42:13 -070067// Controls the use of inline caches in AOT mode.
Calin Juravle8af70892017-03-28 15:31:44 -070068static constexpr bool kUseAOTInlineCaches = true;
Calin Juravlee2492d42017-03-20 11:42:13 -070069
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +000070// We check for line numbers to make sure the DepthString implementation
71// aligns the output nicely.
72#define LOG_INTERNAL(msg) \
73 static_assert(__LINE__ > 10, "Unhandled line number"); \
74 static_assert(__LINE__ < 10000, "Unhandled line number"); \
75 VLOG(compiler) << DepthString(__LINE__) << msg
76
77#define LOG_TRY() LOG_INTERNAL("Try inlinining call: ")
78#define LOG_NOTE() LOG_INTERNAL("Note: ")
79#define LOG_SUCCESS() LOG_INTERNAL("Success: ")
Igor Murashkin1e065a52017-08-09 13:20:34 -070080#define LOG_FAIL(stats_ptr, stat) MaybeRecordStat(stats_ptr, stat); LOG_INTERNAL("Fail: ")
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +000081#define LOG_FAIL_NO_STAT() LOG_INTERNAL("Fail: ")
82
83std::string HInliner::DepthString(int line) const {
84 std::string value;
85 // Indent according to the inlining depth.
86 size_t count = depth_;
87 // Line numbers get printed in the log, so add a space if the log's line is less
88 // than 1000, and two if less than 100. 10 cannot be reached as it's the copyright.
89 if (!kIsTargetBuild) {
90 if (line < 100) {
91 value += " ";
92 }
93 if (line < 1000) {
94 value += " ";
95 }
96 // Safeguard if this file reaches more than 10000 lines.
97 DCHECK_LT(line, 10000);
98 }
99 for (size_t i = 0; i < count; ++i) {
100 value += " ";
101 }
102 return value;
103}
104
105static size_t CountNumberOfInstructions(HGraph* graph) {
106 size_t number_of_instructions = 0;
107 for (HBasicBlock* block : graph->GetReversePostOrderSkipEntryBlock()) {
108 for (HInstructionIterator instr_it(block->GetInstructions());
109 !instr_it.Done();
110 instr_it.Advance()) {
111 ++number_of_instructions;
112 }
113 }
114 return number_of_instructions;
115}
116
117void HInliner::UpdateInliningBudget() {
118 if (total_number_of_instructions_ >= kMaximumNumberOfTotalInstructions) {
119 // Always try to inline small methods.
120 inlining_budget_ = kMaximumNumberOfInstructionsForSmallMethod;
121 } else {
122 inlining_budget_ = std::max(
123 kMaximumNumberOfInstructionsForSmallMethod,
124 kMaximumNumberOfTotalInstructions - total_number_of_instructions_);
125 }
126}
127
Aart Bik24773202018-04-26 10:28:51 -0700128bool HInliner::Run() {
Vladimir Marko213ee2d2018-06-22 11:56:34 +0100129 if (codegen_->GetCompilerOptions().GetInlineMaxCodeUnits() == 0) {
Aart Bik24773202018-04-26 10:28:51 -0700130 // Inlining effectively disabled.
131 return false;
132 } else if (graph_->IsDebuggable()) {
Nicolas Geoffraye50b8d22015-03-13 08:57:42 +0000133 // For simplicity, we currently never inline when the graph is debuggable. This avoids
134 // doing some logic in the runtime to discover if a method could have been inlined.
Aart Bik24773202018-04-26 10:28:51 -0700135 return false;
Nicolas Geoffraye50b8d22015-03-13 08:57:42 +0000136 }
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000137
Aart Bik24773202018-04-26 10:28:51 -0700138 bool didInline = false;
139
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000140 // Initialize the number of instructions for the method being compiled. Recursive calls
141 // to HInliner::Run have already updated the instruction count.
142 if (outermost_graph_ == graph_) {
143 total_number_of_instructions_ = CountNumberOfInstructions(graph_);
144 }
145
146 UpdateInliningBudget();
147 DCHECK_NE(total_number_of_instructions_, 0u);
148 DCHECK_NE(inlining_budget_, 0u);
149
Roland Levillain6c3af162017-04-27 11:18:56 +0100150 // If we're compiling with a core image (which is only used for
151 // test purposes), honor inlining directives in method names:
152 // - if a method's name contains the substring "$inline$", ensure
153 // that this method is actually inlined;
154 // - if a method's name contains the substring "$noinline$", do not
155 // inline that method.
Vladimir Markobe0c7cf2018-03-19 13:40:56 +0000156 // We limit the latter to AOT compilation, as the JIT may or may not inline
Nicolas Geoffray08490b82017-07-18 12:58:10 +0100157 // depending on the state of classes at runtime.
Vladimir Markobe0c7cf2018-03-19 13:40:56 +0000158 const bool honor_noinline_directives = IsCompilingWithCoreImage();
159 const bool honor_inline_directives =
160 honor_noinline_directives && Runtime::Current()->IsAotCompiler();
Roland Levillain6c3af162017-04-27 11:18:56 +0100161
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +0000162 // Keep a copy of all blocks when starting the visit.
163 ArenaVector<HBasicBlock*> blocks = graph_->GetReversePostOrder();
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100164 DCHECK(!blocks.empty());
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +0000165 // Because we are changing the graph when inlining,
166 // we just iterate over the blocks of the outer method.
167 // This avoids doing the inlining work again on the inlined blocks.
168 for (HBasicBlock* block : blocks) {
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +0000169 for (HInstruction* instruction = block->GetFirstInstruction(); instruction != nullptr;) {
170 HInstruction* next = instruction->GetNext();
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100171 HInvoke* call = instruction->AsInvoke();
Razvan A Lupusoru3e90a962015-03-27 13:44:44 -0700172 // As long as the call is not intrinsified, it is worth trying to inline.
173 if (call != nullptr && call->GetIntrinsic() == Intrinsics::kNone) {
Vladimir Markobe0c7cf2018-03-19 13:40:56 +0000174 if (honor_noinline_directives) {
Nicolas Geoffrayb703d182017-02-14 18:05:28 +0000175 // Debugging case: directives in method names control or assert on inlining.
176 std::string callee_name = outer_compilation_unit_.GetDexFile()->PrettyMethod(
177 call->GetDexMethodIndex(), /* with_signature */ false);
178 // Tests prevent inlining by having $noinline$ in their method names.
179 if (callee_name.find("$noinline$") == std::string::npos) {
Aart Bik24773202018-04-26 10:28:51 -0700180 if (TryInline(call)) {
181 didInline = true;
Aart Bik54e45c52018-04-27 13:57:21 -0700182 } else if (honor_inline_directives) {
Nicolas Geoffray1949baf2017-10-17 12:14:53 +0000183 bool should_have_inlined = (callee_name.find("$inline$") != std::string::npos);
184 CHECK(!should_have_inlined) << "Could not inline " << callee_name;
Nicolas Geoffrayb703d182017-02-14 18:05:28 +0000185 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000186 }
Guillaume "Vermeille" Sancheze918d382015-06-03 15:32:41 +0100187 } else {
Vladimir Markobe0c7cf2018-03-19 13:40:56 +0000188 DCHECK(!honor_inline_directives);
Nicolas Geoffrayb703d182017-02-14 18:05:28 +0000189 // Normal case: try to inline.
Aart Bik24773202018-04-26 10:28:51 -0700190 if (TryInline(call)) {
191 didInline = true;
192 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000193 }
194 }
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +0000195 instruction = next;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000196 }
197 }
Aart Bik24773202018-04-26 10:28:51 -0700198
199 return didInline;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000200}
201
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100202static bool IsMethodOrDeclaringClassFinal(ArtMethod* method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700203 REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100204 return method->IsFinal() || method->GetDeclaringClass()->IsFinal();
205}
206
207/**
208 * Given the `resolved_method` looked up in the dex cache, try to find
209 * the actual runtime target of an interface or virtual call.
210 * Return nullptr if the runtime target cannot be proven.
211 */
212static ArtMethod* FindVirtualOrInterfaceTarget(HInvoke* invoke, ArtMethod* resolved_method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700213 REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100214 if (IsMethodOrDeclaringClassFinal(resolved_method)) {
215 // No need to lookup further, the resolved method will be the target.
216 return resolved_method;
217 }
218
219 HInstruction* receiver = invoke->InputAt(0);
220 if (receiver->IsNullCheck()) {
221 // Due to multiple levels of inlining within the same pass, it might be that
222 // null check does not have the reference type of the actual receiver.
223 receiver = receiver->InputAt(0);
224 }
225 ReferenceTypeInfo info = receiver->GetReferenceTypeInfo();
Calin Juravle2e768302015-07-28 14:41:11 +0000226 DCHECK(info.IsValid()) << "Invalid RTI for " << receiver->DebugName();
227 if (!info.IsExact()) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100228 // We currently only support inlining with known receivers.
229 // TODO: Remove this check, we should be able to inline final methods
230 // on unknown receivers.
231 return nullptr;
232 } else if (info.GetTypeHandle()->IsInterface()) {
233 // Statically knowing that the receiver has an interface type cannot
234 // help us find what is the target method.
235 return nullptr;
236 } else if (!resolved_method->GetDeclaringClass()->IsAssignableFrom(info.GetTypeHandle().Get())) {
237 // The method that we're trying to call is not in the receiver's class or super classes.
238 return nullptr;
Nicolas Geoffrayab5327d2016-03-18 11:36:20 +0000239 } else if (info.GetTypeHandle()->IsErroneous()) {
240 // If the type is erroneous, do not go further, as we are going to query the vtable or
241 // imt table, that we can only safely do on non-erroneous classes.
242 return nullptr;
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100243 }
244
245 ClassLinker* cl = Runtime::Current()->GetClassLinker();
Andreas Gampe542451c2016-07-26 09:02:02 -0700246 PointerSize pointer_size = cl->GetImagePointerSize();
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100247 if (invoke->IsInvokeInterface()) {
248 resolved_method = info.GetTypeHandle()->FindVirtualMethodForInterface(
249 resolved_method, pointer_size);
250 } else {
251 DCHECK(invoke->IsInvokeVirtual());
252 resolved_method = info.GetTypeHandle()->FindVirtualMethodForVirtual(
253 resolved_method, pointer_size);
254 }
255
256 if (resolved_method == nullptr) {
257 // The information we had on the receiver was not enough to find
258 // the target method. Since we check above the exact type of the receiver,
259 // the only reason this can happen is an IncompatibleClassChangeError.
260 return nullptr;
Alex Light9139e002015-10-09 15:59:48 -0700261 } else if (!resolved_method->IsInvokable()) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100262 // The information we had on the receiver was not enough to find
263 // the target method. Since we check above the exact type of the receiver,
264 // the only reason this can happen is an IncompatibleClassChangeError.
265 return nullptr;
266 } else if (IsMethodOrDeclaringClassFinal(resolved_method)) {
267 // A final method has to be the target method.
268 return resolved_method;
269 } else if (info.IsExact()) {
270 // If we found a method and the receiver's concrete type is statically
271 // known, we know for sure the target.
272 return resolved_method;
273 } else {
274 // Even if we did find a method, the receiver type was not enough to
275 // statically find the runtime target.
276 return nullptr;
277 }
278}
279
280static uint32_t FindMethodIndexIn(ArtMethod* method,
281 const DexFile& dex_file,
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +0000282 uint32_t name_and_signature_index)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700283 REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100284 if (IsSameDexFile(*method->GetDexFile(), dex_file)) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100285 return method->GetDexMethodIndex();
286 } else {
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +0000287 return method->FindDexMethodIndexInOtherDexFile(dex_file, name_and_signature_index);
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100288 }
289}
290
Andreas Gampea5b09a62016-11-17 15:21:22 -0800291static dex::TypeIndex FindClassIndexIn(mirror::Class* cls,
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000292 const DexCompilationUnit& compilation_unit)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700293 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000294 const DexFile& dex_file = *compilation_unit.GetDexFile();
Andreas Gampea5b09a62016-11-17 15:21:22 -0800295 dex::TypeIndex index;
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100296 if (cls->GetDexCache() == nullptr) {
David Sehr709b0702016-10-13 09:12:37 -0700297 DCHECK(cls->IsArrayClass()) << cls->PrettyClass();
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000298 index = cls->FindTypeIndexInOtherDexFile(dex_file);
Andreas Gampea5b09a62016-11-17 15:21:22 -0800299 } else if (!cls->GetDexTypeIndex().IsValid()) {
David Sehr709b0702016-10-13 09:12:37 -0700300 DCHECK(cls->IsProxyClass()) << cls->PrettyClass();
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100301 // TODO: deal with proxy classes.
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100302 } else if (IsSameDexFile(cls->GetDexFile(), dex_file)) {
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000303 DCHECK_EQ(cls->GetDexCache(), compilation_unit.GetDexCache().Get());
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000304 index = cls->GetDexTypeIndex();
Nicolas Geoffray491617a2016-07-19 17:06:23 +0100305 } else {
306 index = cls->FindTypeIndexInOtherDexFile(dex_file);
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000307 // We cannot guarantee the entry will resolve to the same class,
Nicolas Geoffray491617a2016-07-19 17:06:23 +0100308 // as there may be different class loaders. So only return the index if it's
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000309 // the right class already resolved with the class loader.
310 if (index.IsValid()) {
Vladimir Marko666ee3d2017-12-11 18:37:36 +0000311 ObjPtr<mirror::Class> resolved = compilation_unit.GetClassLinker()->LookupResolvedType(
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000312 index, compilation_unit.GetDexCache().Get(), compilation_unit.GetClassLoader().Get());
313 if (resolved != cls) {
314 index = dex::TypeIndex::Invalid();
315 }
Nicolas Geoffray491617a2016-07-19 17:06:23 +0100316 }
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100317 }
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000318
319 return index;
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100320}
321
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000322class ScopedProfilingInfoInlineUse {
323 public:
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000324 explicit ScopedProfilingInfoInlineUse(ArtMethod* method, Thread* self)
325 : method_(method),
326 self_(self),
327 // Fetch the profiling info ahead of using it. If it's null when fetching,
328 // we should not call JitCodeCache::DoneInlining.
329 profiling_info_(
330 Runtime::Current()->GetJit()->GetCodeCache()->NotifyCompilerUse(method, self)) {
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000331 }
332
333 ~ScopedProfilingInfoInlineUse() {
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000334 if (profiling_info_ != nullptr) {
Andreas Gampe542451c2016-07-26 09:02:02 -0700335 PointerSize pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000336 DCHECK_EQ(profiling_info_, method_->GetProfilingInfo(pointer_size));
337 Runtime::Current()->GetJit()->GetCodeCache()->DoneCompilerUse(method_, self_);
338 }
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000339 }
340
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000341 ProfilingInfo* GetProfilingInfo() const { return profiling_info_; }
342
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000343 private:
344 ArtMethod* const method_;
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000345 Thread* const self_;
346 ProfilingInfo* const profiling_info_;
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000347};
348
Calin Juravle13439f02017-02-21 01:17:21 -0800349HInliner::InlineCacheType HInliner::GetInlineCacheType(
350 const Handle<mirror::ObjectArray<mirror::Class>>& classes)
351 REQUIRES_SHARED(Locks::mutator_lock_) {
352 uint8_t number_of_types = 0;
353 for (; number_of_types < InlineCache::kIndividualCacheSize; ++number_of_types) {
354 if (classes->Get(number_of_types) == nullptr) {
355 break;
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000356 }
357 }
Calin Juravle13439f02017-02-21 01:17:21 -0800358
359 if (number_of_types == 0) {
360 return kInlineCacheUninitialized;
361 } else if (number_of_types == 1) {
362 return kInlineCacheMonomorphic;
363 } else if (number_of_types == InlineCache::kIndividualCacheSize) {
364 return kInlineCacheMegamorphic;
365 } else {
366 return kInlineCachePolymorphic;
367 }
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000368}
369
370static mirror::Class* GetMonomorphicType(Handle<mirror::ObjectArray<mirror::Class>> classes)
371 REQUIRES_SHARED(Locks::mutator_lock_) {
372 DCHECK(classes->Get(0) != nullptr);
373 return classes->Get(0);
374}
375
Mingyao Yang063fc772016-08-02 11:02:54 -0700376ArtMethod* HInliner::TryCHADevirtualization(ArtMethod* resolved_method) {
377 if (!resolved_method->HasSingleImplementation()) {
378 return nullptr;
379 }
380 if (Runtime::Current()->IsAotCompiler()) {
381 // No CHA-based devirtulization for AOT compiler (yet).
382 return nullptr;
383 }
384 if (outermost_graph_->IsCompilingOsr()) {
385 // We do not support HDeoptimize in OSR methods.
386 return nullptr;
387 }
Mingyao Yange8fcd012017-01-20 10:43:30 -0800388 PointerSize pointer_size = caller_compilation_unit_.GetClassLinker()->GetImagePointerSize();
Nicolas Geoffray18ea1c92017-03-27 08:00:18 +0000389 ArtMethod* single_impl = resolved_method->GetSingleImplementation(pointer_size);
390 if (single_impl == nullptr) {
391 return nullptr;
392 }
393 if (single_impl->IsProxyMethod()) {
394 // Proxy method is a generic invoker that's not worth
395 // devirtualizing/inlining. It also causes issues when the proxy
396 // method is in another dex file if we try to rewrite invoke-interface to
397 // invoke-virtual because a proxy method doesn't have a real dex file.
398 return nullptr;
399 }
Nicolas Geoffray8e33e842017-04-03 16:55:16 +0100400 if (!single_impl->GetDeclaringClass()->IsResolved()) {
401 // There's a race with the class loading, which updates the CHA info
402 // before setting the class to resolved. So we just bail for this
403 // rare occurence.
404 return nullptr;
405 }
Nicolas Geoffray18ea1c92017-03-27 08:00:18 +0000406 return single_impl;
Mingyao Yang063fc772016-08-02 11:02:54 -0700407}
408
Aart Bik2c148f02018-02-02 14:30:35 -0800409static bool IsMethodUnverified(CompilerDriver* const compiler_driver, ArtMethod* method)
David Sehr0225f8e2018-01-31 08:52:24 +0000410 REQUIRES_SHARED(Locks::mutator_lock_) {
Aart Bik2c148f02018-02-02 14:30:35 -0800411 if (!method->GetDeclaringClass()->IsVerified()) {
412 if (Runtime::Current()->UseJitCompilation()) {
413 // We're at runtime, we know this is cold code if the class
414 // is not verified, so don't bother analyzing.
415 return true;
416 }
417 uint16_t class_def_idx = method->GetDeclaringClass()->GetDexClassDefIndex();
418 if (!compiler_driver->IsMethodVerifiedWithoutFailures(
419 method->GetDexMethodIndex(), class_def_idx, *method->GetDexFile())) {
420 // Method has soft or hard failures, don't analyze.
421 return true;
422 }
423 }
424 return false;
425}
426
427static bool AlwaysThrows(CompilerDriver* const compiler_driver, ArtMethod* method)
428 REQUIRES_SHARED(Locks::mutator_lock_) {
429 DCHECK(method != nullptr);
430 // Skip non-compilable and unverified methods.
431 if (!method->IsCompilable() || IsMethodUnverified(compiler_driver, method)) {
432 return false;
433 }
Aart Bika8b8e9b2018-01-09 11:01:02 -0800434 // Skip native methods, methods with try blocks, and methods that are too large.
Aart Bik2c148f02018-02-02 14:30:35 -0800435 CodeItemDataAccessor accessor(method->DexInstructionData());
Aart Bika8b8e9b2018-01-09 11:01:02 -0800436 if (!accessor.HasCodeItem() ||
437 accessor.TriesSize() != 0 ||
438 accessor.InsnsSizeInCodeUnits() > kMaximumNumberOfTotalInstructions) {
439 return false;
440 }
441 // Scan for exits.
442 bool throw_seen = false;
443 for (const DexInstructionPcPair& pair : accessor) {
444 switch (pair.Inst().Opcode()) {
445 case Instruction::RETURN:
446 case Instruction::RETURN_VOID:
447 case Instruction::RETURN_WIDE:
448 case Instruction::RETURN_OBJECT:
449 case Instruction::RETURN_VOID_NO_BARRIER:
450 return false; // found regular control flow back
451 case Instruction::THROW:
452 throw_seen = true;
453 break;
454 default:
455 break;
456 }
457 }
458 return throw_seen;
459}
460
Nicolas Geoffraye418dda2015-08-11 20:03:09 -0700461bool HInliner::TryInline(HInvoke* invoke_instruction) {
Orion Hodsonac141392017-01-13 11:53:47 +0000462 if (invoke_instruction->IsInvokeUnresolved() ||
Orion Hodson4c8e12e2018-05-18 08:33:20 +0100463 invoke_instruction->IsInvokePolymorphic() ||
464 invoke_instruction->IsInvokeCustom()) {
465 return false; // Don't bother to move further if we know the method is unresolved or the
466 // invocation is polymorphic (invoke-{polymorphic,custom}).
Calin Juravle175dc732015-08-25 15:42:32 +0100467 }
468
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000469 ScopedObjectAccess soa(Thread::Current());
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +0100470 uint32_t method_index = invoke_instruction->GetDexMethodIndex();
Nicolas Geoffray9437b782015-03-25 10:08:51 +0000471 const DexFile& caller_dex_file = *caller_compilation_unit_.GetDexFile();
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000472 LOG_TRY() << caller_dex_file.PrettyMethod(method_index);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000473
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +0100474 ArtMethod* resolved_method = invoke_instruction->GetResolvedMethod();
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +0100475 if (resolved_method == nullptr) {
476 DCHECK(invoke_instruction->IsInvokeStaticOrDirect());
477 DCHECK(invoke_instruction->AsInvokeStaticOrDirect()->IsStringInit());
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000478 LOG_FAIL_NO_STAT() << "Not inlining a String.<init> method";
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +0100479 return false;
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000480 }
481 ArtMethod* actual_method = nullptr;
482
483 if (invoke_instruction->IsInvokeStaticOrDirect()) {
Andreas Gampefd2140f2015-12-23 16:30:44 -0800484 actual_method = resolved_method;
Vladimir Marko58155012015-08-19 12:49:41 +0000485 } else {
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +0100486 // Check if we can statically find the method.
487 actual_method = FindVirtualOrInterfaceTarget(invoke_instruction, resolved_method);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000488 }
489
Mingyao Yang063fc772016-08-02 11:02:54 -0700490 bool cha_devirtualize = false;
491 if (actual_method == nullptr) {
492 ArtMethod* method = TryCHADevirtualization(resolved_method);
493 if (method != nullptr) {
494 cha_devirtualize = true;
495 actual_method = method;
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000496 LOG_NOTE() << "Try CHA-based inlining of " << actual_method->PrettyMethod();
Mingyao Yang063fc772016-08-02 11:02:54 -0700497 }
498 }
499
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100500 if (actual_method != nullptr) {
Aart Bikd4e328f2018-01-16 14:14:34 -0800501 // Single target.
Mingyao Yang063fc772016-08-02 11:02:54 -0700502 bool result = TryInlineAndReplace(invoke_instruction,
503 actual_method,
Nicolas Geoffray0f001b72017-01-04 16:46:23 +0000504 ReferenceTypeInfo::CreateInvalid(),
Mingyao Yang063fc772016-08-02 11:02:54 -0700505 /* do_rtp */ true,
506 cha_devirtualize);
Aart Bikd4e328f2018-01-16 14:14:34 -0800507 if (result) {
508 // Successfully inlined.
509 if (!invoke_instruction->IsInvokeStaticOrDirect()) {
510 if (cha_devirtualize) {
511 // Add dependency due to devirtualization. We've assumed resolved_method
512 // has single implementation.
513 outermost_graph_->AddCHASingleImplementationDependency(resolved_method);
514 MaybeRecordStat(stats_, MethodCompilationStat::kCHAInline);
515 } else {
516 MaybeRecordStat(stats_, MethodCompilationStat::kInlinedInvokeVirtualOrInterface);
517 }
Mingyao Yang063fc772016-08-02 11:02:54 -0700518 }
Aart Bik2c148f02018-02-02 14:30:35 -0800519 } else if (!cha_devirtualize && AlwaysThrows(compiler_driver_, actual_method)) {
Aart Bikd4e328f2018-01-16 14:14:34 -0800520 // Set always throws property for non-inlined method call with single target
521 // (unless it was obtained through CHA, because that would imply we have
522 // to add the CHA dependency, which seems not worth it).
523 invoke_instruction->SetAlwaysThrows(true);
Calin Juravle69158982016-03-16 11:53:41 +0000524 }
525 return result;
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100526 }
Andreas Gampefd2140f2015-12-23 16:30:44 -0800527 DCHECK(!invoke_instruction->IsInvokeStaticOrDirect());
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100528
Calin Juravle13439f02017-02-21 01:17:21 -0800529 // Try using inline caches.
530 return TryInlineFromInlineCache(caller_dex_file, invoke_instruction, resolved_method);
531}
532
533static Handle<mirror::ObjectArray<mirror::Class>> AllocateInlineCacheHolder(
534 const DexCompilationUnit& compilation_unit,
535 StackHandleScope<1>* hs)
536 REQUIRES_SHARED(Locks::mutator_lock_) {
537 Thread* self = Thread::Current();
538 ClassLinker* class_linker = compilation_unit.GetClassLinker();
539 Handle<mirror::ObjectArray<mirror::Class>> inline_cache = hs->NewHandle(
540 mirror::ObjectArray<mirror::Class>::Alloc(
541 self,
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100542 GetClassRoot<mirror::ObjectArray<mirror::Class>>(class_linker),
Calin Juravle13439f02017-02-21 01:17:21 -0800543 InlineCache::kIndividualCacheSize));
544 if (inline_cache == nullptr) {
545 // We got an OOME. Just clear the exception, and don't inline.
546 DCHECK(self->IsExceptionPending());
547 self->ClearException();
548 VLOG(compiler) << "Out of memory in the compiler when trying to inline";
549 }
550 return inline_cache;
551}
552
Calin Juravleaf44e6c2017-05-23 14:24:55 -0700553bool HInliner::UseOnlyPolymorphicInliningWithNoDeopt() {
554 // If we are compiling AOT or OSR, pretend the call using inline caches is polymorphic and
555 // do not generate a deopt.
556 //
557 // For AOT:
558 // Generating a deopt does not ensure that we will actually capture the new types;
559 // and the danger is that we could be stuck in a loop with "forever" deoptimizations.
560 // Take for example the following scenario:
561 // - we capture the inline cache in one run
562 // - the next run, we deoptimize because we miss a type check, but the method
563 // never becomes hot again
564 // In this case, the inline cache will not be updated in the profile and the AOT code
565 // will keep deoptimizing.
566 // Another scenario is if we use profile compilation for a process which is not allowed
567 // to JIT (e.g. system server). If we deoptimize we will run interpreted code for the
568 // rest of the lifetime.
569 // TODO(calin):
570 // This is a compromise because we will most likely never update the inline cache
571 // in the profile (unless there's another reason to deopt). So we might be stuck with
572 // a sub-optimal inline cache.
573 // We could be smarter when capturing inline caches to mitigate this.
574 // (e.g. by having different thresholds for new and old methods).
575 //
576 // For OSR:
577 // We may come from the interpreter and it may have seen different receiver types.
578 return Runtime::Current()->IsAotCompiler() || outermost_graph_->IsCompilingOsr();
579}
Calin Juravle13439f02017-02-21 01:17:21 -0800580bool HInliner::TryInlineFromInlineCache(const DexFile& caller_dex_file,
581 HInvoke* invoke_instruction,
582 ArtMethod* resolved_method)
583 REQUIRES_SHARED(Locks::mutator_lock_) {
Calin Juravlee2492d42017-03-20 11:42:13 -0700584 if (Runtime::Current()->IsAotCompiler() && !kUseAOTInlineCaches) {
585 return false;
586 }
587
Calin Juravle13439f02017-02-21 01:17:21 -0800588 StackHandleScope<1> hs(Thread::Current());
589 Handle<mirror::ObjectArray<mirror::Class>> inline_cache;
590 InlineCacheType inline_cache_type = Runtime::Current()->IsAotCompiler()
591 ? GetInlineCacheAOT(caller_dex_file, invoke_instruction, &hs, &inline_cache)
592 : GetInlineCacheJIT(invoke_instruction, &hs, &inline_cache);
593
594 switch (inline_cache_type) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000595 case kInlineCacheNoData: {
596 LOG_FAIL_NO_STAT()
597 << "Interface or virtual call to "
598 << caller_dex_file.PrettyMethod(invoke_instruction->GetDexMethodIndex())
599 << " could not be statically determined";
Calin Juravle13439f02017-02-21 01:17:21 -0800600 return false;
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 kInlineCacheUninitialized: {
604 LOG_FAIL_NO_STAT()
605 << "Interface or virtual call to "
606 << caller_dex_file.PrettyMethod(invoke_instruction->GetDexMethodIndex())
607 << " is not hit and not inlined";
608 return false;
609 }
610
611 case kInlineCacheMonomorphic: {
Vladimir Markocd09e1f2017-11-24 15:02:40 +0000612 MaybeRecordStat(stats_, MethodCompilationStat::kMonomorphicCall);
Calin Juravleaf44e6c2017-05-23 14:24:55 -0700613 if (UseOnlyPolymorphicInliningWithNoDeopt()) {
Calin Juravle13439f02017-02-21 01:17:21 -0800614 return TryInlinePolymorphicCall(invoke_instruction, resolved_method, inline_cache);
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000615 } else {
Calin Juravle13439f02017-02-21 01:17:21 -0800616 return TryInlineMonomorphicCall(invoke_instruction, resolved_method, inline_cache);
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000617 }
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000618 }
Calin Juravle13439f02017-02-21 01:17:21 -0800619
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000620 case kInlineCachePolymorphic: {
Vladimir Markocd09e1f2017-11-24 15:02:40 +0000621 MaybeRecordStat(stats_, MethodCompilationStat::kPolymorphicCall);
Calin Juravle13439f02017-02-21 01:17:21 -0800622 return TryInlinePolymorphicCall(invoke_instruction, resolved_method, inline_cache);
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000623 }
Calin Juravle13439f02017-02-21 01:17:21 -0800624
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000625 case kInlineCacheMegamorphic: {
626 LOG_FAIL_NO_STAT()
627 << "Interface or virtual call to "
628 << caller_dex_file.PrettyMethod(invoke_instruction->GetDexMethodIndex())
629 << " is megamorphic and not inlined";
Vladimir Markocd09e1f2017-11-24 15:02:40 +0000630 MaybeRecordStat(stats_, MethodCompilationStat::kMegamorphicCall);
Calin Juravle13439f02017-02-21 01:17:21 -0800631 return false;
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000632 }
Calin Juravle13439f02017-02-21 01:17:21 -0800633
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000634 case kInlineCacheMissingTypes: {
635 LOG_FAIL_NO_STAT()
636 << "Interface or virtual call to "
637 << caller_dex_file.PrettyMethod(invoke_instruction->GetDexMethodIndex())
638 << " is missing types and not inlined";
Calin Juravle13439f02017-02-21 01:17:21 -0800639 return false;
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000640 }
Calin Juravle13439f02017-02-21 01:17:21 -0800641 }
642 UNREACHABLE();
643}
644
645HInliner::InlineCacheType HInliner::GetInlineCacheJIT(
646 HInvoke* invoke_instruction,
647 StackHandleScope<1>* hs,
648 /*out*/Handle<mirror::ObjectArray<mirror::Class>>* inline_cache)
649 REQUIRES_SHARED(Locks::mutator_lock_) {
650 DCHECK(Runtime::Current()->UseJitCompilation());
651
652 ArtMethod* caller = graph_->GetArtMethod();
653 // Under JIT, we should always know the caller.
654 DCHECK(caller != nullptr);
655 ScopedProfilingInfoInlineUse spiis(caller, Thread::Current());
656 ProfilingInfo* profiling_info = spiis.GetProfilingInfo();
657
658 if (profiling_info == nullptr) {
659 return kInlineCacheNoData;
660 }
661
662 *inline_cache = AllocateInlineCacheHolder(caller_compilation_unit_, hs);
663 if (inline_cache->Get() == nullptr) {
664 // We can't extract any data if we failed to allocate;
665 return kInlineCacheNoData;
666 } else {
667 Runtime::Current()->GetJit()->GetCodeCache()->CopyInlineCacheInto(
668 *profiling_info->GetInlineCache(invoke_instruction->GetDexPc()),
669 *inline_cache);
670 return GetInlineCacheType(*inline_cache);
671 }
672}
673
674HInliner::InlineCacheType HInliner::GetInlineCacheAOT(
675 const DexFile& caller_dex_file,
676 HInvoke* invoke_instruction,
677 StackHandleScope<1>* hs,
678 /*out*/Handle<mirror::ObjectArray<mirror::Class>>* inline_cache)
679 REQUIRES_SHARED(Locks::mutator_lock_) {
680 DCHECK(Runtime::Current()->IsAotCompiler());
681 const ProfileCompilationInfo* pci = compiler_driver_->GetProfileCompilationInfo();
682 if (pci == nullptr) {
683 return kInlineCacheNoData;
684 }
685
Calin Juravlecc3171a2017-05-19 16:47:53 -0700686 std::unique_ptr<ProfileCompilationInfo::OfflineProfileMethodInfo> offline_profile =
687 pci->GetMethod(caller_dex_file.GetLocation(),
688 caller_dex_file.GetLocationChecksum(),
689 caller_compilation_unit_.GetDexMethodIndex());
690 if (offline_profile == nullptr) {
Calin Juravle13439f02017-02-21 01:17:21 -0800691 return kInlineCacheNoData; // no profile information for this invocation.
692 }
693
694 *inline_cache = AllocateInlineCacheHolder(caller_compilation_unit_, hs);
695 if (inline_cache == nullptr) {
696 // We can't extract any data if we failed to allocate;
697 return kInlineCacheNoData;
698 } else {
699 return ExtractClassesFromOfflineProfile(invoke_instruction,
Calin Juravlecc3171a2017-05-19 16:47:53 -0700700 *(offline_profile.get()),
Calin Juravle13439f02017-02-21 01:17:21 -0800701 *inline_cache);
702 }
703}
704
705HInliner::InlineCacheType HInliner::ExtractClassesFromOfflineProfile(
706 const HInvoke* invoke_instruction,
707 const ProfileCompilationInfo::OfflineProfileMethodInfo& offline_profile,
708 /*out*/Handle<mirror::ObjectArray<mirror::Class>> inline_cache)
709 REQUIRES_SHARED(Locks::mutator_lock_) {
Calin Juravlee6f87cc2017-05-24 17:41:05 -0700710 const auto it = offline_profile.inline_caches->find(invoke_instruction->GetDexPc());
711 if (it == offline_profile.inline_caches->end()) {
Calin Juravle13439f02017-02-21 01:17:21 -0800712 return kInlineCacheUninitialized;
713 }
714
715 const ProfileCompilationInfo::DexPcData& dex_pc_data = it->second;
716
717 if (dex_pc_data.is_missing_types) {
718 return kInlineCacheMissingTypes;
719 }
720 if (dex_pc_data.is_megamorphic) {
721 return kInlineCacheMegamorphic;
722 }
723
724 DCHECK_LE(dex_pc_data.classes.size(), InlineCache::kIndividualCacheSize);
725 Thread* self = Thread::Current();
726 // We need to resolve the class relative to the containing dex file.
727 // So first, build a mapping from the index of dex file in the profile to
728 // its dex cache. This will avoid repeating the lookup when walking over
729 // the inline cache types.
730 std::vector<ObjPtr<mirror::DexCache>> dex_profile_index_to_dex_cache(
731 offline_profile.dex_references.size());
732 for (size_t i = 0; i < offline_profile.dex_references.size(); i++) {
733 bool found = false;
Vladimir Marko213ee2d2018-06-22 11:56:34 +0100734 for (const DexFile* dex_file : codegen_->GetCompilerOptions().GetDexFilesForOatFile()) {
Calin Juravle13439f02017-02-21 01:17:21 -0800735 if (offline_profile.dex_references[i].MatchesDex(dex_file)) {
736 dex_profile_index_to_dex_cache[i] =
737 caller_compilation_unit_.GetClassLinker()->FindDexCache(self, *dex_file);
738 found = true;
739 }
740 }
741 if (!found) {
742 VLOG(compiler) << "Could not find profiled dex file: "
743 << offline_profile.dex_references[i].dex_location;
744 return kInlineCacheMissingTypes;
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100745 }
746 }
747
Calin Juravle13439f02017-02-21 01:17:21 -0800748 // Walk over the classes and resolve them. If we cannot find a type we return
749 // kInlineCacheMissingTypes.
750 int ic_index = 0;
751 for (const ProfileCompilationInfo::ClassReference& class_ref : dex_pc_data.classes) {
752 ObjPtr<mirror::DexCache> dex_cache =
753 dex_profile_index_to_dex_cache[class_ref.dex_profile_index];
754 DCHECK(dex_cache != nullptr);
Calin Juravle08556882017-05-26 16:40:45 -0700755
756 if (!dex_cache->GetDexFile()->IsTypeIndexValid(class_ref.type_index)) {
757 VLOG(compiler) << "Profile data corrupt: type index " << class_ref.type_index
758 << "is invalid in location" << dex_cache->GetDexFile()->GetLocation();
759 return kInlineCacheNoData;
760 }
Vladimir Marko666ee3d2017-12-11 18:37:36 +0000761 ObjPtr<mirror::Class> clazz = caller_compilation_unit_.GetClassLinker()->LookupResolvedType(
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000762 class_ref.type_index,
763 dex_cache,
764 caller_compilation_unit_.GetClassLoader().Get());
Calin Juravle13439f02017-02-21 01:17:21 -0800765 if (clazz != nullptr) {
766 inline_cache->Set(ic_index++, clazz);
767 } else {
768 VLOG(compiler) << "Could not resolve class from inline cache in AOT mode "
769 << caller_compilation_unit_.GetDexFile()->PrettyMethod(
770 invoke_instruction->GetDexMethodIndex()) << " : "
771 << caller_compilation_unit_
772 .GetDexFile()->StringByTypeIdx(class_ref.type_index);
773 return kInlineCacheMissingTypes;
774 }
775 }
776 return GetInlineCacheType(inline_cache);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100777}
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000778
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000779HInstanceFieldGet* HInliner::BuildGetReceiverClass(ClassLinker* class_linker,
780 HInstruction* receiver,
781 uint32_t dex_pc) const {
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100782 ArtField* field = GetClassRoot<mirror::Object>(class_linker)->GetInstanceField(0);
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000783 DCHECK_EQ(std::string(field->GetName()), "shadow$_klass_");
Vladimir Markoca6fff82017-10-03 14:49:14 +0100784 HInstanceFieldGet* result = new (graph_->GetAllocator()) HInstanceFieldGet(
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000785 receiver,
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +0000786 field,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100787 DataType::Type::kReference,
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000788 field->GetOffset(),
789 field->IsVolatile(),
790 field->GetDexFieldIndex(),
791 field->GetDeclaringClass()->GetDexClassDefIndex(),
792 *field->GetDexFile(),
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000793 dex_pc);
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000794 // The class of a field is effectively final, and does not have any memory dependencies.
795 result->SetSideEffects(SideEffects::None());
796 return result;
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000797}
798
Nicolas Geoffray4c0b4bc2017-03-17 13:08:26 +0000799static ArtMethod* ResolveMethodFromInlineCache(Handle<mirror::Class> klass,
800 ArtMethod* resolved_method,
801 HInstruction* invoke_instruction,
802 PointerSize pointer_size)
803 REQUIRES_SHARED(Locks::mutator_lock_) {
804 if (Runtime::Current()->IsAotCompiler()) {
805 // We can get unrelated types when working with profiles (corruption,
806 // systme updates, or anyone can write to it). So first check if the class
807 // actually implements the declaring class of the method that is being
808 // called in bytecode.
809 // Note: the lookup methods used below require to have assignable types.
810 if (!resolved_method->GetDeclaringClass()->IsAssignableFrom(klass.Get())) {
811 return nullptr;
812 }
813 }
814
815 if (invoke_instruction->IsInvokeInterface()) {
816 resolved_method = klass->FindVirtualMethodForInterface(resolved_method, pointer_size);
817 } else {
818 DCHECK(invoke_instruction->IsInvokeVirtual());
819 resolved_method = klass->FindVirtualMethodForVirtual(resolved_method, pointer_size);
820 }
821 DCHECK(resolved_method != nullptr);
822 return resolved_method;
823}
824
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100825bool HInliner::TryInlineMonomorphicCall(HInvoke* invoke_instruction,
826 ArtMethod* resolved_method,
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000827 Handle<mirror::ObjectArray<mirror::Class>> classes) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000828 DCHECK(invoke_instruction->IsInvokeVirtual() || invoke_instruction->IsInvokeInterface())
829 << invoke_instruction->DebugName();
830
Andreas Gampea5b09a62016-11-17 15:21:22 -0800831 dex::TypeIndex class_index = FindClassIndexIn(
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000832 GetMonomorphicType(classes), caller_compilation_unit_);
Andreas Gampea5b09a62016-11-17 15:21:22 -0800833 if (!class_index.IsValid()) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +0000834 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedDexCache)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000835 << "Call to " << ArtMethod::PrettyMethod(resolved_method)
836 << " from inline cache is not inlined because its class is not"
837 << " accessible to the caller";
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100838 return false;
839 }
840
841 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
Andreas Gampe542451c2016-07-26 09:02:02 -0700842 PointerSize pointer_size = class_linker->GetImagePointerSize();
Nicolas Geoffray4c0b4bc2017-03-17 13:08:26 +0000843 Handle<mirror::Class> monomorphic_type = handles_->NewHandle(GetMonomorphicType(classes));
844 resolved_method = ResolveMethodFromInlineCache(
845 monomorphic_type, resolved_method, invoke_instruction, pointer_size);
846
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000847 LOG_NOTE() << "Try inline monomorphic call to " << resolved_method->PrettyMethod();
Nicolas Geoffray4c0b4bc2017-03-17 13:08:26 +0000848 if (resolved_method == nullptr) {
849 // Bogus AOT profile, bail.
850 DCHECK(Runtime::Current()->IsAotCompiler());
851 return false;
852 }
853
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100854 HInstruction* receiver = invoke_instruction->InputAt(0);
855 HInstruction* cursor = invoke_instruction->GetPrevious();
856 HBasicBlock* bb_cursor = invoke_instruction->GetBlock();
Mingyao Yang063fc772016-08-02 11:02:54 -0700857 if (!TryInlineAndReplace(invoke_instruction,
858 resolved_method,
Nicolas Geoffray5247c082017-01-13 14:17:29 +0000859 ReferenceTypeInfo::Create(monomorphic_type, /* is_exact */ true),
Mingyao Yang063fc772016-08-02 11:02:54 -0700860 /* do_rtp */ false,
861 /* cha_devirtualize */ false)) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100862 return false;
863 }
864
865 // We successfully inlined, now add a guard.
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000866 AddTypeGuard(receiver,
867 cursor,
868 bb_cursor,
869 class_index,
Nicolas Geoffray5247c082017-01-13 14:17:29 +0000870 monomorphic_type,
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000871 invoke_instruction,
872 /* with_deoptimization */ true);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100873
874 // Run type propagation to get the guard typed, and eventually propagate the
875 // type of the receiver.
Vladimir Marko456307a2016-04-19 14:12:13 +0000876 ReferenceTypePropagation rtp_fixup(graph_,
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000877 outer_compilation_unit_.GetClassLoader(),
Vladimir Marko456307a2016-04-19 14:12:13 +0000878 outer_compilation_unit_.GetDexCache(),
879 handles_,
880 /* is_first_run */ false);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100881 rtp_fixup.Run();
882
Vladimir Markocd09e1f2017-11-24 15:02:40 +0000883 MaybeRecordStat(stats_, MethodCompilationStat::kInlinedMonomorphicCall);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100884 return true;
885}
886
Mingyao Yang063fc772016-08-02 11:02:54 -0700887void HInliner::AddCHAGuard(HInstruction* invoke_instruction,
888 uint32_t dex_pc,
889 HInstruction* cursor,
890 HBasicBlock* bb_cursor) {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100891 HShouldDeoptimizeFlag* deopt_flag = new (graph_->GetAllocator())
892 HShouldDeoptimizeFlag(graph_->GetAllocator(), dex_pc);
893 HInstruction* compare = new (graph_->GetAllocator()) HNotEqual(
Mingyao Yang063fc772016-08-02 11:02:54 -0700894 deopt_flag, graph_->GetIntConstant(0, dex_pc));
Vladimir Markoca6fff82017-10-03 14:49:14 +0100895 HInstruction* deopt = new (graph_->GetAllocator()) HDeoptimize(
896 graph_->GetAllocator(), compare, DeoptimizationKind::kCHA, dex_pc);
Mingyao Yang063fc772016-08-02 11:02:54 -0700897
898 if (cursor != nullptr) {
899 bb_cursor->InsertInstructionAfter(deopt_flag, cursor);
900 } else {
901 bb_cursor->InsertInstructionBefore(deopt_flag, bb_cursor->GetFirstInstruction());
902 }
Mingyao Yangb0b051a2016-11-17 09:04:53 -0800903 bb_cursor->InsertInstructionAfter(compare, deopt_flag);
904 bb_cursor->InsertInstructionAfter(deopt, compare);
905
906 // Add receiver as input to aid CHA guard optimization later.
907 deopt_flag->AddInput(invoke_instruction->InputAt(0));
908 DCHECK_EQ(deopt_flag->InputCount(), 1u);
Mingyao Yang063fc772016-08-02 11:02:54 -0700909 deopt->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
Mingyao Yangb0b051a2016-11-17 09:04:53 -0800910 outermost_graph_->IncrementNumberOfCHAGuards();
Mingyao Yang063fc772016-08-02 11:02:54 -0700911}
912
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000913HInstruction* HInliner::AddTypeGuard(HInstruction* receiver,
914 HInstruction* cursor,
915 HBasicBlock* bb_cursor,
Andreas Gampea5b09a62016-11-17 15:21:22 -0800916 dex::TypeIndex class_index,
Nicolas Geoffray5247c082017-01-13 14:17:29 +0000917 Handle<mirror::Class> klass,
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000918 HInstruction* invoke_instruction,
919 bool with_deoptimization) {
920 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
921 HInstanceFieldGet* receiver_class = BuildGetReceiverClass(
922 class_linker, receiver, invoke_instruction->GetDexPc());
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000923 if (cursor != nullptr) {
924 bb_cursor->InsertInstructionAfter(receiver_class, cursor);
925 } else {
926 bb_cursor->InsertInstructionBefore(receiver_class, bb_cursor->GetFirstInstruction());
927 }
Nicolas Geoffray56876342016-12-16 16:09:08 +0000928
929 const DexFile& caller_dex_file = *caller_compilation_unit_.GetDexFile();
Calin Juravle07f01df2017-04-28 19:58:01 -0700930 bool is_referrer;
931 ArtMethod* outermost_art_method = outermost_graph_->GetArtMethod();
932 if (outermost_art_method == nullptr) {
933 DCHECK(Runtime::Current()->IsAotCompiler());
934 // We are in AOT mode and we don't have an ART method to determine
935 // if the inlined method belongs to the referrer. Assume it doesn't.
936 is_referrer = false;
937 } else {
938 is_referrer = klass.Get() == outermost_art_method->GetDeclaringClass();
939 }
940
Nicolas Geoffray56876342016-12-16 16:09:08 +0000941 // Note that we will just compare the classes, so we don't need Java semantics access checks.
942 // Note that the type index and the dex file are relative to the method this type guard is
943 // inlined into.
Vladimir Markoca6fff82017-10-03 14:49:14 +0100944 HLoadClass* load_class = new (graph_->GetAllocator()) HLoadClass(graph_->GetCurrentMethod(),
945 class_index,
946 caller_dex_file,
947 klass,
948 is_referrer,
949 invoke_instruction->GetDexPc(),
950 /* needs_access_check */ false);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +0000951 HLoadClass::LoadKind kind = HSharpening::ComputeLoadClassKind(
Vladimir Markobb089b62018-06-28 17:30:16 +0100952 load_class, codegen_, caller_compilation_unit_);
Nicolas Geoffray83c8e272017-01-31 14:36:37 +0000953 DCHECK(kind != HLoadClass::LoadKind::kInvalid)
954 << "We should always be able to reference a class for inline caches";
Vladimir Marko28e012a2017-12-07 11:22:59 +0000955 // Load kind must be set before inserting the instruction into the graph.
Nicolas Geoffray83c8e272017-01-31 14:36:37 +0000956 load_class->SetLoadKind(kind);
Vladimir Marko28e012a2017-12-07 11:22:59 +0000957 bb_cursor->InsertInstructionAfter(load_class, receiver_class);
Calin Juravle13439f02017-02-21 01:17:21 -0800958 // In AOT mode, we will most likely load the class from BSS, which will involve a call
959 // to the runtime. In this case, the load instruction will need an environment so copy
960 // it from the invoke instruction.
961 if (load_class->NeedsEnvironment()) {
962 DCHECK(Runtime::Current()->IsAotCompiler());
963 load_class->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
964 }
Nicolas Geoffray56876342016-12-16 16:09:08 +0000965
Vladimir Markoca6fff82017-10-03 14:49:14 +0100966 HNotEqual* compare = new (graph_->GetAllocator()) HNotEqual(load_class, receiver_class);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000967 bb_cursor->InsertInstructionAfter(compare, load_class);
968 if (with_deoptimization) {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100969 HDeoptimize* deoptimize = new (graph_->GetAllocator()) HDeoptimize(
970 graph_->GetAllocator(),
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +0000971 compare,
972 receiver,
Nicolas Geoffray4e92c3c2017-05-08 09:34:26 +0100973 Runtime::Current()->IsAotCompiler()
974 ? DeoptimizationKind::kAotInlineCache
975 : DeoptimizationKind::kJitInlineCache,
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +0000976 invoke_instruction->GetDexPc());
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000977 bb_cursor->InsertInstructionAfter(deoptimize, compare);
978 deoptimize->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +0000979 DCHECK_EQ(invoke_instruction->InputAt(0), receiver);
980 receiver->ReplaceUsesDominatedBy(deoptimize, deoptimize);
981 deoptimize->SetReferenceTypeInfo(receiver->GetReferenceTypeInfo());
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000982 }
983 return compare;
984}
985
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000986bool HInliner::TryInlinePolymorphicCall(HInvoke* invoke_instruction,
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100987 ArtMethod* resolved_method,
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000988 Handle<mirror::ObjectArray<mirror::Class>> classes) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000989 DCHECK(invoke_instruction->IsInvokeVirtual() || invoke_instruction->IsInvokeInterface())
990 << invoke_instruction->DebugName();
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000991
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000992 if (TryInlinePolymorphicCallToSameTarget(invoke_instruction, resolved_method, classes)) {
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000993 return true;
994 }
995
996 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
Andreas Gampe542451c2016-07-26 09:02:02 -0700997 PointerSize pointer_size = class_linker->GetImagePointerSize();
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000998
999 bool all_targets_inlined = true;
1000 bool one_target_inlined = false;
1001 for (size_t i = 0; i < InlineCache::kIndividualCacheSize; ++i) {
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +00001002 if (classes->Get(i) == nullptr) {
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001003 break;
1004 }
1005 ArtMethod* method = nullptr;
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001006
1007 Handle<mirror::Class> handle = handles_->NewHandle(classes->Get(i));
Nicolas Geoffray4c0b4bc2017-03-17 13:08:26 +00001008 method = ResolveMethodFromInlineCache(
1009 handle, resolved_method, invoke_instruction, pointer_size);
1010 if (method == nullptr) {
1011 DCHECK(Runtime::Current()->IsAotCompiler());
1012 // AOT profile is bogus. This loop expects to iterate over all entries,
1013 // so just just continue.
1014 all_targets_inlined = false;
1015 continue;
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001016 }
1017
1018 HInstruction* receiver = invoke_instruction->InputAt(0);
1019 HInstruction* cursor = invoke_instruction->GetPrevious();
1020 HBasicBlock* bb_cursor = invoke_instruction->GetBlock();
1021
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001022 dex::TypeIndex class_index = FindClassIndexIn(handle.Get(), caller_compilation_unit_);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001023 HInstruction* return_replacement = nullptr;
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001024 LOG_NOTE() << "Try inline polymorphic call to " << method->PrettyMethod();
Andreas Gampea5b09a62016-11-17 15:21:22 -08001025 if (!class_index.IsValid() ||
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001026 !TryBuildAndInline(invoke_instruction,
1027 method,
1028 ReferenceTypeInfo::Create(handle, /* is_exact */ true),
1029 &return_replacement)) {
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001030 all_targets_inlined = false;
1031 } else {
1032 one_target_inlined = true;
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001033
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001034 LOG_SUCCESS() << "Polymorphic call to " << ArtMethod::PrettyMethod(resolved_method)
1035 << " has inlined " << ArtMethod::PrettyMethod(method);
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00001036
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001037 // If we have inlined all targets before, and this receiver is the last seen,
1038 // we deoptimize instead of keeping the original invoke instruction.
Calin Juravleaf44e6c2017-05-23 14:24:55 -07001039 bool deoptimize = !UseOnlyPolymorphicInliningWithNoDeopt() &&
1040 all_targets_inlined &&
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001041 (i != InlineCache::kIndividualCacheSize - 1) &&
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +00001042 (classes->Get(i + 1) == nullptr);
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01001043
Nicolas Geoffray56876342016-12-16 16:09:08 +00001044 HInstruction* compare = AddTypeGuard(receiver,
1045 cursor,
1046 bb_cursor,
1047 class_index,
Nicolas Geoffray5247c082017-01-13 14:17:29 +00001048 handle,
Nicolas Geoffray56876342016-12-16 16:09:08 +00001049 invoke_instruction,
1050 deoptimize);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001051 if (deoptimize) {
1052 if (return_replacement != nullptr) {
1053 invoke_instruction->ReplaceWith(return_replacement);
1054 }
1055 invoke_instruction->GetBlock()->RemoveInstruction(invoke_instruction);
1056 // Because the inline cache data can be populated concurrently, we force the end of the
Nicolas Geoffray4c0b4bc2017-03-17 13:08:26 +00001057 // iteration. Otherwise, we could see a new receiver type.
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001058 break;
1059 } else {
1060 CreateDiamondPatternForPolymorphicInline(compare, return_replacement, invoke_instruction);
1061 }
1062 }
1063 }
1064
1065 if (!one_target_inlined) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001066 LOG_FAIL_NO_STAT()
1067 << "Call to " << ArtMethod::PrettyMethod(resolved_method)
1068 << " from inline cache is not inlined because none"
1069 << " of its targets could be inlined";
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001070 return false;
1071 }
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00001072
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001073 MaybeRecordStat(stats_, MethodCompilationStat::kInlinedPolymorphicCall);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001074
1075 // Run type propagation to get the guards typed.
Vladimir Marko456307a2016-04-19 14:12:13 +00001076 ReferenceTypePropagation rtp_fixup(graph_,
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001077 outer_compilation_unit_.GetClassLoader(),
Vladimir Marko456307a2016-04-19 14:12:13 +00001078 outer_compilation_unit_.GetDexCache(),
1079 handles_,
1080 /* is_first_run */ false);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001081 rtp_fixup.Run();
1082 return true;
1083}
1084
1085void HInliner::CreateDiamondPatternForPolymorphicInline(HInstruction* compare,
1086 HInstruction* return_replacement,
1087 HInstruction* invoke_instruction) {
1088 uint32_t dex_pc = invoke_instruction->GetDexPc();
1089 HBasicBlock* cursor_block = compare->GetBlock();
1090 HBasicBlock* original_invoke_block = invoke_instruction->GetBlock();
Vladimir Markoca6fff82017-10-03 14:49:14 +01001091 ArenaAllocator* allocator = graph_->GetAllocator();
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001092
1093 // Spit the block after the compare: `cursor_block` will now be the start of the diamond,
1094 // and the returned block is the start of the then branch (that could contain multiple blocks).
1095 HBasicBlock* then = cursor_block->SplitAfterForInlining(compare);
1096
1097 // Split the block containing the invoke before and after the invoke. The returned block
1098 // of the split before will contain the invoke and will be the otherwise branch of
1099 // the diamond. The returned block of the split after will be the merge block
1100 // of the diamond.
1101 HBasicBlock* end_then = invoke_instruction->GetBlock();
1102 HBasicBlock* otherwise = end_then->SplitBeforeForInlining(invoke_instruction);
1103 HBasicBlock* merge = otherwise->SplitAfterForInlining(invoke_instruction);
1104
1105 // If the methods we are inlining return a value, we create a phi in the merge block
1106 // that will have the `invoke_instruction and the `return_replacement` as inputs.
1107 if (return_replacement != nullptr) {
1108 HPhi* phi = new (allocator) HPhi(
1109 allocator, kNoRegNumber, 0, HPhi::ToPhiType(invoke_instruction->GetType()), dex_pc);
1110 merge->AddPhi(phi);
1111 invoke_instruction->ReplaceWith(phi);
1112 phi->AddInput(return_replacement);
1113 phi->AddInput(invoke_instruction);
1114 }
1115
1116 // Add the control flow instructions.
1117 otherwise->AddInstruction(new (allocator) HGoto(dex_pc));
1118 end_then->AddInstruction(new (allocator) HGoto(dex_pc));
1119 cursor_block->AddInstruction(new (allocator) HIf(compare, dex_pc));
1120
1121 // Add the newly created blocks to the graph.
1122 graph_->AddBlock(then);
1123 graph_->AddBlock(otherwise);
1124 graph_->AddBlock(merge);
1125
1126 // Set up successor (and implictly predecessor) relations.
1127 cursor_block->AddSuccessor(otherwise);
1128 cursor_block->AddSuccessor(then);
1129 end_then->AddSuccessor(merge);
1130 otherwise->AddSuccessor(merge);
1131
1132 // Set up dominance information.
1133 then->SetDominator(cursor_block);
1134 cursor_block->AddDominatedBlock(then);
1135 otherwise->SetDominator(cursor_block);
1136 cursor_block->AddDominatedBlock(otherwise);
1137 merge->SetDominator(cursor_block);
1138 cursor_block->AddDominatedBlock(merge);
1139
1140 // Update the revert post order.
1141 size_t index = IndexOfElement(graph_->reverse_post_order_, cursor_block);
1142 MakeRoomFor(&graph_->reverse_post_order_, 1, index);
1143 graph_->reverse_post_order_[++index] = then;
1144 index = IndexOfElement(graph_->reverse_post_order_, end_then);
1145 MakeRoomFor(&graph_->reverse_post_order_, 2, index);
1146 graph_->reverse_post_order_[++index] = otherwise;
1147 graph_->reverse_post_order_[++index] = merge;
1148
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001149
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00001150 graph_->UpdateLoopAndTryInformationOfNewBlock(
1151 then, original_invoke_block, /* replace_if_back_edge */ false);
1152 graph_->UpdateLoopAndTryInformationOfNewBlock(
1153 otherwise, original_invoke_block, /* replace_if_back_edge */ false);
1154
1155 // In case the original invoke location was a back edge, we need to update
1156 // the loop to now have the merge block as a back edge.
1157 graph_->UpdateLoopAndTryInformationOfNewBlock(
1158 merge, original_invoke_block, /* replace_if_back_edge */ true);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001159}
1160
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +00001161bool HInliner::TryInlinePolymorphicCallToSameTarget(
1162 HInvoke* invoke_instruction,
1163 ArtMethod* resolved_method,
1164 Handle<mirror::ObjectArray<mirror::Class>> classes) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001165 // This optimization only works under JIT for now.
Calin Juravle13439f02017-02-21 01:17:21 -08001166 if (!Runtime::Current()->UseJitCompilation()) {
1167 return false;
1168 }
1169
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001170 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
Andreas Gampe542451c2016-07-26 09:02:02 -07001171 PointerSize pointer_size = class_linker->GetImagePointerSize();
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001172
1173 DCHECK(resolved_method != nullptr);
1174 ArtMethod* actual_method = nullptr;
Nicolas Geoffray4f97a212016-02-25 16:17:54 +00001175 size_t method_index = invoke_instruction->IsInvokeVirtual()
1176 ? invoke_instruction->AsInvokeVirtual()->GetVTableIndex()
1177 : invoke_instruction->AsInvokeInterface()->GetImtIndex();
1178
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001179 // Check whether we are actually calling the same method among
1180 // the different types seen.
1181 for (size_t i = 0; i < InlineCache::kIndividualCacheSize; ++i) {
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +00001182 if (classes->Get(i) == nullptr) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001183 break;
1184 }
1185 ArtMethod* new_method = nullptr;
1186 if (invoke_instruction->IsInvokeInterface()) {
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +00001187 new_method = classes->Get(i)->GetImt(pointer_size)->Get(
Matthew Gharrity465ecc82016-07-19 21:32:52 +00001188 method_index, pointer_size);
Nicolas Geoffray4f97a212016-02-25 16:17:54 +00001189 if (new_method->IsRuntimeMethod()) {
1190 // Bail out as soon as we see a conflict trampoline in one of the target's
1191 // interface table.
1192 return false;
1193 }
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001194 } else {
1195 DCHECK(invoke_instruction->IsInvokeVirtual());
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +00001196 new_method = classes->Get(i)->GetEmbeddedVTableEntry(method_index, pointer_size);
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001197 }
Nicolas Geoffray4f97a212016-02-25 16:17:54 +00001198 DCHECK(new_method != nullptr);
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001199 if (actual_method == nullptr) {
1200 actual_method = new_method;
1201 } else if (actual_method != new_method) {
1202 // Different methods, bailout.
1203 return false;
1204 }
1205 }
1206
1207 HInstruction* receiver = invoke_instruction->InputAt(0);
1208 HInstruction* cursor = invoke_instruction->GetPrevious();
1209 HBasicBlock* bb_cursor = invoke_instruction->GetBlock();
1210
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01001211 HInstruction* return_replacement = nullptr;
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001212 if (!TryBuildAndInline(invoke_instruction,
1213 actual_method,
1214 ReferenceTypeInfo::CreateInvalid(),
1215 &return_replacement)) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001216 return false;
1217 }
1218
1219 // We successfully inlined, now add a guard.
1220 HInstanceFieldGet* receiver_class = BuildGetReceiverClass(
1221 class_linker, receiver, invoke_instruction->GetDexPc());
1222
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001223 DataType::Type type = Is64BitInstructionSet(graph_->GetInstructionSet())
1224 ? DataType::Type::kInt64
1225 : DataType::Type::kInt32;
Vladimir Markoca6fff82017-10-03 14:49:14 +01001226 HClassTableGet* class_table_get = new (graph_->GetAllocator()) HClassTableGet(
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001227 receiver_class,
1228 type,
Vladimir Markoa1de9182016-02-25 11:37:38 +00001229 invoke_instruction->IsInvokeVirtual() ? HClassTableGet::TableKind::kVTable
1230 : HClassTableGet::TableKind::kIMTable,
Nicolas Geoffray4f97a212016-02-25 16:17:54 +00001231 method_index,
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001232 invoke_instruction->GetDexPc());
1233
1234 HConstant* constant;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001235 if (type == DataType::Type::kInt64) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001236 constant = graph_->GetLongConstant(
1237 reinterpret_cast<intptr_t>(actual_method), invoke_instruction->GetDexPc());
1238 } else {
1239 constant = graph_->GetIntConstant(
1240 reinterpret_cast<intptr_t>(actual_method), invoke_instruction->GetDexPc());
1241 }
1242
Vladimir Markoca6fff82017-10-03 14:49:14 +01001243 HNotEqual* compare = new (graph_->GetAllocator()) HNotEqual(class_table_get, constant);
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001244 if (cursor != nullptr) {
1245 bb_cursor->InsertInstructionAfter(receiver_class, cursor);
1246 } else {
1247 bb_cursor->InsertInstructionBefore(receiver_class, bb_cursor->GetFirstInstruction());
1248 }
1249 bb_cursor->InsertInstructionAfter(class_table_get, receiver_class);
1250 bb_cursor->InsertInstructionAfter(compare, class_table_get);
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01001251
1252 if (outermost_graph_->IsCompilingOsr()) {
1253 CreateDiamondPatternForPolymorphicInline(compare, return_replacement, invoke_instruction);
1254 } else {
Vladimir Markoca6fff82017-10-03 14:49:14 +01001255 HDeoptimize* deoptimize = new (graph_->GetAllocator()) HDeoptimize(
1256 graph_->GetAllocator(),
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +00001257 compare,
1258 receiver,
Nicolas Geoffray4e92c3c2017-05-08 09:34:26 +01001259 DeoptimizationKind::kJitSameTarget,
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +00001260 invoke_instruction->GetDexPc());
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01001261 bb_cursor->InsertInstructionAfter(deoptimize, compare);
1262 deoptimize->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
1263 if (return_replacement != nullptr) {
1264 invoke_instruction->ReplaceWith(return_replacement);
1265 }
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +00001266 receiver->ReplaceUsesDominatedBy(deoptimize, deoptimize);
Nicolas Geoffray1be7cbd2016-04-29 13:56:01 +01001267 invoke_instruction->GetBlock()->RemoveInstruction(invoke_instruction);
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +00001268 deoptimize->SetReferenceTypeInfo(receiver->GetReferenceTypeInfo());
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01001269 }
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001270
1271 // Run type propagation to get the guard typed.
Vladimir Marko456307a2016-04-19 14:12:13 +00001272 ReferenceTypePropagation rtp_fixup(graph_,
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001273 outer_compilation_unit_.GetClassLoader(),
Vladimir Marko456307a2016-04-19 14:12:13 +00001274 outer_compilation_unit_.GetDexCache(),
1275 handles_,
1276 /* is_first_run */ false);
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001277 rtp_fixup.Run();
1278
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001279 MaybeRecordStat(stats_, MethodCompilationStat::kInlinedPolymorphicCall);
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001280
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001281 LOG_SUCCESS() << "Inlined same polymorphic target " << actual_method->PrettyMethod();
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001282 return true;
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001283}
1284
Mingyao Yang063fc772016-08-02 11:02:54 -07001285bool HInliner::TryInlineAndReplace(HInvoke* invoke_instruction,
1286 ArtMethod* method,
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001287 ReferenceTypeInfo receiver_type,
Mingyao Yang063fc772016-08-02 11:02:54 -07001288 bool do_rtp,
1289 bool cha_devirtualize) {
Mingyao Yang6b1aebe2017-11-27 15:39:04 -08001290 DCHECK(!invoke_instruction->IsIntrinsic());
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001291 HInstruction* return_replacement = nullptr;
Mingyao Yang063fc772016-08-02 11:02:54 -07001292 uint32_t dex_pc = invoke_instruction->GetDexPc();
1293 HInstruction* cursor = invoke_instruction->GetPrevious();
1294 HBasicBlock* bb_cursor = invoke_instruction->GetBlock();
Mingyao Yang6b1aebe2017-11-27 15:39:04 -08001295 bool should_remove_invoke_instruction = false;
1296
1297 // If invoke_instruction is devirtualized to a different method, give intrinsics
1298 // another chance before we try to inline it.
Nicolas Geoffray76d4bb0f32018-09-21 12:58:45 +01001299 if (invoke_instruction->GetResolvedMethod() != method && method->IsIntrinsic()) {
Mingyao Yang6b1aebe2017-11-27 15:39:04 -08001300 MaybeRecordStat(stats_, MethodCompilationStat::kIntrinsicRecognized);
1301 if (invoke_instruction->IsInvokeInterface()) {
1302 // We don't intrinsify an invoke-interface directly.
1303 // Replace the invoke-interface with an invoke-virtual.
1304 HInvokeVirtual* new_invoke = new (graph_->GetAllocator()) HInvokeVirtual(
1305 graph_->GetAllocator(),
1306 invoke_instruction->GetNumberOfArguments(),
1307 invoke_instruction->GetType(),
1308 invoke_instruction->GetDexPc(),
1309 invoke_instruction->GetDexMethodIndex(), // Use interface method's dex method index.
1310 method,
1311 method->GetMethodIndex());
Nicolas Geoffray76d4bb0f32018-09-21 12:58:45 +01001312 DCHECK_NE(new_invoke->GetIntrinsic(), Intrinsics::kNone);
Mingyao Yang6b1aebe2017-11-27 15:39:04 -08001313 HInputsRef inputs = invoke_instruction->GetInputs();
1314 for (size_t index = 0; index != inputs.size(); ++index) {
1315 new_invoke->SetArgumentAt(index, inputs[index]);
1316 }
1317 invoke_instruction->GetBlock()->InsertInstructionBefore(new_invoke, invoke_instruction);
1318 new_invoke->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
1319 if (invoke_instruction->GetType() == DataType::Type::kReference) {
1320 new_invoke->SetReferenceTypeInfo(invoke_instruction->GetReferenceTypeInfo());
1321 }
Mingyao Yang6b1aebe2017-11-27 15:39:04 -08001322 return_replacement = new_invoke;
1323 // invoke_instruction is replaced with new_invoke.
1324 should_remove_invoke_instruction = true;
1325 } else {
Nicolas Geoffray76d4bb0f32018-09-21 12:58:45 +01001326 invoke_instruction->SetResolvedMethod(method);
Mingyao Yang6b1aebe2017-11-27 15:39:04 -08001327 }
1328 } else if (!TryBuildAndInline(invoke_instruction, method, receiver_type, &return_replacement)) {
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +00001329 if (invoke_instruction->IsInvokeInterface()) {
Nicolas Geoffray18ea1c92017-03-27 08:00:18 +00001330 DCHECK(!method->IsProxyMethod());
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +00001331 // Turn an invoke-interface into an invoke-virtual. An invoke-virtual is always
1332 // better than an invoke-interface because:
1333 // 1) In the best case, the interface call has one more indirection (to fetch the IMT).
1334 // 2) We will not go to the conflict trampoline with an invoke-virtual.
1335 // TODO: Consider sharpening once it is not dependent on the compiler driver.
Nicolas Geoffray18ea1c92017-03-27 08:00:18 +00001336
1337 if (method->IsDefault() && !method->IsCopied()) {
1338 // Changing to invoke-virtual cannot be done on an original default method
1339 // since it's not in any vtable. Devirtualization by exact type/inline-cache
1340 // always uses a method in the iftable which is never an original default
1341 // method.
1342 // On the other hand, inlining an original default method by CHA is fine.
1343 DCHECK(cha_devirtualize);
1344 return false;
1345 }
1346
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +00001347 const DexFile& caller_dex_file = *caller_compilation_unit_.GetDexFile();
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +01001348 uint32_t dex_method_index = FindMethodIndexIn(
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +00001349 method, caller_dex_file, invoke_instruction->GetDexMethodIndex());
Andreas Gampee2abbc62017-09-15 11:59:26 -07001350 if (dex_method_index == dex::kDexNoIndex) {
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +00001351 return false;
1352 }
Vladimir Markoca6fff82017-10-03 14:49:14 +01001353 HInvokeVirtual* new_invoke = new (graph_->GetAllocator()) HInvokeVirtual(
1354 graph_->GetAllocator(),
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +00001355 invoke_instruction->GetNumberOfArguments(),
1356 invoke_instruction->GetType(),
1357 invoke_instruction->GetDexPc(),
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +01001358 dex_method_index,
1359 method,
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +00001360 method->GetMethodIndex());
1361 HInputsRef inputs = invoke_instruction->GetInputs();
1362 for (size_t index = 0; index != inputs.size(); ++index) {
1363 new_invoke->SetArgumentAt(index, inputs[index]);
1364 }
1365 invoke_instruction->GetBlock()->InsertInstructionBefore(new_invoke, invoke_instruction);
1366 new_invoke->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001367 if (invoke_instruction->GetType() == DataType::Type::kReference) {
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +00001368 new_invoke->SetReferenceTypeInfo(invoke_instruction->GetReferenceTypeInfo());
1369 }
1370 return_replacement = new_invoke;
Mingyao Yang6b1aebe2017-11-27 15:39:04 -08001371 // invoke_instruction is replaced with new_invoke.
1372 should_remove_invoke_instruction = true;
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +00001373 } else {
1374 // TODO: Consider sharpening an invoke virtual once it is not dependent on the
1375 // compiler driver.
1376 return false;
1377 }
Mingyao Yang6b1aebe2017-11-27 15:39:04 -08001378 } else {
1379 // invoke_instruction is inlined.
1380 should_remove_invoke_instruction = true;
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001381 }
Mingyao Yang6b1aebe2017-11-27 15:39:04 -08001382
Mingyao Yang063fc772016-08-02 11:02:54 -07001383 if (cha_devirtualize) {
1384 AddCHAGuard(invoke_instruction, dex_pc, cursor, bb_cursor);
1385 }
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001386 if (return_replacement != nullptr) {
1387 invoke_instruction->ReplaceWith(return_replacement);
1388 }
Mingyao Yang6b1aebe2017-11-27 15:39:04 -08001389 if (should_remove_invoke_instruction) {
1390 invoke_instruction->GetBlock()->RemoveInstruction(invoke_instruction);
1391 }
David Brazdil94ab38f2016-06-21 17:48:19 +01001392 FixUpReturnReferenceType(method, return_replacement);
1393 if (do_rtp && ReturnTypeMoreSpecific(invoke_instruction, return_replacement)) {
1394 // Actual return value has a more specific type than the method's declared
1395 // return type. Run RTP again on the outer graph to propagate it.
1396 ReferenceTypePropagation(graph_,
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001397 outer_compilation_unit_.GetClassLoader(),
David Brazdil94ab38f2016-06-21 17:48:19 +01001398 outer_compilation_unit_.GetDexCache(),
1399 handles_,
1400 /* is_first_run */ false).Run();
1401 }
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001402 return true;
1403}
1404
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001405size_t HInliner::CountRecursiveCallsOf(ArtMethod* method) const {
1406 const HInliner* current = this;
1407 size_t count = 0;
1408 do {
1409 if (current->graph_->GetArtMethod() == method) {
1410 ++count;
1411 }
1412 current = current->parent_;
1413 } while (current != nullptr);
1414 return count;
1415}
1416
Vladimir Marko213ee2d2018-06-22 11:56:34 +01001417static inline bool MayInline(const CompilerOptions& compiler_options,
1418 const DexFile& inlined_from,
1419 const DexFile& inlined_into) {
1420 if (kIsTargetBuild) {
1421 return true;
1422 }
1423
1424 // We're not allowed to inline across dex files if we're the no-inline-from dex file.
1425 if (!IsSameDexFile(inlined_from, inlined_into) &&
1426 ContainsElement(compiler_options.GetNoInlineFromDexFile(), &inlined_from)) {
1427 return false;
1428 }
1429
1430 return true;
1431}
1432
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001433bool HInliner::TryBuildAndInline(HInvoke* invoke_instruction,
1434 ArtMethod* method,
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001435 ReferenceTypeInfo receiver_type,
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001436 HInstruction** return_replacement) {
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01001437 if (method->IsProxyMethod()) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001438 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedProxy)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001439 << "Method " << method->PrettyMethod()
1440 << " is not inlined because of unimplemented inline support for proxy methods.";
1441 return false;
1442 }
1443
1444 if (CountRecursiveCallsOf(method) > kMaximumNumberOfRecursiveCalls) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001445 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedRecursiveBudget)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001446 << "Method "
1447 << method->PrettyMethod()
1448 << " is not inlined because it has reached its recursive call budget.";
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01001449 return false;
1450 }
1451
Jeff Haodcdc85b2015-12-04 14:06:18 -08001452 // Check whether we're allowed to inline. The outermost compilation unit is the relevant
1453 // dex file here (though the transitivity of an inline chain would allow checking the calller).
Vladimir Marko213ee2d2018-06-22 11:56:34 +01001454 if (!MayInline(codegen_->GetCompilerOptions(),
1455 *method->GetDexFile(),
1456 *outer_compilation_unit_.GetDexFile())) {
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001457 if (TryPatternSubstitution(invoke_instruction, method, return_replacement)) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001458 LOG_SUCCESS() << "Successfully replaced pattern of invoke "
1459 << method->PrettyMethod();
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001460 MaybeRecordStat(stats_, MethodCompilationStat::kReplacedInvokeWithSimplePattern);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001461 return true;
1462 }
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001463 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedWont)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001464 << "Won't inline " << method->PrettyMethod() << " in "
1465 << outer_compilation_unit_.GetDexFile()->GetLocation() << " ("
1466 << caller_compilation_unit_.GetDexFile()->GetLocation() << ") from "
1467 << method->GetDexFile()->GetLocation();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001468 return false;
1469 }
1470
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001471 bool same_dex_file = IsSameDexFile(*outer_compilation_unit_.GetDexFile(), *method->GetDexFile());
1472
David Sehr0225f8e2018-01-31 08:52:24 +00001473 CodeItemDataAccessor accessor(method->DexInstructionData());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001474
Mathieu Chartier808c7a52017-12-15 11:19:33 -08001475 if (!accessor.HasCodeItem()) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001476 LOG_FAIL_NO_STAT()
1477 << "Method " << method->PrettyMethod() << " is not inlined because it is native";
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001478 return false;
1479 }
1480
Vladimir Marko213ee2d2018-06-22 11:56:34 +01001481 size_t inline_max_code_units = codegen_->GetCompilerOptions().GetInlineMaxCodeUnits();
Mathieu Chartier808c7a52017-12-15 11:19:33 -08001482 if (accessor.InsnsSizeInCodeUnits() > inline_max_code_units) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001483 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedCodeItem)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001484 << "Method " << method->PrettyMethod()
1485 << " is not inlined because its code item is too big: "
Mathieu Chartier808c7a52017-12-15 11:19:33 -08001486 << accessor.InsnsSizeInCodeUnits()
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001487 << " > "
1488 << inline_max_code_units;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001489 return false;
1490 }
1491
Mathieu Chartier808c7a52017-12-15 11:19:33 -08001492 if (accessor.TriesSize() != 0) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001493 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedTryCatch)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001494 << "Method " << method->PrettyMethod() << " is not inlined because of try block";
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001495 return false;
1496 }
1497
Nicolas Geoffray250a3782016-04-20 16:27:53 +01001498 if (!method->IsCompilable()) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001499 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedNotVerified)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001500 << "Method " << method->PrettyMethod()
1501 << " has soft failures un-handled by the compiler, so it cannot be inlined";
Aart Bik897df032018-02-07 13:29:11 -08001502 return false;
Nicolas Geoffray250a3782016-04-20 16:27:53 +01001503 }
1504
Aart Bik2c148f02018-02-02 14:30:35 -08001505 if (IsMethodUnverified(compiler_driver_, method)) {
1506 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedNotVerified)
1507 << "Method " << method->PrettyMethod()
1508 << " couldn't be verified, so it cannot be inlined";
1509 return false;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001510 }
1511
Roland Levillain4c0eb422015-04-24 16:43:49 +01001512 if (invoke_instruction->IsInvokeStaticOrDirect() &&
1513 invoke_instruction->AsInvokeStaticOrDirect()->IsStaticWithImplicitClinitCheck()) {
1514 // Case of a static method that cannot be inlined because it implicitly
1515 // requires an initialization check of its declaring class.
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001516 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedDexCache)
1517 << "Method " << method->PrettyMethod()
1518 << " is not inlined because it is static and requires a clinit"
1519 << " check that cannot be emitted due to Dex cache limitations";
Roland Levillain4c0eb422015-04-24 16:43:49 +01001520 return false;
1521 }
1522
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001523 if (!TryBuildAndInlineHelper(
1524 invoke_instruction, method, receiver_type, same_dex_file, return_replacement)) {
Nicolas Geoffrayc0365b12015-03-18 18:31:52 +00001525 return false;
1526 }
1527
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001528 LOG_SUCCESS() << method->PrettyMethod();
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001529 MaybeRecordStat(stats_, MethodCompilationStat::kInlinedInvoke);
Nicolas Geoffrayc0365b12015-03-18 18:31:52 +00001530 return true;
1531}
1532
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001533static HInstruction* GetInvokeInputForArgVRegIndex(HInvoke* invoke_instruction,
1534 size_t arg_vreg_index)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001535 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001536 size_t input_index = 0;
1537 for (size_t i = 0; i < arg_vreg_index; ++i, ++input_index) {
1538 DCHECK_LT(input_index, invoke_instruction->GetNumberOfArguments());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001539 if (DataType::Is64BitType(invoke_instruction->InputAt(input_index)->GetType())) {
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001540 ++i;
1541 DCHECK_NE(i, arg_vreg_index);
1542 }
1543 }
1544 DCHECK_LT(input_index, invoke_instruction->GetNumberOfArguments());
1545 return invoke_instruction->InputAt(input_index);
1546}
1547
1548// Try to recognize known simple patterns and replace invoke call with appropriate instructions.
1549bool HInliner::TryPatternSubstitution(HInvoke* invoke_instruction,
1550 ArtMethod* resolved_method,
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001551 HInstruction** return_replacement) {
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001552 InlineMethod inline_method;
1553 if (!InlineMethodAnalyser::AnalyseMethodCode(resolved_method, &inline_method)) {
1554 return false;
1555 }
1556
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001557 switch (inline_method.opcode) {
1558 case kInlineOpNop:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001559 DCHECK_EQ(invoke_instruction->GetType(), DataType::Type::kVoid);
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001560 *return_replacement = nullptr;
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001561 break;
1562 case kInlineOpReturnArg:
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001563 *return_replacement = GetInvokeInputForArgVRegIndex(invoke_instruction,
1564 inline_method.d.return_data.arg);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001565 break;
1566 case kInlineOpNonWideConst:
1567 if (resolved_method->GetShorty()[0] == 'L') {
1568 DCHECK_EQ(inline_method.d.data, 0u);
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001569 *return_replacement = graph_->GetNullConstant();
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001570 } else {
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001571 *return_replacement = graph_->GetIntConstant(static_cast<int32_t>(inline_method.d.data));
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001572 }
1573 break;
1574 case kInlineOpIGet: {
1575 const InlineIGetIPutData& data = inline_method.d.ifield_data;
1576 if (data.method_is_static || data.object_arg != 0u) {
1577 // TODO: Needs null check.
1578 return false;
1579 }
1580 HInstruction* obj = GetInvokeInputForArgVRegIndex(invoke_instruction, data.object_arg);
Vladimir Markof44d36c2017-03-14 14:18:46 +00001581 HInstanceFieldGet* iget = CreateInstanceFieldGet(data.field_idx, resolved_method, obj);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001582 DCHECK_EQ(iget->GetFieldOffset().Uint32Value(), data.field_offset);
1583 DCHECK_EQ(iget->IsVolatile() ? 1u : 0u, data.is_volatile);
1584 invoke_instruction->GetBlock()->InsertInstructionBefore(iget, invoke_instruction);
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001585 *return_replacement = iget;
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001586 break;
1587 }
1588 case kInlineOpIPut: {
1589 const InlineIGetIPutData& data = inline_method.d.ifield_data;
1590 if (data.method_is_static || data.object_arg != 0u) {
1591 // TODO: Needs null check.
1592 return false;
1593 }
1594 HInstruction* obj = GetInvokeInputForArgVRegIndex(invoke_instruction, data.object_arg);
1595 HInstruction* value = GetInvokeInputForArgVRegIndex(invoke_instruction, data.src_arg);
Vladimir Markof44d36c2017-03-14 14:18:46 +00001596 HInstanceFieldSet* iput = CreateInstanceFieldSet(data.field_idx, resolved_method, obj, value);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001597 DCHECK_EQ(iput->GetFieldOffset().Uint32Value(), data.field_offset);
1598 DCHECK_EQ(iput->IsVolatile() ? 1u : 0u, data.is_volatile);
1599 invoke_instruction->GetBlock()->InsertInstructionBefore(iput, invoke_instruction);
1600 if (data.return_arg_plus1 != 0u) {
1601 size_t return_arg = data.return_arg_plus1 - 1u;
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001602 *return_replacement = GetInvokeInputForArgVRegIndex(invoke_instruction, return_arg);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001603 }
1604 break;
1605 }
Vladimir Marko354efa62016-02-04 19:46:56 +00001606 case kInlineOpConstructor: {
1607 const InlineConstructorData& data = inline_method.d.constructor_data;
1608 // Get the indexes to arrays for easier processing.
1609 uint16_t iput_field_indexes[] = {
1610 data.iput0_field_index, data.iput1_field_index, data.iput2_field_index
1611 };
1612 uint16_t iput_args[] = { data.iput0_arg, data.iput1_arg, data.iput2_arg };
1613 static_assert(arraysize(iput_args) == arraysize(iput_field_indexes), "Size mismatch");
1614 // Count valid field indexes.
1615 size_t number_of_iputs = 0u;
1616 while (number_of_iputs != arraysize(iput_field_indexes) &&
1617 iput_field_indexes[number_of_iputs] != DexFile::kDexNoIndex16) {
1618 // Check that there are no duplicate valid field indexes.
1619 DCHECK_EQ(0, std::count(iput_field_indexes + number_of_iputs + 1,
1620 iput_field_indexes + arraysize(iput_field_indexes),
1621 iput_field_indexes[number_of_iputs]));
1622 ++number_of_iputs;
1623 }
1624 // Check that there are no valid field indexes in the rest of the array.
1625 DCHECK_EQ(0, std::count_if(iput_field_indexes + number_of_iputs,
1626 iput_field_indexes + arraysize(iput_field_indexes),
1627 [](uint16_t index) { return index != DexFile::kDexNoIndex16; }));
1628
1629 // Create HInstanceFieldSet for each IPUT that stores non-zero data.
Vladimir Marko354efa62016-02-04 19:46:56 +00001630 HInstruction* obj = GetInvokeInputForArgVRegIndex(invoke_instruction, /* this */ 0u);
1631 bool needs_constructor_barrier = false;
1632 for (size_t i = 0; i != number_of_iputs; ++i) {
1633 HInstruction* value = GetInvokeInputForArgVRegIndex(invoke_instruction, iput_args[i]);
Roland Levillain1a653882016-03-18 18:05:57 +00001634 if (!value->IsConstant() || !value->AsConstant()->IsZeroBitPattern()) {
Vladimir Marko354efa62016-02-04 19:46:56 +00001635 uint16_t field_index = iput_field_indexes[i];
Vladimir Markof44d36c2017-03-14 14:18:46 +00001636 bool is_final;
1637 HInstanceFieldSet* iput =
1638 CreateInstanceFieldSet(field_index, resolved_method, obj, value, &is_final);
Vladimir Marko354efa62016-02-04 19:46:56 +00001639 invoke_instruction->GetBlock()->InsertInstructionBefore(iput, invoke_instruction);
1640
1641 // Check whether the field is final. If it is, we need to add a barrier.
Vladimir Markof44d36c2017-03-14 14:18:46 +00001642 if (is_final) {
Vladimir Marko354efa62016-02-04 19:46:56 +00001643 needs_constructor_barrier = true;
1644 }
1645 }
1646 }
1647 if (needs_constructor_barrier) {
Igor Murashkind01745e2017-04-05 16:40:31 -07001648 // See CompilerDriver::RequiresConstructorBarrier for more details.
1649 DCHECK(obj != nullptr) << "only non-static methods can have a constructor fence";
1650
1651 HConstructorFence* constructor_fence =
Vladimir Markoca6fff82017-10-03 14:49:14 +01001652 new (graph_->GetAllocator()) HConstructorFence(obj, kNoDexPc, graph_->GetAllocator());
Igor Murashkind01745e2017-04-05 16:40:31 -07001653 invoke_instruction->GetBlock()->InsertInstructionBefore(constructor_fence,
1654 invoke_instruction);
Vladimir Marko354efa62016-02-04 19:46:56 +00001655 }
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001656 *return_replacement = nullptr;
Vladimir Marko354efa62016-02-04 19:46:56 +00001657 break;
1658 }
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001659 default:
1660 LOG(FATAL) << "UNREACHABLE";
1661 UNREACHABLE();
1662 }
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001663 return true;
1664}
1665
Vladimir Markof44d36c2017-03-14 14:18:46 +00001666HInstanceFieldGet* HInliner::CreateInstanceFieldGet(uint32_t field_index,
1667 ArtMethod* referrer,
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001668 HInstruction* obj)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001669 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markof44d36c2017-03-14 14:18:46 +00001670 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1671 ArtField* resolved_field =
1672 class_linker->LookupResolvedField(field_index, referrer, /* is_static */ false);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001673 DCHECK(resolved_field != nullptr);
Vladimir Markoca6fff82017-10-03 14:49:14 +01001674 HInstanceFieldGet* iget = new (graph_->GetAllocator()) HInstanceFieldGet(
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001675 obj,
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00001676 resolved_field,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001677 DataType::FromShorty(resolved_field->GetTypeDescriptor()[0]),
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001678 resolved_field->GetOffset(),
1679 resolved_field->IsVolatile(),
1680 field_index,
1681 resolved_field->GetDeclaringClass()->GetDexClassDefIndex(),
Vladimir Markof44d36c2017-03-14 14:18:46 +00001682 *referrer->GetDexFile(),
Vladimir Markoadda4352016-01-29 10:24:41 +00001683 // Read barrier generates a runtime call in slow path and we need a valid
1684 // dex pc for the associated stack map. 0 is bogus but valid. Bug: 26854537.
1685 /* dex_pc */ 0);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001686 if (iget->GetType() == DataType::Type::kReference) {
Vladimir Marko456307a2016-04-19 14:12:13 +00001687 // Use the same dex_cache that we used for field lookup as the hint_dex_cache.
Vladimir Markof44d36c2017-03-14 14:18:46 +00001688 Handle<mirror::DexCache> dex_cache = handles_->NewHandle(referrer->GetDexCache());
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001689 ReferenceTypePropagation rtp(graph_,
1690 outer_compilation_unit_.GetClassLoader(),
1691 dex_cache,
1692 handles_,
1693 /* is_first_run */ false);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001694 rtp.Visit(iget);
1695 }
1696 return iget;
1697}
1698
Vladimir Markof44d36c2017-03-14 14:18:46 +00001699HInstanceFieldSet* HInliner::CreateInstanceFieldSet(uint32_t field_index,
1700 ArtMethod* referrer,
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001701 HInstruction* obj,
Vladimir Markof44d36c2017-03-14 14:18:46 +00001702 HInstruction* value,
1703 bool* is_final)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001704 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markof44d36c2017-03-14 14:18:46 +00001705 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1706 ArtField* resolved_field =
1707 class_linker->LookupResolvedField(field_index, referrer, /* is_static */ false);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001708 DCHECK(resolved_field != nullptr);
Vladimir Markof44d36c2017-03-14 14:18:46 +00001709 if (is_final != nullptr) {
1710 // This information is needed only for constructors.
1711 DCHECK(referrer->IsConstructor());
1712 *is_final = resolved_field->IsFinal();
1713 }
Vladimir Markoca6fff82017-10-03 14:49:14 +01001714 HInstanceFieldSet* iput = new (graph_->GetAllocator()) HInstanceFieldSet(
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001715 obj,
1716 value,
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00001717 resolved_field,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001718 DataType::FromShorty(resolved_field->GetTypeDescriptor()[0]),
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001719 resolved_field->GetOffset(),
1720 resolved_field->IsVolatile(),
1721 field_index,
1722 resolved_field->GetDeclaringClass()->GetDexClassDefIndex(),
Vladimir Markof44d36c2017-03-14 14:18:46 +00001723 *referrer->GetDexFile(),
Vladimir Markoadda4352016-01-29 10:24:41 +00001724 // Read barrier generates a runtime call in slow path and we need a valid
1725 // dex pc for the associated stack map. 0 is bogus but valid. Bug: 26854537.
1726 /* dex_pc */ 0);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001727 return iput;
1728}
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +00001729
Vladimir Markob1d0ee12017-04-20 19:50:32 +01001730template <typename T>
1731static inline Handle<T> NewHandleIfDifferent(T* object,
1732 Handle<T> hint,
1733 VariableSizedHandleScope* handles)
1734 REQUIRES_SHARED(Locks::mutator_lock_) {
1735 return (object != hint.Get()) ? handles->NewHandle(object) : hint;
1736}
1737
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001738bool HInliner::TryBuildAndInlineHelper(HInvoke* invoke_instruction,
1739 ArtMethod* resolved_method,
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001740 ReferenceTypeInfo receiver_type,
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001741 bool same_dex_file,
1742 HInstruction** return_replacement) {
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001743 DCHECK(!(resolved_method->IsStatic() && receiver_type.IsValid()));
Nicolas Geoffrayc0365b12015-03-18 18:31:52 +00001744 ScopedObjectAccess soa(Thread::Current());
1745 const DexFile::CodeItem* code_item = resolved_method->GetCodeItem();
Guillaume "Vermeille" Sanchezae09d2d2015-05-29 10:52:55 +01001746 const DexFile& callee_dex_file = *resolved_method->GetDexFile();
1747 uint32_t method_index = resolved_method->GetDexMethodIndex();
David Sehr0225f8e2018-01-31 08:52:24 +00001748 CodeItemDebugInfoAccessor code_item_accessor(resolved_method->DexInstructionDebugInfo());
Calin Juravle2e768302015-07-28 14:41:11 +00001749 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
Vladimir Markob1d0ee12017-04-20 19:50:32 +01001750 Handle<mirror::DexCache> dex_cache = NewHandleIfDifferent(resolved_method->GetDexCache(),
1751 caller_compilation_unit_.GetDexCache(),
1752 handles_);
1753 Handle<mirror::ClassLoader> class_loader =
1754 NewHandleIfDifferent(resolved_method->GetDeclaringClass()->GetClassLoader(),
1755 caller_compilation_unit_.GetClassLoader(),
1756 handles_);
Nicolas Geoffrayf1aedb12016-07-28 03:49:14 +01001757
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001758 DexCompilationUnit dex_compilation_unit(
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001759 class_loader,
Nicolas Geoffray5b82d332016-02-18 14:22:32 +00001760 class_linker,
1761 callee_dex_file,
1762 code_item,
1763 resolved_method->GetDeclaringClass()->GetDexClassDefIndex(),
1764 method_index,
1765 resolved_method->GetAccessFlags(),
1766 /* verified_method */ nullptr,
1767 dex_cache);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001768
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +01001769 InvokeType invoke_type = invoke_instruction->GetInvokeType();
Nicolas Geoffray35071052015-06-09 15:43:38 +01001770 if (invoke_type == kInterface) {
1771 // We have statically resolved the dispatch. To please the class linker
1772 // at runtime, we change this call as if it was a virtual call.
1773 invoke_type = kVirtual;
1774 }
David Brazdil3f523062016-02-29 16:53:33 +00001775
1776 const int32_t caller_instruction_counter = graph_->GetCurrentInstructionId();
Vladimir Markoca6fff82017-10-03 14:49:14 +01001777 HGraph* callee_graph = new (graph_->GetAllocator()) HGraph(
1778 graph_->GetAllocator(),
1779 graph_->GetArenaStack(),
Guillaume "Vermeille" Sanchezae09d2d2015-05-29 10:52:55 +01001780 callee_dex_file,
Nicolas Geoffray0a23d742015-05-07 11:57:35 +01001781 method_index,
Vladimir Markoa0431112018-06-25 09:32:54 +01001782 codegen_->GetCompilerOptions().GetInstructionSet(),
Nicolas Geoffray35071052015-06-09 15:43:38 +01001783 invoke_type,
Nicolas Geoffray0a23d742015-05-07 11:57:35 +01001784 graph_->IsDebuggable(),
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001785 /* osr */ false,
David Brazdil3f523062016-02-29 16:53:33 +00001786 caller_instruction_counter);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001787 callee_graph->SetArtMethod(resolved_method);
David Brazdil5e8b1372015-01-23 14:39:08 +00001788
Vladimir Marko438709f2017-02-23 18:56:13 +00001789 // When they are needed, allocate `inline_stats_` on the Arena instead
Roland Levillaina8013fd2016-04-04 15:34:31 +01001790 // of on the stack, as Clang might produce a stack frame too large
1791 // for this function, that would not fit the requirements of the
1792 // `-Wframe-larger-than` option.
Vladimir Marko438709f2017-02-23 18:56:13 +00001793 if (stats_ != nullptr) {
1794 // Reuse one object for all inline attempts from this caller to keep Arena memory usage low.
1795 if (inline_stats_ == nullptr) {
Vladimir Markoca6fff82017-10-03 14:49:14 +01001796 void* storage = graph_->GetAllocator()->Alloc<OptimizingCompilerStats>(kArenaAllocMisc);
Vladimir Marko438709f2017-02-23 18:56:13 +00001797 inline_stats_ = new (storage) OptimizingCompilerStats;
1798 } else {
1799 inline_stats_->Reset();
1800 }
1801 }
David Brazdil5e8b1372015-01-23 14:39:08 +00001802 HGraphBuilder builder(callee_graph,
Mathieu Chartier808c7a52017-12-15 11:19:33 -08001803 code_item_accessor,
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001804 &dex_compilation_unit,
1805 &outer_compilation_unit_,
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001806 compiler_driver_,
Nicolas Geoffray83c8e272017-01-31 14:36:37 +00001807 codegen_,
Vladimir Marko438709f2017-02-23 18:56:13 +00001808 inline_stats_,
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +00001809 resolved_method->GetQuickenedInfo(),
David Brazdildee58d62016-04-07 09:54:26 +00001810 handles_);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001811
David Brazdildee58d62016-04-07 09:54:26 +00001812 if (builder.BuildGraph() != kAnalysisSuccess) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001813 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedCannotBuild)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001814 << "Method " << callee_dex_file.PrettyMethod(method_index)
1815 << " could not be built, so cannot be inlined";
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001816 return false;
1817 }
1818
Vladimir Markoa0431112018-06-25 09:32:54 +01001819 if (!RegisterAllocator::CanAllocateRegistersFor(
1820 *callee_graph, codegen_->GetCompilerOptions().GetInstructionSet())) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001821 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedRegisterAllocator)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001822 << "Method " << callee_dex_file.PrettyMethod(method_index)
1823 << " cannot be inlined because of the register allocator";
Nicolas Geoffray259136f2014-12-17 23:21:58 +00001824 return false;
1825 }
1826
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001827 size_t parameter_index = 0;
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001828 bool run_rtp = false;
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001829 for (HInstructionIterator instructions(callee_graph->GetEntryBlock()->GetInstructions());
1830 !instructions.Done();
1831 instructions.Advance()) {
1832 HInstruction* current = instructions.Current();
1833 if (current->IsParameterValue()) {
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001834 HInstruction* argument = invoke_instruction->InputAt(parameter_index);
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001835 if (argument->IsNullConstant()) {
1836 current->ReplaceWith(callee_graph->GetNullConstant());
1837 } else if (argument->IsIntConstant()) {
1838 current->ReplaceWith(callee_graph->GetIntConstant(argument->AsIntConstant()->GetValue()));
1839 } else if (argument->IsLongConstant()) {
1840 current->ReplaceWith(callee_graph->GetLongConstant(argument->AsLongConstant()->GetValue()));
1841 } else if (argument->IsFloatConstant()) {
1842 current->ReplaceWith(
1843 callee_graph->GetFloatConstant(argument->AsFloatConstant()->GetValue()));
1844 } else if (argument->IsDoubleConstant()) {
1845 current->ReplaceWith(
1846 callee_graph->GetDoubleConstant(argument->AsDoubleConstant()->GetValue()));
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001847 } else if (argument->GetType() == DataType::Type::kReference) {
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001848 if (!resolved_method->IsStatic() && parameter_index == 0 && receiver_type.IsValid()) {
1849 run_rtp = true;
1850 current->SetReferenceTypeInfo(receiver_type);
1851 } else {
1852 current->SetReferenceTypeInfo(argument->GetReferenceTypeInfo());
1853 }
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001854 current->AsParameterValue()->SetCanBeNull(argument->CanBeNull());
1855 }
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001856 ++parameter_index;
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001857 }
1858 }
1859
David Brazdil94ab38f2016-06-21 17:48:19 +01001860 // We have replaced formal arguments with actual arguments. If actual types
1861 // are more specific than the declared ones, run RTP again on the inner graph.
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001862 if (run_rtp || ArgumentTypesMoreSpecific(invoke_instruction, resolved_method)) {
David Brazdil94ab38f2016-06-21 17:48:19 +01001863 ReferenceTypePropagation(callee_graph,
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001864 outer_compilation_unit_.GetClassLoader(),
David Brazdil94ab38f2016-06-21 17:48:19 +01001865 dex_compilation_unit.GetDexCache(),
1866 handles_,
1867 /* is_first_run */ false).Run();
1868 }
1869
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001870 RunOptimizations(callee_graph, code_item, dex_compilation_unit);
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +00001871
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001872 HBasicBlock* exit_block = callee_graph->GetExitBlock();
1873 if (exit_block == nullptr) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001874 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedInfiniteLoop)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001875 << "Method " << callee_dex_file.PrettyMethod(method_index)
1876 << " could not be inlined because it has an infinite loop";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001877 return false;
1878 }
1879
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00001880 bool has_one_return = false;
Vladimir Marko60584552015-09-03 13:35:12 +00001881 for (HBasicBlock* predecessor : exit_block->GetPredecessors()) {
1882 if (predecessor->GetLastInstruction()->IsThrow()) {
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00001883 if (invoke_instruction->GetBlock()->IsTryBlock()) {
1884 // TODO(ngeoffray): Support adding HTryBoundary in Hgraph::InlineInto.
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001885 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedTryCatch)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001886 << "Method " << callee_dex_file.PrettyMethod(method_index)
1887 << " could not be inlined because one branch always throws and"
1888 << " caller is in a try/catch block";
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00001889 return false;
1890 } else if (graph_->GetExitBlock() == nullptr) {
1891 // TODO(ngeoffray): Support adding HExit in the caller graph.
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001892 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedInfiniteLoop)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001893 << "Method " << callee_dex_file.PrettyMethod(method_index)
1894 << " could not be inlined because one branch always throws and"
1895 << " caller does not have an exit block";
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00001896 return false;
Nicolas Geoffray1eede6a2017-03-02 16:14:53 +00001897 } else if (graph_->HasIrreducibleLoops()) {
1898 // TODO(ngeoffray): Support re-computing loop information to graphs with
1899 // irreducible loops?
1900 VLOG(compiler) << "Method " << callee_dex_file.PrettyMethod(method_index)
1901 << " could not be inlined because one branch always throws and"
1902 << " caller has irreducible loops";
1903 return false;
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00001904 }
1905 } else {
1906 has_one_return = true;
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001907 }
1908 }
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00001909
1910 if (!has_one_return) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001911 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedAlwaysThrows)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001912 << "Method " << callee_dex_file.PrettyMethod(method_index)
1913 << " could not be inlined because it always throws";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001914 return false;
1915 }
1916
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001917 size_t number_of_instructions = 0;
Vladimir Marko2c45bc92016-10-25 16:54:12 +01001918 // Skip the entry block, it does not contain instructions that prevent inlining.
1919 for (HBasicBlock* block : callee_graph->GetReversePostOrderSkipEntryBlock()) {
David Sehrc757dec2016-11-04 15:48:34 -07001920 if (block->IsLoopHeader()) {
1921 if (block->GetLoopInformation()->IsIrreducible()) {
1922 // Don't inline methods with irreducible loops, they could prevent some
1923 // optimizations to run.
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001924 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedIrreducibleLoop)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001925 << "Method " << callee_dex_file.PrettyMethod(method_index)
1926 << " could not be inlined because it contains an irreducible loop";
David Sehrc757dec2016-11-04 15:48:34 -07001927 return false;
1928 }
1929 if (!block->GetLoopInformation()->HasExitEdge()) {
1930 // Don't inline methods with loops without exit, since they cause the
1931 // loop information to be computed incorrectly when updating after
1932 // inlining.
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001933 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedLoopWithoutExit)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001934 << "Method " << callee_dex_file.PrettyMethod(method_index)
1935 << " could not be inlined because it contains a loop with no exit";
David Sehrc757dec2016-11-04 15:48:34 -07001936 return false;
1937 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001938 }
1939
1940 for (HInstructionIterator instr_it(block->GetInstructions());
1941 !instr_it.Done();
1942 instr_it.Advance()) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001943 if (++number_of_instructions >= inlining_budget_) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001944 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedInstructionBudget)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001945 << "Method " << callee_dex_file.PrettyMethod(method_index)
1946 << " is not inlined because the outer method has reached"
1947 << " its instruction budget limit.";
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001948 return false;
1949 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001950 HInstruction* current = instr_it.Current();
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001951 if (current->NeedsEnvironment() &&
1952 (total_number_of_dex_registers_ >= kMaximumNumberOfCumulatedDexRegisters)) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001953 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedEnvironmentBudget)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001954 << "Method " << callee_dex_file.PrettyMethod(method_index)
1955 << " is not inlined because its caller has reached"
1956 << " its environment budget limit.";
Nicolas Geoffray5949fa02015-12-18 10:57:10 +00001957 return false;
1958 }
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001959
Nicolas Geoffrayfbdfa6d2017-02-03 10:43:13 +00001960 if (current->NeedsEnvironment() &&
1961 !CanEncodeInlinedMethodInStackMap(*caller_compilation_unit_.GetDexFile(),
1962 resolved_method)) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001963 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedStackMaps)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001964 << "Method " << callee_dex_file.PrettyMethod(method_index)
1965 << " could not be inlined because " << current->DebugName()
1966 << " needs an environment, is in a different dex file"
1967 << ", and cannot be encoded in the stack maps.";
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001968 return false;
1969 }
Nicolas Geoffray9437b782015-03-25 10:08:51 +00001970
Vladimir Markodc151b22015-10-15 18:02:30 +01001971 if (!same_dex_file && current->NeedsDexCacheOfDeclaringClass()) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001972 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedDexCache)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001973 << "Method " << callee_dex_file.PrettyMethod(method_index)
1974 << " could not be inlined because " << current->DebugName()
1975 << " it is in a different dex file and requires access to the dex cache";
Nicolas Geoffray9437b782015-03-25 10:08:51 +00001976 return false;
1977 }
Nicolas Geoffrayd9309292015-10-31 22:21:31 +00001978
Nicolas Geoffrayd9309292015-10-31 22:21:31 +00001979 if (current->IsUnresolvedStaticFieldGet() ||
1980 current->IsUnresolvedInstanceFieldGet() ||
1981 current->IsUnresolvedStaticFieldSet() ||
1982 current->IsUnresolvedInstanceFieldSet()) {
1983 // Entrypoint for unresolved fields does not handle inlined frames.
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001984 LOG_FAIL(stats_, MethodCompilationStat::kNotInlinedUnresolvedEntrypoint)
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001985 << "Method " << callee_dex_file.PrettyMethod(method_index)
1986 << " could not be inlined because it is using an unresolved"
1987 << " entrypoint";
Nicolas Geoffrayd9309292015-10-31 22:21:31 +00001988 return false;
1989 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001990 }
1991 }
David Brazdil3f523062016-02-29 16:53:33 +00001992 DCHECK_EQ(caller_instruction_counter, graph_->GetCurrentInstructionId())
1993 << "No instructions can be added to the outer graph while inner graph is being built";
1994
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001995 // Inline the callee graph inside the caller graph.
David Brazdil3f523062016-02-29 16:53:33 +00001996 const int32_t callee_instruction_counter = callee_graph->GetCurrentInstructionId();
1997 graph_->SetCurrentInstructionId(callee_instruction_counter);
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001998 *return_replacement = callee_graph->InlineInto(graph_, invoke_instruction);
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001999 // Update our budget for other inlining attempts in `caller_graph`.
2000 total_number_of_instructions_ += number_of_instructions;
2001 UpdateInliningBudget();
David Brazdil3f523062016-02-29 16:53:33 +00002002
2003 DCHECK_EQ(callee_instruction_counter, callee_graph->GetCurrentInstructionId())
2004 << "No instructions can be added to the inner graph during inlining into the outer graph";
2005
Vladimir Marko438709f2017-02-23 18:56:13 +00002006 if (stats_ != nullptr) {
2007 DCHECK(inline_stats_ != nullptr);
2008 inline_stats_->AddTo(stats_);
2009 }
2010
Vladimir Markobe10e8e2016-01-22 12:09:44 +00002011 return true;
2012}
Calin Juravle2e768302015-07-28 14:41:11 +00002013
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00002014void HInliner::RunOptimizations(HGraph* callee_graph,
2015 const DexFile::CodeItem* code_item,
2016 const DexCompilationUnit& dex_compilation_unit) {
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01002017 // Note: if the outermost_graph_ is being compiled OSR, we should not run any
2018 // optimization that could lead to a HDeoptimize. The following optimizations do not.
Vladimir Marko438709f2017-02-23 18:56:13 +00002019 HDeadCodeElimination dce(callee_graph, inline_stats_, "dead_code_elimination$inliner");
Andreas Gampeca620d72016-11-08 08:09:33 -08002020 HConstantFolding fold(callee_graph, "constant_folding$inliner");
Vladimir Markobb089b62018-06-28 17:30:16 +01002021 InstructionSimplifier simplify(callee_graph, codegen_, inline_stats_);
Roland Levillaina3aef2e2016-04-06 17:45:58 +01002022
2023 HOptimization* optimizations[] = {
Roland Levillaina3aef2e2016-04-06 17:45:58 +01002024 &simplify,
2025 &fold,
2026 &dce,
2027 };
2028
2029 for (size_t i = 0; i < arraysize(optimizations); ++i) {
2030 HOptimization* optimization = optimizations[i];
2031 optimization->Run();
2032 }
2033
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00002034 // Bail early for pathological cases on the environment (for example recursive calls,
2035 // or too large environment).
2036 if (total_number_of_dex_registers_ >= kMaximumNumberOfCumulatedDexRegisters) {
2037 LOG_NOTE() << "Calls in " << callee_graph->GetArtMethod()->PrettyMethod()
2038 << " will not be inlined because the outer method has reached"
2039 << " its environment budget limit.";
2040 return;
Roland Levillaina3aef2e2016-04-06 17:45:58 +01002041 }
2042
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00002043 // Bail early if we know we already are over the limit.
2044 size_t number_of_instructions = CountNumberOfInstructions(callee_graph);
2045 if (number_of_instructions > inlining_budget_) {
2046 LOG_NOTE() << "Calls in " << callee_graph->GetArtMethod()->PrettyMethod()
2047 << " will not be inlined because the outer method has reached"
2048 << " its instruction budget limit. " << number_of_instructions;
2049 return;
2050 }
2051
Mathieu Chartier698ebbc2018-01-05 11:00:42 -08002052 CodeItemDataAccessor accessor(callee_graph->GetDexFile(), code_item);
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00002053 HInliner inliner(callee_graph,
2054 outermost_graph_,
2055 codegen_,
2056 outer_compilation_unit_,
2057 dex_compilation_unit,
2058 compiler_driver_,
2059 handles_,
2060 inline_stats_,
Mathieu Chartier808c7a52017-12-15 11:19:33 -08002061 total_number_of_dex_registers_ + accessor.RegistersSize(),
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00002062 total_number_of_instructions_ + number_of_instructions,
2063 this,
2064 depth_ + 1);
2065 inliner.Run();
Roland Levillaina3aef2e2016-04-06 17:45:58 +01002066}
2067
David Brazdil94ab38f2016-06-21 17:48:19 +01002068static bool IsReferenceTypeRefinement(ReferenceTypeInfo declared_rti,
2069 bool declared_can_be_null,
2070 HInstruction* actual_obj)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002071 REQUIRES_SHARED(Locks::mutator_lock_) {
David Brazdil94ab38f2016-06-21 17:48:19 +01002072 if (declared_can_be_null && !actual_obj->CanBeNull()) {
2073 return true;
2074 }
2075
2076 ReferenceTypeInfo actual_rti = actual_obj->GetReferenceTypeInfo();
2077 return (actual_rti.IsExact() && !declared_rti.IsExact()) ||
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00002078 declared_rti.IsStrictSupertypeOf(actual_rti);
David Brazdil94ab38f2016-06-21 17:48:19 +01002079}
2080
Vladimir Markob45528c2017-07-27 14:14:28 +01002081ReferenceTypeInfo HInliner::GetClassRTI(ObjPtr<mirror::Class> klass) {
David Brazdil94ab38f2016-06-21 17:48:19 +01002082 return ReferenceTypePropagation::IsAdmissible(klass)
2083 ? ReferenceTypeInfo::Create(handles_->NewHandle(klass))
2084 : graph_->GetInexactObjectRti();
2085}
2086
2087bool HInliner::ArgumentTypesMoreSpecific(HInvoke* invoke_instruction, ArtMethod* resolved_method) {
2088 // If this is an instance call, test whether the type of the `this` argument
2089 // is more specific than the class which declares the method.
2090 if (!resolved_method->IsStatic()) {
2091 if (IsReferenceTypeRefinement(GetClassRTI(resolved_method->GetDeclaringClass()),
2092 /* declared_can_be_null */ false,
2093 invoke_instruction->InputAt(0u))) {
2094 return true;
2095 }
2096 }
2097
David Brazdil94ab38f2016-06-21 17:48:19 +01002098 // Iterate over the list of parameter types and test whether any of the
2099 // actual inputs has a more specific reference type than the type declared in
2100 // the signature.
2101 const DexFile::TypeList* param_list = resolved_method->GetParameterTypeList();
2102 for (size_t param_idx = 0,
2103 input_idx = resolved_method->IsStatic() ? 0 : 1,
2104 e = (param_list == nullptr ? 0 : param_list->Size());
2105 param_idx < e;
2106 ++param_idx, ++input_idx) {
2107 HInstruction* input = invoke_instruction->InputAt(input_idx);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002108 if (input->GetType() == DataType::Type::kReference) {
Vladimir Markob45528c2017-07-27 14:14:28 +01002109 ObjPtr<mirror::Class> param_cls = resolved_method->LookupResolvedClassFromTypeIndex(
2110 param_list->GetTypeItem(param_idx).type_idx_);
David Brazdil94ab38f2016-06-21 17:48:19 +01002111 if (IsReferenceTypeRefinement(GetClassRTI(param_cls),
2112 /* declared_can_be_null */ true,
2113 input)) {
2114 return true;
2115 }
2116 }
2117 }
2118
2119 return false;
2120}
2121
2122bool HInliner::ReturnTypeMoreSpecific(HInvoke* invoke_instruction,
2123 HInstruction* return_replacement) {
Alex Light68289a52015-12-15 17:30:30 -08002124 // Check the integrity of reference types and run another type propagation if needed.
David Brazdil4833f5a2015-12-16 10:37:39 +00002125 if (return_replacement != nullptr) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002126 if (return_replacement->GetType() == DataType::Type::kReference) {
David Brazdil94ab38f2016-06-21 17:48:19 +01002127 // Test if the return type is a refinement of the declared return type.
2128 if (IsReferenceTypeRefinement(invoke_instruction->GetReferenceTypeInfo(),
2129 /* declared_can_be_null */ true,
2130 return_replacement)) {
2131 return true;
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00002132 } else if (return_replacement->IsInstanceFieldGet()) {
2133 HInstanceFieldGet* field_get = return_replacement->AsInstanceFieldGet();
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00002134 if (field_get->GetFieldInfo().GetField() ==
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002135 GetClassRoot<mirror::Object>()->GetInstanceField(0)) {
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00002136 return true;
2137 }
David Brazdil94ab38f2016-06-21 17:48:19 +01002138 }
2139 } else if (return_replacement->IsInstanceOf()) {
2140 // Inlining InstanceOf into an If may put a tighter bound on reference types.
2141 return true;
2142 }
2143 }
2144
2145 return false;
2146}
2147
2148void HInliner::FixUpReturnReferenceType(ArtMethod* resolved_method,
2149 HInstruction* return_replacement) {
2150 if (return_replacement != nullptr) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002151 if (return_replacement->GetType() == DataType::Type::kReference) {
David Brazdil4833f5a2015-12-16 10:37:39 +00002152 if (!return_replacement->GetReferenceTypeInfo().IsValid()) {
2153 // Make sure that we have a valid type for the return. We may get an invalid one when
2154 // we inline invokes with multiple branches and create a Phi for the result.
2155 // TODO: we could be more precise by merging the phi inputs but that requires
2156 // some functionality from the reference type propagation.
2157 DCHECK(return_replacement->IsPhi());
Vladimir Markob45528c2017-07-27 14:14:28 +01002158 ObjPtr<mirror::Class> cls = resolved_method->LookupResolvedReturnType();
David Brazdil94ab38f2016-06-21 17:48:19 +01002159 return_replacement->SetReferenceTypeInfo(GetClassRTI(cls));
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01002160 }
Calin Juravlecdfed3d2015-10-26 14:05:01 +00002161 }
Calin Juravle2e768302015-07-28 14:41:11 +00002162 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002163}
2164
2165} // namespace art