blob: 62f5114e59aab060a5e12f4fbde4e10a74f3c6e6 [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"
23#include "constant_folding.h"
24#include "dead_code_elimination.h"
Vladimir Markobe10e8e2016-01-22 12:09:44 +000025#include "dex/verified_method.h"
26#include "dex/verification_results.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000027#include "driver/compiler_driver-inl.h"
Calin Juravleec748352015-07-29 13:52:12 +010028#include "driver/compiler_options.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000029#include "driver/dex_compilation_unit.h"
30#include "instruction_simplifier.h"
Scott Wakelingd60a1af2015-07-22 14:32:44 +010031#include "intrinsics.h"
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +000032#include "jit/jit.h"
33#include "jit/jit_code_cache.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000034#include "mirror/class_loader.h"
35#include "mirror/dex_cache.h"
36#include "nodes.h"
Nicolas Geoffray335005e2015-06-25 10:01:47 +010037#include "optimizing_compiler.h"
Nicolas Geoffray454a4812015-06-09 10:37:32 +010038#include "reference_type_propagation.h"
Matthew Gharritye9288852016-07-14 14:08:16 -070039#include "register_allocator_linear_scan.h"
Vladimir Markobe10e8e2016-01-22 12:09:44 +000040#include "quick/inline_method_analyser.h"
Vladimir Markodc151b22015-10-15 18:02:30 +010041#include "sharpening.h"
David Brazdil4833f5a2015-12-16 10:37:39 +000042#include "ssa_builder.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000043#include "ssa_phi_elimination.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070044#include "scoped_thread_state_change-inl.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000045#include "thread.h"
46
47namespace art {
48
Nicolas Geoffray5949fa02015-12-18 10:57:10 +000049static constexpr size_t kMaximumNumberOfHInstructions = 32;
50
51// Limit the number of dex registers that we accumulate while inlining
52// to avoid creating large amount of nested environments.
53static constexpr size_t kMaximumNumberOfCumulatedDexRegisters = 64;
54
55// Avoid inlining within a huge method due to memory pressure.
56static constexpr size_t kMaximumCodeUnitSize = 4096;
Nicolas Geoffraye418dda2015-08-11 20:03:09 -070057
Calin Juravlee2492d42017-03-20 11:42:13 -070058// Controls the use of inline caches in AOT mode.
59static constexpr bool kUseAOTInlineCaches = false;
60
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000061void HInliner::Run() {
Calin Juravle8f96df82015-07-29 15:58:48 +010062 const CompilerOptions& compiler_options = compiler_driver_->GetCompilerOptions();
63 if ((compiler_options.GetInlineDepthLimit() == 0)
64 || (compiler_options.GetInlineMaxCodeUnits() == 0)) {
65 return;
66 }
Nicolas Geoffray5949fa02015-12-18 10:57:10 +000067 if (caller_compilation_unit_.GetCodeItem()->insns_size_in_code_units_ > kMaximumCodeUnitSize) {
68 return;
69 }
Nicolas Geoffraye50b8d22015-03-13 08:57:42 +000070 if (graph_->IsDebuggable()) {
71 // For simplicity, we currently never inline when the graph is debuggable. This avoids
72 // doing some logic in the runtime to discover if a method could have been inlined.
73 return;
74 }
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +000075 // Keep a copy of all blocks when starting the visit.
76 ArenaVector<HBasicBlock*> blocks = graph_->GetReversePostOrder();
Vladimir Markofa6b93c2015-09-15 10:15:55 +010077 DCHECK(!blocks.empty());
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +000078 // Because we are changing the graph when inlining,
79 // we just iterate over the blocks of the outer method.
80 // This avoids doing the inlining work again on the inlined blocks.
81 for (HBasicBlock* block : blocks) {
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +000082 for (HInstruction* instruction = block->GetFirstInstruction(); instruction != nullptr;) {
83 HInstruction* next = instruction->GetNext();
Nicolas Geoffray454a4812015-06-09 10:37:32 +010084 HInvoke* call = instruction->AsInvoke();
Razvan A Lupusoru3e90a962015-03-27 13:44:44 -070085 // As long as the call is not intrinsified, it is worth trying to inline.
86 if (call != nullptr && call->GetIntrinsic() == Intrinsics::kNone) {
Nicolas Geoffrayb703d182017-02-14 18:05:28 +000087 if (kIsDebugBuild && IsCompilingWithCoreImage()) {
88 // Debugging case: directives in method names control or assert on inlining.
89 std::string callee_name = outer_compilation_unit_.GetDexFile()->PrettyMethod(
90 call->GetDexMethodIndex(), /* with_signature */ false);
91 // Tests prevent inlining by having $noinline$ in their method names.
92 if (callee_name.find("$noinline$") == std::string::npos) {
93 if (!TryInline(call)) {
94 bool should_have_inlined = (callee_name.find("$inline$") != std::string::npos);
95 CHECK(!should_have_inlined) << "Could not inline " << callee_name;
96 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000097 }
Guillaume "Vermeille" Sancheze918d382015-06-03 15:32:41 +010098 } else {
Nicolas Geoffrayb703d182017-02-14 18:05:28 +000099 // Normal case: try to inline.
100 TryInline(call);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000101 }
102 }
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +0000103 instruction = next;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000104 }
105 }
106}
107
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100108static bool IsMethodOrDeclaringClassFinal(ArtMethod* method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700109 REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100110 return method->IsFinal() || method->GetDeclaringClass()->IsFinal();
111}
112
113/**
114 * Given the `resolved_method` looked up in the dex cache, try to find
115 * the actual runtime target of an interface or virtual call.
116 * Return nullptr if the runtime target cannot be proven.
117 */
118static ArtMethod* FindVirtualOrInterfaceTarget(HInvoke* invoke, ArtMethod* resolved_method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700119 REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100120 if (IsMethodOrDeclaringClassFinal(resolved_method)) {
121 // No need to lookup further, the resolved method will be the target.
122 return resolved_method;
123 }
124
125 HInstruction* receiver = invoke->InputAt(0);
126 if (receiver->IsNullCheck()) {
127 // Due to multiple levels of inlining within the same pass, it might be that
128 // null check does not have the reference type of the actual receiver.
129 receiver = receiver->InputAt(0);
130 }
131 ReferenceTypeInfo info = receiver->GetReferenceTypeInfo();
Calin Juravle2e768302015-07-28 14:41:11 +0000132 DCHECK(info.IsValid()) << "Invalid RTI for " << receiver->DebugName();
133 if (!info.IsExact()) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100134 // We currently only support inlining with known receivers.
135 // TODO: Remove this check, we should be able to inline final methods
136 // on unknown receivers.
137 return nullptr;
138 } else if (info.GetTypeHandle()->IsInterface()) {
139 // Statically knowing that the receiver has an interface type cannot
140 // help us find what is the target method.
141 return nullptr;
142 } else if (!resolved_method->GetDeclaringClass()->IsAssignableFrom(info.GetTypeHandle().Get())) {
143 // The method that we're trying to call is not in the receiver's class or super classes.
144 return nullptr;
Nicolas Geoffrayab5327d2016-03-18 11:36:20 +0000145 } else if (info.GetTypeHandle()->IsErroneous()) {
146 // If the type is erroneous, do not go further, as we are going to query the vtable or
147 // imt table, that we can only safely do on non-erroneous classes.
148 return nullptr;
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100149 }
150
151 ClassLinker* cl = Runtime::Current()->GetClassLinker();
Andreas Gampe542451c2016-07-26 09:02:02 -0700152 PointerSize pointer_size = cl->GetImagePointerSize();
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100153 if (invoke->IsInvokeInterface()) {
154 resolved_method = info.GetTypeHandle()->FindVirtualMethodForInterface(
155 resolved_method, pointer_size);
156 } else {
157 DCHECK(invoke->IsInvokeVirtual());
158 resolved_method = info.GetTypeHandle()->FindVirtualMethodForVirtual(
159 resolved_method, pointer_size);
160 }
161
162 if (resolved_method == nullptr) {
163 // The information we had on the receiver was not enough to find
164 // the target method. Since we check above the exact type of the receiver,
165 // the only reason this can happen is an IncompatibleClassChangeError.
166 return nullptr;
Alex Light9139e002015-10-09 15:59:48 -0700167 } else if (!resolved_method->IsInvokable()) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100168 // The information we had on the receiver was not enough to find
169 // the target method. Since we check above the exact type of the receiver,
170 // the only reason this can happen is an IncompatibleClassChangeError.
171 return nullptr;
172 } else if (IsMethodOrDeclaringClassFinal(resolved_method)) {
173 // A final method has to be the target method.
174 return resolved_method;
175 } else if (info.IsExact()) {
176 // If we found a method and the receiver's concrete type is statically
177 // known, we know for sure the target.
178 return resolved_method;
179 } else {
180 // Even if we did find a method, the receiver type was not enough to
181 // statically find the runtime target.
182 return nullptr;
183 }
184}
185
186static uint32_t FindMethodIndexIn(ArtMethod* method,
187 const DexFile& dex_file,
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +0000188 uint32_t name_and_signature_index)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700189 REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100190 if (IsSameDexFile(*method->GetDexFile(), dex_file)) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100191 return method->GetDexMethodIndex();
192 } else {
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +0000193 return method->FindDexMethodIndexInOtherDexFile(dex_file, name_and_signature_index);
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100194 }
195}
196
Andreas Gampea5b09a62016-11-17 15:21:22 -0800197static dex::TypeIndex FindClassIndexIn(mirror::Class* cls,
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000198 const DexCompilationUnit& compilation_unit)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700199 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000200 const DexFile& dex_file = *compilation_unit.GetDexFile();
Andreas Gampea5b09a62016-11-17 15:21:22 -0800201 dex::TypeIndex index;
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100202 if (cls->GetDexCache() == nullptr) {
David Sehr709b0702016-10-13 09:12:37 -0700203 DCHECK(cls->IsArrayClass()) << cls->PrettyClass();
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000204 index = cls->FindTypeIndexInOtherDexFile(dex_file);
Andreas Gampea5b09a62016-11-17 15:21:22 -0800205 } else if (!cls->GetDexTypeIndex().IsValid()) {
David Sehr709b0702016-10-13 09:12:37 -0700206 DCHECK(cls->IsProxyClass()) << cls->PrettyClass();
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100207 // TODO: deal with proxy classes.
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100208 } else if (IsSameDexFile(cls->GetDexFile(), dex_file)) {
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000209 DCHECK_EQ(cls->GetDexCache(), compilation_unit.GetDexCache().Get());
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000210 index = cls->GetDexTypeIndex();
Nicolas Geoffray491617a2016-07-19 17:06:23 +0100211 } else {
212 index = cls->FindTypeIndexInOtherDexFile(dex_file);
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000213 // We cannot guarantee the entry will resolve to the same class,
Nicolas Geoffray491617a2016-07-19 17:06:23 +0100214 // as there may be different class loaders. So only return the index if it's
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000215 // the right class already resolved with the class loader.
216 if (index.IsValid()) {
217 ObjPtr<mirror::Class> resolved = ClassLinker::LookupResolvedType(
218 index, compilation_unit.GetDexCache().Get(), compilation_unit.GetClassLoader().Get());
219 if (resolved != cls) {
220 index = dex::TypeIndex::Invalid();
221 }
Nicolas Geoffray491617a2016-07-19 17:06:23 +0100222 }
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100223 }
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000224
225 return index;
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100226}
227
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000228class ScopedProfilingInfoInlineUse {
229 public:
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000230 explicit ScopedProfilingInfoInlineUse(ArtMethod* method, Thread* self)
231 : method_(method),
232 self_(self),
233 // Fetch the profiling info ahead of using it. If it's null when fetching,
234 // we should not call JitCodeCache::DoneInlining.
235 profiling_info_(
236 Runtime::Current()->GetJit()->GetCodeCache()->NotifyCompilerUse(method, self)) {
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000237 }
238
239 ~ScopedProfilingInfoInlineUse() {
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000240 if (profiling_info_ != nullptr) {
Andreas Gampe542451c2016-07-26 09:02:02 -0700241 PointerSize pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000242 DCHECK_EQ(profiling_info_, method_->GetProfilingInfo(pointer_size));
243 Runtime::Current()->GetJit()->GetCodeCache()->DoneCompilerUse(method_, self_);
244 }
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000245 }
246
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000247 ProfilingInfo* GetProfilingInfo() const { return profiling_info_; }
248
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000249 private:
250 ArtMethod* const method_;
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000251 Thread* const self_;
252 ProfilingInfo* const profiling_info_;
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000253};
254
Calin Juravle13439f02017-02-21 01:17:21 -0800255HInliner::InlineCacheType HInliner::GetInlineCacheType(
256 const Handle<mirror::ObjectArray<mirror::Class>>& classes)
257 REQUIRES_SHARED(Locks::mutator_lock_) {
258 uint8_t number_of_types = 0;
259 for (; number_of_types < InlineCache::kIndividualCacheSize; ++number_of_types) {
260 if (classes->Get(number_of_types) == nullptr) {
261 break;
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000262 }
263 }
Calin Juravle13439f02017-02-21 01:17:21 -0800264
265 if (number_of_types == 0) {
266 return kInlineCacheUninitialized;
267 } else if (number_of_types == 1) {
268 return kInlineCacheMonomorphic;
269 } else if (number_of_types == InlineCache::kIndividualCacheSize) {
270 return kInlineCacheMegamorphic;
271 } else {
272 return kInlineCachePolymorphic;
273 }
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000274}
275
276static mirror::Class* GetMonomorphicType(Handle<mirror::ObjectArray<mirror::Class>> classes)
277 REQUIRES_SHARED(Locks::mutator_lock_) {
278 DCHECK(classes->Get(0) != nullptr);
279 return classes->Get(0);
280}
281
Mingyao Yang063fc772016-08-02 11:02:54 -0700282ArtMethod* HInliner::TryCHADevirtualization(ArtMethod* resolved_method) {
283 if (!resolved_method->HasSingleImplementation()) {
284 return nullptr;
285 }
286 if (Runtime::Current()->IsAotCompiler()) {
287 // No CHA-based devirtulization for AOT compiler (yet).
288 return nullptr;
289 }
290 if (outermost_graph_->IsCompilingOsr()) {
291 // We do not support HDeoptimize in OSR methods.
292 return nullptr;
293 }
Mingyao Yange8fcd012017-01-20 10:43:30 -0800294 PointerSize pointer_size = caller_compilation_unit_.GetClassLinker()->GetImagePointerSize();
295 return resolved_method->GetSingleImplementation(pointer_size);
Mingyao Yang063fc772016-08-02 11:02:54 -0700296}
297
Nicolas Geoffraye418dda2015-08-11 20:03:09 -0700298bool HInliner::TryInline(HInvoke* invoke_instruction) {
Orion Hodsonac141392017-01-13 11:53:47 +0000299 if (invoke_instruction->IsInvokeUnresolved() ||
300 invoke_instruction->IsInvokePolymorphic()) {
301 return false; // Don't bother to move further if we know the method is unresolved or an
302 // invoke-polymorphic.
Calin Juravle175dc732015-08-25 15:42:32 +0100303 }
304
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000305 ScopedObjectAccess soa(Thread::Current());
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +0100306 uint32_t method_index = invoke_instruction->GetDexMethodIndex();
Nicolas Geoffray9437b782015-03-25 10:08:51 +0000307 const DexFile& caller_dex_file = *caller_compilation_unit_.GetDexFile();
David Sehr709b0702016-10-13 09:12:37 -0700308 VLOG(compiler) << "Try inlining " << caller_dex_file.PrettyMethod(method_index);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000309
Nicolas Geoffray35071052015-06-09 15:43:38 +0100310 // We can query the dex cache directly. The verifier has populated it already.
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +0100311 ArtMethod* resolved_method = invoke_instruction->GetResolvedMethod();
Andreas Gampefd2140f2015-12-23 16:30:44 -0800312 ArtMethod* actual_method = nullptr;
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +0100313 if (resolved_method == nullptr) {
314 DCHECK(invoke_instruction->IsInvokeStaticOrDirect());
315 DCHECK(invoke_instruction->AsInvokeStaticOrDirect()->IsStringInit());
316 VLOG(compiler) << "Not inlining a String.<init> method";
317 return false;
318 } else if (invoke_instruction->IsInvokeStaticOrDirect()) {
Andreas Gampefd2140f2015-12-23 16:30:44 -0800319 actual_method = resolved_method;
Vladimir Marko58155012015-08-19 12:49:41 +0000320 } else {
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +0100321 // Check if we can statically find the method.
322 actual_method = FindVirtualOrInterfaceTarget(invoke_instruction, resolved_method);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000323 }
324
Mingyao Yang063fc772016-08-02 11:02:54 -0700325 bool cha_devirtualize = false;
326 if (actual_method == nullptr) {
327 ArtMethod* method = TryCHADevirtualization(resolved_method);
328 if (method != nullptr) {
329 cha_devirtualize = true;
330 actual_method = method;
331 }
332 }
333
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100334 if (actual_method != nullptr) {
Mingyao Yang063fc772016-08-02 11:02:54 -0700335 bool result = TryInlineAndReplace(invoke_instruction,
336 actual_method,
Nicolas Geoffray0f001b72017-01-04 16:46:23 +0000337 ReferenceTypeInfo::CreateInvalid(),
Mingyao Yang063fc772016-08-02 11:02:54 -0700338 /* do_rtp */ true,
339 cha_devirtualize);
Calin Juravle69158982016-03-16 11:53:41 +0000340 if (result && !invoke_instruction->IsInvokeStaticOrDirect()) {
Mingyao Yang063fc772016-08-02 11:02:54 -0700341 if (cha_devirtualize) {
342 // Add dependency due to devirtulization. We've assumed resolved_method
343 // has single implementation.
344 outermost_graph_->AddCHASingleImplementationDependency(resolved_method);
345 MaybeRecordStat(kCHAInline);
346 } else {
347 MaybeRecordStat(kInlinedInvokeVirtualOrInterface);
348 }
Calin Juravle69158982016-03-16 11:53:41 +0000349 }
350 return result;
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100351 }
Andreas Gampefd2140f2015-12-23 16:30:44 -0800352 DCHECK(!invoke_instruction->IsInvokeStaticOrDirect());
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100353
Calin Juravle13439f02017-02-21 01:17:21 -0800354 // Try using inline caches.
355 return TryInlineFromInlineCache(caller_dex_file, invoke_instruction, resolved_method);
356}
357
358static Handle<mirror::ObjectArray<mirror::Class>> AllocateInlineCacheHolder(
359 const DexCompilationUnit& compilation_unit,
360 StackHandleScope<1>* hs)
361 REQUIRES_SHARED(Locks::mutator_lock_) {
362 Thread* self = Thread::Current();
363 ClassLinker* class_linker = compilation_unit.GetClassLinker();
364 Handle<mirror::ObjectArray<mirror::Class>> inline_cache = hs->NewHandle(
365 mirror::ObjectArray<mirror::Class>::Alloc(
366 self,
367 class_linker->GetClassRoot(ClassLinker::kClassArrayClass),
368 InlineCache::kIndividualCacheSize));
369 if (inline_cache == nullptr) {
370 // We got an OOME. Just clear the exception, and don't inline.
371 DCHECK(self->IsExceptionPending());
372 self->ClearException();
373 VLOG(compiler) << "Out of memory in the compiler when trying to inline";
374 }
375 return inline_cache;
376}
377
378bool HInliner::TryInlineFromInlineCache(const DexFile& caller_dex_file,
379 HInvoke* invoke_instruction,
380 ArtMethod* resolved_method)
381 REQUIRES_SHARED(Locks::mutator_lock_) {
Calin Juravlee2492d42017-03-20 11:42:13 -0700382 if (Runtime::Current()->IsAotCompiler() && !kUseAOTInlineCaches) {
383 return false;
384 }
385
Calin Juravle13439f02017-02-21 01:17:21 -0800386 StackHandleScope<1> hs(Thread::Current());
387 Handle<mirror::ObjectArray<mirror::Class>> inline_cache;
388 InlineCacheType inline_cache_type = Runtime::Current()->IsAotCompiler()
389 ? GetInlineCacheAOT(caller_dex_file, invoke_instruction, &hs, &inline_cache)
390 : GetInlineCacheJIT(invoke_instruction, &hs, &inline_cache);
391
392 switch (inline_cache_type) {
393 case kInlineCacheNoData:
394 break;
395
396 case kInlineCacheUninitialized:
397 VLOG(compiler) << "Interface or virtual call to "
398 << caller_dex_file.PrettyMethod(invoke_instruction->GetDexMethodIndex())
399 << " is not hit and not inlined";
400 return false;
401
402 case kInlineCacheMonomorphic:
403 MaybeRecordStat(kMonomorphicCall);
404 if (outermost_graph_->IsCompilingOsr()) {
405 // If we are compiling OSR, we pretend this call is polymorphic, as we may come from the
406 // interpreter and it may have seen different receiver types.
407 return TryInlinePolymorphicCall(invoke_instruction, resolved_method, inline_cache);
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000408 } else {
Calin Juravle13439f02017-02-21 01:17:21 -0800409 return TryInlineMonomorphicCall(invoke_instruction, resolved_method, inline_cache);
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000410 }
Calin Juravle13439f02017-02-21 01:17:21 -0800411
412 case kInlineCachePolymorphic:
413 MaybeRecordStat(kPolymorphicCall);
414 return TryInlinePolymorphicCall(invoke_instruction, resolved_method, inline_cache);
415
416 case kInlineCacheMegamorphic:
417 VLOG(compiler) << "Interface or virtual call to "
418 << caller_dex_file.PrettyMethod(invoke_instruction->GetDexMethodIndex())
419 << " is megamorphic and not inlined";
420 MaybeRecordStat(kMegamorphicCall);
421 return false;
422
423 case kInlineCacheMissingTypes:
424 VLOG(compiler) << "Interface or virtual call to "
425 << caller_dex_file.PrettyMethod(invoke_instruction->GetDexMethodIndex())
426 << " is missing types and not inlined";
427 return false;
428 }
429 UNREACHABLE();
430}
431
432HInliner::InlineCacheType HInliner::GetInlineCacheJIT(
433 HInvoke* invoke_instruction,
434 StackHandleScope<1>* hs,
435 /*out*/Handle<mirror::ObjectArray<mirror::Class>>* inline_cache)
436 REQUIRES_SHARED(Locks::mutator_lock_) {
437 DCHECK(Runtime::Current()->UseJitCompilation());
438
439 ArtMethod* caller = graph_->GetArtMethod();
440 // Under JIT, we should always know the caller.
441 DCHECK(caller != nullptr);
442 ScopedProfilingInfoInlineUse spiis(caller, Thread::Current());
443 ProfilingInfo* profiling_info = spiis.GetProfilingInfo();
444
445 if (profiling_info == nullptr) {
446 return kInlineCacheNoData;
447 }
448
449 *inline_cache = AllocateInlineCacheHolder(caller_compilation_unit_, hs);
450 if (inline_cache->Get() == nullptr) {
451 // We can't extract any data if we failed to allocate;
452 return kInlineCacheNoData;
453 } else {
454 Runtime::Current()->GetJit()->GetCodeCache()->CopyInlineCacheInto(
455 *profiling_info->GetInlineCache(invoke_instruction->GetDexPc()),
456 *inline_cache);
457 return GetInlineCacheType(*inline_cache);
458 }
459}
460
461HInliner::InlineCacheType HInliner::GetInlineCacheAOT(
462 const DexFile& caller_dex_file,
463 HInvoke* invoke_instruction,
464 StackHandleScope<1>* hs,
465 /*out*/Handle<mirror::ObjectArray<mirror::Class>>* inline_cache)
466 REQUIRES_SHARED(Locks::mutator_lock_) {
467 DCHECK(Runtime::Current()->IsAotCompiler());
468 const ProfileCompilationInfo* pci = compiler_driver_->GetProfileCompilationInfo();
469 if (pci == nullptr) {
470 return kInlineCacheNoData;
471 }
472
473 ProfileCompilationInfo::OfflineProfileMethodInfo offline_profile;
474 bool found = pci->GetMethod(caller_dex_file.GetLocation(),
475 caller_dex_file.GetLocationChecksum(),
476 caller_compilation_unit_.GetDexMethodIndex(),
477 &offline_profile);
478 if (!found) {
479 return kInlineCacheNoData; // no profile information for this invocation.
480 }
481
482 *inline_cache = AllocateInlineCacheHolder(caller_compilation_unit_, hs);
483 if (inline_cache == nullptr) {
484 // We can't extract any data if we failed to allocate;
485 return kInlineCacheNoData;
486 } else {
487 return ExtractClassesFromOfflineProfile(invoke_instruction,
488 offline_profile,
489 *inline_cache);
490 }
491}
492
493HInliner::InlineCacheType HInliner::ExtractClassesFromOfflineProfile(
494 const HInvoke* invoke_instruction,
495 const ProfileCompilationInfo::OfflineProfileMethodInfo& offline_profile,
496 /*out*/Handle<mirror::ObjectArray<mirror::Class>> inline_cache)
497 REQUIRES_SHARED(Locks::mutator_lock_) {
498 const auto it = offline_profile.inline_caches.find(invoke_instruction->GetDexPc());
499 if (it == offline_profile.inline_caches.end()) {
500 return kInlineCacheUninitialized;
501 }
502
503 const ProfileCompilationInfo::DexPcData& dex_pc_data = it->second;
504
505 if (dex_pc_data.is_missing_types) {
506 return kInlineCacheMissingTypes;
507 }
508 if (dex_pc_data.is_megamorphic) {
509 return kInlineCacheMegamorphic;
510 }
511
512 DCHECK_LE(dex_pc_data.classes.size(), InlineCache::kIndividualCacheSize);
513 Thread* self = Thread::Current();
514 // We need to resolve the class relative to the containing dex file.
515 // So first, build a mapping from the index of dex file in the profile to
516 // its dex cache. This will avoid repeating the lookup when walking over
517 // the inline cache types.
518 std::vector<ObjPtr<mirror::DexCache>> dex_profile_index_to_dex_cache(
519 offline_profile.dex_references.size());
520 for (size_t i = 0; i < offline_profile.dex_references.size(); i++) {
521 bool found = false;
522 for (const DexFile* dex_file : compiler_driver_->GetDexFilesForOatFile()) {
523 if (offline_profile.dex_references[i].MatchesDex(dex_file)) {
524 dex_profile_index_to_dex_cache[i] =
525 caller_compilation_unit_.GetClassLinker()->FindDexCache(self, *dex_file);
526 found = true;
527 }
528 }
529 if (!found) {
530 VLOG(compiler) << "Could not find profiled dex file: "
531 << offline_profile.dex_references[i].dex_location;
532 return kInlineCacheMissingTypes;
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100533 }
534 }
535
Calin Juravle13439f02017-02-21 01:17:21 -0800536 // Walk over the classes and resolve them. If we cannot find a type we return
537 // kInlineCacheMissingTypes.
538 int ic_index = 0;
539 for (const ProfileCompilationInfo::ClassReference& class_ref : dex_pc_data.classes) {
540 ObjPtr<mirror::DexCache> dex_cache =
541 dex_profile_index_to_dex_cache[class_ref.dex_profile_index];
542 DCHECK(dex_cache != nullptr);
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000543 ObjPtr<mirror::Class> clazz = ClassLinker::LookupResolvedType(
544 class_ref.type_index,
545 dex_cache,
546 caller_compilation_unit_.GetClassLoader().Get());
Calin Juravle13439f02017-02-21 01:17:21 -0800547 if (clazz != nullptr) {
548 inline_cache->Set(ic_index++, clazz);
549 } else {
550 VLOG(compiler) << "Could not resolve class from inline cache in AOT mode "
551 << caller_compilation_unit_.GetDexFile()->PrettyMethod(
552 invoke_instruction->GetDexMethodIndex()) << " : "
553 << caller_compilation_unit_
554 .GetDexFile()->StringByTypeIdx(class_ref.type_index);
555 return kInlineCacheMissingTypes;
556 }
557 }
558 return GetInlineCacheType(inline_cache);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100559}
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000560
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000561HInstanceFieldGet* HInliner::BuildGetReceiverClass(ClassLinker* class_linker,
562 HInstruction* receiver,
563 uint32_t dex_pc) const {
564 ArtField* field = class_linker->GetClassRoot(ClassLinker::kJavaLangObject)->GetInstanceField(0);
565 DCHECK_EQ(std::string(field->GetName()), "shadow$_klass_");
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000566 HInstanceFieldGet* result = new (graph_->GetArena()) HInstanceFieldGet(
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000567 receiver,
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +0000568 field,
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000569 Primitive::kPrimNot,
570 field->GetOffset(),
571 field->IsVolatile(),
572 field->GetDexFieldIndex(),
573 field->GetDeclaringClass()->GetDexClassDefIndex(),
574 *field->GetDexFile(),
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000575 dex_pc);
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000576 // The class of a field is effectively final, and does not have any memory dependencies.
577 result->SetSideEffects(SideEffects::None());
578 return result;
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000579}
580
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100581bool HInliner::TryInlineMonomorphicCall(HInvoke* invoke_instruction,
582 ArtMethod* resolved_method,
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000583 Handle<mirror::ObjectArray<mirror::Class>> classes) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000584 DCHECK(invoke_instruction->IsInvokeVirtual() || invoke_instruction->IsInvokeInterface())
585 << invoke_instruction->DebugName();
586
Andreas Gampea5b09a62016-11-17 15:21:22 -0800587 dex::TypeIndex class_index = FindClassIndexIn(
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000588 GetMonomorphicType(classes), caller_compilation_unit_);
Andreas Gampea5b09a62016-11-17 15:21:22 -0800589 if (!class_index.IsValid()) {
David Sehr709b0702016-10-13 09:12:37 -0700590 VLOG(compiler) << "Call to " << ArtMethod::PrettyMethod(resolved_method)
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100591 << " from inline cache is not inlined because its class is not"
592 << " accessible to the caller";
593 return false;
594 }
595
596 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
Andreas Gampe542451c2016-07-26 09:02:02 -0700597 PointerSize pointer_size = class_linker->GetImagePointerSize();
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100598 if (invoke_instruction->IsInvokeInterface()) {
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000599 resolved_method = GetMonomorphicType(classes)->FindVirtualMethodForInterface(
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100600 resolved_method, pointer_size);
601 } else {
602 DCHECK(invoke_instruction->IsInvokeVirtual());
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000603 resolved_method = GetMonomorphicType(classes)->FindVirtualMethodForVirtual(
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100604 resolved_method, pointer_size);
605 }
606 DCHECK(resolved_method != nullptr);
607 HInstruction* receiver = invoke_instruction->InputAt(0);
608 HInstruction* cursor = invoke_instruction->GetPrevious();
609 HBasicBlock* bb_cursor = invoke_instruction->GetBlock();
Nicolas Geoffray5247c082017-01-13 14:17:29 +0000610 Handle<mirror::Class> monomorphic_type = handles_->NewHandle(GetMonomorphicType(classes));
Mingyao Yang063fc772016-08-02 11:02:54 -0700611 if (!TryInlineAndReplace(invoke_instruction,
612 resolved_method,
Nicolas Geoffray5247c082017-01-13 14:17:29 +0000613 ReferenceTypeInfo::Create(monomorphic_type, /* is_exact */ true),
Mingyao Yang063fc772016-08-02 11:02:54 -0700614 /* do_rtp */ false,
615 /* cha_devirtualize */ false)) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100616 return false;
617 }
618
619 // We successfully inlined, now add a guard.
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000620 AddTypeGuard(receiver,
621 cursor,
622 bb_cursor,
623 class_index,
Nicolas Geoffray5247c082017-01-13 14:17:29 +0000624 monomorphic_type,
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000625 invoke_instruction,
626 /* with_deoptimization */ true);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100627
628 // Run type propagation to get the guard typed, and eventually propagate the
629 // type of the receiver.
Vladimir Marko456307a2016-04-19 14:12:13 +0000630 ReferenceTypePropagation rtp_fixup(graph_,
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000631 outer_compilation_unit_.GetClassLoader(),
Vladimir Marko456307a2016-04-19 14:12:13 +0000632 outer_compilation_unit_.GetDexCache(),
633 handles_,
634 /* is_first_run */ false);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100635 rtp_fixup.Run();
636
637 MaybeRecordStat(kInlinedMonomorphicCall);
638 return true;
639}
640
Mingyao Yang063fc772016-08-02 11:02:54 -0700641void HInliner::AddCHAGuard(HInstruction* invoke_instruction,
642 uint32_t dex_pc,
643 HInstruction* cursor,
644 HBasicBlock* bb_cursor) {
Mingyao Yangb0b051a2016-11-17 09:04:53 -0800645 HShouldDeoptimizeFlag* deopt_flag = new (graph_->GetArena())
646 HShouldDeoptimizeFlag(graph_->GetArena(), dex_pc);
647 HInstruction* compare = new (graph_->GetArena()) HNotEqual(
Mingyao Yang063fc772016-08-02 11:02:54 -0700648 deopt_flag, graph_->GetIntConstant(0, dex_pc));
Mingyao Yangb0b051a2016-11-17 09:04:53 -0800649 HInstruction* deopt = new (graph_->GetArena()) HDeoptimize(compare, dex_pc);
Mingyao Yang063fc772016-08-02 11:02:54 -0700650
651 if (cursor != nullptr) {
652 bb_cursor->InsertInstructionAfter(deopt_flag, cursor);
653 } else {
654 bb_cursor->InsertInstructionBefore(deopt_flag, bb_cursor->GetFirstInstruction());
655 }
Mingyao Yangb0b051a2016-11-17 09:04:53 -0800656 bb_cursor->InsertInstructionAfter(compare, deopt_flag);
657 bb_cursor->InsertInstructionAfter(deopt, compare);
658
659 // Add receiver as input to aid CHA guard optimization later.
660 deopt_flag->AddInput(invoke_instruction->InputAt(0));
661 DCHECK_EQ(deopt_flag->InputCount(), 1u);
Mingyao Yang063fc772016-08-02 11:02:54 -0700662 deopt->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
Mingyao Yangb0b051a2016-11-17 09:04:53 -0800663 outermost_graph_->IncrementNumberOfCHAGuards();
Mingyao Yang063fc772016-08-02 11:02:54 -0700664}
665
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000666HInstruction* HInliner::AddTypeGuard(HInstruction* receiver,
667 HInstruction* cursor,
668 HBasicBlock* bb_cursor,
Andreas Gampea5b09a62016-11-17 15:21:22 -0800669 dex::TypeIndex class_index,
Nicolas Geoffray5247c082017-01-13 14:17:29 +0000670 Handle<mirror::Class> klass,
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000671 HInstruction* invoke_instruction,
672 bool with_deoptimization) {
673 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
674 HInstanceFieldGet* receiver_class = BuildGetReceiverClass(
675 class_linker, receiver, invoke_instruction->GetDexPc());
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000676 if (cursor != nullptr) {
677 bb_cursor->InsertInstructionAfter(receiver_class, cursor);
678 } else {
679 bb_cursor->InsertInstructionBefore(receiver_class, bb_cursor->GetFirstInstruction());
680 }
Nicolas Geoffray56876342016-12-16 16:09:08 +0000681
682 const DexFile& caller_dex_file = *caller_compilation_unit_.GetDexFile();
Nicolas Geoffray5247c082017-01-13 14:17:29 +0000683 bool is_referrer = (klass.Get() == outermost_graph_->GetArtMethod()->GetDeclaringClass());
Nicolas Geoffray56876342016-12-16 16:09:08 +0000684 // Note that we will just compare the classes, so we don't need Java semantics access checks.
685 // Note that the type index and the dex file are relative to the method this type guard is
686 // inlined into.
687 HLoadClass* load_class = new (graph_->GetArena()) HLoadClass(graph_->GetCurrentMethod(),
688 class_index,
689 caller_dex_file,
Nicolas Geoffray5247c082017-01-13 14:17:29 +0000690 klass,
Nicolas Geoffray56876342016-12-16 16:09:08 +0000691 is_referrer,
692 invoke_instruction->GetDexPc(),
693 /* needs_access_check */ false);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +0000694 HLoadClass::LoadKind kind = HSharpening::ComputeLoadClassKind(
Nicolas Geoffray83c8e272017-01-31 14:36:37 +0000695 load_class, codegen_, compiler_driver_, caller_compilation_unit_);
696 DCHECK(kind != HLoadClass::LoadKind::kInvalid)
697 << "We should always be able to reference a class for inline caches";
698 // Insert before setting the kind, as setting the kind affects the inputs.
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000699 bb_cursor->InsertInstructionAfter(load_class, receiver_class);
Nicolas Geoffray83c8e272017-01-31 14:36:37 +0000700 load_class->SetLoadKind(kind);
Calin Juravle13439f02017-02-21 01:17:21 -0800701 // In AOT mode, we will most likely load the class from BSS, which will involve a call
702 // to the runtime. In this case, the load instruction will need an environment so copy
703 // it from the invoke instruction.
704 if (load_class->NeedsEnvironment()) {
705 DCHECK(Runtime::Current()->IsAotCompiler());
706 load_class->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
707 }
Nicolas Geoffray56876342016-12-16 16:09:08 +0000708
Nicolas Geoffray56876342016-12-16 16:09:08 +0000709 HNotEqual* compare = new (graph_->GetArena()) HNotEqual(load_class, receiver_class);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000710 bb_cursor->InsertInstructionAfter(compare, load_class);
711 if (with_deoptimization) {
712 HDeoptimize* deoptimize = new (graph_->GetArena()) HDeoptimize(
713 compare, invoke_instruction->GetDexPc());
714 bb_cursor->InsertInstructionAfter(deoptimize, compare);
715 deoptimize->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
716 }
717 return compare;
718}
719
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000720bool HInliner::TryInlinePolymorphicCall(HInvoke* invoke_instruction,
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100721 ArtMethod* resolved_method,
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000722 Handle<mirror::ObjectArray<mirror::Class>> classes) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000723 DCHECK(invoke_instruction->IsInvokeVirtual() || invoke_instruction->IsInvokeInterface())
724 << invoke_instruction->DebugName();
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000725
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000726 if (TryInlinePolymorphicCallToSameTarget(invoke_instruction, resolved_method, classes)) {
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000727 return true;
728 }
729
730 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
Andreas Gampe542451c2016-07-26 09:02:02 -0700731 PointerSize pointer_size = class_linker->GetImagePointerSize();
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000732
733 bool all_targets_inlined = true;
734 bool one_target_inlined = false;
735 for (size_t i = 0; i < InlineCache::kIndividualCacheSize; ++i) {
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000736 if (classes->Get(i) == nullptr) {
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000737 break;
738 }
739 ArtMethod* method = nullptr;
Nicolas Geoffray0f001b72017-01-04 16:46:23 +0000740
741 Handle<mirror::Class> handle = handles_->NewHandle(classes->Get(i));
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000742 if (invoke_instruction->IsInvokeInterface()) {
Nicolas Geoffray0f001b72017-01-04 16:46:23 +0000743 method = handle->FindVirtualMethodForInterface(resolved_method, pointer_size);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000744 } else {
745 DCHECK(invoke_instruction->IsInvokeVirtual());
Nicolas Geoffray0f001b72017-01-04 16:46:23 +0000746 method = handle->FindVirtualMethodForVirtual(resolved_method, pointer_size);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000747 }
748
749 HInstruction* receiver = invoke_instruction->InputAt(0);
750 HInstruction* cursor = invoke_instruction->GetPrevious();
751 HBasicBlock* bb_cursor = invoke_instruction->GetBlock();
752
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000753 dex::TypeIndex class_index = FindClassIndexIn(handle.Get(), caller_compilation_unit_);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000754 HInstruction* return_replacement = nullptr;
Andreas Gampea5b09a62016-11-17 15:21:22 -0800755 if (!class_index.IsValid() ||
Nicolas Geoffray0f001b72017-01-04 16:46:23 +0000756 !TryBuildAndInline(invoke_instruction,
757 method,
758 ReferenceTypeInfo::Create(handle, /* is_exact */ true),
759 &return_replacement)) {
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000760 all_targets_inlined = false;
761 } else {
762 one_target_inlined = true;
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000763
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +0000764 VLOG(compiler) << "Polymorphic call to " << ArtMethod::PrettyMethod(resolved_method)
765 << " has inlined " << ArtMethod::PrettyMethod(method);
766
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000767 // If we have inlined all targets before, and this receiver is the last seen,
768 // we deoptimize instead of keeping the original invoke instruction.
769 bool deoptimize = all_targets_inlined &&
770 (i != InlineCache::kIndividualCacheSize - 1) &&
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000771 (classes->Get(i + 1) == nullptr);
Nicolas Geoffray93a18c52016-04-22 13:16:14 +0100772
773 if (outermost_graph_->IsCompilingOsr()) {
774 // We do not support HDeoptimize in OSR methods.
775 deoptimize = false;
776 }
Nicolas Geoffray56876342016-12-16 16:09:08 +0000777 HInstruction* compare = AddTypeGuard(receiver,
778 cursor,
779 bb_cursor,
780 class_index,
Nicolas Geoffray5247c082017-01-13 14:17:29 +0000781 handle,
Nicolas Geoffray56876342016-12-16 16:09:08 +0000782 invoke_instruction,
783 deoptimize);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000784 if (deoptimize) {
785 if (return_replacement != nullptr) {
786 invoke_instruction->ReplaceWith(return_replacement);
787 }
788 invoke_instruction->GetBlock()->RemoveInstruction(invoke_instruction);
789 // Because the inline cache data can be populated concurrently, we force the end of the
790 // iteration. Otherhwise, we could see a new receiver type.
791 break;
792 } else {
793 CreateDiamondPatternForPolymorphicInline(compare, return_replacement, invoke_instruction);
794 }
795 }
796 }
797
798 if (!one_target_inlined) {
David Sehr709b0702016-10-13 09:12:37 -0700799 VLOG(compiler) << "Call to " << ArtMethod::PrettyMethod(resolved_method)
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000800 << " from inline cache is not inlined because none"
801 << " of its targets could be inlined";
802 return false;
803 }
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +0000804
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000805 MaybeRecordStat(kInlinedPolymorphicCall);
806
807 // Run type propagation to get the guards typed.
Vladimir Marko456307a2016-04-19 14:12:13 +0000808 ReferenceTypePropagation rtp_fixup(graph_,
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000809 outer_compilation_unit_.GetClassLoader(),
Vladimir Marko456307a2016-04-19 14:12:13 +0000810 outer_compilation_unit_.GetDexCache(),
811 handles_,
812 /* is_first_run */ false);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000813 rtp_fixup.Run();
814 return true;
815}
816
817void HInliner::CreateDiamondPatternForPolymorphicInline(HInstruction* compare,
818 HInstruction* return_replacement,
819 HInstruction* invoke_instruction) {
820 uint32_t dex_pc = invoke_instruction->GetDexPc();
821 HBasicBlock* cursor_block = compare->GetBlock();
822 HBasicBlock* original_invoke_block = invoke_instruction->GetBlock();
823 ArenaAllocator* allocator = graph_->GetArena();
824
825 // Spit the block after the compare: `cursor_block` will now be the start of the diamond,
826 // and the returned block is the start of the then branch (that could contain multiple blocks).
827 HBasicBlock* then = cursor_block->SplitAfterForInlining(compare);
828
829 // Split the block containing the invoke before and after the invoke. The returned block
830 // of the split before will contain the invoke and will be the otherwise branch of
831 // the diamond. The returned block of the split after will be the merge block
832 // of the diamond.
833 HBasicBlock* end_then = invoke_instruction->GetBlock();
834 HBasicBlock* otherwise = end_then->SplitBeforeForInlining(invoke_instruction);
835 HBasicBlock* merge = otherwise->SplitAfterForInlining(invoke_instruction);
836
837 // If the methods we are inlining return a value, we create a phi in the merge block
838 // that will have the `invoke_instruction and the `return_replacement` as inputs.
839 if (return_replacement != nullptr) {
840 HPhi* phi = new (allocator) HPhi(
841 allocator, kNoRegNumber, 0, HPhi::ToPhiType(invoke_instruction->GetType()), dex_pc);
842 merge->AddPhi(phi);
843 invoke_instruction->ReplaceWith(phi);
844 phi->AddInput(return_replacement);
845 phi->AddInput(invoke_instruction);
846 }
847
848 // Add the control flow instructions.
849 otherwise->AddInstruction(new (allocator) HGoto(dex_pc));
850 end_then->AddInstruction(new (allocator) HGoto(dex_pc));
851 cursor_block->AddInstruction(new (allocator) HIf(compare, dex_pc));
852
853 // Add the newly created blocks to the graph.
854 graph_->AddBlock(then);
855 graph_->AddBlock(otherwise);
856 graph_->AddBlock(merge);
857
858 // Set up successor (and implictly predecessor) relations.
859 cursor_block->AddSuccessor(otherwise);
860 cursor_block->AddSuccessor(then);
861 end_then->AddSuccessor(merge);
862 otherwise->AddSuccessor(merge);
863
864 // Set up dominance information.
865 then->SetDominator(cursor_block);
866 cursor_block->AddDominatedBlock(then);
867 otherwise->SetDominator(cursor_block);
868 cursor_block->AddDominatedBlock(otherwise);
869 merge->SetDominator(cursor_block);
870 cursor_block->AddDominatedBlock(merge);
871
872 // Update the revert post order.
873 size_t index = IndexOfElement(graph_->reverse_post_order_, cursor_block);
874 MakeRoomFor(&graph_->reverse_post_order_, 1, index);
875 graph_->reverse_post_order_[++index] = then;
876 index = IndexOfElement(graph_->reverse_post_order_, end_then);
877 MakeRoomFor(&graph_->reverse_post_order_, 2, index);
878 graph_->reverse_post_order_[++index] = otherwise;
879 graph_->reverse_post_order_[++index] = merge;
880
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000881
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +0000882 graph_->UpdateLoopAndTryInformationOfNewBlock(
883 then, original_invoke_block, /* replace_if_back_edge */ false);
884 graph_->UpdateLoopAndTryInformationOfNewBlock(
885 otherwise, original_invoke_block, /* replace_if_back_edge */ false);
886
887 // In case the original invoke location was a back edge, we need to update
888 // the loop to now have the merge block as a back edge.
889 graph_->UpdateLoopAndTryInformationOfNewBlock(
890 merge, original_invoke_block, /* replace_if_back_edge */ true);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000891}
892
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000893bool HInliner::TryInlinePolymorphicCallToSameTarget(
894 HInvoke* invoke_instruction,
895 ArtMethod* resolved_method,
896 Handle<mirror::ObjectArray<mirror::Class>> classes) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000897 // This optimization only works under JIT for now.
Calin Juravle13439f02017-02-21 01:17:21 -0800898 if (!Runtime::Current()->UseJitCompilation()) {
899 return false;
900 }
901
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000902 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
Andreas Gampe542451c2016-07-26 09:02:02 -0700903 PointerSize pointer_size = class_linker->GetImagePointerSize();
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000904
905 DCHECK(resolved_method != nullptr);
906 ArtMethod* actual_method = nullptr;
Nicolas Geoffray4f97a212016-02-25 16:17:54 +0000907 size_t method_index = invoke_instruction->IsInvokeVirtual()
908 ? invoke_instruction->AsInvokeVirtual()->GetVTableIndex()
909 : invoke_instruction->AsInvokeInterface()->GetImtIndex();
910
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000911 // Check whether we are actually calling the same method among
912 // the different types seen.
913 for (size_t i = 0; i < InlineCache::kIndividualCacheSize; ++i) {
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000914 if (classes->Get(i) == nullptr) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000915 break;
916 }
917 ArtMethod* new_method = nullptr;
918 if (invoke_instruction->IsInvokeInterface()) {
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000919 new_method = classes->Get(i)->GetImt(pointer_size)->Get(
Matthew Gharrity465ecc82016-07-19 21:32:52 +0000920 method_index, pointer_size);
Nicolas Geoffray4f97a212016-02-25 16:17:54 +0000921 if (new_method->IsRuntimeMethod()) {
922 // Bail out as soon as we see a conflict trampoline in one of the target's
923 // interface table.
924 return false;
925 }
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000926 } else {
927 DCHECK(invoke_instruction->IsInvokeVirtual());
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000928 new_method = classes->Get(i)->GetEmbeddedVTableEntry(method_index, pointer_size);
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000929 }
Nicolas Geoffray4f97a212016-02-25 16:17:54 +0000930 DCHECK(new_method != nullptr);
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000931 if (actual_method == nullptr) {
932 actual_method = new_method;
933 } else if (actual_method != new_method) {
934 // Different methods, bailout.
David Sehr709b0702016-10-13 09:12:37 -0700935 VLOG(compiler) << "Call to " << ArtMethod::PrettyMethod(resolved_method)
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +0000936 << " from inline cache is not inlined because it resolves"
937 << " to different methods";
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000938 return false;
939 }
940 }
941
942 HInstruction* receiver = invoke_instruction->InputAt(0);
943 HInstruction* cursor = invoke_instruction->GetPrevious();
944 HBasicBlock* bb_cursor = invoke_instruction->GetBlock();
945
Nicolas Geoffray93a18c52016-04-22 13:16:14 +0100946 HInstruction* return_replacement = nullptr;
Nicolas Geoffray0f001b72017-01-04 16:46:23 +0000947 if (!TryBuildAndInline(invoke_instruction,
948 actual_method,
949 ReferenceTypeInfo::CreateInvalid(),
950 &return_replacement)) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000951 return false;
952 }
953
954 // We successfully inlined, now add a guard.
955 HInstanceFieldGet* receiver_class = BuildGetReceiverClass(
956 class_linker, receiver, invoke_instruction->GetDexPc());
957
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000958 Primitive::Type type = Is64BitInstructionSet(graph_->GetInstructionSet())
959 ? Primitive::kPrimLong
960 : Primitive::kPrimInt;
961 HClassTableGet* class_table_get = new (graph_->GetArena()) HClassTableGet(
962 receiver_class,
963 type,
Vladimir Markoa1de9182016-02-25 11:37:38 +0000964 invoke_instruction->IsInvokeVirtual() ? HClassTableGet::TableKind::kVTable
965 : HClassTableGet::TableKind::kIMTable,
Nicolas Geoffray4f97a212016-02-25 16:17:54 +0000966 method_index,
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000967 invoke_instruction->GetDexPc());
968
969 HConstant* constant;
970 if (type == Primitive::kPrimLong) {
971 constant = graph_->GetLongConstant(
972 reinterpret_cast<intptr_t>(actual_method), invoke_instruction->GetDexPc());
973 } else {
974 constant = graph_->GetIntConstant(
975 reinterpret_cast<intptr_t>(actual_method), invoke_instruction->GetDexPc());
976 }
977
978 HNotEqual* compare = new (graph_->GetArena()) HNotEqual(class_table_get, constant);
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000979 if (cursor != nullptr) {
980 bb_cursor->InsertInstructionAfter(receiver_class, cursor);
981 } else {
982 bb_cursor->InsertInstructionBefore(receiver_class, bb_cursor->GetFirstInstruction());
983 }
984 bb_cursor->InsertInstructionAfter(class_table_get, receiver_class);
985 bb_cursor->InsertInstructionAfter(compare, class_table_get);
Nicolas Geoffray93a18c52016-04-22 13:16:14 +0100986
987 if (outermost_graph_->IsCompilingOsr()) {
988 CreateDiamondPatternForPolymorphicInline(compare, return_replacement, invoke_instruction);
989 } else {
Nicolas Geoffray93a18c52016-04-22 13:16:14 +0100990 HDeoptimize* deoptimize = new (graph_->GetArena()) HDeoptimize(
991 compare, invoke_instruction->GetDexPc());
992 bb_cursor->InsertInstructionAfter(deoptimize, compare);
993 deoptimize->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
994 if (return_replacement != nullptr) {
995 invoke_instruction->ReplaceWith(return_replacement);
996 }
Nicolas Geoffray1be7cbd2016-04-29 13:56:01 +0100997 invoke_instruction->GetBlock()->RemoveInstruction(invoke_instruction);
Nicolas Geoffray93a18c52016-04-22 13:16:14 +0100998 }
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000999
1000 // Run type propagation to get the guard typed.
Vladimir Marko456307a2016-04-19 14:12:13 +00001001 ReferenceTypePropagation rtp_fixup(graph_,
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001002 outer_compilation_unit_.GetClassLoader(),
Vladimir Marko456307a2016-04-19 14:12:13 +00001003 outer_compilation_unit_.GetDexCache(),
1004 handles_,
1005 /* is_first_run */ false);
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001006 rtp_fixup.Run();
1007
1008 MaybeRecordStat(kInlinedPolymorphicCall);
1009
1010 return true;
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001011}
1012
Mingyao Yang063fc772016-08-02 11:02:54 -07001013bool HInliner::TryInlineAndReplace(HInvoke* invoke_instruction,
1014 ArtMethod* method,
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001015 ReferenceTypeInfo receiver_type,
Mingyao Yang063fc772016-08-02 11:02:54 -07001016 bool do_rtp,
1017 bool cha_devirtualize) {
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001018 HInstruction* return_replacement = nullptr;
Mingyao Yang063fc772016-08-02 11:02:54 -07001019 uint32_t dex_pc = invoke_instruction->GetDexPc();
1020 HInstruction* cursor = invoke_instruction->GetPrevious();
1021 HBasicBlock* bb_cursor = invoke_instruction->GetBlock();
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001022 if (!TryBuildAndInline(invoke_instruction, method, receiver_type, &return_replacement)) {
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +00001023 if (invoke_instruction->IsInvokeInterface()) {
1024 // Turn an invoke-interface into an invoke-virtual. An invoke-virtual is always
1025 // better than an invoke-interface because:
1026 // 1) In the best case, the interface call has one more indirection (to fetch the IMT).
1027 // 2) We will not go to the conflict trampoline with an invoke-virtual.
1028 // TODO: Consider sharpening once it is not dependent on the compiler driver.
1029 const DexFile& caller_dex_file = *caller_compilation_unit_.GetDexFile();
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +01001030 uint32_t dex_method_index = FindMethodIndexIn(
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +00001031 method, caller_dex_file, invoke_instruction->GetDexMethodIndex());
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +01001032 if (dex_method_index == DexFile::kDexNoIndex) {
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +00001033 return false;
1034 }
1035 HInvokeVirtual* new_invoke = new (graph_->GetArena()) HInvokeVirtual(
1036 graph_->GetArena(),
1037 invoke_instruction->GetNumberOfArguments(),
1038 invoke_instruction->GetType(),
1039 invoke_instruction->GetDexPc(),
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +01001040 dex_method_index,
1041 method,
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +00001042 method->GetMethodIndex());
1043 HInputsRef inputs = invoke_instruction->GetInputs();
1044 for (size_t index = 0; index != inputs.size(); ++index) {
1045 new_invoke->SetArgumentAt(index, inputs[index]);
1046 }
1047 invoke_instruction->GetBlock()->InsertInstructionBefore(new_invoke, invoke_instruction);
1048 new_invoke->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
1049 if (invoke_instruction->GetType() == Primitive::kPrimNot) {
1050 new_invoke->SetReferenceTypeInfo(invoke_instruction->GetReferenceTypeInfo());
1051 }
1052 return_replacement = new_invoke;
1053 } else {
1054 // TODO: Consider sharpening an invoke virtual once it is not dependent on the
1055 // compiler driver.
1056 return false;
1057 }
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001058 }
Mingyao Yang063fc772016-08-02 11:02:54 -07001059 if (cha_devirtualize) {
1060 AddCHAGuard(invoke_instruction, dex_pc, cursor, bb_cursor);
1061 }
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001062 if (return_replacement != nullptr) {
1063 invoke_instruction->ReplaceWith(return_replacement);
1064 }
1065 invoke_instruction->GetBlock()->RemoveInstruction(invoke_instruction);
David Brazdil94ab38f2016-06-21 17:48:19 +01001066 FixUpReturnReferenceType(method, return_replacement);
1067 if (do_rtp && ReturnTypeMoreSpecific(invoke_instruction, return_replacement)) {
1068 // Actual return value has a more specific type than the method's declared
1069 // return type. Run RTP again on the outer graph to propagate it.
1070 ReferenceTypePropagation(graph_,
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001071 outer_compilation_unit_.GetClassLoader(),
David Brazdil94ab38f2016-06-21 17:48:19 +01001072 outer_compilation_unit_.GetDexCache(),
1073 handles_,
1074 /* is_first_run */ false).Run();
1075 }
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001076 return true;
1077}
1078
1079bool HInliner::TryBuildAndInline(HInvoke* invoke_instruction,
1080 ArtMethod* method,
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001081 ReferenceTypeInfo receiver_type,
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001082 HInstruction** return_replacement) {
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01001083 if (method->IsProxyMethod()) {
David Sehr709b0702016-10-13 09:12:37 -07001084 VLOG(compiler) << "Method " << method->PrettyMethod()
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01001085 << " is not inlined because of unimplemented inline support for proxy methods.";
1086 return false;
1087 }
1088
Jeff Haodcdc85b2015-12-04 14:06:18 -08001089 // Check whether we're allowed to inline. The outermost compilation unit is the relevant
1090 // dex file here (though the transitivity of an inline chain would allow checking the calller).
1091 if (!compiler_driver_->MayInline(method->GetDexFile(),
1092 outer_compilation_unit_.GetDexFile())) {
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001093 if (TryPatternSubstitution(invoke_instruction, method, return_replacement)) {
David Sehr709b0702016-10-13 09:12:37 -07001094 VLOG(compiler) << "Successfully replaced pattern of invoke "
1095 << method->PrettyMethod();
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001096 MaybeRecordStat(kReplacedInvokeWithSimplePattern);
1097 return true;
1098 }
David Sehr709b0702016-10-13 09:12:37 -07001099 VLOG(compiler) << "Won't inline " << method->PrettyMethod() << " in "
Jeff Haodcdc85b2015-12-04 14:06:18 -08001100 << outer_compilation_unit_.GetDexFile()->GetLocation() << " ("
1101 << caller_compilation_unit_.GetDexFile()->GetLocation() << ") from "
1102 << method->GetDexFile()->GetLocation();
1103 return false;
1104 }
1105
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001106 bool same_dex_file = IsSameDexFile(*outer_compilation_unit_.GetDexFile(), *method->GetDexFile());
1107
1108 const DexFile::CodeItem* code_item = method->GetCodeItem();
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001109
1110 if (code_item == nullptr) {
David Sehr709b0702016-10-13 09:12:37 -07001111 VLOG(compiler) << "Method " << method->PrettyMethod()
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001112 << " is not inlined because it is native";
1113 return false;
1114 }
1115
Calin Juravleec748352015-07-29 13:52:12 +01001116 size_t inline_max_code_units = compiler_driver_->GetCompilerOptions().GetInlineMaxCodeUnits();
1117 if (code_item->insns_size_in_code_units_ > inline_max_code_units) {
David Sehr709b0702016-10-13 09:12:37 -07001118 VLOG(compiler) << "Method " << method->PrettyMethod()
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00001119 << " is too big to inline: "
1120 << code_item->insns_size_in_code_units_
1121 << " > "
1122 << inline_max_code_units;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001123 return false;
1124 }
1125
1126 if (code_item->tries_size_ != 0) {
David Sehr709b0702016-10-13 09:12:37 -07001127 VLOG(compiler) << "Method " << method->PrettyMethod()
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001128 << " is not inlined because of try block";
1129 return false;
1130 }
1131
Nicolas Geoffray250a3782016-04-20 16:27:53 +01001132 if (!method->IsCompilable()) {
David Sehr709b0702016-10-13 09:12:37 -07001133 VLOG(compiler) << "Method " << method->PrettyMethod()
Nicolas Geoffray250a3782016-04-20 16:27:53 +01001134 << " has soft failures un-handled by the compiler, so it cannot be inlined";
1135 }
1136
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001137 if (!method->GetDeclaringClass()->IsVerified()) {
1138 uint16_t class_def_idx = method->GetDeclaringClass()->GetDexClassDefIndex();
Calin Juravleffc87072016-04-20 14:22:09 +01001139 if (Runtime::Current()->UseJitCompilation() ||
Nicolas Geoffray5b82d332016-02-18 14:22:32 +00001140 !compiler_driver_->IsMethodVerifiedWithoutFailures(
1141 method->GetDexMethodIndex(), class_def_idx, *method->GetDexFile())) {
David Sehr709b0702016-10-13 09:12:37 -07001142 VLOG(compiler) << "Method " << method->PrettyMethod()
Nicolas Geoffrayccc61972015-10-01 14:34:20 +01001143 << " couldn't be verified, so it cannot be inlined";
1144 return false;
1145 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001146 }
1147
Roland Levillain4c0eb422015-04-24 16:43:49 +01001148 if (invoke_instruction->IsInvokeStaticOrDirect() &&
1149 invoke_instruction->AsInvokeStaticOrDirect()->IsStaticWithImplicitClinitCheck()) {
1150 // Case of a static method that cannot be inlined because it implicitly
1151 // requires an initialization check of its declaring class.
David Sehr709b0702016-10-13 09:12:37 -07001152 VLOG(compiler) << "Method " << method->PrettyMethod()
Roland Levillain4c0eb422015-04-24 16:43:49 +01001153 << " is not inlined because it is static and requires a clinit"
1154 << " check that cannot be emitted due to Dex cache limitations";
1155 return false;
1156 }
1157
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001158 if (!TryBuildAndInlineHelper(
1159 invoke_instruction, method, receiver_type, same_dex_file, return_replacement)) {
Nicolas Geoffrayc0365b12015-03-18 18:31:52 +00001160 return false;
1161 }
1162
David Sehr709b0702016-10-13 09:12:37 -07001163 VLOG(compiler) << "Successfully inlined " << method->PrettyMethod();
Nicolas Geoffrayc0365b12015-03-18 18:31:52 +00001164 MaybeRecordStat(kInlinedInvoke);
1165 return true;
1166}
1167
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001168static HInstruction* GetInvokeInputForArgVRegIndex(HInvoke* invoke_instruction,
1169 size_t arg_vreg_index)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001170 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001171 size_t input_index = 0;
1172 for (size_t i = 0; i < arg_vreg_index; ++i, ++input_index) {
1173 DCHECK_LT(input_index, invoke_instruction->GetNumberOfArguments());
1174 if (Primitive::Is64BitType(invoke_instruction->InputAt(input_index)->GetType())) {
1175 ++i;
1176 DCHECK_NE(i, arg_vreg_index);
1177 }
1178 }
1179 DCHECK_LT(input_index, invoke_instruction->GetNumberOfArguments());
1180 return invoke_instruction->InputAt(input_index);
1181}
1182
1183// Try to recognize known simple patterns and replace invoke call with appropriate instructions.
1184bool HInliner::TryPatternSubstitution(HInvoke* invoke_instruction,
1185 ArtMethod* resolved_method,
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001186 HInstruction** return_replacement) {
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001187 InlineMethod inline_method;
1188 if (!InlineMethodAnalyser::AnalyseMethodCode(resolved_method, &inline_method)) {
1189 return false;
1190 }
1191
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001192 switch (inline_method.opcode) {
1193 case kInlineOpNop:
1194 DCHECK_EQ(invoke_instruction->GetType(), Primitive::kPrimVoid);
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001195 *return_replacement = nullptr;
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001196 break;
1197 case kInlineOpReturnArg:
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001198 *return_replacement = GetInvokeInputForArgVRegIndex(invoke_instruction,
1199 inline_method.d.return_data.arg);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001200 break;
1201 case kInlineOpNonWideConst:
1202 if (resolved_method->GetShorty()[0] == 'L') {
1203 DCHECK_EQ(inline_method.d.data, 0u);
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001204 *return_replacement = graph_->GetNullConstant();
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001205 } else {
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001206 *return_replacement = graph_->GetIntConstant(static_cast<int32_t>(inline_method.d.data));
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001207 }
1208 break;
1209 case kInlineOpIGet: {
1210 const InlineIGetIPutData& data = inline_method.d.ifield_data;
1211 if (data.method_is_static || data.object_arg != 0u) {
1212 // TODO: Needs null check.
1213 return false;
1214 }
1215 HInstruction* obj = GetInvokeInputForArgVRegIndex(invoke_instruction, data.object_arg);
Vladimir Markof44d36c2017-03-14 14:18:46 +00001216 HInstanceFieldGet* iget = CreateInstanceFieldGet(data.field_idx, resolved_method, obj);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001217 DCHECK_EQ(iget->GetFieldOffset().Uint32Value(), data.field_offset);
1218 DCHECK_EQ(iget->IsVolatile() ? 1u : 0u, data.is_volatile);
1219 invoke_instruction->GetBlock()->InsertInstructionBefore(iget, invoke_instruction);
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001220 *return_replacement = iget;
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001221 break;
1222 }
1223 case kInlineOpIPut: {
1224 const InlineIGetIPutData& data = inline_method.d.ifield_data;
1225 if (data.method_is_static || data.object_arg != 0u) {
1226 // TODO: Needs null check.
1227 return false;
1228 }
1229 HInstruction* obj = GetInvokeInputForArgVRegIndex(invoke_instruction, data.object_arg);
1230 HInstruction* value = GetInvokeInputForArgVRegIndex(invoke_instruction, data.src_arg);
Vladimir Markof44d36c2017-03-14 14:18:46 +00001231 HInstanceFieldSet* iput = CreateInstanceFieldSet(data.field_idx, resolved_method, obj, value);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001232 DCHECK_EQ(iput->GetFieldOffset().Uint32Value(), data.field_offset);
1233 DCHECK_EQ(iput->IsVolatile() ? 1u : 0u, data.is_volatile);
1234 invoke_instruction->GetBlock()->InsertInstructionBefore(iput, invoke_instruction);
1235 if (data.return_arg_plus1 != 0u) {
1236 size_t return_arg = data.return_arg_plus1 - 1u;
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001237 *return_replacement = GetInvokeInputForArgVRegIndex(invoke_instruction, return_arg);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001238 }
1239 break;
1240 }
Vladimir Marko354efa62016-02-04 19:46:56 +00001241 case kInlineOpConstructor: {
1242 const InlineConstructorData& data = inline_method.d.constructor_data;
1243 // Get the indexes to arrays for easier processing.
1244 uint16_t iput_field_indexes[] = {
1245 data.iput0_field_index, data.iput1_field_index, data.iput2_field_index
1246 };
1247 uint16_t iput_args[] = { data.iput0_arg, data.iput1_arg, data.iput2_arg };
1248 static_assert(arraysize(iput_args) == arraysize(iput_field_indexes), "Size mismatch");
1249 // Count valid field indexes.
1250 size_t number_of_iputs = 0u;
1251 while (number_of_iputs != arraysize(iput_field_indexes) &&
1252 iput_field_indexes[number_of_iputs] != DexFile::kDexNoIndex16) {
1253 // Check that there are no duplicate valid field indexes.
1254 DCHECK_EQ(0, std::count(iput_field_indexes + number_of_iputs + 1,
1255 iput_field_indexes + arraysize(iput_field_indexes),
1256 iput_field_indexes[number_of_iputs]));
1257 ++number_of_iputs;
1258 }
1259 // Check that there are no valid field indexes in the rest of the array.
1260 DCHECK_EQ(0, std::count_if(iput_field_indexes + number_of_iputs,
1261 iput_field_indexes + arraysize(iput_field_indexes),
1262 [](uint16_t index) { return index != DexFile::kDexNoIndex16; }));
1263
1264 // Create HInstanceFieldSet for each IPUT that stores non-zero data.
Vladimir Marko354efa62016-02-04 19:46:56 +00001265 HInstruction* obj = GetInvokeInputForArgVRegIndex(invoke_instruction, /* this */ 0u);
1266 bool needs_constructor_barrier = false;
1267 for (size_t i = 0; i != number_of_iputs; ++i) {
1268 HInstruction* value = GetInvokeInputForArgVRegIndex(invoke_instruction, iput_args[i]);
Roland Levillain1a653882016-03-18 18:05:57 +00001269 if (!value->IsConstant() || !value->AsConstant()->IsZeroBitPattern()) {
Vladimir Marko354efa62016-02-04 19:46:56 +00001270 uint16_t field_index = iput_field_indexes[i];
Vladimir Markof44d36c2017-03-14 14:18:46 +00001271 bool is_final;
1272 HInstanceFieldSet* iput =
1273 CreateInstanceFieldSet(field_index, resolved_method, obj, value, &is_final);
Vladimir Marko354efa62016-02-04 19:46:56 +00001274 invoke_instruction->GetBlock()->InsertInstructionBefore(iput, invoke_instruction);
1275
1276 // Check whether the field is final. If it is, we need to add a barrier.
Vladimir Markof44d36c2017-03-14 14:18:46 +00001277 if (is_final) {
Vladimir Marko354efa62016-02-04 19:46:56 +00001278 needs_constructor_barrier = true;
1279 }
1280 }
1281 }
1282 if (needs_constructor_barrier) {
1283 HMemoryBarrier* barrier = new (graph_->GetArena()) HMemoryBarrier(kStoreStore, kNoDexPc);
1284 invoke_instruction->GetBlock()->InsertInstructionBefore(barrier, invoke_instruction);
1285 }
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001286 *return_replacement = nullptr;
Vladimir Marko354efa62016-02-04 19:46:56 +00001287 break;
1288 }
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001289 default:
1290 LOG(FATAL) << "UNREACHABLE";
1291 UNREACHABLE();
1292 }
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001293 return true;
1294}
1295
Vladimir Markof44d36c2017-03-14 14:18:46 +00001296HInstanceFieldGet* HInliner::CreateInstanceFieldGet(uint32_t field_index,
1297 ArtMethod* referrer,
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001298 HInstruction* obj)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001299 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markof44d36c2017-03-14 14:18:46 +00001300 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1301 ArtField* resolved_field =
1302 class_linker->LookupResolvedField(field_index, referrer, /* is_static */ false);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001303 DCHECK(resolved_field != nullptr);
1304 HInstanceFieldGet* iget = new (graph_->GetArena()) HInstanceFieldGet(
1305 obj,
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00001306 resolved_field,
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001307 resolved_field->GetTypeAsPrimitiveType(),
1308 resolved_field->GetOffset(),
1309 resolved_field->IsVolatile(),
1310 field_index,
1311 resolved_field->GetDeclaringClass()->GetDexClassDefIndex(),
Vladimir Markof44d36c2017-03-14 14:18:46 +00001312 *referrer->GetDexFile(),
Vladimir Markoadda4352016-01-29 10:24:41 +00001313 // Read barrier generates a runtime call in slow path and we need a valid
1314 // dex pc for the associated stack map. 0 is bogus but valid. Bug: 26854537.
1315 /* dex_pc */ 0);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001316 if (iget->GetType() == Primitive::kPrimNot) {
Vladimir Marko456307a2016-04-19 14:12:13 +00001317 // Use the same dex_cache that we used for field lookup as the hint_dex_cache.
Vladimir Markof44d36c2017-03-14 14:18:46 +00001318 Handle<mirror::DexCache> dex_cache = handles_->NewHandle(referrer->GetDexCache());
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001319 ReferenceTypePropagation rtp(graph_,
1320 outer_compilation_unit_.GetClassLoader(),
1321 dex_cache,
1322 handles_,
1323 /* is_first_run */ false);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001324 rtp.Visit(iget);
1325 }
1326 return iget;
1327}
1328
Vladimir Markof44d36c2017-03-14 14:18:46 +00001329HInstanceFieldSet* HInliner::CreateInstanceFieldSet(uint32_t field_index,
1330 ArtMethod* referrer,
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001331 HInstruction* obj,
Vladimir Markof44d36c2017-03-14 14:18:46 +00001332 HInstruction* value,
1333 bool* is_final)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001334 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markof44d36c2017-03-14 14:18:46 +00001335 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1336 ArtField* resolved_field =
1337 class_linker->LookupResolvedField(field_index, referrer, /* is_static */ false);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001338 DCHECK(resolved_field != nullptr);
Vladimir Markof44d36c2017-03-14 14:18:46 +00001339 if (is_final != nullptr) {
1340 // This information is needed only for constructors.
1341 DCHECK(referrer->IsConstructor());
1342 *is_final = resolved_field->IsFinal();
1343 }
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001344 HInstanceFieldSet* iput = new (graph_->GetArena()) HInstanceFieldSet(
1345 obj,
1346 value,
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00001347 resolved_field,
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001348 resolved_field->GetTypeAsPrimitiveType(),
1349 resolved_field->GetOffset(),
1350 resolved_field->IsVolatile(),
1351 field_index,
1352 resolved_field->GetDeclaringClass()->GetDexClassDefIndex(),
Vladimir Markof44d36c2017-03-14 14:18:46 +00001353 *referrer->GetDexFile(),
Vladimir Markoadda4352016-01-29 10:24:41 +00001354 // Read barrier generates a runtime call in slow path and we need a valid
1355 // dex pc for the associated stack map. 0 is bogus but valid. Bug: 26854537.
1356 /* dex_pc */ 0);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001357 return iput;
1358}
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +00001359
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001360bool HInliner::TryBuildAndInlineHelper(HInvoke* invoke_instruction,
1361 ArtMethod* resolved_method,
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001362 ReferenceTypeInfo receiver_type,
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001363 bool same_dex_file,
1364 HInstruction** return_replacement) {
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001365 DCHECK(!(resolved_method->IsStatic() && receiver_type.IsValid()));
Nicolas Geoffrayc0365b12015-03-18 18:31:52 +00001366 ScopedObjectAccess soa(Thread::Current());
1367 const DexFile::CodeItem* code_item = resolved_method->GetCodeItem();
Guillaume "Vermeille" Sanchezae09d2d2015-05-29 10:52:55 +01001368 const DexFile& callee_dex_file = *resolved_method->GetDexFile();
1369 uint32_t method_index = resolved_method->GetDexMethodIndex();
Calin Juravle2e768302015-07-28 14:41:11 +00001370 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
Mathieu Chartier736b5602015-09-02 14:54:11 -07001371 Handle<mirror::DexCache> dex_cache(handles_->NewHandle(resolved_method->GetDexCache()));
Nicolas Geoffrayf1aedb12016-07-28 03:49:14 +01001372 Handle<mirror::ClassLoader> class_loader(handles_->NewHandle(
1373 resolved_method->GetDeclaringClass()->GetClassLoader()));
1374
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001375 DexCompilationUnit dex_compilation_unit(
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001376 class_loader,
Nicolas Geoffray5b82d332016-02-18 14:22:32 +00001377 class_linker,
1378 callee_dex_file,
1379 code_item,
1380 resolved_method->GetDeclaringClass()->GetDexClassDefIndex(),
1381 method_index,
1382 resolved_method->GetAccessFlags(),
1383 /* verified_method */ nullptr,
1384 dex_cache);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001385
Calin Juravle3cd4fc82015-05-14 15:15:42 +01001386 bool requires_ctor_barrier = false;
1387
1388 if (dex_compilation_unit.IsConstructor()) {
1389 // If it's a super invocation and we already generate a barrier there's no need
1390 // to generate another one.
1391 // We identify super calls by looking at the "this" pointer. If its value is the
1392 // same as the local "this" pointer then we must have a super invocation.
1393 bool is_super_invocation = invoke_instruction->InputAt(0)->IsParameterValue()
1394 && invoke_instruction->InputAt(0)->AsParameterValue()->IsThis();
1395 if (is_super_invocation && graph_->ShouldGenerateConstructorBarrier()) {
1396 requires_ctor_barrier = false;
1397 } else {
1398 Thread* self = Thread::Current();
1399 requires_ctor_barrier = compiler_driver_->RequiresConstructorBarrier(self,
1400 dex_compilation_unit.GetDexFile(),
1401 dex_compilation_unit.GetClassDefIndex());
1402 }
1403 }
1404
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +01001405 InvokeType invoke_type = invoke_instruction->GetInvokeType();
Nicolas Geoffray35071052015-06-09 15:43:38 +01001406 if (invoke_type == kInterface) {
1407 // We have statically resolved the dispatch. To please the class linker
1408 // at runtime, we change this call as if it was a virtual call.
1409 invoke_type = kVirtual;
1410 }
David Brazdil3f523062016-02-29 16:53:33 +00001411
1412 const int32_t caller_instruction_counter = graph_->GetCurrentInstructionId();
Nicolas Geoffraye0fe7ae2015-03-09 10:02:49 +00001413 HGraph* callee_graph = new (graph_->GetArena()) HGraph(
Nicolas Geoffray0a23d742015-05-07 11:57:35 +01001414 graph_->GetArena(),
Guillaume "Vermeille" Sanchezae09d2d2015-05-29 10:52:55 +01001415 callee_dex_file,
Nicolas Geoffray0a23d742015-05-07 11:57:35 +01001416 method_index,
Calin Juravle3cd4fc82015-05-14 15:15:42 +01001417 requires_ctor_barrier,
Mathieu Chartiere401d142015-04-22 13:56:20 -07001418 compiler_driver_->GetInstructionSet(),
Nicolas Geoffray35071052015-06-09 15:43:38 +01001419 invoke_type,
Nicolas Geoffray0a23d742015-05-07 11:57:35 +01001420 graph_->IsDebuggable(),
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001421 /* osr */ false,
David Brazdil3f523062016-02-29 16:53:33 +00001422 caller_instruction_counter);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001423 callee_graph->SetArtMethod(resolved_method);
David Brazdil5e8b1372015-01-23 14:39:08 +00001424
Vladimir Marko438709f2017-02-23 18:56:13 +00001425 // When they are needed, allocate `inline_stats_` on the Arena instead
Roland Levillaina8013fd2016-04-04 15:34:31 +01001426 // of on the stack, as Clang might produce a stack frame too large
1427 // for this function, that would not fit the requirements of the
1428 // `-Wframe-larger-than` option.
Vladimir Marko438709f2017-02-23 18:56:13 +00001429 if (stats_ != nullptr) {
1430 // Reuse one object for all inline attempts from this caller to keep Arena memory usage low.
1431 if (inline_stats_ == nullptr) {
1432 void* storage = graph_->GetArena()->Alloc<OptimizingCompilerStats>(kArenaAllocMisc);
1433 inline_stats_ = new (storage) OptimizingCompilerStats;
1434 } else {
1435 inline_stats_->Reset();
1436 }
1437 }
David Brazdil5e8b1372015-01-23 14:39:08 +00001438 HGraphBuilder builder(callee_graph,
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001439 &dex_compilation_unit,
1440 &outer_compilation_unit_,
Nicolas Geoffray9437b782015-03-25 10:08:51 +00001441 resolved_method->GetDexFile(),
David Brazdil86ea7ee2016-02-16 09:26:07 +00001442 *code_item,
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001443 compiler_driver_,
Nicolas Geoffray83c8e272017-01-31 14:36:37 +00001444 codegen_,
Vladimir Marko438709f2017-02-23 18:56:13 +00001445 inline_stats_,
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01001446 resolved_method->GetQuickenedInfo(class_linker->GetImagePointerSize()),
David Brazdildee58d62016-04-07 09:54:26 +00001447 dex_cache,
1448 handles_);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001449
David Brazdildee58d62016-04-07 09:54:26 +00001450 if (builder.BuildGraph() != kAnalysisSuccess) {
David Sehr709b0702016-10-13 09:12:37 -07001451 VLOG(compiler) << "Method " << callee_dex_file.PrettyMethod(method_index)
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001452 << " could not be built, so cannot be inlined";
1453 return false;
1454 }
1455
Nicolas Geoffray259136f2014-12-17 23:21:58 +00001456 if (!RegisterAllocator::CanAllocateRegistersFor(*callee_graph,
1457 compiler_driver_->GetInstructionSet())) {
David Sehr709b0702016-10-13 09:12:37 -07001458 VLOG(compiler) << "Method " << callee_dex_file.PrettyMethod(method_index)
Nicolas Geoffray259136f2014-12-17 23:21:58 +00001459 << " cannot be inlined because of the register allocator";
1460 return false;
1461 }
1462
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001463 size_t parameter_index = 0;
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001464 bool run_rtp = false;
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001465 for (HInstructionIterator instructions(callee_graph->GetEntryBlock()->GetInstructions());
1466 !instructions.Done();
1467 instructions.Advance()) {
1468 HInstruction* current = instructions.Current();
1469 if (current->IsParameterValue()) {
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001470 HInstruction* argument = invoke_instruction->InputAt(parameter_index);
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001471 if (argument->IsNullConstant()) {
1472 current->ReplaceWith(callee_graph->GetNullConstant());
1473 } else if (argument->IsIntConstant()) {
1474 current->ReplaceWith(callee_graph->GetIntConstant(argument->AsIntConstant()->GetValue()));
1475 } else if (argument->IsLongConstant()) {
1476 current->ReplaceWith(callee_graph->GetLongConstant(argument->AsLongConstant()->GetValue()));
1477 } else if (argument->IsFloatConstant()) {
1478 current->ReplaceWith(
1479 callee_graph->GetFloatConstant(argument->AsFloatConstant()->GetValue()));
1480 } else if (argument->IsDoubleConstant()) {
1481 current->ReplaceWith(
1482 callee_graph->GetDoubleConstant(argument->AsDoubleConstant()->GetValue()));
1483 } else if (argument->GetType() == Primitive::kPrimNot) {
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001484 if (!resolved_method->IsStatic() && parameter_index == 0 && receiver_type.IsValid()) {
1485 run_rtp = true;
1486 current->SetReferenceTypeInfo(receiver_type);
1487 } else {
1488 current->SetReferenceTypeInfo(argument->GetReferenceTypeInfo());
1489 }
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001490 current->AsParameterValue()->SetCanBeNull(argument->CanBeNull());
1491 }
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001492 ++parameter_index;
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001493 }
1494 }
1495
David Brazdil94ab38f2016-06-21 17:48:19 +01001496 // We have replaced formal arguments with actual arguments. If actual types
1497 // are more specific than the declared ones, run RTP again on the inner graph.
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001498 if (run_rtp || ArgumentTypesMoreSpecific(invoke_instruction, resolved_method)) {
David Brazdil94ab38f2016-06-21 17:48:19 +01001499 ReferenceTypePropagation(callee_graph,
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001500 outer_compilation_unit_.GetClassLoader(),
David Brazdil94ab38f2016-06-21 17:48:19 +01001501 dex_compilation_unit.GetDexCache(),
1502 handles_,
1503 /* is_first_run */ false).Run();
1504 }
1505
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001506 size_t number_of_instructions_budget = kMaximumNumberOfHInstructions;
Roland Levillaina3aef2e2016-04-06 17:45:58 +01001507 size_t number_of_inlined_instructions =
1508 RunOptimizations(callee_graph, code_item, dex_compilation_unit);
1509 number_of_instructions_budget += number_of_inlined_instructions;
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +00001510
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001511 HBasicBlock* exit_block = callee_graph->GetExitBlock();
1512 if (exit_block == nullptr) {
David Sehr709b0702016-10-13 09:12:37 -07001513 VLOG(compiler) << "Method " << callee_dex_file.PrettyMethod(method_index)
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001514 << " could not be inlined because it has an infinite loop";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001515 return false;
1516 }
1517
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00001518 bool has_one_return = false;
Vladimir Marko60584552015-09-03 13:35:12 +00001519 for (HBasicBlock* predecessor : exit_block->GetPredecessors()) {
1520 if (predecessor->GetLastInstruction()->IsThrow()) {
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00001521 if (invoke_instruction->GetBlock()->IsTryBlock()) {
1522 // TODO(ngeoffray): Support adding HTryBoundary in Hgraph::InlineInto.
1523 VLOG(compiler) << "Method " << callee_dex_file.PrettyMethod(method_index)
1524 << " could not be inlined because one branch always throws and"
1525 << " caller is in a try/catch block";
1526 return false;
1527 } else if (graph_->GetExitBlock() == nullptr) {
1528 // TODO(ngeoffray): Support adding HExit in the caller graph.
1529 VLOG(compiler) << "Method " << callee_dex_file.PrettyMethod(method_index)
1530 << " could not be inlined because one branch always throws and"
1531 << " caller does not have an exit block";
1532 return false;
Nicolas Geoffray1eede6a2017-03-02 16:14:53 +00001533 } else if (graph_->HasIrreducibleLoops()) {
1534 // TODO(ngeoffray): Support re-computing loop information to graphs with
1535 // irreducible loops?
1536 VLOG(compiler) << "Method " << callee_dex_file.PrettyMethod(method_index)
1537 << " could not be inlined because one branch always throws and"
1538 << " caller has irreducible loops";
1539 return false;
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00001540 }
1541 } else {
1542 has_one_return = true;
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001543 }
1544 }
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00001545
1546 if (!has_one_return) {
David Sehr709b0702016-10-13 09:12:37 -07001547 VLOG(compiler) << "Method " << callee_dex_file.PrettyMethod(method_index)
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00001548 << " could not be inlined because it always throws";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001549 return false;
1550 }
1551
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001552 size_t number_of_instructions = 0;
Nicolas Geoffray5949fa02015-12-18 10:57:10 +00001553
1554 bool can_inline_environment =
1555 total_number_of_dex_registers_ < kMaximumNumberOfCumulatedDexRegisters;
1556
Vladimir Marko2c45bc92016-10-25 16:54:12 +01001557 // Skip the entry block, it does not contain instructions that prevent inlining.
1558 for (HBasicBlock* block : callee_graph->GetReversePostOrderSkipEntryBlock()) {
David Sehrc757dec2016-11-04 15:48:34 -07001559 if (block->IsLoopHeader()) {
1560 if (block->GetLoopInformation()->IsIrreducible()) {
1561 // Don't inline methods with irreducible loops, they could prevent some
1562 // optimizations to run.
1563 VLOG(compiler) << "Method " << callee_dex_file.PrettyMethod(method_index)
1564 << " could not be inlined because it contains an irreducible loop";
1565 return false;
1566 }
1567 if (!block->GetLoopInformation()->HasExitEdge()) {
1568 // Don't inline methods with loops without exit, since they cause the
1569 // loop information to be computed incorrectly when updating after
1570 // inlining.
1571 VLOG(compiler) << "Method " << callee_dex_file.PrettyMethod(method_index)
1572 << " could not be inlined because it contains a loop with no exit";
1573 return false;
1574 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001575 }
1576
1577 for (HInstructionIterator instr_it(block->GetInstructions());
1578 !instr_it.Done();
1579 instr_it.Advance()) {
Roland Levillaina3aef2e2016-04-06 17:45:58 +01001580 if (number_of_instructions++ == number_of_instructions_budget) {
David Sehr709b0702016-10-13 09:12:37 -07001581 VLOG(compiler) << "Method " << callee_dex_file.PrettyMethod(method_index)
Nicolas Geoffray5949fa02015-12-18 10:57:10 +00001582 << " is not inlined because its caller has reached"
1583 << " its instruction budget limit.";
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001584 return false;
1585 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001586 HInstruction* current = instr_it.Current();
Nicolas Geoffray5949fa02015-12-18 10:57:10 +00001587 if (!can_inline_environment && current->NeedsEnvironment()) {
David Sehr709b0702016-10-13 09:12:37 -07001588 VLOG(compiler) << "Method " << callee_dex_file.PrettyMethod(method_index)
Nicolas Geoffray5949fa02015-12-18 10:57:10 +00001589 << " is not inlined because its caller has reached"
1590 << " its environment budget limit.";
1591 return false;
1592 }
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001593
Nicolas Geoffrayfbdfa6d2017-02-03 10:43:13 +00001594 if (current->NeedsEnvironment() &&
1595 !CanEncodeInlinedMethodInStackMap(*caller_compilation_unit_.GetDexFile(),
1596 resolved_method)) {
David Sehr709b0702016-10-13 09:12:37 -07001597 VLOG(compiler) << "Method " << callee_dex_file.PrettyMethod(method_index)
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001598 << " could not be inlined because " << current->DebugName()
Nicolas Geoffrayfbdfa6d2017-02-03 10:43:13 +00001599 << " needs an environment, is in a different dex file"
1600 << ", and cannot be encoded in the stack maps.";
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001601 return false;
1602 }
Nicolas Geoffray9437b782015-03-25 10:08:51 +00001603
Vladimir Markodc151b22015-10-15 18:02:30 +01001604 if (!same_dex_file && current->NeedsDexCacheOfDeclaringClass()) {
David Sehr709b0702016-10-13 09:12:37 -07001605 VLOG(compiler) << "Method " << callee_dex_file.PrettyMethod(method_index)
Nicolas Geoffray9437b782015-03-25 10:08:51 +00001606 << " could not be inlined because " << current->DebugName()
1607 << " it is in a different dex file and requires access to the dex cache";
1608 return false;
1609 }
Nicolas Geoffrayd9309292015-10-31 22:21:31 +00001610
Nicolas Geoffrayd9309292015-10-31 22:21:31 +00001611 if (current->IsUnresolvedStaticFieldGet() ||
1612 current->IsUnresolvedInstanceFieldGet() ||
1613 current->IsUnresolvedStaticFieldSet() ||
1614 current->IsUnresolvedInstanceFieldSet()) {
1615 // Entrypoint for unresolved fields does not handle inlined frames.
David Sehr709b0702016-10-13 09:12:37 -07001616 VLOG(compiler) << "Method " << callee_dex_file.PrettyMethod(method_index)
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +00001617 << " could not be inlined because it is using an unresolved"
1618 << " entrypoint";
Nicolas Geoffrayd9309292015-10-31 22:21:31 +00001619 return false;
1620 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001621 }
1622 }
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001623 number_of_inlined_instructions_ += number_of_instructions;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001624
David Brazdil3f523062016-02-29 16:53:33 +00001625 DCHECK_EQ(caller_instruction_counter, graph_->GetCurrentInstructionId())
1626 << "No instructions can be added to the outer graph while inner graph is being built";
1627
1628 const int32_t callee_instruction_counter = callee_graph->GetCurrentInstructionId();
1629 graph_->SetCurrentInstructionId(callee_instruction_counter);
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001630 *return_replacement = callee_graph->InlineInto(graph_, invoke_instruction);
David Brazdil3f523062016-02-29 16:53:33 +00001631
1632 DCHECK_EQ(callee_instruction_counter, callee_graph->GetCurrentInstructionId())
1633 << "No instructions can be added to the inner graph during inlining into the outer graph";
1634
Vladimir Marko438709f2017-02-23 18:56:13 +00001635 if (stats_ != nullptr) {
1636 DCHECK(inline_stats_ != nullptr);
1637 inline_stats_->AddTo(stats_);
1638 }
1639
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001640 return true;
1641}
Calin Juravle2e768302015-07-28 14:41:11 +00001642
Roland Levillaina3aef2e2016-04-06 17:45:58 +01001643size_t HInliner::RunOptimizations(HGraph* callee_graph,
1644 const DexFile::CodeItem* code_item,
1645 const DexCompilationUnit& dex_compilation_unit) {
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01001646 // Note: if the outermost_graph_ is being compiled OSR, we should not run any
1647 // optimization that could lead to a HDeoptimize. The following optimizations do not.
Vladimir Marko438709f2017-02-23 18:56:13 +00001648 HDeadCodeElimination dce(callee_graph, inline_stats_, "dead_code_elimination$inliner");
Andreas Gampeca620d72016-11-08 08:09:33 -08001649 HConstantFolding fold(callee_graph, "constant_folding$inliner");
Nicolas Geoffray22384ae2016-12-12 22:33:36 +00001650 HSharpening sharpening(callee_graph, codegen_, dex_compilation_unit, compiler_driver_, handles_);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00001651 InstructionSimplifier simplify(callee_graph, codegen_, inline_stats_);
Vladimir Marko438709f2017-02-23 18:56:13 +00001652 IntrinsicsRecognizer intrinsics(callee_graph, inline_stats_);
Roland Levillaina3aef2e2016-04-06 17:45:58 +01001653
1654 HOptimization* optimizations[] = {
1655 &intrinsics,
1656 &sharpening,
1657 &simplify,
1658 &fold,
1659 &dce,
1660 };
1661
1662 for (size_t i = 0; i < arraysize(optimizations); ++i) {
1663 HOptimization* optimization = optimizations[i];
1664 optimization->Run();
1665 }
1666
1667 size_t number_of_inlined_instructions = 0u;
1668 if (depth_ + 1 < compiler_driver_->GetCompilerOptions().GetInlineDepthLimit()) {
1669 HInliner inliner(callee_graph,
1670 outermost_graph_,
1671 codegen_,
1672 outer_compilation_unit_,
1673 dex_compilation_unit,
1674 compiler_driver_,
1675 handles_,
Vladimir Marko438709f2017-02-23 18:56:13 +00001676 inline_stats_,
Roland Levillaina3aef2e2016-04-06 17:45:58 +01001677 total_number_of_dex_registers_ + code_item->registers_size_,
1678 depth_ + 1);
1679 inliner.Run();
1680 number_of_inlined_instructions += inliner.number_of_inlined_instructions_;
1681 }
1682
1683 return number_of_inlined_instructions;
1684}
1685
David Brazdil94ab38f2016-06-21 17:48:19 +01001686static bool IsReferenceTypeRefinement(ReferenceTypeInfo declared_rti,
1687 bool declared_can_be_null,
1688 HInstruction* actual_obj)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001689 REQUIRES_SHARED(Locks::mutator_lock_) {
David Brazdil94ab38f2016-06-21 17:48:19 +01001690 if (declared_can_be_null && !actual_obj->CanBeNull()) {
1691 return true;
1692 }
1693
1694 ReferenceTypeInfo actual_rti = actual_obj->GetReferenceTypeInfo();
1695 return (actual_rti.IsExact() && !declared_rti.IsExact()) ||
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001696 declared_rti.IsStrictSupertypeOf(actual_rti);
David Brazdil94ab38f2016-06-21 17:48:19 +01001697}
1698
1699ReferenceTypeInfo HInliner::GetClassRTI(mirror::Class* klass) {
1700 return ReferenceTypePropagation::IsAdmissible(klass)
1701 ? ReferenceTypeInfo::Create(handles_->NewHandle(klass))
1702 : graph_->GetInexactObjectRti();
1703}
1704
1705bool HInliner::ArgumentTypesMoreSpecific(HInvoke* invoke_instruction, ArtMethod* resolved_method) {
1706 // If this is an instance call, test whether the type of the `this` argument
1707 // is more specific than the class which declares the method.
1708 if (!resolved_method->IsStatic()) {
1709 if (IsReferenceTypeRefinement(GetClassRTI(resolved_method->GetDeclaringClass()),
1710 /* declared_can_be_null */ false,
1711 invoke_instruction->InputAt(0u))) {
1712 return true;
1713 }
1714 }
1715
David Brazdil94ab38f2016-06-21 17:48:19 +01001716 // Iterate over the list of parameter types and test whether any of the
1717 // actual inputs has a more specific reference type than the type declared in
1718 // the signature.
1719 const DexFile::TypeList* param_list = resolved_method->GetParameterTypeList();
1720 for (size_t param_idx = 0,
1721 input_idx = resolved_method->IsStatic() ? 0 : 1,
1722 e = (param_list == nullptr ? 0 : param_list->Size());
1723 param_idx < e;
1724 ++param_idx, ++input_idx) {
1725 HInstruction* input = invoke_instruction->InputAt(input_idx);
1726 if (input->GetType() == Primitive::kPrimNot) {
Vladimir Marko942fd312017-01-16 20:52:19 +00001727 mirror::Class* param_cls = resolved_method->GetClassFromTypeIndex(
David Brazdil94ab38f2016-06-21 17:48:19 +01001728 param_list->GetTypeItem(param_idx).type_idx_,
Vladimir Marko942fd312017-01-16 20:52:19 +00001729 /* resolve */ false);
David Brazdil94ab38f2016-06-21 17:48:19 +01001730 if (IsReferenceTypeRefinement(GetClassRTI(param_cls),
1731 /* declared_can_be_null */ true,
1732 input)) {
1733 return true;
1734 }
1735 }
1736 }
1737
1738 return false;
1739}
1740
1741bool HInliner::ReturnTypeMoreSpecific(HInvoke* invoke_instruction,
1742 HInstruction* return_replacement) {
Alex Light68289a52015-12-15 17:30:30 -08001743 // Check the integrity of reference types and run another type propagation if needed.
David Brazdil4833f5a2015-12-16 10:37:39 +00001744 if (return_replacement != nullptr) {
1745 if (return_replacement->GetType() == Primitive::kPrimNot) {
David Brazdil94ab38f2016-06-21 17:48:19 +01001746 // Test if the return type is a refinement of the declared return type.
1747 if (IsReferenceTypeRefinement(invoke_instruction->GetReferenceTypeInfo(),
1748 /* declared_can_be_null */ true,
1749 return_replacement)) {
1750 return true;
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00001751 } else if (return_replacement->IsInstanceFieldGet()) {
1752 HInstanceFieldGet* field_get = return_replacement->AsInstanceFieldGet();
1753 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1754 if (field_get->GetFieldInfo().GetField() ==
1755 class_linker->GetClassRoot(ClassLinker::kJavaLangObject)->GetInstanceField(0)) {
1756 return true;
1757 }
David Brazdil94ab38f2016-06-21 17:48:19 +01001758 }
1759 } else if (return_replacement->IsInstanceOf()) {
1760 // Inlining InstanceOf into an If may put a tighter bound on reference types.
1761 return true;
1762 }
1763 }
1764
1765 return false;
1766}
1767
1768void HInliner::FixUpReturnReferenceType(ArtMethod* resolved_method,
1769 HInstruction* return_replacement) {
1770 if (return_replacement != nullptr) {
1771 if (return_replacement->GetType() == Primitive::kPrimNot) {
David Brazdil4833f5a2015-12-16 10:37:39 +00001772 if (!return_replacement->GetReferenceTypeInfo().IsValid()) {
1773 // Make sure that we have a valid type for the return. We may get an invalid one when
1774 // we inline invokes with multiple branches and create a Phi for the result.
1775 // TODO: we could be more precise by merging the phi inputs but that requires
1776 // some functionality from the reference type propagation.
1777 DCHECK(return_replacement->IsPhi());
Vladimir Marko942fd312017-01-16 20:52:19 +00001778 mirror::Class* cls = resolved_method->GetReturnType(false /* resolve */);
David Brazdil94ab38f2016-06-21 17:48:19 +01001779 return_replacement->SetReferenceTypeInfo(GetClassRTI(cls));
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001780 }
Calin Juravlecdfed3d2015-10-26 14:05:01 +00001781 }
Calin Juravle2e768302015-07-28 14:41:11 +00001782 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001783}
1784
1785} // namespace art