blob: ce531342357f3537cd961ac4426219796e686350 [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"
44#include "scoped_thread_state_change.h"
45#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
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000058void HInliner::Run() {
Calin Juravle8f96df82015-07-29 15:58:48 +010059 const CompilerOptions& compiler_options = compiler_driver_->GetCompilerOptions();
60 if ((compiler_options.GetInlineDepthLimit() == 0)
61 || (compiler_options.GetInlineMaxCodeUnits() == 0)) {
62 return;
63 }
Nicolas Geoffray5949fa02015-12-18 10:57:10 +000064 if (caller_compilation_unit_.GetCodeItem()->insns_size_in_code_units_ > kMaximumCodeUnitSize) {
65 return;
66 }
Nicolas Geoffraye50b8d22015-03-13 08:57:42 +000067 if (graph_->IsDebuggable()) {
68 // For simplicity, we currently never inline when the graph is debuggable. This avoids
69 // doing some logic in the runtime to discover if a method could have been inlined.
70 return;
71 }
Vladimir Markofa6b93c2015-09-15 10:15:55 +010072 const ArenaVector<HBasicBlock*>& blocks = graph_->GetReversePostOrder();
73 DCHECK(!blocks.empty());
74 HBasicBlock* next_block = blocks[0];
75 for (size_t i = 0; i < blocks.size(); ++i) {
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +010076 // Because we are changing the graph when inlining, we need to remember the next block.
77 // This avoids doing the inlining work again on the inlined blocks.
Vladimir Markofa6b93c2015-09-15 10:15:55 +010078 if (blocks[i] != next_block) {
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +010079 continue;
80 }
81 HBasicBlock* block = next_block;
Vladimir Markofa6b93c2015-09-15 10:15:55 +010082 next_block = (i == blocks.size() - 1) ? nullptr : blocks[i + 1];
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +000083 for (HInstruction* instruction = block->GetFirstInstruction(); instruction != nullptr;) {
84 HInstruction* next = instruction->GetNext();
Nicolas Geoffray454a4812015-06-09 10:37:32 +010085 HInvoke* call = instruction->AsInvoke();
Razvan A Lupusoru3e90a962015-03-27 13:44:44 -070086 // As long as the call is not intrinsified, it is worth trying to inline.
87 if (call != nullptr && call->GetIntrinsic() == Intrinsics::kNone) {
Nicolas Geoffray79041292015-03-26 10:05:54 +000088 // We use the original invoke type to ensure the resolution of the called method
89 // works properly.
Vladimir Marko58155012015-08-19 12:49:41 +000090 if (!TryInline(call)) {
Nicolas Geoffray335005e2015-06-25 10:01:47 +010091 if (kIsDebugBuild && IsCompilingWithCoreImage()) {
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000092 std::string callee_name =
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +000093 PrettyMethod(call->GetDexMethodIndex(), *outer_compilation_unit_.GetDexFile());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000094 bool should_inline = callee_name.find("$inline$") != std::string::npos;
95 CHECK(!should_inline) << "Could not inline " << callee_name;
96 }
Guillaume "Vermeille" Sancheze918d382015-06-03 15:32:41 +010097 } else {
Nicolas Geoffray335005e2015-06-25 10:01:47 +010098 if (kIsDebugBuild && IsCompilingWithCoreImage()) {
Guillaume "Vermeille" Sancheze918d382015-06-03 15:32:41 +010099 std::string callee_name =
100 PrettyMethod(call->GetDexMethodIndex(), *outer_compilation_unit_.GetDexFile());
101 bool must_not_inline = callee_name.find("$noinline$") != std::string::npos;
102 CHECK(!must_not_inline) << "Should not have inlined " << callee_name;
103 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000104 }
105 }
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +0000106 instruction = next;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000107 }
108 }
109}
110
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100111static bool IsMethodOrDeclaringClassFinal(ArtMethod* method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700112 REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100113 return method->IsFinal() || method->GetDeclaringClass()->IsFinal();
114}
115
116/**
117 * Given the `resolved_method` looked up in the dex cache, try to find
118 * the actual runtime target of an interface or virtual call.
119 * Return nullptr if the runtime target cannot be proven.
120 */
121static ArtMethod* FindVirtualOrInterfaceTarget(HInvoke* invoke, ArtMethod* resolved_method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700122 REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100123 if (IsMethodOrDeclaringClassFinal(resolved_method)) {
124 // No need to lookup further, the resolved method will be the target.
125 return resolved_method;
126 }
127
128 HInstruction* receiver = invoke->InputAt(0);
129 if (receiver->IsNullCheck()) {
130 // Due to multiple levels of inlining within the same pass, it might be that
131 // null check does not have the reference type of the actual receiver.
132 receiver = receiver->InputAt(0);
133 }
134 ReferenceTypeInfo info = receiver->GetReferenceTypeInfo();
Calin Juravle2e768302015-07-28 14:41:11 +0000135 DCHECK(info.IsValid()) << "Invalid RTI for " << receiver->DebugName();
136 if (!info.IsExact()) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100137 // We currently only support inlining with known receivers.
138 // TODO: Remove this check, we should be able to inline final methods
139 // on unknown receivers.
140 return nullptr;
141 } else if (info.GetTypeHandle()->IsInterface()) {
142 // Statically knowing that the receiver has an interface type cannot
143 // help us find what is the target method.
144 return nullptr;
145 } else if (!resolved_method->GetDeclaringClass()->IsAssignableFrom(info.GetTypeHandle().Get())) {
146 // The method that we're trying to call is not in the receiver's class or super classes.
147 return nullptr;
Nicolas Geoffrayab5327d2016-03-18 11:36:20 +0000148 } else if (info.GetTypeHandle()->IsErroneous()) {
149 // If the type is erroneous, do not go further, as we are going to query the vtable or
150 // imt table, that we can only safely do on non-erroneous classes.
151 return nullptr;
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100152 }
153
154 ClassLinker* cl = Runtime::Current()->GetClassLinker();
Andreas Gampe542451c2016-07-26 09:02:02 -0700155 PointerSize pointer_size = cl->GetImagePointerSize();
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100156 if (invoke->IsInvokeInterface()) {
157 resolved_method = info.GetTypeHandle()->FindVirtualMethodForInterface(
158 resolved_method, pointer_size);
159 } else {
160 DCHECK(invoke->IsInvokeVirtual());
161 resolved_method = info.GetTypeHandle()->FindVirtualMethodForVirtual(
162 resolved_method, pointer_size);
163 }
164
165 if (resolved_method == nullptr) {
166 // The information we had on the receiver was not enough to find
167 // the target method. Since we check above the exact type of the receiver,
168 // the only reason this can happen is an IncompatibleClassChangeError.
169 return nullptr;
Alex Light9139e002015-10-09 15:59:48 -0700170 } else if (!resolved_method->IsInvokable()) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100171 // The information we had on the receiver was not enough to find
172 // the target method. Since we check above the exact type of the receiver,
173 // the only reason this can happen is an IncompatibleClassChangeError.
174 return nullptr;
175 } else if (IsMethodOrDeclaringClassFinal(resolved_method)) {
176 // A final method has to be the target method.
177 return resolved_method;
178 } else if (info.IsExact()) {
179 // If we found a method and the receiver's concrete type is statically
180 // known, we know for sure the target.
181 return resolved_method;
182 } else {
183 // Even if we did find a method, the receiver type was not enough to
184 // statically find the runtime target.
185 return nullptr;
186 }
187}
188
189static uint32_t FindMethodIndexIn(ArtMethod* method,
190 const DexFile& dex_file,
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +0000191 uint32_t name_and_signature_index)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700192 REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100193 if (IsSameDexFile(*method->GetDexFile(), dex_file)) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100194 return method->GetDexMethodIndex();
195 } else {
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +0000196 return method->FindDexMethodIndexInOtherDexFile(dex_file, name_and_signature_index);
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100197 }
198}
199
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000200static uint32_t FindClassIndexIn(mirror::Class* cls,
201 const DexFile& dex_file,
202 Handle<mirror::DexCache> dex_cache)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700203 REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000204 uint32_t index = DexFile::kDexNoIndex;
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100205 if (cls->GetDexCache() == nullptr) {
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000206 DCHECK(cls->IsArrayClass()) << PrettyClass(cls);
207 index = cls->FindTypeIndexInOtherDexFile(dex_file);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100208 } else if (cls->GetDexTypeIndex() == DexFile::kDexNoIndex16) {
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000209 DCHECK(cls->IsProxyClass()) << PrettyClass(cls);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100210 // TODO: deal with proxy classes.
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100211 } else if (IsSameDexFile(cls->GetDexFile(), dex_file)) {
Nicolas Geoffray491617a2016-07-19 17:06:23 +0100212 DCHECK_EQ(cls->GetDexCache(), dex_cache.Get());
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000213 index = cls->GetDexTypeIndex();
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100214 // Update the dex cache to ensure the class is in. The generated code will
215 // consider it is. We make it safe by updating the dex cache, as other
216 // dex files might also load the class, and there is no guarantee the dex
217 // cache of the dex file of the class will be updated.
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000218 if (dex_cache->GetResolvedType(index) == nullptr) {
219 dex_cache->SetResolvedType(index, cls);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100220 }
Nicolas Geoffray491617a2016-07-19 17:06:23 +0100221 } else {
222 index = cls->FindTypeIndexInOtherDexFile(dex_file);
223 // We cannot guarantee the entry in the dex cache will resolve to the same class,
224 // as there may be different class loaders. So only return the index if it's
225 // the right class in the dex cache already.
226 if (index != DexFile::kDexNoIndex && dex_cache->GetResolvedType(index) != cls) {
227 index = DexFile::kDexNoIndex;
228 }
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100229 }
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000230
231 return index;
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100232}
233
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000234class ScopedProfilingInfoInlineUse {
235 public:
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000236 explicit ScopedProfilingInfoInlineUse(ArtMethod* method, Thread* self)
237 : method_(method),
238 self_(self),
239 // Fetch the profiling info ahead of using it. If it's null when fetching,
240 // we should not call JitCodeCache::DoneInlining.
241 profiling_info_(
242 Runtime::Current()->GetJit()->GetCodeCache()->NotifyCompilerUse(method, self)) {
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000243 }
244
245 ~ScopedProfilingInfoInlineUse() {
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000246 if (profiling_info_ != nullptr) {
Andreas Gampe542451c2016-07-26 09:02:02 -0700247 PointerSize pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000248 DCHECK_EQ(profiling_info_, method_->GetProfilingInfo(pointer_size));
249 Runtime::Current()->GetJit()->GetCodeCache()->DoneCompilerUse(method_, self_);
250 }
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000251 }
252
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000253 ProfilingInfo* GetProfilingInfo() const { return profiling_info_; }
254
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000255 private:
256 ArtMethod* const method_;
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000257 Thread* const self_;
258 ProfilingInfo* const profiling_info_;
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000259};
260
Nicolas Geoffraye418dda2015-08-11 20:03:09 -0700261bool HInliner::TryInline(HInvoke* invoke_instruction) {
Calin Juravle175dc732015-08-25 15:42:32 +0100262 if (invoke_instruction->IsInvokeUnresolved()) {
263 return false; // Don't bother to move further if we know the method is unresolved.
264 }
265
Vladimir Marko58155012015-08-19 12:49:41 +0000266 uint32_t method_index = invoke_instruction->GetDexMethodIndex();
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000267 ScopedObjectAccess soa(Thread::Current());
Nicolas Geoffray9437b782015-03-25 10:08:51 +0000268 const DexFile& caller_dex_file = *caller_compilation_unit_.GetDexFile();
269 VLOG(compiler) << "Try inlining " << PrettyMethod(method_index, caller_dex_file);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000270
Nicolas Geoffray35071052015-06-09 15:43:38 +0100271 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
272 // We can query the dex cache directly. The verifier has populated it already.
Vladimir Marko58155012015-08-19 12:49:41 +0000273 ArtMethod* resolved_method;
Andreas Gampefd2140f2015-12-23 16:30:44 -0800274 ArtMethod* actual_method = nullptr;
Vladimir Marko58155012015-08-19 12:49:41 +0000275 if (invoke_instruction->IsInvokeStaticOrDirect()) {
Nicolas Geoffraye5234232015-12-02 09:06:11 +0000276 if (invoke_instruction->AsInvokeStaticOrDirect()->IsStringInit()) {
277 VLOG(compiler) << "Not inlining a String.<init> method";
278 return false;
279 }
Vladimir Marko58155012015-08-19 12:49:41 +0000280 MethodReference ref = invoke_instruction->AsInvokeStaticOrDirect()->GetTargetMethod();
Nicolas Geoffray491617a2016-07-19 17:06:23 +0100281 mirror::DexCache* const dex_cache = IsSameDexFile(caller_dex_file, *ref.dex_file)
Mathieu Chartier736b5602015-09-02 14:54:11 -0700282 ? caller_compilation_unit_.GetDexCache().Get()
283 : class_linker->FindDexCache(soa.Self(), *ref.dex_file);
284 resolved_method = dex_cache->GetResolvedMethod(
Vladimir Marko58155012015-08-19 12:49:41 +0000285 ref.dex_method_index, class_linker->GetImagePointerSize());
Andreas Gampefd2140f2015-12-23 16:30:44 -0800286 // actual_method == resolved_method for direct or static calls.
287 actual_method = resolved_method;
Vladimir Marko58155012015-08-19 12:49:41 +0000288 } else {
Mathieu Chartier736b5602015-09-02 14:54:11 -0700289 resolved_method = caller_compilation_unit_.GetDexCache().Get()->GetResolvedMethod(
Vladimir Marko58155012015-08-19 12:49:41 +0000290 method_index, class_linker->GetImagePointerSize());
Andreas Gampefd2140f2015-12-23 16:30:44 -0800291 if (resolved_method != nullptr) {
292 // Check if we can statically find the method.
293 actual_method = FindVirtualOrInterfaceTarget(invoke_instruction, resolved_method);
294 }
Vladimir Marko58155012015-08-19 12:49:41 +0000295 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000296
Mathieu Chartiere401d142015-04-22 13:56:20 -0700297 if (resolved_method == nullptr) {
Calin Juravle175dc732015-08-25 15:42:32 +0100298 // TODO: Can this still happen?
Nicolas Geoffray35071052015-06-09 15:43:38 +0100299 // Method cannot be resolved if it is in another dex file we do not have access to.
Nicolas Geoffray9437b782015-03-25 10:08:51 +0000300 VLOG(compiler) << "Method cannot be resolved " << PrettyMethod(method_index, caller_dex_file);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000301 return false;
302 }
303
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100304 if (actual_method != nullptr) {
Calin Juravle69158982016-03-16 11:53:41 +0000305 bool result = TryInlineAndReplace(invoke_instruction, actual_method, /* do_rtp */ true);
306 if (result && !invoke_instruction->IsInvokeStaticOrDirect()) {
307 MaybeRecordStat(kInlinedInvokeVirtualOrInterface);
308 }
309 return result;
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100310 }
Nicolas Geoffray55bd7492016-02-16 15:37:12 +0000311
Andreas Gampefd2140f2015-12-23 16:30:44 -0800312 DCHECK(!invoke_instruction->IsInvokeStaticOrDirect());
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100313
314 // Check if we can use an inline cache.
315 ArtMethod* caller = graph_->GetArtMethod();
Calin Juravleffc87072016-04-20 14:22:09 +0100316 if (Runtime::Current()->UseJitCompilation()) {
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000317 // Under JIT, we should always know the caller.
318 DCHECK(caller != nullptr);
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000319 ScopedProfilingInfoInlineUse spiis(caller, soa.Self());
320 ProfilingInfo* profiling_info = spiis.GetProfilingInfo();
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000321 if (profiling_info != nullptr) {
322 const InlineCache& ic = *profiling_info->GetInlineCache(invoke_instruction->GetDexPc());
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000323 if (ic.IsUninitialized()) {
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000324 VLOG(compiler) << "Interface or virtual call to "
325 << PrettyMethod(method_index, caller_dex_file)
326 << " is not hit and not inlined";
327 return false;
328 } else if (ic.IsMonomorphic()) {
329 MaybeRecordStat(kMonomorphicCall);
Nicolas Geoffray93a18c52016-04-22 13:16:14 +0100330 if (outermost_graph_->IsCompilingOsr()) {
331 // If we are compiling OSR, we pretend this call is polymorphic, as we may come from the
332 // interpreter and it may have seen different receiver types.
333 return TryInlinePolymorphicCall(invoke_instruction, resolved_method, ic);
334 } else {
335 return TryInlineMonomorphicCall(invoke_instruction, resolved_method, ic);
336 }
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000337 } else if (ic.IsPolymorphic()) {
338 MaybeRecordStat(kPolymorphicCall);
339 return TryInlinePolymorphicCall(invoke_instruction, resolved_method, ic);
340 } else {
341 DCHECK(ic.IsMegamorphic());
342 VLOG(compiler) << "Interface or virtual call to "
343 << PrettyMethod(method_index, caller_dex_file)
344 << " is megamorphic and not inlined";
345 MaybeRecordStat(kMegamorphicCall);
346 return false;
347 }
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100348 }
349 }
350
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100351 VLOG(compiler) << "Interface or virtual call to "
352 << PrettyMethod(method_index, caller_dex_file)
353 << " could not be statically determined";
354 return false;
355}
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000356
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000357HInstanceFieldGet* HInliner::BuildGetReceiverClass(ClassLinker* class_linker,
358 HInstruction* receiver,
359 uint32_t dex_pc) const {
360 ArtField* field = class_linker->GetClassRoot(ClassLinker::kJavaLangObject)->GetInstanceField(0);
361 DCHECK_EQ(std::string(field->GetName()), "shadow$_klass_");
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000362 HInstanceFieldGet* result = new (graph_->GetArena()) HInstanceFieldGet(
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000363 receiver,
364 Primitive::kPrimNot,
365 field->GetOffset(),
366 field->IsVolatile(),
367 field->GetDexFieldIndex(),
368 field->GetDeclaringClass()->GetDexClassDefIndex(),
369 *field->GetDexFile(),
370 handles_->NewHandle(field->GetDexCache()),
371 dex_pc);
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000372 // The class of a field is effectively final, and does not have any memory dependencies.
373 result->SetSideEffects(SideEffects::None());
374 return result;
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000375}
376
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100377bool HInliner::TryInlineMonomorphicCall(HInvoke* invoke_instruction,
378 ArtMethod* resolved_method,
379 const InlineCache& ic) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000380 DCHECK(invoke_instruction->IsInvokeVirtual() || invoke_instruction->IsInvokeInterface())
381 << invoke_instruction->DebugName();
382
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100383 const DexFile& caller_dex_file = *caller_compilation_unit_.GetDexFile();
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000384 uint32_t class_index = FindClassIndexIn(
385 ic.GetMonomorphicType(), caller_dex_file, caller_compilation_unit_.GetDexCache());
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100386 if (class_index == DexFile::kDexNoIndex) {
387 VLOG(compiler) << "Call to " << PrettyMethod(resolved_method)
388 << " from inline cache is not inlined because its class is not"
389 << " accessible to the caller";
390 return false;
391 }
392
393 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
Andreas Gampe542451c2016-07-26 09:02:02 -0700394 PointerSize pointer_size = class_linker->GetImagePointerSize();
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100395 if (invoke_instruction->IsInvokeInterface()) {
396 resolved_method = ic.GetMonomorphicType()->FindVirtualMethodForInterface(
397 resolved_method, pointer_size);
398 } else {
399 DCHECK(invoke_instruction->IsInvokeVirtual());
400 resolved_method = ic.GetMonomorphicType()->FindVirtualMethodForVirtual(
401 resolved_method, pointer_size);
402 }
403 DCHECK(resolved_method != nullptr);
404 HInstruction* receiver = invoke_instruction->InputAt(0);
405 HInstruction* cursor = invoke_instruction->GetPrevious();
406 HBasicBlock* bb_cursor = invoke_instruction->GetBlock();
407
Nicolas Geoffray55bd7492016-02-16 15:37:12 +0000408 if (!TryInlineAndReplace(invoke_instruction, resolved_method, /* do_rtp */ false)) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100409 return false;
410 }
411
412 // We successfully inlined, now add a guard.
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100413 bool is_referrer =
414 (ic.GetMonomorphicType() == outermost_graph_->GetArtMethod()->GetDeclaringClass());
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000415 AddTypeGuard(receiver,
416 cursor,
417 bb_cursor,
418 class_index,
419 is_referrer,
420 invoke_instruction,
421 /* with_deoptimization */ true);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100422
423 // Run type propagation to get the guard typed, and eventually propagate the
424 // type of the receiver.
Vladimir Marko456307a2016-04-19 14:12:13 +0000425 ReferenceTypePropagation rtp_fixup(graph_,
426 outer_compilation_unit_.GetDexCache(),
427 handles_,
428 /* is_first_run */ false);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100429 rtp_fixup.Run();
430
431 MaybeRecordStat(kInlinedMonomorphicCall);
432 return true;
433}
434
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000435HInstruction* HInliner::AddTypeGuard(HInstruction* receiver,
436 HInstruction* cursor,
437 HBasicBlock* bb_cursor,
438 uint32_t class_index,
439 bool is_referrer,
440 HInstruction* invoke_instruction,
441 bool with_deoptimization) {
442 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
443 HInstanceFieldGet* receiver_class = BuildGetReceiverClass(
444 class_linker, receiver, invoke_instruction->GetDexPc());
445
446 const DexFile& caller_dex_file = *caller_compilation_unit_.GetDexFile();
447 // Note that we will just compare the classes, so we don't need Java semantics access checks.
448 // Also, the caller of `AddTypeGuard` must have guaranteed that the class is in the dex cache.
449 HLoadClass* load_class = new (graph_->GetArena()) HLoadClass(graph_->GetCurrentMethod(),
450 class_index,
451 caller_dex_file,
452 is_referrer,
453 invoke_instruction->GetDexPc(),
454 /* needs_access_check */ false,
Mathieu Chartier31b12e32016-09-02 17:11:57 -0700455 /* is_in_dex_cache */ true,
456 /* is_in_boot_image */ false);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000457
458 HNotEqual* compare = new (graph_->GetArena()) HNotEqual(load_class, receiver_class);
459 // TODO: Extend reference type propagation to understand the guard.
460 if (cursor != nullptr) {
461 bb_cursor->InsertInstructionAfter(receiver_class, cursor);
462 } else {
463 bb_cursor->InsertInstructionBefore(receiver_class, bb_cursor->GetFirstInstruction());
464 }
465 bb_cursor->InsertInstructionAfter(load_class, receiver_class);
466 bb_cursor->InsertInstructionAfter(compare, load_class);
467 if (with_deoptimization) {
468 HDeoptimize* deoptimize = new (graph_->GetArena()) HDeoptimize(
469 compare, invoke_instruction->GetDexPc());
470 bb_cursor->InsertInstructionAfter(deoptimize, compare);
471 deoptimize->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
472 }
473 return compare;
474}
475
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000476bool HInliner::TryInlinePolymorphicCall(HInvoke* invoke_instruction,
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100477 ArtMethod* resolved_method,
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000478 const InlineCache& ic) {
479 DCHECK(invoke_instruction->IsInvokeVirtual() || invoke_instruction->IsInvokeInterface())
480 << invoke_instruction->DebugName();
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000481
482 if (TryInlinePolymorphicCallToSameTarget(invoke_instruction, resolved_method, ic)) {
483 return true;
484 }
485
486 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
Andreas Gampe542451c2016-07-26 09:02:02 -0700487 PointerSize pointer_size = class_linker->GetImagePointerSize();
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000488 const DexFile& caller_dex_file = *caller_compilation_unit_.GetDexFile();
489
490 bool all_targets_inlined = true;
491 bool one_target_inlined = false;
492 for (size_t i = 0; i < InlineCache::kIndividualCacheSize; ++i) {
493 if (ic.GetTypeAt(i) == nullptr) {
494 break;
495 }
496 ArtMethod* method = nullptr;
497 if (invoke_instruction->IsInvokeInterface()) {
498 method = ic.GetTypeAt(i)->FindVirtualMethodForInterface(
499 resolved_method, pointer_size);
500 } else {
501 DCHECK(invoke_instruction->IsInvokeVirtual());
502 method = ic.GetTypeAt(i)->FindVirtualMethodForVirtual(
503 resolved_method, pointer_size);
504 }
505
506 HInstruction* receiver = invoke_instruction->InputAt(0);
507 HInstruction* cursor = invoke_instruction->GetPrevious();
508 HBasicBlock* bb_cursor = invoke_instruction->GetBlock();
509
Nicolas Geoffray1fe26e12016-02-18 16:55:42 +0000510 uint32_t class_index = FindClassIndexIn(
511 ic.GetTypeAt(i), caller_dex_file, caller_compilation_unit_.GetDexCache());
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000512 HInstruction* return_replacement = nullptr;
513 if (class_index == DexFile::kDexNoIndex ||
514 !TryBuildAndInline(invoke_instruction, method, &return_replacement)) {
515 all_targets_inlined = false;
516 } else {
517 one_target_inlined = true;
518 bool is_referrer = (ic.GetTypeAt(i) == outermost_graph_->GetArtMethod()->GetDeclaringClass());
519
520 // If we have inlined all targets before, and this receiver is the last seen,
521 // we deoptimize instead of keeping the original invoke instruction.
522 bool deoptimize = all_targets_inlined &&
523 (i != InlineCache::kIndividualCacheSize - 1) &&
524 (ic.GetTypeAt(i + 1) == nullptr);
Nicolas Geoffray93a18c52016-04-22 13:16:14 +0100525
526 if (outermost_graph_->IsCompilingOsr()) {
527 // We do not support HDeoptimize in OSR methods.
528 deoptimize = false;
529 }
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000530 HInstruction* compare = AddTypeGuard(
531 receiver, cursor, bb_cursor, class_index, is_referrer, invoke_instruction, deoptimize);
532 if (deoptimize) {
533 if (return_replacement != nullptr) {
534 invoke_instruction->ReplaceWith(return_replacement);
535 }
536 invoke_instruction->GetBlock()->RemoveInstruction(invoke_instruction);
537 // Because the inline cache data can be populated concurrently, we force the end of the
538 // iteration. Otherhwise, we could see a new receiver type.
539 break;
540 } else {
541 CreateDiamondPatternForPolymorphicInline(compare, return_replacement, invoke_instruction);
542 }
543 }
544 }
545
546 if (!one_target_inlined) {
547 VLOG(compiler) << "Call to " << PrettyMethod(resolved_method)
548 << " from inline cache is not inlined because none"
549 << " of its targets could be inlined";
550 return false;
551 }
552 MaybeRecordStat(kInlinedPolymorphicCall);
553
554 // Run type propagation to get the guards typed.
Vladimir Marko456307a2016-04-19 14:12:13 +0000555 ReferenceTypePropagation rtp_fixup(graph_,
556 outer_compilation_unit_.GetDexCache(),
557 handles_,
558 /* is_first_run */ false);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000559 rtp_fixup.Run();
560 return true;
561}
562
563void HInliner::CreateDiamondPatternForPolymorphicInline(HInstruction* compare,
564 HInstruction* return_replacement,
565 HInstruction* invoke_instruction) {
566 uint32_t dex_pc = invoke_instruction->GetDexPc();
567 HBasicBlock* cursor_block = compare->GetBlock();
568 HBasicBlock* original_invoke_block = invoke_instruction->GetBlock();
569 ArenaAllocator* allocator = graph_->GetArena();
570
571 // Spit the block after the compare: `cursor_block` will now be the start of the diamond,
572 // and the returned block is the start of the then branch (that could contain multiple blocks).
573 HBasicBlock* then = cursor_block->SplitAfterForInlining(compare);
574
575 // Split the block containing the invoke before and after the invoke. The returned block
576 // of the split before will contain the invoke and will be the otherwise branch of
577 // the diamond. The returned block of the split after will be the merge block
578 // of the diamond.
579 HBasicBlock* end_then = invoke_instruction->GetBlock();
580 HBasicBlock* otherwise = end_then->SplitBeforeForInlining(invoke_instruction);
581 HBasicBlock* merge = otherwise->SplitAfterForInlining(invoke_instruction);
582
583 // If the methods we are inlining return a value, we create a phi in the merge block
584 // that will have the `invoke_instruction and the `return_replacement` as inputs.
585 if (return_replacement != nullptr) {
586 HPhi* phi = new (allocator) HPhi(
587 allocator, kNoRegNumber, 0, HPhi::ToPhiType(invoke_instruction->GetType()), dex_pc);
588 merge->AddPhi(phi);
589 invoke_instruction->ReplaceWith(phi);
590 phi->AddInput(return_replacement);
591 phi->AddInput(invoke_instruction);
592 }
593
594 // Add the control flow instructions.
595 otherwise->AddInstruction(new (allocator) HGoto(dex_pc));
596 end_then->AddInstruction(new (allocator) HGoto(dex_pc));
597 cursor_block->AddInstruction(new (allocator) HIf(compare, dex_pc));
598
599 // Add the newly created blocks to the graph.
600 graph_->AddBlock(then);
601 graph_->AddBlock(otherwise);
602 graph_->AddBlock(merge);
603
604 // Set up successor (and implictly predecessor) relations.
605 cursor_block->AddSuccessor(otherwise);
606 cursor_block->AddSuccessor(then);
607 end_then->AddSuccessor(merge);
608 otherwise->AddSuccessor(merge);
609
610 // Set up dominance information.
611 then->SetDominator(cursor_block);
612 cursor_block->AddDominatedBlock(then);
613 otherwise->SetDominator(cursor_block);
614 cursor_block->AddDominatedBlock(otherwise);
615 merge->SetDominator(cursor_block);
616 cursor_block->AddDominatedBlock(merge);
617
618 // Update the revert post order.
619 size_t index = IndexOfElement(graph_->reverse_post_order_, cursor_block);
620 MakeRoomFor(&graph_->reverse_post_order_, 1, index);
621 graph_->reverse_post_order_[++index] = then;
622 index = IndexOfElement(graph_->reverse_post_order_, end_then);
623 MakeRoomFor(&graph_->reverse_post_order_, 2, index);
624 graph_->reverse_post_order_[++index] = otherwise;
625 graph_->reverse_post_order_[++index] = merge;
626
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000627
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +0000628 graph_->UpdateLoopAndTryInformationOfNewBlock(
629 then, original_invoke_block, /* replace_if_back_edge */ false);
630 graph_->UpdateLoopAndTryInformationOfNewBlock(
631 otherwise, original_invoke_block, /* replace_if_back_edge */ false);
632
633 // In case the original invoke location was a back edge, we need to update
634 // the loop to now have the merge block as a back edge.
635 graph_->UpdateLoopAndTryInformationOfNewBlock(
636 merge, original_invoke_block, /* replace_if_back_edge */ true);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000637}
638
639bool HInliner::TryInlinePolymorphicCallToSameTarget(HInvoke* invoke_instruction,
640 ArtMethod* resolved_method,
641 const InlineCache& ic) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000642 // This optimization only works under JIT for now.
Calin Juravleffc87072016-04-20 14:22:09 +0100643 DCHECK(Runtime::Current()->UseJitCompilation());
Roland Levillain2aba7cd2016-02-03 12:27:20 +0000644 if (graph_->GetInstructionSet() == kMips64) {
645 // TODO: Support HClassTableGet for mips64.
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000646 return false;
647 }
648 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
Andreas Gampe542451c2016-07-26 09:02:02 -0700649 PointerSize pointer_size = class_linker->GetImagePointerSize();
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000650
651 DCHECK(resolved_method != nullptr);
652 ArtMethod* actual_method = nullptr;
Nicolas Geoffray4f97a212016-02-25 16:17:54 +0000653 size_t method_index = invoke_instruction->IsInvokeVirtual()
654 ? invoke_instruction->AsInvokeVirtual()->GetVTableIndex()
655 : invoke_instruction->AsInvokeInterface()->GetImtIndex();
656
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000657 // Check whether we are actually calling the same method among
658 // the different types seen.
659 for (size_t i = 0; i < InlineCache::kIndividualCacheSize; ++i) {
660 if (ic.GetTypeAt(i) == nullptr) {
661 break;
662 }
663 ArtMethod* new_method = nullptr;
664 if (invoke_instruction->IsInvokeInterface()) {
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +0000665 new_method = ic.GetTypeAt(i)->GetImt(pointer_size)->Get(
Matthew Gharrity465ecc82016-07-19 21:32:52 +0000666 method_index, pointer_size);
Nicolas Geoffray4f97a212016-02-25 16:17:54 +0000667 if (new_method->IsRuntimeMethod()) {
668 // Bail out as soon as we see a conflict trampoline in one of the target's
669 // interface table.
670 return false;
671 }
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000672 } else {
673 DCHECK(invoke_instruction->IsInvokeVirtual());
Nicolas Geoffray4f97a212016-02-25 16:17:54 +0000674 new_method = ic.GetTypeAt(i)->GetEmbeddedVTableEntry(method_index, pointer_size);
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000675 }
Nicolas Geoffray4f97a212016-02-25 16:17:54 +0000676 DCHECK(new_method != nullptr);
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000677 if (actual_method == nullptr) {
678 actual_method = new_method;
679 } else if (actual_method != new_method) {
680 // Different methods, bailout.
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +0000681 VLOG(compiler) << "Call to " << PrettyMethod(resolved_method)
682 << " from inline cache is not inlined because it resolves"
683 << " to different methods";
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000684 return false;
685 }
686 }
687
688 HInstruction* receiver = invoke_instruction->InputAt(0);
689 HInstruction* cursor = invoke_instruction->GetPrevious();
690 HBasicBlock* bb_cursor = invoke_instruction->GetBlock();
691
Nicolas Geoffray93a18c52016-04-22 13:16:14 +0100692 HInstruction* return_replacement = nullptr;
693 if (!TryBuildAndInline(invoke_instruction, actual_method, &return_replacement)) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000694 return false;
695 }
696
697 // We successfully inlined, now add a guard.
698 HInstanceFieldGet* receiver_class = BuildGetReceiverClass(
699 class_linker, receiver, invoke_instruction->GetDexPc());
700
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000701 Primitive::Type type = Is64BitInstructionSet(graph_->GetInstructionSet())
702 ? Primitive::kPrimLong
703 : Primitive::kPrimInt;
704 HClassTableGet* class_table_get = new (graph_->GetArena()) HClassTableGet(
705 receiver_class,
706 type,
Vladimir Markoa1de9182016-02-25 11:37:38 +0000707 invoke_instruction->IsInvokeVirtual() ? HClassTableGet::TableKind::kVTable
708 : HClassTableGet::TableKind::kIMTable,
Nicolas Geoffray4f97a212016-02-25 16:17:54 +0000709 method_index,
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000710 invoke_instruction->GetDexPc());
711
712 HConstant* constant;
713 if (type == Primitive::kPrimLong) {
714 constant = graph_->GetLongConstant(
715 reinterpret_cast<intptr_t>(actual_method), invoke_instruction->GetDexPc());
716 } else {
717 constant = graph_->GetIntConstant(
718 reinterpret_cast<intptr_t>(actual_method), invoke_instruction->GetDexPc());
719 }
720
721 HNotEqual* compare = new (graph_->GetArena()) HNotEqual(class_table_get, constant);
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000722 if (cursor != nullptr) {
723 bb_cursor->InsertInstructionAfter(receiver_class, cursor);
724 } else {
725 bb_cursor->InsertInstructionBefore(receiver_class, bb_cursor->GetFirstInstruction());
726 }
727 bb_cursor->InsertInstructionAfter(class_table_get, receiver_class);
728 bb_cursor->InsertInstructionAfter(compare, class_table_get);
Nicolas Geoffray93a18c52016-04-22 13:16:14 +0100729
730 if (outermost_graph_->IsCompilingOsr()) {
731 CreateDiamondPatternForPolymorphicInline(compare, return_replacement, invoke_instruction);
732 } else {
733 // TODO: Extend reference type propagation to understand the guard.
734 HDeoptimize* deoptimize = new (graph_->GetArena()) HDeoptimize(
735 compare, invoke_instruction->GetDexPc());
736 bb_cursor->InsertInstructionAfter(deoptimize, compare);
737 deoptimize->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
738 if (return_replacement != nullptr) {
739 invoke_instruction->ReplaceWith(return_replacement);
740 }
Nicolas Geoffray1be7cbd2016-04-29 13:56:01 +0100741 invoke_instruction->GetBlock()->RemoveInstruction(invoke_instruction);
Nicolas Geoffray93a18c52016-04-22 13:16:14 +0100742 }
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000743
744 // Run type propagation to get the guard typed.
Vladimir Marko456307a2016-04-19 14:12:13 +0000745 ReferenceTypePropagation rtp_fixup(graph_,
746 outer_compilation_unit_.GetDexCache(),
747 handles_,
748 /* is_first_run */ false);
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000749 rtp_fixup.Run();
750
751 MaybeRecordStat(kInlinedPolymorphicCall);
752
753 return true;
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100754}
755
Nicolas Geoffray55bd7492016-02-16 15:37:12 +0000756bool HInliner::TryInlineAndReplace(HInvoke* invoke_instruction, ArtMethod* method, bool do_rtp) {
757 HInstruction* return_replacement = nullptr;
758 if (!TryBuildAndInline(invoke_instruction, method, &return_replacement)) {
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +0000759 if (invoke_instruction->IsInvokeInterface()) {
760 // Turn an invoke-interface into an invoke-virtual. An invoke-virtual is always
761 // better than an invoke-interface because:
762 // 1) In the best case, the interface call has one more indirection (to fetch the IMT).
763 // 2) We will not go to the conflict trampoline with an invoke-virtual.
764 // TODO: Consider sharpening once it is not dependent on the compiler driver.
765 const DexFile& caller_dex_file = *caller_compilation_unit_.GetDexFile();
766 uint32_t method_index = FindMethodIndexIn(
767 method, caller_dex_file, invoke_instruction->GetDexMethodIndex());
768 if (method_index == DexFile::kDexNoIndex) {
769 return false;
770 }
771 HInvokeVirtual* new_invoke = new (graph_->GetArena()) HInvokeVirtual(
772 graph_->GetArena(),
773 invoke_instruction->GetNumberOfArguments(),
774 invoke_instruction->GetType(),
775 invoke_instruction->GetDexPc(),
776 method_index,
777 method->GetMethodIndex());
778 HInputsRef inputs = invoke_instruction->GetInputs();
779 for (size_t index = 0; index != inputs.size(); ++index) {
780 new_invoke->SetArgumentAt(index, inputs[index]);
781 }
782 invoke_instruction->GetBlock()->InsertInstructionBefore(new_invoke, invoke_instruction);
783 new_invoke->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
784 if (invoke_instruction->GetType() == Primitive::kPrimNot) {
785 new_invoke->SetReferenceTypeInfo(invoke_instruction->GetReferenceTypeInfo());
786 }
787 return_replacement = new_invoke;
788 } else {
789 // TODO: Consider sharpening an invoke virtual once it is not dependent on the
790 // compiler driver.
791 return false;
792 }
Nicolas Geoffray55bd7492016-02-16 15:37:12 +0000793 }
794 if (return_replacement != nullptr) {
795 invoke_instruction->ReplaceWith(return_replacement);
796 }
797 invoke_instruction->GetBlock()->RemoveInstruction(invoke_instruction);
David Brazdil94ab38f2016-06-21 17:48:19 +0100798 FixUpReturnReferenceType(method, return_replacement);
799 if (do_rtp && ReturnTypeMoreSpecific(invoke_instruction, return_replacement)) {
800 // Actual return value has a more specific type than the method's declared
801 // return type. Run RTP again on the outer graph to propagate it.
802 ReferenceTypePropagation(graph_,
803 outer_compilation_unit_.GetDexCache(),
804 handles_,
805 /* is_first_run */ false).Run();
806 }
Nicolas Geoffray55bd7492016-02-16 15:37:12 +0000807 return true;
808}
809
810bool HInliner::TryBuildAndInline(HInvoke* invoke_instruction,
811 ArtMethod* method,
812 HInstruction** return_replacement) {
Nicolas Geoffray93a18c52016-04-22 13:16:14 +0100813 if (method->IsProxyMethod()) {
814 VLOG(compiler) << "Method " << PrettyMethod(method)
815 << " is not inlined because of unimplemented inline support for proxy methods.";
816 return false;
817 }
818
Jeff Haodcdc85b2015-12-04 14:06:18 -0800819 // Check whether we're allowed to inline. The outermost compilation unit is the relevant
820 // dex file here (though the transitivity of an inline chain would allow checking the calller).
821 if (!compiler_driver_->MayInline(method->GetDexFile(),
822 outer_compilation_unit_.GetDexFile())) {
Nicolas Geoffray55bd7492016-02-16 15:37:12 +0000823 if (TryPatternSubstitution(invoke_instruction, method, return_replacement)) {
Vladimir Markobe10e8e2016-01-22 12:09:44 +0000824 VLOG(compiler) << "Successfully replaced pattern of invoke " << PrettyMethod(method);
825 MaybeRecordStat(kReplacedInvokeWithSimplePattern);
826 return true;
827 }
Jeff Haodcdc85b2015-12-04 14:06:18 -0800828 VLOG(compiler) << "Won't inline " << PrettyMethod(method) << " in "
829 << outer_compilation_unit_.GetDexFile()->GetLocation() << " ("
830 << caller_compilation_unit_.GetDexFile()->GetLocation() << ") from "
831 << method->GetDexFile()->GetLocation();
832 return false;
833 }
834
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100835 bool same_dex_file = IsSameDexFile(*outer_compilation_unit_.GetDexFile(), *method->GetDexFile());
836
837 const DexFile::CodeItem* code_item = method->GetCodeItem();
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000838
839 if (code_item == nullptr) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100840 VLOG(compiler) << "Method " << PrettyMethod(method)
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000841 << " is not inlined because it is native";
842 return false;
843 }
844
Calin Juravleec748352015-07-29 13:52:12 +0100845 size_t inline_max_code_units = compiler_driver_->GetCompilerOptions().GetInlineMaxCodeUnits();
846 if (code_item->insns_size_in_code_units_ > inline_max_code_units) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100847 VLOG(compiler) << "Method " << PrettyMethod(method)
Nicolas Geoffray788f2f02016-01-22 12:41:38 +0000848 << " is too big to inline: "
849 << code_item->insns_size_in_code_units_
850 << " > "
851 << inline_max_code_units;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000852 return false;
853 }
854
855 if (code_item->tries_size_ != 0) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100856 VLOG(compiler) << "Method " << PrettyMethod(method)
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000857 << " is not inlined because of try block";
858 return false;
859 }
860
Nicolas Geoffray250a3782016-04-20 16:27:53 +0100861 if (!method->IsCompilable()) {
862 VLOG(compiler) << "Method " << PrettyMethod(method)
863 << " has soft failures un-handled by the compiler, so it cannot be inlined";
864 }
865
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100866 if (!method->GetDeclaringClass()->IsVerified()) {
867 uint16_t class_def_idx = method->GetDeclaringClass()->GetDexClassDefIndex();
Calin Juravleffc87072016-04-20 14:22:09 +0100868 if (Runtime::Current()->UseJitCompilation() ||
Nicolas Geoffray5b82d332016-02-18 14:22:32 +0000869 !compiler_driver_->IsMethodVerifiedWithoutFailures(
870 method->GetDexMethodIndex(), class_def_idx, *method->GetDexFile())) {
Nicolas Geoffray491617a2016-07-19 17:06:23 +0100871 VLOG(compiler) << "Method " << PrettyMethod(method)
Nicolas Geoffrayccc61972015-10-01 14:34:20 +0100872 << " couldn't be verified, so it cannot be inlined";
873 return false;
874 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000875 }
876
Roland Levillain4c0eb422015-04-24 16:43:49 +0100877 if (invoke_instruction->IsInvokeStaticOrDirect() &&
878 invoke_instruction->AsInvokeStaticOrDirect()->IsStaticWithImplicitClinitCheck()) {
879 // Case of a static method that cannot be inlined because it implicitly
880 // requires an initialization check of its declaring class.
Nicolas Geoffray491617a2016-07-19 17:06:23 +0100881 VLOG(compiler) << "Method " << PrettyMethod(method)
Roland Levillain4c0eb422015-04-24 16:43:49 +0100882 << " is not inlined because it is static and requires a clinit"
883 << " check that cannot be emitted due to Dex cache limitations";
884 return false;
885 }
886
Nicolas Geoffray55bd7492016-02-16 15:37:12 +0000887 if (!TryBuildAndInlineHelper(invoke_instruction, method, same_dex_file, return_replacement)) {
Nicolas Geoffrayc0365b12015-03-18 18:31:52 +0000888 return false;
889 }
890
Nicolas Geoffray491617a2016-07-19 17:06:23 +0100891 VLOG(compiler) << "Successfully inlined " << PrettyMethod(method);
Nicolas Geoffrayc0365b12015-03-18 18:31:52 +0000892 MaybeRecordStat(kInlinedInvoke);
893 return true;
894}
895
Vladimir Markobe10e8e2016-01-22 12:09:44 +0000896static HInstruction* GetInvokeInputForArgVRegIndex(HInvoke* invoke_instruction,
897 size_t arg_vreg_index)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700898 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markobe10e8e2016-01-22 12:09:44 +0000899 size_t input_index = 0;
900 for (size_t i = 0; i < arg_vreg_index; ++i, ++input_index) {
901 DCHECK_LT(input_index, invoke_instruction->GetNumberOfArguments());
902 if (Primitive::Is64BitType(invoke_instruction->InputAt(input_index)->GetType())) {
903 ++i;
904 DCHECK_NE(i, arg_vreg_index);
905 }
906 }
907 DCHECK_LT(input_index, invoke_instruction->GetNumberOfArguments());
908 return invoke_instruction->InputAt(input_index);
909}
910
911// Try to recognize known simple patterns and replace invoke call with appropriate instructions.
912bool HInliner::TryPatternSubstitution(HInvoke* invoke_instruction,
913 ArtMethod* resolved_method,
Nicolas Geoffray55bd7492016-02-16 15:37:12 +0000914 HInstruction** return_replacement) {
Vladimir Markobe10e8e2016-01-22 12:09:44 +0000915 InlineMethod inline_method;
916 if (!InlineMethodAnalyser::AnalyseMethodCode(resolved_method, &inline_method)) {
917 return false;
918 }
919
Vladimir Markobe10e8e2016-01-22 12:09:44 +0000920 switch (inline_method.opcode) {
921 case kInlineOpNop:
922 DCHECK_EQ(invoke_instruction->GetType(), Primitive::kPrimVoid);
Nicolas Geoffray55bd7492016-02-16 15:37:12 +0000923 *return_replacement = nullptr;
Vladimir Markobe10e8e2016-01-22 12:09:44 +0000924 break;
925 case kInlineOpReturnArg:
Nicolas Geoffray55bd7492016-02-16 15:37:12 +0000926 *return_replacement = GetInvokeInputForArgVRegIndex(invoke_instruction,
927 inline_method.d.return_data.arg);
Vladimir Markobe10e8e2016-01-22 12:09:44 +0000928 break;
929 case kInlineOpNonWideConst:
930 if (resolved_method->GetShorty()[0] == 'L') {
931 DCHECK_EQ(inline_method.d.data, 0u);
Nicolas Geoffray55bd7492016-02-16 15:37:12 +0000932 *return_replacement = graph_->GetNullConstant();
Vladimir Markobe10e8e2016-01-22 12:09:44 +0000933 } else {
Nicolas Geoffray55bd7492016-02-16 15:37:12 +0000934 *return_replacement = graph_->GetIntConstant(static_cast<int32_t>(inline_method.d.data));
Vladimir Markobe10e8e2016-01-22 12:09:44 +0000935 }
936 break;
937 case kInlineOpIGet: {
938 const InlineIGetIPutData& data = inline_method.d.ifield_data;
939 if (data.method_is_static || data.object_arg != 0u) {
940 // TODO: Needs null check.
941 return false;
942 }
Vladimir Marko354efa62016-02-04 19:46:56 +0000943 Handle<mirror::DexCache> dex_cache(handles_->NewHandle(resolved_method->GetDexCache()));
Vladimir Markobe10e8e2016-01-22 12:09:44 +0000944 HInstruction* obj = GetInvokeInputForArgVRegIndex(invoke_instruction, data.object_arg);
Vladimir Marko354efa62016-02-04 19:46:56 +0000945 HInstanceFieldGet* iget = CreateInstanceFieldGet(dex_cache, data.field_idx, obj);
Vladimir Markobe10e8e2016-01-22 12:09:44 +0000946 DCHECK_EQ(iget->GetFieldOffset().Uint32Value(), data.field_offset);
947 DCHECK_EQ(iget->IsVolatile() ? 1u : 0u, data.is_volatile);
948 invoke_instruction->GetBlock()->InsertInstructionBefore(iget, invoke_instruction);
Nicolas Geoffray55bd7492016-02-16 15:37:12 +0000949 *return_replacement = iget;
Vladimir Markobe10e8e2016-01-22 12:09:44 +0000950 break;
951 }
952 case kInlineOpIPut: {
953 const InlineIGetIPutData& data = inline_method.d.ifield_data;
954 if (data.method_is_static || data.object_arg != 0u) {
955 // TODO: Needs null check.
956 return false;
957 }
Vladimir Marko354efa62016-02-04 19:46:56 +0000958 Handle<mirror::DexCache> dex_cache(handles_->NewHandle(resolved_method->GetDexCache()));
Vladimir Markobe10e8e2016-01-22 12:09:44 +0000959 HInstruction* obj = GetInvokeInputForArgVRegIndex(invoke_instruction, data.object_arg);
960 HInstruction* value = GetInvokeInputForArgVRegIndex(invoke_instruction, data.src_arg);
Vladimir Marko354efa62016-02-04 19:46:56 +0000961 HInstanceFieldSet* iput = CreateInstanceFieldSet(dex_cache, data.field_idx, obj, value);
Vladimir Markobe10e8e2016-01-22 12:09:44 +0000962 DCHECK_EQ(iput->GetFieldOffset().Uint32Value(), data.field_offset);
963 DCHECK_EQ(iput->IsVolatile() ? 1u : 0u, data.is_volatile);
964 invoke_instruction->GetBlock()->InsertInstructionBefore(iput, invoke_instruction);
965 if (data.return_arg_plus1 != 0u) {
966 size_t return_arg = data.return_arg_plus1 - 1u;
Nicolas Geoffray55bd7492016-02-16 15:37:12 +0000967 *return_replacement = GetInvokeInputForArgVRegIndex(invoke_instruction, return_arg);
Vladimir Markobe10e8e2016-01-22 12:09:44 +0000968 }
969 break;
970 }
Vladimir Marko354efa62016-02-04 19:46:56 +0000971 case kInlineOpConstructor: {
972 const InlineConstructorData& data = inline_method.d.constructor_data;
973 // Get the indexes to arrays for easier processing.
974 uint16_t iput_field_indexes[] = {
975 data.iput0_field_index, data.iput1_field_index, data.iput2_field_index
976 };
977 uint16_t iput_args[] = { data.iput0_arg, data.iput1_arg, data.iput2_arg };
978 static_assert(arraysize(iput_args) == arraysize(iput_field_indexes), "Size mismatch");
979 // Count valid field indexes.
980 size_t number_of_iputs = 0u;
981 while (number_of_iputs != arraysize(iput_field_indexes) &&
982 iput_field_indexes[number_of_iputs] != DexFile::kDexNoIndex16) {
983 // Check that there are no duplicate valid field indexes.
984 DCHECK_EQ(0, std::count(iput_field_indexes + number_of_iputs + 1,
985 iput_field_indexes + arraysize(iput_field_indexes),
986 iput_field_indexes[number_of_iputs]));
987 ++number_of_iputs;
988 }
989 // Check that there are no valid field indexes in the rest of the array.
990 DCHECK_EQ(0, std::count_if(iput_field_indexes + number_of_iputs,
991 iput_field_indexes + arraysize(iput_field_indexes),
992 [](uint16_t index) { return index != DexFile::kDexNoIndex16; }));
993
994 // Create HInstanceFieldSet for each IPUT that stores non-zero data.
995 Handle<mirror::DexCache> dex_cache;
996 HInstruction* obj = GetInvokeInputForArgVRegIndex(invoke_instruction, /* this */ 0u);
997 bool needs_constructor_barrier = false;
998 for (size_t i = 0; i != number_of_iputs; ++i) {
999 HInstruction* value = GetInvokeInputForArgVRegIndex(invoke_instruction, iput_args[i]);
Roland Levillain1a653882016-03-18 18:05:57 +00001000 if (!value->IsConstant() || !value->AsConstant()->IsZeroBitPattern()) {
Vladimir Marko354efa62016-02-04 19:46:56 +00001001 if (dex_cache.GetReference() == nullptr) {
1002 dex_cache = handles_->NewHandle(resolved_method->GetDexCache());
1003 }
1004 uint16_t field_index = iput_field_indexes[i];
1005 HInstanceFieldSet* iput = CreateInstanceFieldSet(dex_cache, field_index, obj, value);
1006 invoke_instruction->GetBlock()->InsertInstructionBefore(iput, invoke_instruction);
1007
1008 // Check whether the field is final. If it is, we need to add a barrier.
Andreas Gampe542451c2016-07-26 09:02:02 -07001009 PointerSize pointer_size = InstructionSetPointerSize(codegen_->GetInstructionSet());
Vladimir Marko354efa62016-02-04 19:46:56 +00001010 ArtField* resolved_field = dex_cache->GetResolvedField(field_index, pointer_size);
1011 DCHECK(resolved_field != nullptr);
1012 if (resolved_field->IsFinal()) {
1013 needs_constructor_barrier = true;
1014 }
1015 }
1016 }
1017 if (needs_constructor_barrier) {
1018 HMemoryBarrier* barrier = new (graph_->GetArena()) HMemoryBarrier(kStoreStore, kNoDexPc);
1019 invoke_instruction->GetBlock()->InsertInstructionBefore(barrier, invoke_instruction);
1020 }
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001021 *return_replacement = nullptr;
Vladimir Marko354efa62016-02-04 19:46:56 +00001022 break;
1023 }
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001024 default:
1025 LOG(FATAL) << "UNREACHABLE";
1026 UNREACHABLE();
1027 }
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001028 return true;
1029}
1030
Vladimir Marko354efa62016-02-04 19:46:56 +00001031HInstanceFieldGet* HInliner::CreateInstanceFieldGet(Handle<mirror::DexCache> dex_cache,
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001032 uint32_t field_index,
1033 HInstruction* obj)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001034 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe542451c2016-07-26 09:02:02 -07001035 PointerSize pointer_size = InstructionSetPointerSize(codegen_->GetInstructionSet());
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001036 ArtField* resolved_field = dex_cache->GetResolvedField(field_index, pointer_size);
1037 DCHECK(resolved_field != nullptr);
1038 HInstanceFieldGet* iget = new (graph_->GetArena()) HInstanceFieldGet(
1039 obj,
1040 resolved_field->GetTypeAsPrimitiveType(),
1041 resolved_field->GetOffset(),
1042 resolved_field->IsVolatile(),
1043 field_index,
1044 resolved_field->GetDeclaringClass()->GetDexClassDefIndex(),
Vladimir Marko354efa62016-02-04 19:46:56 +00001045 *dex_cache->GetDexFile(),
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001046 dex_cache,
Vladimir Markoadda4352016-01-29 10:24:41 +00001047 // Read barrier generates a runtime call in slow path and we need a valid
1048 // dex pc for the associated stack map. 0 is bogus but valid. Bug: 26854537.
1049 /* dex_pc */ 0);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001050 if (iget->GetType() == Primitive::kPrimNot) {
Vladimir Marko456307a2016-04-19 14:12:13 +00001051 // Use the same dex_cache that we used for field lookup as the hint_dex_cache.
1052 ReferenceTypePropagation rtp(graph_, dex_cache, handles_, /* is_first_run */ false);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001053 rtp.Visit(iget);
1054 }
1055 return iget;
1056}
1057
Vladimir Marko354efa62016-02-04 19:46:56 +00001058HInstanceFieldSet* HInliner::CreateInstanceFieldSet(Handle<mirror::DexCache> dex_cache,
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001059 uint32_t field_index,
1060 HInstruction* obj,
1061 HInstruction* value)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001062 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe542451c2016-07-26 09:02:02 -07001063 PointerSize pointer_size = InstructionSetPointerSize(codegen_->GetInstructionSet());
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001064 ArtField* resolved_field = dex_cache->GetResolvedField(field_index, pointer_size);
1065 DCHECK(resolved_field != nullptr);
1066 HInstanceFieldSet* iput = new (graph_->GetArena()) HInstanceFieldSet(
1067 obj,
1068 value,
1069 resolved_field->GetTypeAsPrimitiveType(),
1070 resolved_field->GetOffset(),
1071 resolved_field->IsVolatile(),
1072 field_index,
1073 resolved_field->GetDeclaringClass()->GetDexClassDefIndex(),
Vladimir Marko354efa62016-02-04 19:46:56 +00001074 *dex_cache->GetDexFile(),
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001075 dex_cache,
Vladimir Markoadda4352016-01-29 10:24:41 +00001076 // Read barrier generates a runtime call in slow path and we need a valid
1077 // dex pc for the associated stack map. 0 is bogus but valid. Bug: 26854537.
1078 /* dex_pc */ 0);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001079 return iput;
1080}
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +00001081
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001082bool HInliner::TryBuildAndInlineHelper(HInvoke* invoke_instruction,
1083 ArtMethod* resolved_method,
1084 bool same_dex_file,
1085 HInstruction** return_replacement) {
Nicolas Geoffrayc0365b12015-03-18 18:31:52 +00001086 ScopedObjectAccess soa(Thread::Current());
1087 const DexFile::CodeItem* code_item = resolved_method->GetCodeItem();
Guillaume "Vermeille" Sanchezae09d2d2015-05-29 10:52:55 +01001088 const DexFile& callee_dex_file = *resolved_method->GetDexFile();
1089 uint32_t method_index = resolved_method->GetDexMethodIndex();
Calin Juravle2e768302015-07-28 14:41:11 +00001090 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
Mathieu Chartier736b5602015-09-02 14:54:11 -07001091 Handle<mirror::DexCache> dex_cache(handles_->NewHandle(resolved_method->GetDexCache()));
Nicolas Geoffrayf1aedb12016-07-28 03:49:14 +01001092 Handle<mirror::ClassLoader> class_loader(handles_->NewHandle(
1093 resolved_method->GetDeclaringClass()->GetClassLoader()));
1094
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001095 DexCompilationUnit dex_compilation_unit(
Nicolas Geoffrayf1aedb12016-07-28 03:49:14 +01001096 class_loader.ToJObject(),
Nicolas Geoffray5b82d332016-02-18 14:22:32 +00001097 class_linker,
1098 callee_dex_file,
1099 code_item,
1100 resolved_method->GetDeclaringClass()->GetDexClassDefIndex(),
1101 method_index,
1102 resolved_method->GetAccessFlags(),
1103 /* verified_method */ nullptr,
1104 dex_cache);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001105
Calin Juravle3cd4fc82015-05-14 15:15:42 +01001106 bool requires_ctor_barrier = false;
1107
1108 if (dex_compilation_unit.IsConstructor()) {
1109 // If it's a super invocation and we already generate a barrier there's no need
1110 // to generate another one.
1111 // We identify super calls by looking at the "this" pointer. If its value is the
1112 // same as the local "this" pointer then we must have a super invocation.
1113 bool is_super_invocation = invoke_instruction->InputAt(0)->IsParameterValue()
1114 && invoke_instruction->InputAt(0)->AsParameterValue()->IsThis();
1115 if (is_super_invocation && graph_->ShouldGenerateConstructorBarrier()) {
1116 requires_ctor_barrier = false;
1117 } else {
1118 Thread* self = Thread::Current();
1119 requires_ctor_barrier = compiler_driver_->RequiresConstructorBarrier(self,
1120 dex_compilation_unit.GetDexFile(),
1121 dex_compilation_unit.GetClassDefIndex());
1122 }
1123 }
1124
Nicolas Geoffray35071052015-06-09 15:43:38 +01001125 InvokeType invoke_type = invoke_instruction->GetOriginalInvokeType();
1126 if (invoke_type == kInterface) {
1127 // We have statically resolved the dispatch. To please the class linker
1128 // at runtime, we change this call as if it was a virtual call.
1129 invoke_type = kVirtual;
1130 }
David Brazdil3f523062016-02-29 16:53:33 +00001131
1132 const int32_t caller_instruction_counter = graph_->GetCurrentInstructionId();
Nicolas Geoffraye0fe7ae2015-03-09 10:02:49 +00001133 HGraph* callee_graph = new (graph_->GetArena()) HGraph(
Nicolas Geoffray0a23d742015-05-07 11:57:35 +01001134 graph_->GetArena(),
Guillaume "Vermeille" Sanchezae09d2d2015-05-29 10:52:55 +01001135 callee_dex_file,
Nicolas Geoffray0a23d742015-05-07 11:57:35 +01001136 method_index,
Calin Juravle3cd4fc82015-05-14 15:15:42 +01001137 requires_ctor_barrier,
Mathieu Chartiere401d142015-04-22 13:56:20 -07001138 compiler_driver_->GetInstructionSet(),
Nicolas Geoffray35071052015-06-09 15:43:38 +01001139 invoke_type,
Nicolas Geoffray0a23d742015-05-07 11:57:35 +01001140 graph_->IsDebuggable(),
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001141 /* osr */ false,
David Brazdil3f523062016-02-29 16:53:33 +00001142 caller_instruction_counter);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001143 callee_graph->SetArtMethod(resolved_method);
David Brazdil5e8b1372015-01-23 14:39:08 +00001144
Roland Levillaina8013fd2016-04-04 15:34:31 +01001145 // When they are needed, allocate `inline_stats` on the heap instead
1146 // of on the stack, as Clang might produce a stack frame too large
1147 // for this function, that would not fit the requirements of the
1148 // `-Wframe-larger-than` option.
1149 std::unique_ptr<OptimizingCompilerStats> inline_stats =
1150 (stats_ == nullptr) ? nullptr : MakeUnique<OptimizingCompilerStats>();
David Brazdil5e8b1372015-01-23 14:39:08 +00001151 HGraphBuilder builder(callee_graph,
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001152 &dex_compilation_unit,
1153 &outer_compilation_unit_,
Nicolas Geoffray9437b782015-03-25 10:08:51 +00001154 resolved_method->GetDexFile(),
David Brazdil86ea7ee2016-02-16 09:26:07 +00001155 *code_item,
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001156 compiler_driver_,
Roland Levillaina8013fd2016-04-04 15:34:31 +01001157 inline_stats.get(),
Mathieu Chartier736b5602015-09-02 14:54:11 -07001158 resolved_method->GetQuickenedInfo(),
David Brazdildee58d62016-04-07 09:54:26 +00001159 dex_cache,
1160 handles_);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001161
David Brazdildee58d62016-04-07 09:54:26 +00001162 if (builder.BuildGraph() != kAnalysisSuccess) {
Guillaume "Vermeille" Sanchezae09d2d2015-05-29 10:52:55 +01001163 VLOG(compiler) << "Method " << PrettyMethod(method_index, callee_dex_file)
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001164 << " could not be built, so cannot be inlined";
1165 return false;
1166 }
1167
Nicolas Geoffray259136f2014-12-17 23:21:58 +00001168 if (!RegisterAllocator::CanAllocateRegistersFor(*callee_graph,
1169 compiler_driver_->GetInstructionSet())) {
Guillaume "Vermeille" Sanchezae09d2d2015-05-29 10:52:55 +01001170 VLOG(compiler) << "Method " << PrettyMethod(method_index, callee_dex_file)
Nicolas Geoffray259136f2014-12-17 23:21:58 +00001171 << " cannot be inlined because of the register allocator";
1172 return false;
1173 }
1174
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001175 size_t parameter_index = 0;
1176 for (HInstructionIterator instructions(callee_graph->GetEntryBlock()->GetInstructions());
1177 !instructions.Done();
1178 instructions.Advance()) {
1179 HInstruction* current = instructions.Current();
1180 if (current->IsParameterValue()) {
1181 HInstruction* argument = invoke_instruction->InputAt(parameter_index++);
1182 if (argument->IsNullConstant()) {
1183 current->ReplaceWith(callee_graph->GetNullConstant());
1184 } else if (argument->IsIntConstant()) {
1185 current->ReplaceWith(callee_graph->GetIntConstant(argument->AsIntConstant()->GetValue()));
1186 } else if (argument->IsLongConstant()) {
1187 current->ReplaceWith(callee_graph->GetLongConstant(argument->AsLongConstant()->GetValue()));
1188 } else if (argument->IsFloatConstant()) {
1189 current->ReplaceWith(
1190 callee_graph->GetFloatConstant(argument->AsFloatConstant()->GetValue()));
1191 } else if (argument->IsDoubleConstant()) {
1192 current->ReplaceWith(
1193 callee_graph->GetDoubleConstant(argument->AsDoubleConstant()->GetValue()));
1194 } else if (argument->GetType() == Primitive::kPrimNot) {
1195 current->SetReferenceTypeInfo(argument->GetReferenceTypeInfo());
1196 current->AsParameterValue()->SetCanBeNull(argument->CanBeNull());
1197 }
1198 }
1199 }
1200
David Brazdil94ab38f2016-06-21 17:48:19 +01001201 // We have replaced formal arguments with actual arguments. If actual types
1202 // are more specific than the declared ones, run RTP again on the inner graph.
1203 if (ArgumentTypesMoreSpecific(invoke_instruction, resolved_method)) {
1204 ReferenceTypePropagation(callee_graph,
1205 dex_compilation_unit.GetDexCache(),
1206 handles_,
1207 /* is_first_run */ false).Run();
1208 }
1209
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001210 size_t number_of_instructions_budget = kMaximumNumberOfHInstructions;
Roland Levillaina3aef2e2016-04-06 17:45:58 +01001211 size_t number_of_inlined_instructions =
1212 RunOptimizations(callee_graph, code_item, dex_compilation_unit);
1213 number_of_instructions_budget += number_of_inlined_instructions;
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +00001214
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001215 // TODO: We should abort only if all predecessors throw. However,
1216 // HGraph::InlineInto currently does not handle an exit block with
1217 // a throw predecessor.
1218 HBasicBlock* exit_block = callee_graph->GetExitBlock();
1219 if (exit_block == nullptr) {
Guillaume "Vermeille" Sanchezae09d2d2015-05-29 10:52:55 +01001220 VLOG(compiler) << "Method " << PrettyMethod(method_index, callee_dex_file)
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001221 << " could not be inlined because it has an infinite loop";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001222 return false;
1223 }
1224
1225 bool has_throw_predecessor = false;
Vladimir Marko60584552015-09-03 13:35:12 +00001226 for (HBasicBlock* predecessor : exit_block->GetPredecessors()) {
1227 if (predecessor->GetLastInstruction()->IsThrow()) {
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001228 has_throw_predecessor = true;
1229 break;
1230 }
1231 }
1232 if (has_throw_predecessor) {
Guillaume "Vermeille" Sanchezae09d2d2015-05-29 10:52:55 +01001233 VLOG(compiler) << "Method " << PrettyMethod(method_index, callee_dex_file)
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001234 << " could not be inlined because one branch always throws";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001235 return false;
1236 }
1237
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001238 HReversePostOrderIterator it(*callee_graph);
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +00001239 it.Advance(); // Past the entry block, it does not contain instructions that prevent inlining.
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001240 size_t number_of_instructions = 0;
Nicolas Geoffray5949fa02015-12-18 10:57:10 +00001241
1242 bool can_inline_environment =
1243 total_number_of_dex_registers_ < kMaximumNumberOfCumulatedDexRegisters;
1244
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001245 for (; !it.Done(); it.Advance()) {
1246 HBasicBlock* block = it.Current();
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00001247
1248 if (block->IsLoopHeader() && block->GetLoopInformation()->IsIrreducible()) {
1249 // Don't inline methods with irreducible loops, they could prevent some
1250 // optimizations to run.
Guillaume "Vermeille" Sanchezae09d2d2015-05-29 10:52:55 +01001251 VLOG(compiler) << "Method " << PrettyMethod(method_index, callee_dex_file)
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00001252 << " could not be inlined because it contains an irreducible loop";
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001253 return false;
1254 }
1255
1256 for (HInstructionIterator instr_it(block->GetInstructions());
1257 !instr_it.Done();
1258 instr_it.Advance()) {
Roland Levillaina3aef2e2016-04-06 17:45:58 +01001259 if (number_of_instructions++ == number_of_instructions_budget) {
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001260 VLOG(compiler) << "Method " << PrettyMethod(method_index, callee_dex_file)
Nicolas Geoffray5949fa02015-12-18 10:57:10 +00001261 << " is not inlined because its caller has reached"
1262 << " its instruction budget limit.";
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001263 return false;
1264 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001265 HInstruction* current = instr_it.Current();
Nicolas Geoffray5949fa02015-12-18 10:57:10 +00001266 if (!can_inline_environment && current->NeedsEnvironment()) {
1267 VLOG(compiler) << "Method " << PrettyMethod(method_index, callee_dex_file)
1268 << " is not inlined because its caller has reached"
1269 << " its environment budget limit.";
1270 return false;
1271 }
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001272
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001273 if (!same_dex_file && current->NeedsEnvironment()) {
Guillaume "Vermeille" Sanchezae09d2d2015-05-29 10:52:55 +01001274 VLOG(compiler) << "Method " << PrettyMethod(method_index, callee_dex_file)
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001275 << " could not be inlined because " << current->DebugName()
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001276 << " needs an environment and is in a different dex file";
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001277 return false;
1278 }
Nicolas Geoffray9437b782015-03-25 10:08:51 +00001279
Vladimir Markodc151b22015-10-15 18:02:30 +01001280 if (!same_dex_file && current->NeedsDexCacheOfDeclaringClass()) {
Guillaume "Vermeille" Sanchezae09d2d2015-05-29 10:52:55 +01001281 VLOG(compiler) << "Method " << PrettyMethod(method_index, callee_dex_file)
Nicolas Geoffray9437b782015-03-25 10:08:51 +00001282 << " could not be inlined because " << current->DebugName()
1283 << " it is in a different dex file and requires access to the dex cache";
1284 return false;
1285 }
Nicolas Geoffrayd9309292015-10-31 22:21:31 +00001286
1287 if (current->IsNewInstance() &&
1288 (current->AsNewInstance()->GetEntrypoint() == kQuickAllocObjectWithAccessCheck)) {
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +00001289 VLOG(compiler) << "Method " << PrettyMethod(method_index, callee_dex_file)
1290 << " could not be inlined because it is using an entrypoint"
1291 << " with access checks";
Nicolas Geoffrayd9309292015-10-31 22:21:31 +00001292 // Allocation entrypoint does not handle inlined frames.
1293 return false;
1294 }
1295
1296 if (current->IsNewArray() &&
1297 (current->AsNewArray()->GetEntrypoint() == kQuickAllocArrayWithAccessCheck)) {
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +00001298 VLOG(compiler) << "Method " << PrettyMethod(method_index, callee_dex_file)
1299 << " could not be inlined because it is using an entrypoint"
1300 << " with access checks";
Nicolas Geoffrayd9309292015-10-31 22:21:31 +00001301 // Allocation entrypoint does not handle inlined frames.
1302 return false;
1303 }
1304
1305 if (current->IsUnresolvedStaticFieldGet() ||
1306 current->IsUnresolvedInstanceFieldGet() ||
1307 current->IsUnresolvedStaticFieldSet() ||
1308 current->IsUnresolvedInstanceFieldSet()) {
1309 // Entrypoint for unresolved fields does not handle inlined frames.
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +00001310 VLOG(compiler) << "Method " << PrettyMethod(method_index, callee_dex_file)
1311 << " could not be inlined because it is using an unresolved"
1312 << " entrypoint";
Nicolas Geoffrayd9309292015-10-31 22:21:31 +00001313 return false;
1314 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001315 }
1316 }
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001317 number_of_inlined_instructions_ += number_of_instructions;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001318
David Brazdil3f523062016-02-29 16:53:33 +00001319 DCHECK_EQ(caller_instruction_counter, graph_->GetCurrentInstructionId())
1320 << "No instructions can be added to the outer graph while inner graph is being built";
1321
1322 const int32_t callee_instruction_counter = callee_graph->GetCurrentInstructionId();
1323 graph_->SetCurrentInstructionId(callee_instruction_counter);
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001324 *return_replacement = callee_graph->InlineInto(graph_, invoke_instruction);
David Brazdil3f523062016-02-29 16:53:33 +00001325
1326 DCHECK_EQ(callee_instruction_counter, callee_graph->GetCurrentInstructionId())
1327 << "No instructions can be added to the inner graph during inlining into the outer graph";
1328
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001329 return true;
1330}
Calin Juravle2e768302015-07-28 14:41:11 +00001331
Roland Levillaina3aef2e2016-04-06 17:45:58 +01001332size_t HInliner::RunOptimizations(HGraph* callee_graph,
1333 const DexFile::CodeItem* code_item,
1334 const DexCompilationUnit& dex_compilation_unit) {
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01001335 // Note: if the outermost_graph_ is being compiled OSR, we should not run any
1336 // optimization that could lead to a HDeoptimize. The following optimizations do not.
Roland Levillaina3aef2e2016-04-06 17:45:58 +01001337 HDeadCodeElimination dce(callee_graph, stats_);
1338 HConstantFolding fold(callee_graph);
1339 HSharpening sharpening(callee_graph, codegen_, dex_compilation_unit, compiler_driver_);
1340 InstructionSimplifier simplify(callee_graph, stats_);
1341 IntrinsicsRecognizer intrinsics(callee_graph, compiler_driver_, stats_);
1342
1343 HOptimization* optimizations[] = {
1344 &intrinsics,
1345 &sharpening,
1346 &simplify,
1347 &fold,
1348 &dce,
1349 };
1350
1351 for (size_t i = 0; i < arraysize(optimizations); ++i) {
1352 HOptimization* optimization = optimizations[i];
1353 optimization->Run();
1354 }
1355
1356 size_t number_of_inlined_instructions = 0u;
1357 if (depth_ + 1 < compiler_driver_->GetCompilerOptions().GetInlineDepthLimit()) {
1358 HInliner inliner(callee_graph,
1359 outermost_graph_,
1360 codegen_,
1361 outer_compilation_unit_,
1362 dex_compilation_unit,
1363 compiler_driver_,
1364 handles_,
1365 stats_,
1366 total_number_of_dex_registers_ + code_item->registers_size_,
1367 depth_ + 1);
1368 inliner.Run();
1369 number_of_inlined_instructions += inliner.number_of_inlined_instructions_;
1370 }
1371
1372 return number_of_inlined_instructions;
1373}
1374
David Brazdil94ab38f2016-06-21 17:48:19 +01001375static bool IsReferenceTypeRefinement(ReferenceTypeInfo declared_rti,
1376 bool declared_can_be_null,
1377 HInstruction* actual_obj)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001378 REQUIRES_SHARED(Locks::mutator_lock_) {
David Brazdil94ab38f2016-06-21 17:48:19 +01001379 if (declared_can_be_null && !actual_obj->CanBeNull()) {
1380 return true;
1381 }
1382
1383 ReferenceTypeInfo actual_rti = actual_obj->GetReferenceTypeInfo();
1384 return (actual_rti.IsExact() && !declared_rti.IsExact()) ||
1385 declared_rti.IsStrictSupertypeOf(actual_rti);
1386}
1387
1388ReferenceTypeInfo HInliner::GetClassRTI(mirror::Class* klass) {
1389 return ReferenceTypePropagation::IsAdmissible(klass)
1390 ? ReferenceTypeInfo::Create(handles_->NewHandle(klass))
1391 : graph_->GetInexactObjectRti();
1392}
1393
1394bool HInliner::ArgumentTypesMoreSpecific(HInvoke* invoke_instruction, ArtMethod* resolved_method) {
1395 // If this is an instance call, test whether the type of the `this` argument
1396 // is more specific than the class which declares the method.
1397 if (!resolved_method->IsStatic()) {
1398 if (IsReferenceTypeRefinement(GetClassRTI(resolved_method->GetDeclaringClass()),
1399 /* declared_can_be_null */ false,
1400 invoke_instruction->InputAt(0u))) {
1401 return true;
1402 }
1403 }
1404
Andreas Gampe542451c2016-07-26 09:02:02 -07001405 PointerSize pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
David Brazdil94ab38f2016-06-21 17:48:19 +01001406
1407 // Iterate over the list of parameter types and test whether any of the
1408 // actual inputs has a more specific reference type than the type declared in
1409 // the signature.
1410 const DexFile::TypeList* param_list = resolved_method->GetParameterTypeList();
1411 for (size_t param_idx = 0,
1412 input_idx = resolved_method->IsStatic() ? 0 : 1,
1413 e = (param_list == nullptr ? 0 : param_list->Size());
1414 param_idx < e;
1415 ++param_idx, ++input_idx) {
1416 HInstruction* input = invoke_instruction->InputAt(input_idx);
1417 if (input->GetType() == Primitive::kPrimNot) {
1418 mirror::Class* param_cls = resolved_method->GetDexCacheResolvedType(
1419 param_list->GetTypeItem(param_idx).type_idx_,
1420 pointer_size);
1421 if (IsReferenceTypeRefinement(GetClassRTI(param_cls),
1422 /* declared_can_be_null */ true,
1423 input)) {
1424 return true;
1425 }
1426 }
1427 }
1428
1429 return false;
1430}
1431
1432bool HInliner::ReturnTypeMoreSpecific(HInvoke* invoke_instruction,
1433 HInstruction* return_replacement) {
Alex Light68289a52015-12-15 17:30:30 -08001434 // Check the integrity of reference types and run another type propagation if needed.
David Brazdil4833f5a2015-12-16 10:37:39 +00001435 if (return_replacement != nullptr) {
1436 if (return_replacement->GetType() == Primitive::kPrimNot) {
David Brazdil94ab38f2016-06-21 17:48:19 +01001437 // Test if the return type is a refinement of the declared return type.
1438 if (IsReferenceTypeRefinement(invoke_instruction->GetReferenceTypeInfo(),
1439 /* declared_can_be_null */ true,
1440 return_replacement)) {
1441 return true;
1442 }
1443 } else if (return_replacement->IsInstanceOf()) {
1444 // Inlining InstanceOf into an If may put a tighter bound on reference types.
1445 return true;
1446 }
1447 }
1448
1449 return false;
1450}
1451
1452void HInliner::FixUpReturnReferenceType(ArtMethod* resolved_method,
1453 HInstruction* return_replacement) {
1454 if (return_replacement != nullptr) {
1455 if (return_replacement->GetType() == Primitive::kPrimNot) {
David Brazdil4833f5a2015-12-16 10:37:39 +00001456 if (!return_replacement->GetReferenceTypeInfo().IsValid()) {
1457 // Make sure that we have a valid type for the return. We may get an invalid one when
1458 // we inline invokes with multiple branches and create a Phi for the result.
1459 // TODO: we could be more precise by merging the phi inputs but that requires
1460 // some functionality from the reference type propagation.
1461 DCHECK(return_replacement->IsPhi());
Andreas Gampe542451c2016-07-26 09:02:02 -07001462 PointerSize pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
Nicolas Geoffray44fd0e52016-03-16 15:16:06 +00001463 mirror::Class* cls = resolved_method->GetReturnType(false /* resolve */, pointer_size);
David Brazdil94ab38f2016-06-21 17:48:19 +01001464 return_replacement->SetReferenceTypeInfo(GetClassRTI(cls));
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001465 }
Calin Juravlecdfed3d2015-10-26 14:05:01 +00001466 }
Calin Juravle2e768302015-07-28 14:41:11 +00001467 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001468}
1469
1470} // namespace art