blob: 80835532fe36723a10dfe9c63ddde1be4907d34c [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"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000020#include "builder.h"
21#include "class_linker.h"
22#include "constant_folding.h"
23#include "dead_code_elimination.h"
Vladimir Markobe10e8e2016-01-22 12:09:44 +000024#include "dex/verified_method.h"
25#include "dex/verification_results.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000026#include "driver/compiler_driver-inl.h"
Calin Juravleec748352015-07-29 13:52:12 +010027#include "driver/compiler_options.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000028#include "driver/dex_compilation_unit.h"
29#include "instruction_simplifier.h"
Scott Wakelingd60a1af2015-07-22 14:32:44 +010030#include "intrinsics.h"
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +000031#include "jit/jit.h"
32#include "jit/jit_code_cache.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000033#include "mirror/class_loader.h"
34#include "mirror/dex_cache.h"
35#include "nodes.h"
Nicolas Geoffray335005e2015-06-25 10:01:47 +010036#include "optimizing_compiler.h"
Nicolas Geoffray454a4812015-06-09 10:37:32 +010037#include "reference_type_propagation.h"
Nicolas Geoffray259136f2014-12-17 23:21:58 +000038#include "register_allocator.h"
Vladimir Markobe10e8e2016-01-22 12:09:44 +000039#include "quick/inline_method_analyser.h"
Vladimir Markodc151b22015-10-15 18:02:30 +010040#include "sharpening.h"
David Brazdil4833f5a2015-12-16 10:37:39 +000041#include "ssa_builder.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000042#include "ssa_phi_elimination.h"
43#include "scoped_thread_state_change.h"
44#include "thread.h"
45
46namespace art {
47
Nicolas Geoffray5949fa02015-12-18 10:57:10 +000048static constexpr size_t kMaximumNumberOfHInstructions = 32;
49
50// Limit the number of dex registers that we accumulate while inlining
51// to avoid creating large amount of nested environments.
52static constexpr size_t kMaximumNumberOfCumulatedDexRegisters = 64;
53
54// Avoid inlining within a huge method due to memory pressure.
55static constexpr size_t kMaximumCodeUnitSize = 4096;
Nicolas Geoffraye418dda2015-08-11 20:03:09 -070056
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000057void HInliner::Run() {
Calin Juravle8f96df82015-07-29 15:58:48 +010058 const CompilerOptions& compiler_options = compiler_driver_->GetCompilerOptions();
59 if ((compiler_options.GetInlineDepthLimit() == 0)
60 || (compiler_options.GetInlineMaxCodeUnits() == 0)) {
61 return;
62 }
Nicolas Geoffray5949fa02015-12-18 10:57:10 +000063 if (caller_compilation_unit_.GetCodeItem()->insns_size_in_code_units_ > kMaximumCodeUnitSize) {
64 return;
65 }
Nicolas Geoffraye50b8d22015-03-13 08:57:42 +000066 if (graph_->IsDebuggable()) {
67 // For simplicity, we currently never inline when the graph is debuggable. This avoids
68 // doing some logic in the runtime to discover if a method could have been inlined.
69 return;
70 }
Vladimir Markofa6b93c2015-09-15 10:15:55 +010071 const ArenaVector<HBasicBlock*>& blocks = graph_->GetReversePostOrder();
72 DCHECK(!blocks.empty());
73 HBasicBlock* next_block = blocks[0];
74 for (size_t i = 0; i < blocks.size(); ++i) {
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +010075 // Because we are changing the graph when inlining, we need to remember the next block.
76 // This avoids doing the inlining work again on the inlined blocks.
Vladimir Markofa6b93c2015-09-15 10:15:55 +010077 if (blocks[i] != next_block) {
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +010078 continue;
79 }
80 HBasicBlock* block = next_block;
Vladimir Markofa6b93c2015-09-15 10:15:55 +010081 next_block = (i == blocks.size() - 1) ? nullptr : blocks[i + 1];
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 Geoffray79041292015-03-26 10:05:54 +000087 // We use the original invoke type to ensure the resolution of the called method
88 // works properly.
Vladimir Marko58155012015-08-19 12:49:41 +000089 if (!TryInline(call)) {
Nicolas Geoffray335005e2015-06-25 10:01:47 +010090 if (kIsDebugBuild && IsCompilingWithCoreImage()) {
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000091 std::string callee_name =
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +000092 PrettyMethod(call->GetDexMethodIndex(), *outer_compilation_unit_.GetDexFile());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000093 bool should_inline = callee_name.find("$inline$") != std::string::npos;
94 CHECK(!should_inline) << "Could not inline " << callee_name;
95 }
Guillaume "Vermeille" Sancheze918d382015-06-03 15:32:41 +010096 } else {
Nicolas Geoffray335005e2015-06-25 10:01:47 +010097 if (kIsDebugBuild && IsCompilingWithCoreImage()) {
Guillaume "Vermeille" Sancheze918d382015-06-03 15:32:41 +010098 std::string callee_name =
99 PrettyMethod(call->GetDexMethodIndex(), *outer_compilation_unit_.GetDexFile());
100 bool must_not_inline = callee_name.find("$noinline$") != std::string::npos;
101 CHECK(!must_not_inline) << "Should not have inlined " << callee_name;
102 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000103 }
104 }
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +0000105 instruction = next;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000106 }
107 }
108}
109
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100110static bool IsMethodOrDeclaringClassFinal(ArtMethod* method)
Mathieu Chartier90443472015-07-16 20:32:27 -0700111 SHARED_REQUIRES(Locks::mutator_lock_) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100112 return method->IsFinal() || method->GetDeclaringClass()->IsFinal();
113}
114
115/**
116 * Given the `resolved_method` looked up in the dex cache, try to find
117 * the actual runtime target of an interface or virtual call.
118 * Return nullptr if the runtime target cannot be proven.
119 */
120static ArtMethod* FindVirtualOrInterfaceTarget(HInvoke* invoke, ArtMethod* resolved_method)
Mathieu Chartier90443472015-07-16 20:32:27 -0700121 SHARED_REQUIRES(Locks::mutator_lock_) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100122 if (IsMethodOrDeclaringClassFinal(resolved_method)) {
123 // No need to lookup further, the resolved method will be the target.
124 return resolved_method;
125 }
126
127 HInstruction* receiver = invoke->InputAt(0);
128 if (receiver->IsNullCheck()) {
129 // Due to multiple levels of inlining within the same pass, it might be that
130 // null check does not have the reference type of the actual receiver.
131 receiver = receiver->InputAt(0);
132 }
133 ReferenceTypeInfo info = receiver->GetReferenceTypeInfo();
Calin Juravle2e768302015-07-28 14:41:11 +0000134 DCHECK(info.IsValid()) << "Invalid RTI for " << receiver->DebugName();
135 if (!info.IsExact()) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100136 // We currently only support inlining with known receivers.
137 // TODO: Remove this check, we should be able to inline final methods
138 // on unknown receivers.
139 return nullptr;
140 } else if (info.GetTypeHandle()->IsInterface()) {
141 // Statically knowing that the receiver has an interface type cannot
142 // help us find what is the target method.
143 return nullptr;
144 } else if (!resolved_method->GetDeclaringClass()->IsAssignableFrom(info.GetTypeHandle().Get())) {
145 // The method that we're trying to call is not in the receiver's class or super classes.
146 return nullptr;
147 }
148
149 ClassLinker* cl = Runtime::Current()->GetClassLinker();
150 size_t pointer_size = cl->GetImagePointerSize();
151 if (invoke->IsInvokeInterface()) {
152 resolved_method = info.GetTypeHandle()->FindVirtualMethodForInterface(
153 resolved_method, pointer_size);
154 } else {
155 DCHECK(invoke->IsInvokeVirtual());
156 resolved_method = info.GetTypeHandle()->FindVirtualMethodForVirtual(
157 resolved_method, pointer_size);
158 }
159
160 if (resolved_method == nullptr) {
161 // The information we had on the receiver was not enough to find
162 // the target method. Since we check above the exact type of the receiver,
163 // the only reason this can happen is an IncompatibleClassChangeError.
164 return nullptr;
Alex Light9139e002015-10-09 15:59:48 -0700165 } else if (!resolved_method->IsInvokable()) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100166 // 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;
170 } else if (IsMethodOrDeclaringClassFinal(resolved_method)) {
171 // A final method has to be the target method.
172 return resolved_method;
173 } else if (info.IsExact()) {
174 // If we found a method and the receiver's concrete type is statically
175 // known, we know for sure the target.
176 return resolved_method;
177 } else {
178 // Even if we did find a method, the receiver type was not enough to
179 // statically find the runtime target.
180 return nullptr;
181 }
182}
183
184static uint32_t FindMethodIndexIn(ArtMethod* method,
185 const DexFile& dex_file,
186 uint32_t referrer_index)
Mathieu Chartier90443472015-07-16 20:32:27 -0700187 SHARED_REQUIRES(Locks::mutator_lock_) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100188 if (IsSameDexFile(*method->GetDexFile(), dex_file)) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100189 return method->GetDexMethodIndex();
190 } else {
191 return method->FindDexMethodIndexInOtherDexFile(dex_file, referrer_index);
192 }
193}
194
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000195static uint32_t FindClassIndexIn(mirror::Class* cls,
196 const DexFile& dex_file,
197 Handle<mirror::DexCache> dex_cache)
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100198 SHARED_REQUIRES(Locks::mutator_lock_) {
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000199 uint32_t index = DexFile::kDexNoIndex;
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100200 if (cls->GetDexCache() == nullptr) {
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000201 DCHECK(cls->IsArrayClass()) << PrettyClass(cls);
202 index = cls->FindTypeIndexInOtherDexFile(dex_file);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100203 } else if (cls->GetDexTypeIndex() == DexFile::kDexNoIndex16) {
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000204 DCHECK(cls->IsProxyClass()) << PrettyClass(cls);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100205 // TODO: deal with proxy classes.
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100206 } else if (IsSameDexFile(cls->GetDexFile(), dex_file)) {
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000207 index = cls->GetDexTypeIndex();
208 } else {
209 index = cls->FindTypeIndexInOtherDexFile(dex_file);
210 }
211
212 if (index != DexFile::kDexNoIndex) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100213 // Update the dex cache to ensure the class is in. The generated code will
214 // consider it is. We make it safe by updating the dex cache, as other
215 // dex files might also load the class, and there is no guarantee the dex
216 // cache of the dex file of the class will be updated.
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000217 if (dex_cache->GetResolvedType(index) == nullptr) {
218 dex_cache->SetResolvedType(index, cls);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100219 }
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100220 }
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000221
222 return index;
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100223}
224
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000225class ScopedProfilingInfoInlineUse {
226 public:
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000227 explicit ScopedProfilingInfoInlineUse(ArtMethod* method, Thread* self)
228 : method_(method),
229 self_(self),
230 // Fetch the profiling info ahead of using it. If it's null when fetching,
231 // we should not call JitCodeCache::DoneInlining.
232 profiling_info_(
233 Runtime::Current()->GetJit()->GetCodeCache()->NotifyCompilerUse(method, self)) {
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000234 }
235
236 ~ScopedProfilingInfoInlineUse() {
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000237 if (profiling_info_ != nullptr) {
238 size_t pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
239 DCHECK_EQ(profiling_info_, method_->GetProfilingInfo(pointer_size));
240 Runtime::Current()->GetJit()->GetCodeCache()->DoneCompilerUse(method_, self_);
241 }
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000242 }
243
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000244 ProfilingInfo* GetProfilingInfo() const { return profiling_info_; }
245
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000246 private:
247 ArtMethod* const method_;
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000248 Thread* const self_;
249 ProfilingInfo* const profiling_info_;
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000250};
251
Nicolas Geoffraye418dda2015-08-11 20:03:09 -0700252bool HInliner::TryInline(HInvoke* invoke_instruction) {
Calin Juravle175dc732015-08-25 15:42:32 +0100253 if (invoke_instruction->IsInvokeUnresolved()) {
254 return false; // Don't bother to move further if we know the method is unresolved.
255 }
256
Vladimir Marko58155012015-08-19 12:49:41 +0000257 uint32_t method_index = invoke_instruction->GetDexMethodIndex();
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000258 ScopedObjectAccess soa(Thread::Current());
Nicolas Geoffray9437b782015-03-25 10:08:51 +0000259 const DexFile& caller_dex_file = *caller_compilation_unit_.GetDexFile();
260 VLOG(compiler) << "Try inlining " << PrettyMethod(method_index, caller_dex_file);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000261
Nicolas Geoffray35071052015-06-09 15:43:38 +0100262 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
263 // We can query the dex cache directly. The verifier has populated it already.
Vladimir Marko58155012015-08-19 12:49:41 +0000264 ArtMethod* resolved_method;
Andreas Gampefd2140f2015-12-23 16:30:44 -0800265 ArtMethod* actual_method = nullptr;
Vladimir Marko58155012015-08-19 12:49:41 +0000266 if (invoke_instruction->IsInvokeStaticOrDirect()) {
Nicolas Geoffraye5234232015-12-02 09:06:11 +0000267 if (invoke_instruction->AsInvokeStaticOrDirect()->IsStringInit()) {
268 VLOG(compiler) << "Not inlining a String.<init> method";
269 return false;
270 }
Vladimir Marko58155012015-08-19 12:49:41 +0000271 MethodReference ref = invoke_instruction->AsInvokeStaticOrDirect()->GetTargetMethod();
Mathieu Chartier736b5602015-09-02 14:54:11 -0700272 mirror::DexCache* const dex_cache = (&caller_dex_file == ref.dex_file)
273 ? caller_compilation_unit_.GetDexCache().Get()
274 : class_linker->FindDexCache(soa.Self(), *ref.dex_file);
275 resolved_method = dex_cache->GetResolvedMethod(
Vladimir Marko58155012015-08-19 12:49:41 +0000276 ref.dex_method_index, class_linker->GetImagePointerSize());
Andreas Gampefd2140f2015-12-23 16:30:44 -0800277 // actual_method == resolved_method for direct or static calls.
278 actual_method = resolved_method;
Vladimir Marko58155012015-08-19 12:49:41 +0000279 } else {
Mathieu Chartier736b5602015-09-02 14:54:11 -0700280 resolved_method = caller_compilation_unit_.GetDexCache().Get()->GetResolvedMethod(
Vladimir Marko58155012015-08-19 12:49:41 +0000281 method_index, class_linker->GetImagePointerSize());
Andreas Gampefd2140f2015-12-23 16:30:44 -0800282 if (resolved_method != nullptr) {
283 // Check if we can statically find the method.
284 actual_method = FindVirtualOrInterfaceTarget(invoke_instruction, resolved_method);
285 }
Vladimir Marko58155012015-08-19 12:49:41 +0000286 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000287
Mathieu Chartiere401d142015-04-22 13:56:20 -0700288 if (resolved_method == nullptr) {
Calin Juravle175dc732015-08-25 15:42:32 +0100289 // TODO: Can this still happen?
Nicolas Geoffray35071052015-06-09 15:43:38 +0100290 // Method cannot be resolved if it is in another dex file we do not have access to.
Nicolas Geoffray9437b782015-03-25 10:08:51 +0000291 VLOG(compiler) << "Method cannot be resolved " << PrettyMethod(method_index, caller_dex_file);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000292 return false;
293 }
294
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100295 if (actual_method != nullptr) {
Calin Juravle69158982016-03-16 11:53:41 +0000296 bool result = TryInlineAndReplace(invoke_instruction, actual_method, /* do_rtp */ true);
297 if (result && !invoke_instruction->IsInvokeStaticOrDirect()) {
298 MaybeRecordStat(kInlinedInvokeVirtualOrInterface);
299 }
300 return result;
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100301 }
Nicolas Geoffray55bd7492016-02-16 15:37:12 +0000302
Andreas Gampefd2140f2015-12-23 16:30:44 -0800303 DCHECK(!invoke_instruction->IsInvokeStaticOrDirect());
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100304
305 // Check if we can use an inline cache.
306 ArtMethod* caller = graph_->GetArtMethod();
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000307 if (Runtime::Current()->UseJit()) {
308 // Under JIT, we should always know the caller.
309 DCHECK(caller != nullptr);
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000310 ScopedProfilingInfoInlineUse spiis(caller, soa.Self());
311 ProfilingInfo* profiling_info = spiis.GetProfilingInfo();
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000312 if (profiling_info != nullptr) {
313 const InlineCache& ic = *profiling_info->GetInlineCache(invoke_instruction->GetDexPc());
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000314 if (ic.IsUninitialized()) {
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000315 VLOG(compiler) << "Interface or virtual call to "
316 << PrettyMethod(method_index, caller_dex_file)
317 << " is not hit and not inlined";
318 return false;
319 } else if (ic.IsMonomorphic()) {
320 MaybeRecordStat(kMonomorphicCall);
321 return TryInlineMonomorphicCall(invoke_instruction, resolved_method, ic);
322 } else if (ic.IsPolymorphic()) {
323 MaybeRecordStat(kPolymorphicCall);
324 return TryInlinePolymorphicCall(invoke_instruction, resolved_method, ic);
325 } else {
326 DCHECK(ic.IsMegamorphic());
327 VLOG(compiler) << "Interface or virtual call to "
328 << PrettyMethod(method_index, caller_dex_file)
329 << " is megamorphic and not inlined";
330 MaybeRecordStat(kMegamorphicCall);
331 return false;
332 }
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100333 }
334 }
335
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100336 VLOG(compiler) << "Interface or virtual call to "
337 << PrettyMethod(method_index, caller_dex_file)
338 << " could not be statically determined";
339 return false;
340}
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000341
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000342HInstanceFieldGet* HInliner::BuildGetReceiverClass(ClassLinker* class_linker,
343 HInstruction* receiver,
344 uint32_t dex_pc) const {
345 ArtField* field = class_linker->GetClassRoot(ClassLinker::kJavaLangObject)->GetInstanceField(0);
346 DCHECK_EQ(std::string(field->GetName()), "shadow$_klass_");
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000347 HInstanceFieldGet* result = new (graph_->GetArena()) HInstanceFieldGet(
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000348 receiver,
349 Primitive::kPrimNot,
350 field->GetOffset(),
351 field->IsVolatile(),
352 field->GetDexFieldIndex(),
353 field->GetDeclaringClass()->GetDexClassDefIndex(),
354 *field->GetDexFile(),
355 handles_->NewHandle(field->GetDexCache()),
356 dex_pc);
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000357 // The class of a field is effectively final, and does not have any memory dependencies.
358 result->SetSideEffects(SideEffects::None());
359 return result;
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000360}
361
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100362bool HInliner::TryInlineMonomorphicCall(HInvoke* invoke_instruction,
363 ArtMethod* resolved_method,
364 const InlineCache& ic) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000365 DCHECK(invoke_instruction->IsInvokeVirtual() || invoke_instruction->IsInvokeInterface())
366 << invoke_instruction->DebugName();
367
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100368 const DexFile& caller_dex_file = *caller_compilation_unit_.GetDexFile();
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000369 uint32_t class_index = FindClassIndexIn(
370 ic.GetMonomorphicType(), caller_dex_file, caller_compilation_unit_.GetDexCache());
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100371 if (class_index == DexFile::kDexNoIndex) {
372 VLOG(compiler) << "Call to " << PrettyMethod(resolved_method)
373 << " from inline cache is not inlined because its class is not"
374 << " accessible to the caller";
375 return false;
376 }
377
378 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
379 size_t pointer_size = class_linker->GetImagePointerSize();
380 if (invoke_instruction->IsInvokeInterface()) {
381 resolved_method = ic.GetMonomorphicType()->FindVirtualMethodForInterface(
382 resolved_method, pointer_size);
383 } else {
384 DCHECK(invoke_instruction->IsInvokeVirtual());
385 resolved_method = ic.GetMonomorphicType()->FindVirtualMethodForVirtual(
386 resolved_method, pointer_size);
387 }
388 DCHECK(resolved_method != nullptr);
389 HInstruction* receiver = invoke_instruction->InputAt(0);
390 HInstruction* cursor = invoke_instruction->GetPrevious();
391 HBasicBlock* bb_cursor = invoke_instruction->GetBlock();
392
Nicolas Geoffray55bd7492016-02-16 15:37:12 +0000393 if (!TryInlineAndReplace(invoke_instruction, resolved_method, /* do_rtp */ false)) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100394 return false;
395 }
396
397 // We successfully inlined, now add a guard.
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100398 bool is_referrer =
399 (ic.GetMonomorphicType() == outermost_graph_->GetArtMethod()->GetDeclaringClass());
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000400 AddTypeGuard(receiver,
401 cursor,
402 bb_cursor,
403 class_index,
404 is_referrer,
405 invoke_instruction,
406 /* with_deoptimization */ true);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100407
408 // Run type propagation to get the guard typed, and eventually propagate the
409 // type of the receiver.
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +0000410 ReferenceTypePropagation rtp_fixup(graph_, handles_, /* is_first_run */ false);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100411 rtp_fixup.Run();
412
413 MaybeRecordStat(kInlinedMonomorphicCall);
414 return true;
415}
416
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000417HInstruction* HInliner::AddTypeGuard(HInstruction* receiver,
418 HInstruction* cursor,
419 HBasicBlock* bb_cursor,
420 uint32_t class_index,
421 bool is_referrer,
422 HInstruction* invoke_instruction,
423 bool with_deoptimization) {
424 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
425 HInstanceFieldGet* receiver_class = BuildGetReceiverClass(
426 class_linker, receiver, invoke_instruction->GetDexPc());
427
428 const DexFile& caller_dex_file = *caller_compilation_unit_.GetDexFile();
429 // Note that we will just compare the classes, so we don't need Java semantics access checks.
430 // Also, the caller of `AddTypeGuard` must have guaranteed that the class is in the dex cache.
431 HLoadClass* load_class = new (graph_->GetArena()) HLoadClass(graph_->GetCurrentMethod(),
432 class_index,
433 caller_dex_file,
434 is_referrer,
435 invoke_instruction->GetDexPc(),
436 /* needs_access_check */ false,
437 /* is_in_dex_cache */ true);
438
439 HNotEqual* compare = new (graph_->GetArena()) HNotEqual(load_class, receiver_class);
440 // TODO: Extend reference type propagation to understand the guard.
441 if (cursor != nullptr) {
442 bb_cursor->InsertInstructionAfter(receiver_class, cursor);
443 } else {
444 bb_cursor->InsertInstructionBefore(receiver_class, bb_cursor->GetFirstInstruction());
445 }
446 bb_cursor->InsertInstructionAfter(load_class, receiver_class);
447 bb_cursor->InsertInstructionAfter(compare, load_class);
448 if (with_deoptimization) {
449 HDeoptimize* deoptimize = new (graph_->GetArena()) HDeoptimize(
450 compare, invoke_instruction->GetDexPc());
451 bb_cursor->InsertInstructionAfter(deoptimize, compare);
452 deoptimize->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
453 }
454 return compare;
455}
456
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000457bool HInliner::TryInlinePolymorphicCall(HInvoke* invoke_instruction,
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100458 ArtMethod* resolved_method,
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000459 const InlineCache& ic) {
460 DCHECK(invoke_instruction->IsInvokeVirtual() || invoke_instruction->IsInvokeInterface())
461 << invoke_instruction->DebugName();
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000462
463 if (TryInlinePolymorphicCallToSameTarget(invoke_instruction, resolved_method, ic)) {
464 return true;
465 }
466
467 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
468 size_t pointer_size = class_linker->GetImagePointerSize();
469 const DexFile& caller_dex_file = *caller_compilation_unit_.GetDexFile();
470
471 bool all_targets_inlined = true;
472 bool one_target_inlined = false;
473 for (size_t i = 0; i < InlineCache::kIndividualCacheSize; ++i) {
474 if (ic.GetTypeAt(i) == nullptr) {
475 break;
476 }
477 ArtMethod* method = nullptr;
478 if (invoke_instruction->IsInvokeInterface()) {
479 method = ic.GetTypeAt(i)->FindVirtualMethodForInterface(
480 resolved_method, pointer_size);
481 } else {
482 DCHECK(invoke_instruction->IsInvokeVirtual());
483 method = ic.GetTypeAt(i)->FindVirtualMethodForVirtual(
484 resolved_method, pointer_size);
485 }
486
487 HInstruction* receiver = invoke_instruction->InputAt(0);
488 HInstruction* cursor = invoke_instruction->GetPrevious();
489 HBasicBlock* bb_cursor = invoke_instruction->GetBlock();
490
Nicolas Geoffray1fe26e12016-02-18 16:55:42 +0000491 uint32_t class_index = FindClassIndexIn(
492 ic.GetTypeAt(i), caller_dex_file, caller_compilation_unit_.GetDexCache());
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000493 HInstruction* return_replacement = nullptr;
494 if (class_index == DexFile::kDexNoIndex ||
495 !TryBuildAndInline(invoke_instruction, method, &return_replacement)) {
496 all_targets_inlined = false;
497 } else {
498 one_target_inlined = true;
499 bool is_referrer = (ic.GetTypeAt(i) == outermost_graph_->GetArtMethod()->GetDeclaringClass());
500
501 // If we have inlined all targets before, and this receiver is the last seen,
502 // we deoptimize instead of keeping the original invoke instruction.
503 bool deoptimize = all_targets_inlined &&
504 (i != InlineCache::kIndividualCacheSize - 1) &&
505 (ic.GetTypeAt(i + 1) == nullptr);
506 HInstruction* compare = AddTypeGuard(
507 receiver, cursor, bb_cursor, class_index, is_referrer, invoke_instruction, deoptimize);
508 if (deoptimize) {
509 if (return_replacement != nullptr) {
510 invoke_instruction->ReplaceWith(return_replacement);
511 }
512 invoke_instruction->GetBlock()->RemoveInstruction(invoke_instruction);
513 // Because the inline cache data can be populated concurrently, we force the end of the
514 // iteration. Otherhwise, we could see a new receiver type.
515 break;
516 } else {
517 CreateDiamondPatternForPolymorphicInline(compare, return_replacement, invoke_instruction);
518 }
519 }
520 }
521
522 if (!one_target_inlined) {
523 VLOG(compiler) << "Call to " << PrettyMethod(resolved_method)
524 << " from inline cache is not inlined because none"
525 << " of its targets could be inlined";
526 return false;
527 }
528 MaybeRecordStat(kInlinedPolymorphicCall);
529
530 // Run type propagation to get the guards typed.
531 ReferenceTypePropagation rtp_fixup(graph_, handles_, /* is_first_run */ false);
532 rtp_fixup.Run();
533 return true;
534}
535
536void HInliner::CreateDiamondPatternForPolymorphicInline(HInstruction* compare,
537 HInstruction* return_replacement,
538 HInstruction* invoke_instruction) {
539 uint32_t dex_pc = invoke_instruction->GetDexPc();
540 HBasicBlock* cursor_block = compare->GetBlock();
541 HBasicBlock* original_invoke_block = invoke_instruction->GetBlock();
542 ArenaAllocator* allocator = graph_->GetArena();
543
544 // Spit the block after the compare: `cursor_block` will now be the start of the diamond,
545 // and the returned block is the start of the then branch (that could contain multiple blocks).
546 HBasicBlock* then = cursor_block->SplitAfterForInlining(compare);
547
548 // Split the block containing the invoke before and after the invoke. The returned block
549 // of the split before will contain the invoke and will be the otherwise branch of
550 // the diamond. The returned block of the split after will be the merge block
551 // of the diamond.
552 HBasicBlock* end_then = invoke_instruction->GetBlock();
553 HBasicBlock* otherwise = end_then->SplitBeforeForInlining(invoke_instruction);
554 HBasicBlock* merge = otherwise->SplitAfterForInlining(invoke_instruction);
555
556 // If the methods we are inlining return a value, we create a phi in the merge block
557 // that will have the `invoke_instruction and the `return_replacement` as inputs.
558 if (return_replacement != nullptr) {
559 HPhi* phi = new (allocator) HPhi(
560 allocator, kNoRegNumber, 0, HPhi::ToPhiType(invoke_instruction->GetType()), dex_pc);
561 merge->AddPhi(phi);
562 invoke_instruction->ReplaceWith(phi);
563 phi->AddInput(return_replacement);
564 phi->AddInput(invoke_instruction);
565 }
566
567 // Add the control flow instructions.
568 otherwise->AddInstruction(new (allocator) HGoto(dex_pc));
569 end_then->AddInstruction(new (allocator) HGoto(dex_pc));
570 cursor_block->AddInstruction(new (allocator) HIf(compare, dex_pc));
571
572 // Add the newly created blocks to the graph.
573 graph_->AddBlock(then);
574 graph_->AddBlock(otherwise);
575 graph_->AddBlock(merge);
576
577 // Set up successor (and implictly predecessor) relations.
578 cursor_block->AddSuccessor(otherwise);
579 cursor_block->AddSuccessor(then);
580 end_then->AddSuccessor(merge);
581 otherwise->AddSuccessor(merge);
582
583 // Set up dominance information.
584 then->SetDominator(cursor_block);
585 cursor_block->AddDominatedBlock(then);
586 otherwise->SetDominator(cursor_block);
587 cursor_block->AddDominatedBlock(otherwise);
588 merge->SetDominator(cursor_block);
589 cursor_block->AddDominatedBlock(merge);
590
591 // Update the revert post order.
592 size_t index = IndexOfElement(graph_->reverse_post_order_, cursor_block);
593 MakeRoomFor(&graph_->reverse_post_order_, 1, index);
594 graph_->reverse_post_order_[++index] = then;
595 index = IndexOfElement(graph_->reverse_post_order_, end_then);
596 MakeRoomFor(&graph_->reverse_post_order_, 2, index);
597 graph_->reverse_post_order_[++index] = otherwise;
598 graph_->reverse_post_order_[++index] = merge;
599
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000600
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +0000601 graph_->UpdateLoopAndTryInformationOfNewBlock(
602 then, original_invoke_block, /* replace_if_back_edge */ false);
603 graph_->UpdateLoopAndTryInformationOfNewBlock(
604 otherwise, original_invoke_block, /* replace_if_back_edge */ false);
605
606 // In case the original invoke location was a back edge, we need to update
607 // the loop to now have the merge block as a back edge.
608 graph_->UpdateLoopAndTryInformationOfNewBlock(
609 merge, original_invoke_block, /* replace_if_back_edge */ true);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000610}
611
612bool HInliner::TryInlinePolymorphicCallToSameTarget(HInvoke* invoke_instruction,
613 ArtMethod* resolved_method,
614 const InlineCache& ic) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000615 // This optimization only works under JIT for now.
616 DCHECK(Runtime::Current()->UseJit());
Roland Levillain2aba7cd2016-02-03 12:27:20 +0000617 if (graph_->GetInstructionSet() == kMips64) {
618 // TODO: Support HClassTableGet for mips64.
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000619 return false;
620 }
621 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
622 size_t pointer_size = class_linker->GetImagePointerSize();
623
624 DCHECK(resolved_method != nullptr);
625 ArtMethod* actual_method = nullptr;
Nicolas Geoffray4f97a212016-02-25 16:17:54 +0000626 size_t method_index = invoke_instruction->IsInvokeVirtual()
627 ? invoke_instruction->AsInvokeVirtual()->GetVTableIndex()
628 : invoke_instruction->AsInvokeInterface()->GetImtIndex();
629
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000630 // Check whether we are actually calling the same method among
631 // the different types seen.
632 for (size_t i = 0; i < InlineCache::kIndividualCacheSize; ++i) {
633 if (ic.GetTypeAt(i) == nullptr) {
634 break;
635 }
636 ArtMethod* new_method = nullptr;
637 if (invoke_instruction->IsInvokeInterface()) {
Nicolas Geoffray4f97a212016-02-25 16:17:54 +0000638 new_method = ic.GetTypeAt(i)->GetEmbeddedImTableEntry(
639 method_index % mirror::Class::kImtSize, pointer_size);
640 if (new_method->IsRuntimeMethod()) {
641 // Bail out as soon as we see a conflict trampoline in one of the target's
642 // interface table.
643 return false;
644 }
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000645 } else {
646 DCHECK(invoke_instruction->IsInvokeVirtual());
Nicolas Geoffray4f97a212016-02-25 16:17:54 +0000647 new_method = ic.GetTypeAt(i)->GetEmbeddedVTableEntry(method_index, pointer_size);
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000648 }
Nicolas Geoffray4f97a212016-02-25 16:17:54 +0000649 DCHECK(new_method != nullptr);
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000650 if (actual_method == nullptr) {
651 actual_method = new_method;
652 } else if (actual_method != new_method) {
653 // Different methods, bailout.
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +0000654 VLOG(compiler) << "Call to " << PrettyMethod(resolved_method)
655 << " from inline cache is not inlined because it resolves"
656 << " to different methods";
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000657 return false;
658 }
659 }
660
661 HInstruction* receiver = invoke_instruction->InputAt(0);
662 HInstruction* cursor = invoke_instruction->GetPrevious();
663 HBasicBlock* bb_cursor = invoke_instruction->GetBlock();
664
Nicolas Geoffray55bd7492016-02-16 15:37:12 +0000665 if (!TryInlineAndReplace(invoke_instruction, actual_method, /* do_rtp */ false)) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000666 return false;
667 }
668
669 // We successfully inlined, now add a guard.
670 HInstanceFieldGet* receiver_class = BuildGetReceiverClass(
671 class_linker, receiver, invoke_instruction->GetDexPc());
672
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000673 Primitive::Type type = Is64BitInstructionSet(graph_->GetInstructionSet())
674 ? Primitive::kPrimLong
675 : Primitive::kPrimInt;
676 HClassTableGet* class_table_get = new (graph_->GetArena()) HClassTableGet(
677 receiver_class,
678 type,
Vladimir Markoa1de9182016-02-25 11:37:38 +0000679 invoke_instruction->IsInvokeVirtual() ? HClassTableGet::TableKind::kVTable
680 : HClassTableGet::TableKind::kIMTable,
Nicolas Geoffray4f97a212016-02-25 16:17:54 +0000681 method_index,
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000682 invoke_instruction->GetDexPc());
683
684 HConstant* constant;
685 if (type == Primitive::kPrimLong) {
686 constant = graph_->GetLongConstant(
687 reinterpret_cast<intptr_t>(actual_method), invoke_instruction->GetDexPc());
688 } else {
689 constant = graph_->GetIntConstant(
690 reinterpret_cast<intptr_t>(actual_method), invoke_instruction->GetDexPc());
691 }
692
693 HNotEqual* compare = new (graph_->GetArena()) HNotEqual(class_table_get, constant);
694 HDeoptimize* deoptimize = new (graph_->GetArena()) HDeoptimize(
695 compare, invoke_instruction->GetDexPc());
696 // TODO: Extend reference type propagation to understand the guard.
697 if (cursor != nullptr) {
698 bb_cursor->InsertInstructionAfter(receiver_class, cursor);
699 } else {
700 bb_cursor->InsertInstructionBefore(receiver_class, bb_cursor->GetFirstInstruction());
701 }
702 bb_cursor->InsertInstructionAfter(class_table_get, receiver_class);
703 bb_cursor->InsertInstructionAfter(compare, class_table_get);
704 bb_cursor->InsertInstructionAfter(deoptimize, compare);
705 deoptimize->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
706
707 // Run type propagation to get the guard typed.
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +0000708 ReferenceTypePropagation rtp_fixup(graph_, handles_, /* is_first_run */ false);
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000709 rtp_fixup.Run();
710
711 MaybeRecordStat(kInlinedPolymorphicCall);
712
713 return true;
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100714}
715
Nicolas Geoffray55bd7492016-02-16 15:37:12 +0000716bool HInliner::TryInlineAndReplace(HInvoke* invoke_instruction, ArtMethod* method, bool do_rtp) {
717 HInstruction* return_replacement = nullptr;
718 if (!TryBuildAndInline(invoke_instruction, method, &return_replacement)) {
719 return false;
720 }
721 if (return_replacement != nullptr) {
722 invoke_instruction->ReplaceWith(return_replacement);
723 }
724 invoke_instruction->GetBlock()->RemoveInstruction(invoke_instruction);
725 FixUpReturnReferenceType(invoke_instruction, method, return_replacement, do_rtp);
726 return true;
727}
728
729bool HInliner::TryBuildAndInline(HInvoke* invoke_instruction,
730 ArtMethod* method,
731 HInstruction** return_replacement) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100732 const DexFile& caller_dex_file = *caller_compilation_unit_.GetDexFile();
Jeff Haodcdc85b2015-12-04 14:06:18 -0800733
734 // Check whether we're allowed to inline. The outermost compilation unit is the relevant
735 // dex file here (though the transitivity of an inline chain would allow checking the calller).
736 if (!compiler_driver_->MayInline(method->GetDexFile(),
737 outer_compilation_unit_.GetDexFile())) {
Nicolas Geoffray55bd7492016-02-16 15:37:12 +0000738 if (TryPatternSubstitution(invoke_instruction, method, return_replacement)) {
Vladimir Markobe10e8e2016-01-22 12:09:44 +0000739 VLOG(compiler) << "Successfully replaced pattern of invoke " << PrettyMethod(method);
740 MaybeRecordStat(kReplacedInvokeWithSimplePattern);
741 return true;
742 }
Jeff Haodcdc85b2015-12-04 14:06:18 -0800743 VLOG(compiler) << "Won't inline " << PrettyMethod(method) << " in "
744 << outer_compilation_unit_.GetDexFile()->GetLocation() << " ("
745 << caller_compilation_unit_.GetDexFile()->GetLocation() << ") from "
746 << method->GetDexFile()->GetLocation();
747 return false;
748 }
749
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100750 uint32_t method_index = FindMethodIndexIn(
751 method, caller_dex_file, invoke_instruction->GetDexMethodIndex());
752 if (method_index == DexFile::kDexNoIndex) {
753 VLOG(compiler) << "Call to "
754 << PrettyMethod(method)
755 << " cannot be inlined because unaccessible to caller";
756 return false;
757 }
758
759 bool same_dex_file = IsSameDexFile(*outer_compilation_unit_.GetDexFile(), *method->GetDexFile());
760
761 const DexFile::CodeItem* code_item = method->GetCodeItem();
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000762
763 if (code_item == nullptr) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100764 VLOG(compiler) << "Method " << PrettyMethod(method)
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000765 << " is not inlined because it is native";
766 return false;
767 }
768
Calin Juravleec748352015-07-29 13:52:12 +0100769 size_t inline_max_code_units = compiler_driver_->GetCompilerOptions().GetInlineMaxCodeUnits();
770 if (code_item->insns_size_in_code_units_ > inline_max_code_units) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100771 VLOG(compiler) << "Method " << PrettyMethod(method)
Nicolas Geoffray788f2f02016-01-22 12:41:38 +0000772 << " is too big to inline: "
773 << code_item->insns_size_in_code_units_
774 << " > "
775 << inline_max_code_units;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000776 return false;
777 }
778
779 if (code_item->tries_size_ != 0) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100780 VLOG(compiler) << "Method " << PrettyMethod(method)
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000781 << " is not inlined because of try block";
782 return false;
783 }
784
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100785 if (!method->GetDeclaringClass()->IsVerified()) {
786 uint16_t class_def_idx = method->GetDeclaringClass()->GetDexClassDefIndex();
Nicolas Geoffray5b82d332016-02-18 14:22:32 +0000787 if (Runtime::Current()->UseJit() ||
788 !compiler_driver_->IsMethodVerifiedWithoutFailures(
789 method->GetDexMethodIndex(), class_def_idx, *method->GetDexFile())) {
Nicolas Geoffrayccc61972015-10-01 14:34:20 +0100790 VLOG(compiler) << "Method " << PrettyMethod(method_index, caller_dex_file)
791 << " couldn't be verified, so it cannot be inlined";
792 return false;
793 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000794 }
795
Roland Levillain4c0eb422015-04-24 16:43:49 +0100796 if (invoke_instruction->IsInvokeStaticOrDirect() &&
797 invoke_instruction->AsInvokeStaticOrDirect()->IsStaticWithImplicitClinitCheck()) {
798 // Case of a static method that cannot be inlined because it implicitly
799 // requires an initialization check of its declaring class.
800 VLOG(compiler) << "Method " << PrettyMethod(method_index, caller_dex_file)
801 << " is not inlined because it is static and requires a clinit"
802 << " check that cannot be emitted due to Dex cache limitations";
803 return false;
804 }
805
Nicolas Geoffray55bd7492016-02-16 15:37:12 +0000806 if (!TryBuildAndInlineHelper(invoke_instruction, method, same_dex_file, return_replacement)) {
Nicolas Geoffrayc0365b12015-03-18 18:31:52 +0000807 return false;
808 }
809
Nicolas Geoffray9437b782015-03-25 10:08:51 +0000810 VLOG(compiler) << "Successfully inlined " << PrettyMethod(method_index, caller_dex_file);
Nicolas Geoffrayc0365b12015-03-18 18:31:52 +0000811 MaybeRecordStat(kInlinedInvoke);
812 return true;
813}
814
Vladimir Markobe10e8e2016-01-22 12:09:44 +0000815static HInstruction* GetInvokeInputForArgVRegIndex(HInvoke* invoke_instruction,
816 size_t arg_vreg_index)
817 SHARED_REQUIRES(Locks::mutator_lock_) {
818 size_t input_index = 0;
819 for (size_t i = 0; i < arg_vreg_index; ++i, ++input_index) {
820 DCHECK_LT(input_index, invoke_instruction->GetNumberOfArguments());
821 if (Primitive::Is64BitType(invoke_instruction->InputAt(input_index)->GetType())) {
822 ++i;
823 DCHECK_NE(i, arg_vreg_index);
824 }
825 }
826 DCHECK_LT(input_index, invoke_instruction->GetNumberOfArguments());
827 return invoke_instruction->InputAt(input_index);
828}
829
830// Try to recognize known simple patterns and replace invoke call with appropriate instructions.
831bool HInliner::TryPatternSubstitution(HInvoke* invoke_instruction,
832 ArtMethod* resolved_method,
Nicolas Geoffray55bd7492016-02-16 15:37:12 +0000833 HInstruction** return_replacement) {
Vladimir Markobe10e8e2016-01-22 12:09:44 +0000834 InlineMethod inline_method;
835 if (!InlineMethodAnalyser::AnalyseMethodCode(resolved_method, &inline_method)) {
836 return false;
837 }
838
Vladimir Markobe10e8e2016-01-22 12:09:44 +0000839 switch (inline_method.opcode) {
840 case kInlineOpNop:
841 DCHECK_EQ(invoke_instruction->GetType(), Primitive::kPrimVoid);
Nicolas Geoffray55bd7492016-02-16 15:37:12 +0000842 *return_replacement = nullptr;
Vladimir Markobe10e8e2016-01-22 12:09:44 +0000843 break;
844 case kInlineOpReturnArg:
Nicolas Geoffray55bd7492016-02-16 15:37:12 +0000845 *return_replacement = GetInvokeInputForArgVRegIndex(invoke_instruction,
846 inline_method.d.return_data.arg);
Vladimir Markobe10e8e2016-01-22 12:09:44 +0000847 break;
848 case kInlineOpNonWideConst:
849 if (resolved_method->GetShorty()[0] == 'L') {
850 DCHECK_EQ(inline_method.d.data, 0u);
Nicolas Geoffray55bd7492016-02-16 15:37:12 +0000851 *return_replacement = graph_->GetNullConstant();
Vladimir Markobe10e8e2016-01-22 12:09:44 +0000852 } else {
Nicolas Geoffray55bd7492016-02-16 15:37:12 +0000853 *return_replacement = graph_->GetIntConstant(static_cast<int32_t>(inline_method.d.data));
Vladimir Markobe10e8e2016-01-22 12:09:44 +0000854 }
855 break;
856 case kInlineOpIGet: {
857 const InlineIGetIPutData& data = inline_method.d.ifield_data;
858 if (data.method_is_static || data.object_arg != 0u) {
859 // TODO: Needs null check.
860 return false;
861 }
Vladimir Marko354efa62016-02-04 19:46:56 +0000862 Handle<mirror::DexCache> dex_cache(handles_->NewHandle(resolved_method->GetDexCache()));
Vladimir Markobe10e8e2016-01-22 12:09:44 +0000863 HInstruction* obj = GetInvokeInputForArgVRegIndex(invoke_instruction, data.object_arg);
Vladimir Marko354efa62016-02-04 19:46:56 +0000864 HInstanceFieldGet* iget = CreateInstanceFieldGet(dex_cache, data.field_idx, obj);
Vladimir Markobe10e8e2016-01-22 12:09:44 +0000865 DCHECK_EQ(iget->GetFieldOffset().Uint32Value(), data.field_offset);
866 DCHECK_EQ(iget->IsVolatile() ? 1u : 0u, data.is_volatile);
867 invoke_instruction->GetBlock()->InsertInstructionBefore(iget, invoke_instruction);
Nicolas Geoffray55bd7492016-02-16 15:37:12 +0000868 *return_replacement = iget;
Vladimir Markobe10e8e2016-01-22 12:09:44 +0000869 break;
870 }
871 case kInlineOpIPut: {
872 const InlineIGetIPutData& data = inline_method.d.ifield_data;
873 if (data.method_is_static || data.object_arg != 0u) {
874 // TODO: Needs null check.
875 return false;
876 }
Vladimir Marko354efa62016-02-04 19:46:56 +0000877 Handle<mirror::DexCache> dex_cache(handles_->NewHandle(resolved_method->GetDexCache()));
Vladimir Markobe10e8e2016-01-22 12:09:44 +0000878 HInstruction* obj = GetInvokeInputForArgVRegIndex(invoke_instruction, data.object_arg);
879 HInstruction* value = GetInvokeInputForArgVRegIndex(invoke_instruction, data.src_arg);
Vladimir Marko354efa62016-02-04 19:46:56 +0000880 HInstanceFieldSet* iput = CreateInstanceFieldSet(dex_cache, data.field_idx, obj, value);
Vladimir Markobe10e8e2016-01-22 12:09:44 +0000881 DCHECK_EQ(iput->GetFieldOffset().Uint32Value(), data.field_offset);
882 DCHECK_EQ(iput->IsVolatile() ? 1u : 0u, data.is_volatile);
883 invoke_instruction->GetBlock()->InsertInstructionBefore(iput, invoke_instruction);
884 if (data.return_arg_plus1 != 0u) {
885 size_t return_arg = data.return_arg_plus1 - 1u;
Nicolas Geoffray55bd7492016-02-16 15:37:12 +0000886 *return_replacement = GetInvokeInputForArgVRegIndex(invoke_instruction, return_arg);
Vladimir Markobe10e8e2016-01-22 12:09:44 +0000887 }
888 break;
889 }
Vladimir Marko354efa62016-02-04 19:46:56 +0000890 case kInlineOpConstructor: {
891 const InlineConstructorData& data = inline_method.d.constructor_data;
892 // Get the indexes to arrays for easier processing.
893 uint16_t iput_field_indexes[] = {
894 data.iput0_field_index, data.iput1_field_index, data.iput2_field_index
895 };
896 uint16_t iput_args[] = { data.iput0_arg, data.iput1_arg, data.iput2_arg };
897 static_assert(arraysize(iput_args) == arraysize(iput_field_indexes), "Size mismatch");
898 // Count valid field indexes.
899 size_t number_of_iputs = 0u;
900 while (number_of_iputs != arraysize(iput_field_indexes) &&
901 iput_field_indexes[number_of_iputs] != DexFile::kDexNoIndex16) {
902 // Check that there are no duplicate valid field indexes.
903 DCHECK_EQ(0, std::count(iput_field_indexes + number_of_iputs + 1,
904 iput_field_indexes + arraysize(iput_field_indexes),
905 iput_field_indexes[number_of_iputs]));
906 ++number_of_iputs;
907 }
908 // Check that there are no valid field indexes in the rest of the array.
909 DCHECK_EQ(0, std::count_if(iput_field_indexes + number_of_iputs,
910 iput_field_indexes + arraysize(iput_field_indexes),
911 [](uint16_t index) { return index != DexFile::kDexNoIndex16; }));
912
913 // Create HInstanceFieldSet for each IPUT that stores non-zero data.
914 Handle<mirror::DexCache> dex_cache;
915 HInstruction* obj = GetInvokeInputForArgVRegIndex(invoke_instruction, /* this */ 0u);
916 bool needs_constructor_barrier = false;
917 for (size_t i = 0; i != number_of_iputs; ++i) {
918 HInstruction* value = GetInvokeInputForArgVRegIndex(invoke_instruction, iput_args[i]);
919 if (!value->IsConstant() ||
920 (!value->AsConstant()->IsZero() && !value->IsNullConstant())) {
921 if (dex_cache.GetReference() == nullptr) {
922 dex_cache = handles_->NewHandle(resolved_method->GetDexCache());
923 }
924 uint16_t field_index = iput_field_indexes[i];
925 HInstanceFieldSet* iput = CreateInstanceFieldSet(dex_cache, field_index, obj, value);
926 invoke_instruction->GetBlock()->InsertInstructionBefore(iput, invoke_instruction);
927
928 // Check whether the field is final. If it is, we need to add a barrier.
929 size_t pointer_size = InstructionSetPointerSize(codegen_->GetInstructionSet());
930 ArtField* resolved_field = dex_cache->GetResolvedField(field_index, pointer_size);
931 DCHECK(resolved_field != nullptr);
932 if (resolved_field->IsFinal()) {
933 needs_constructor_barrier = true;
934 }
935 }
936 }
937 if (needs_constructor_barrier) {
938 HMemoryBarrier* barrier = new (graph_->GetArena()) HMemoryBarrier(kStoreStore, kNoDexPc);
939 invoke_instruction->GetBlock()->InsertInstructionBefore(barrier, invoke_instruction);
940 }
Nicolas Geoffray55bd7492016-02-16 15:37:12 +0000941 *return_replacement = nullptr;
Vladimir Marko354efa62016-02-04 19:46:56 +0000942 break;
943 }
Vladimir Markobe10e8e2016-01-22 12:09:44 +0000944 default:
945 LOG(FATAL) << "UNREACHABLE";
946 UNREACHABLE();
947 }
Vladimir Markobe10e8e2016-01-22 12:09:44 +0000948 return true;
949}
950
Vladimir Marko354efa62016-02-04 19:46:56 +0000951HInstanceFieldGet* HInliner::CreateInstanceFieldGet(Handle<mirror::DexCache> dex_cache,
Vladimir Markobe10e8e2016-01-22 12:09:44 +0000952 uint32_t field_index,
953 HInstruction* obj)
954 SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Markobe10e8e2016-01-22 12:09:44 +0000955 size_t pointer_size = InstructionSetPointerSize(codegen_->GetInstructionSet());
956 ArtField* resolved_field = dex_cache->GetResolvedField(field_index, pointer_size);
957 DCHECK(resolved_field != nullptr);
958 HInstanceFieldGet* iget = new (graph_->GetArena()) HInstanceFieldGet(
959 obj,
960 resolved_field->GetTypeAsPrimitiveType(),
961 resolved_field->GetOffset(),
962 resolved_field->IsVolatile(),
963 field_index,
964 resolved_field->GetDeclaringClass()->GetDexClassDefIndex(),
Vladimir Marko354efa62016-02-04 19:46:56 +0000965 *dex_cache->GetDexFile(),
Vladimir Markobe10e8e2016-01-22 12:09:44 +0000966 dex_cache,
Vladimir Markoadda4352016-01-29 10:24:41 +0000967 // Read barrier generates a runtime call in slow path and we need a valid
968 // dex pc for the associated stack map. 0 is bogus but valid. Bug: 26854537.
969 /* dex_pc */ 0);
Vladimir Markobe10e8e2016-01-22 12:09:44 +0000970 if (iget->GetType() == Primitive::kPrimNot) {
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +0000971 ReferenceTypePropagation rtp(graph_, handles_, /* is_first_run */ false);
Vladimir Markobe10e8e2016-01-22 12:09:44 +0000972 rtp.Visit(iget);
973 }
974 return iget;
975}
976
Vladimir Marko354efa62016-02-04 19:46:56 +0000977HInstanceFieldSet* HInliner::CreateInstanceFieldSet(Handle<mirror::DexCache> dex_cache,
Vladimir Markobe10e8e2016-01-22 12:09:44 +0000978 uint32_t field_index,
979 HInstruction* obj,
980 HInstruction* value)
981 SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Markobe10e8e2016-01-22 12:09:44 +0000982 size_t pointer_size = InstructionSetPointerSize(codegen_->GetInstructionSet());
983 ArtField* resolved_field = dex_cache->GetResolvedField(field_index, pointer_size);
984 DCHECK(resolved_field != nullptr);
985 HInstanceFieldSet* iput = new (graph_->GetArena()) HInstanceFieldSet(
986 obj,
987 value,
988 resolved_field->GetTypeAsPrimitiveType(),
989 resolved_field->GetOffset(),
990 resolved_field->IsVolatile(),
991 field_index,
992 resolved_field->GetDeclaringClass()->GetDexClassDefIndex(),
Vladimir Marko354efa62016-02-04 19:46:56 +0000993 *dex_cache->GetDexFile(),
Vladimir Markobe10e8e2016-01-22 12:09:44 +0000994 dex_cache,
Vladimir Markoadda4352016-01-29 10:24:41 +0000995 // Read barrier generates a runtime call in slow path and we need a valid
996 // dex pc for the associated stack map. 0 is bogus but valid. Bug: 26854537.
997 /* dex_pc */ 0);
Vladimir Markobe10e8e2016-01-22 12:09:44 +0000998 return iput;
999}
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +00001000
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001001bool HInliner::TryBuildAndInlineHelper(HInvoke* invoke_instruction,
1002 ArtMethod* resolved_method,
1003 bool same_dex_file,
1004 HInstruction** return_replacement) {
Nicolas Geoffrayc0365b12015-03-18 18:31:52 +00001005 ScopedObjectAccess soa(Thread::Current());
1006 const DexFile::CodeItem* code_item = resolved_method->GetCodeItem();
Guillaume "Vermeille" Sanchezae09d2d2015-05-29 10:52:55 +01001007 const DexFile& callee_dex_file = *resolved_method->GetDexFile();
1008 uint32_t method_index = resolved_method->GetDexMethodIndex();
Calin Juravle2e768302015-07-28 14:41:11 +00001009 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
Mathieu Chartier736b5602015-09-02 14:54:11 -07001010 Handle<mirror::DexCache> dex_cache(handles_->NewHandle(resolved_method->GetDexCache()));
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001011 DexCompilationUnit dex_compilation_unit(
Nicolas Geoffray5b82d332016-02-18 14:22:32 +00001012 nullptr,
1013 caller_compilation_unit_.GetClassLoader(),
1014 class_linker,
1015 callee_dex_file,
1016 code_item,
1017 resolved_method->GetDeclaringClass()->GetDexClassDefIndex(),
1018 method_index,
1019 resolved_method->GetAccessFlags(),
1020 /* verified_method */ nullptr,
1021 dex_cache);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001022
Calin Juravle3cd4fc82015-05-14 15:15:42 +01001023 bool requires_ctor_barrier = false;
1024
1025 if (dex_compilation_unit.IsConstructor()) {
1026 // If it's a super invocation and we already generate a barrier there's no need
1027 // to generate another one.
1028 // We identify super calls by looking at the "this" pointer. If its value is the
1029 // same as the local "this" pointer then we must have a super invocation.
1030 bool is_super_invocation = invoke_instruction->InputAt(0)->IsParameterValue()
1031 && invoke_instruction->InputAt(0)->AsParameterValue()->IsThis();
1032 if (is_super_invocation && graph_->ShouldGenerateConstructorBarrier()) {
1033 requires_ctor_barrier = false;
1034 } else {
1035 Thread* self = Thread::Current();
1036 requires_ctor_barrier = compiler_driver_->RequiresConstructorBarrier(self,
1037 dex_compilation_unit.GetDexFile(),
1038 dex_compilation_unit.GetClassDefIndex());
1039 }
1040 }
1041
Nicolas Geoffray35071052015-06-09 15:43:38 +01001042 InvokeType invoke_type = invoke_instruction->GetOriginalInvokeType();
1043 if (invoke_type == kInterface) {
1044 // We have statically resolved the dispatch. To please the class linker
1045 // at runtime, we change this call as if it was a virtual call.
1046 invoke_type = kVirtual;
1047 }
David Brazdil3f523062016-02-29 16:53:33 +00001048
1049 const int32_t caller_instruction_counter = graph_->GetCurrentInstructionId();
Nicolas Geoffraye0fe7ae2015-03-09 10:02:49 +00001050 HGraph* callee_graph = new (graph_->GetArena()) HGraph(
Nicolas Geoffray0a23d742015-05-07 11:57:35 +01001051 graph_->GetArena(),
Guillaume "Vermeille" Sanchezae09d2d2015-05-29 10:52:55 +01001052 callee_dex_file,
Nicolas Geoffray0a23d742015-05-07 11:57:35 +01001053 method_index,
Calin Juravle3cd4fc82015-05-14 15:15:42 +01001054 requires_ctor_barrier,
Mathieu Chartiere401d142015-04-22 13:56:20 -07001055 compiler_driver_->GetInstructionSet(),
Nicolas Geoffray35071052015-06-09 15:43:38 +01001056 invoke_type,
Nicolas Geoffray0a23d742015-05-07 11:57:35 +01001057 graph_->IsDebuggable(),
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001058 /* osr */ false,
David Brazdil3f523062016-02-29 16:53:33 +00001059 caller_instruction_counter);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001060 callee_graph->SetArtMethod(resolved_method);
David Brazdil5e8b1372015-01-23 14:39:08 +00001061
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001062 OptimizingCompilerStats inline_stats;
David Brazdil5e8b1372015-01-23 14:39:08 +00001063 HGraphBuilder builder(callee_graph,
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001064 &dex_compilation_unit,
1065 &outer_compilation_unit_,
Nicolas Geoffray9437b782015-03-25 10:08:51 +00001066 resolved_method->GetDexFile(),
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001067 compiler_driver_,
Nicolas Geoffray9523a3e2015-07-17 11:51:28 +00001068 &inline_stats,
Mathieu Chartier736b5602015-09-02 14:54:11 -07001069 resolved_method->GetQuickenedInfo(),
1070 dex_cache);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001071
David Brazdilbadd8262016-02-02 16:28:56 +00001072 if (builder.BuildGraph(*code_item, handles_) != kAnalysisSuccess) {
Guillaume "Vermeille" Sanchezae09d2d2015-05-29 10:52:55 +01001073 VLOG(compiler) << "Method " << PrettyMethod(method_index, callee_dex_file)
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001074 << " could not be built, so cannot be inlined";
1075 return false;
1076 }
1077
Nicolas Geoffray259136f2014-12-17 23:21:58 +00001078 if (!RegisterAllocator::CanAllocateRegistersFor(*callee_graph,
1079 compiler_driver_->GetInstructionSet())) {
Guillaume "Vermeille" Sanchezae09d2d2015-05-29 10:52:55 +01001080 VLOG(compiler) << "Method " << PrettyMethod(method_index, callee_dex_file)
Nicolas Geoffray259136f2014-12-17 23:21:58 +00001081 << " cannot be inlined because of the register allocator";
1082 return false;
1083 }
1084
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001085 size_t parameter_index = 0;
1086 for (HInstructionIterator instructions(callee_graph->GetEntryBlock()->GetInstructions());
1087 !instructions.Done();
1088 instructions.Advance()) {
1089 HInstruction* current = instructions.Current();
1090 if (current->IsParameterValue()) {
1091 HInstruction* argument = invoke_instruction->InputAt(parameter_index++);
1092 if (argument->IsNullConstant()) {
1093 current->ReplaceWith(callee_graph->GetNullConstant());
1094 } else if (argument->IsIntConstant()) {
1095 current->ReplaceWith(callee_graph->GetIntConstant(argument->AsIntConstant()->GetValue()));
1096 } else if (argument->IsLongConstant()) {
1097 current->ReplaceWith(callee_graph->GetLongConstant(argument->AsLongConstant()->GetValue()));
1098 } else if (argument->IsFloatConstant()) {
1099 current->ReplaceWith(
1100 callee_graph->GetFloatConstant(argument->AsFloatConstant()->GetValue()));
1101 } else if (argument->IsDoubleConstant()) {
1102 current->ReplaceWith(
1103 callee_graph->GetDoubleConstant(argument->AsDoubleConstant()->GetValue()));
1104 } else if (argument->GetType() == Primitive::kPrimNot) {
1105 current->SetReferenceTypeInfo(argument->GetReferenceTypeInfo());
1106 current->AsParameterValue()->SetCanBeNull(argument->CanBeNull());
1107 }
1108 }
1109 }
1110
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +00001111 // Run simple optimizations on the graph.
Calin Juravle7a9c8852015-04-21 14:07:50 +01001112 HDeadCodeElimination dce(callee_graph, stats_);
Nicolas Geoffraye34648d2015-11-23 08:59:07 +00001113 HConstantFolding fold(callee_graph);
Vladimir Markodc151b22015-10-15 18:02:30 +01001114 HSharpening sharpening(callee_graph, codegen_, dex_compilation_unit, compiler_driver_);
Calin Juravleacf735c2015-02-12 15:25:22 +00001115 InstructionSimplifier simplify(callee_graph, stats_);
Jean-Philippe Halimi38e9e802016-02-18 16:42:03 +01001116 IntrinsicsRecognizer intrinsics(callee_graph, compiler_driver_, stats_);
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +00001117
1118 HOptimization* optimizations[] = {
Scott Wakelingd60a1af2015-07-22 14:32:44 +01001119 &intrinsics,
Vladimir Markodc151b22015-10-15 18:02:30 +01001120 &sharpening,
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +00001121 &simplify,
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001122 &fold,
Vladimir Marko9e23df52015-11-10 17:14:35 +00001123 &dce,
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +00001124 };
1125
1126 for (size_t i = 0; i < arraysize(optimizations); ++i) {
1127 HOptimization* optimization = optimizations[i];
1128 optimization->Run();
1129 }
1130
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001131 size_t number_of_instructions_budget = kMaximumNumberOfHInstructions;
Calin Juravleec748352015-07-29 13:52:12 +01001132 if (depth_ + 1 < compiler_driver_->GetCompilerOptions().GetInlineDepthLimit()) {
Nicolas Geoffray9437b782015-03-25 10:08:51 +00001133 HInliner inliner(callee_graph,
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001134 outermost_graph_,
Vladimir Markodc151b22015-10-15 18:02:30 +01001135 codegen_,
Nicolas Geoffray9437b782015-03-25 10:08:51 +00001136 outer_compilation_unit_,
1137 dex_compilation_unit,
1138 compiler_driver_,
Nicolas Geoffray454a4812015-06-09 10:37:32 +01001139 handles_,
Nicolas Geoffray9437b782015-03-25 10:08:51 +00001140 stats_,
Nicolas Geoffray5949fa02015-12-18 10:57:10 +00001141 total_number_of_dex_registers_ + code_item->registers_size_,
Nicolas Geoffray9437b782015-03-25 10:08:51 +00001142 depth_ + 1);
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +00001143 inliner.Run();
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001144 number_of_instructions_budget += inliner.number_of_inlined_instructions_;
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +00001145 }
1146
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001147 // TODO: We should abort only if all predecessors throw. However,
1148 // HGraph::InlineInto currently does not handle an exit block with
1149 // a throw predecessor.
1150 HBasicBlock* exit_block = callee_graph->GetExitBlock();
1151 if (exit_block == nullptr) {
Guillaume "Vermeille" Sanchezae09d2d2015-05-29 10:52:55 +01001152 VLOG(compiler) << "Method " << PrettyMethod(method_index, callee_dex_file)
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001153 << " could not be inlined because it has an infinite loop";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001154 return false;
1155 }
1156
1157 bool has_throw_predecessor = false;
Vladimir Marko60584552015-09-03 13:35:12 +00001158 for (HBasicBlock* predecessor : exit_block->GetPredecessors()) {
1159 if (predecessor->GetLastInstruction()->IsThrow()) {
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001160 has_throw_predecessor = true;
1161 break;
1162 }
1163 }
1164 if (has_throw_predecessor) {
Guillaume "Vermeille" Sanchezae09d2d2015-05-29 10:52:55 +01001165 VLOG(compiler) << "Method " << PrettyMethod(method_index, callee_dex_file)
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001166 << " could not be inlined because one branch always throws";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001167 return false;
1168 }
1169
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001170 HReversePostOrderIterator it(*callee_graph);
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +00001171 it.Advance(); // Past the entry block, it does not contain instructions that prevent inlining.
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001172 size_t number_of_instructions = 0;
Nicolas Geoffray5949fa02015-12-18 10:57:10 +00001173
1174 bool can_inline_environment =
1175 total_number_of_dex_registers_ < kMaximumNumberOfCumulatedDexRegisters;
1176
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001177 for (; !it.Done(); it.Advance()) {
1178 HBasicBlock* block = it.Current();
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00001179
1180 if (block->IsLoopHeader() && block->GetLoopInformation()->IsIrreducible()) {
1181 // Don't inline methods with irreducible loops, they could prevent some
1182 // optimizations to run.
Guillaume "Vermeille" Sanchezae09d2d2015-05-29 10:52:55 +01001183 VLOG(compiler) << "Method " << PrettyMethod(method_index, callee_dex_file)
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00001184 << " could not be inlined because it contains an irreducible loop";
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001185 return false;
1186 }
1187
1188 for (HInstructionIterator instr_it(block->GetInstructions());
1189 !instr_it.Done();
1190 instr_it.Advance()) {
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001191 if (number_of_instructions++ == number_of_instructions_budget) {
1192 VLOG(compiler) << "Method " << PrettyMethod(method_index, callee_dex_file)
Nicolas Geoffray5949fa02015-12-18 10:57:10 +00001193 << " is not inlined because its caller has reached"
1194 << " its instruction budget limit.";
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001195 return false;
1196 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001197 HInstruction* current = instr_it.Current();
Nicolas Geoffray5949fa02015-12-18 10:57:10 +00001198 if (!can_inline_environment && current->NeedsEnvironment()) {
1199 VLOG(compiler) << "Method " << PrettyMethod(method_index, callee_dex_file)
1200 << " is not inlined because its caller has reached"
1201 << " its environment budget limit.";
1202 return false;
1203 }
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001204
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001205 if (current->IsInvokeInterface()) {
1206 // Disable inlining of interface calls. The cost in case of entering the
1207 // resolution conflict is currently too high.
Guillaume "Vermeille" Sanchezae09d2d2015-05-29 10:52:55 +01001208 VLOG(compiler) << "Method " << PrettyMethod(method_index, callee_dex_file)
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001209 << " could not be inlined because it has an interface call.";
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001210 return false;
1211 }
1212
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001213 if (!same_dex_file && current->NeedsEnvironment()) {
Guillaume "Vermeille" Sanchezae09d2d2015-05-29 10:52:55 +01001214 VLOG(compiler) << "Method " << PrettyMethod(method_index, callee_dex_file)
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001215 << " could not be inlined because " << current->DebugName()
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001216 << " needs an environment and is in a different dex file";
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001217 return false;
1218 }
Nicolas Geoffray9437b782015-03-25 10:08:51 +00001219
Vladimir Markodc151b22015-10-15 18:02:30 +01001220 if (!same_dex_file && current->NeedsDexCacheOfDeclaringClass()) {
Guillaume "Vermeille" Sanchezae09d2d2015-05-29 10:52:55 +01001221 VLOG(compiler) << "Method " << PrettyMethod(method_index, callee_dex_file)
Nicolas Geoffray9437b782015-03-25 10:08:51 +00001222 << " could not be inlined because " << current->DebugName()
1223 << " it is in a different dex file and requires access to the dex cache";
1224 return false;
1225 }
Nicolas Geoffrayd9309292015-10-31 22:21:31 +00001226
1227 if (current->IsNewInstance() &&
1228 (current->AsNewInstance()->GetEntrypoint() == kQuickAllocObjectWithAccessCheck)) {
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +00001229 VLOG(compiler) << "Method " << PrettyMethod(method_index, callee_dex_file)
1230 << " could not be inlined because it is using an entrypoint"
1231 << " with access checks";
Nicolas Geoffrayd9309292015-10-31 22:21:31 +00001232 // Allocation entrypoint does not handle inlined frames.
1233 return false;
1234 }
1235
1236 if (current->IsNewArray() &&
1237 (current->AsNewArray()->GetEntrypoint() == kQuickAllocArrayWithAccessCheck)) {
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +00001238 VLOG(compiler) << "Method " << PrettyMethod(method_index, callee_dex_file)
1239 << " could not be inlined because it is using an entrypoint"
1240 << " with access checks";
Nicolas Geoffrayd9309292015-10-31 22:21:31 +00001241 // Allocation entrypoint does not handle inlined frames.
1242 return false;
1243 }
1244
1245 if (current->IsUnresolvedStaticFieldGet() ||
1246 current->IsUnresolvedInstanceFieldGet() ||
1247 current->IsUnresolvedStaticFieldSet() ||
1248 current->IsUnresolvedInstanceFieldSet()) {
1249 // Entrypoint for unresolved fields does not handle inlined frames.
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +00001250 VLOG(compiler) << "Method " << PrettyMethod(method_index, callee_dex_file)
1251 << " could not be inlined because it is using an unresolved"
1252 << " entrypoint";
Nicolas Geoffrayd9309292015-10-31 22:21:31 +00001253 return false;
1254 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001255 }
1256 }
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001257 number_of_inlined_instructions_ += number_of_instructions;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001258
David Brazdil3f523062016-02-29 16:53:33 +00001259 DCHECK_EQ(caller_instruction_counter, graph_->GetCurrentInstructionId())
1260 << "No instructions can be added to the outer graph while inner graph is being built";
1261
1262 const int32_t callee_instruction_counter = callee_graph->GetCurrentInstructionId();
1263 graph_->SetCurrentInstructionId(callee_instruction_counter);
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001264 *return_replacement = callee_graph->InlineInto(graph_, invoke_instruction);
David Brazdil3f523062016-02-29 16:53:33 +00001265
1266 DCHECK_EQ(callee_instruction_counter, callee_graph->GetCurrentInstructionId())
1267 << "No instructions can be added to the inner graph during inlining into the outer graph";
1268
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001269 return true;
1270}
Calin Juravle2e768302015-07-28 14:41:11 +00001271
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001272void HInliner::FixUpReturnReferenceType(HInvoke* invoke_instruction,
1273 ArtMethod* resolved_method,
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001274 HInstruction* return_replacement,
1275 bool do_rtp) {
Alex Light68289a52015-12-15 17:30:30 -08001276 // Check the integrity of reference types and run another type propagation if needed.
David Brazdil4833f5a2015-12-16 10:37:39 +00001277 if (return_replacement != nullptr) {
1278 if (return_replacement->GetType() == Primitive::kPrimNot) {
1279 if (!return_replacement->GetReferenceTypeInfo().IsValid()) {
1280 // Make sure that we have a valid type for the return. We may get an invalid one when
1281 // we inline invokes with multiple branches and create a Phi for the result.
1282 // TODO: we could be more precise by merging the phi inputs but that requires
1283 // some functionality from the reference type propagation.
1284 DCHECK(return_replacement->IsPhi());
1285 size_t pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
1286 ReferenceTypeInfo::TypeHandle return_handle =
1287 handles_->NewHandle(resolved_method->GetReturnType(true /* resolve */, pointer_size));
1288 return_replacement->SetReferenceTypeInfo(ReferenceTypeInfo::Create(
1289 return_handle, return_handle->CannotBeAssignedFromOtherTypes() /* is_exact */));
1290 }
Alex Light68289a52015-12-15 17:30:30 -08001291
David Brazdil4833f5a2015-12-16 10:37:39 +00001292 if (do_rtp) {
1293 // If the return type is a refinement of the declared type run the type propagation again.
1294 ReferenceTypeInfo return_rti = return_replacement->GetReferenceTypeInfo();
1295 ReferenceTypeInfo invoke_rti = invoke_instruction->GetReferenceTypeInfo();
1296 if (invoke_rti.IsStrictSupertypeOf(return_rti)
1297 || (return_rti.IsExact() && !invoke_rti.IsExact())
1298 || !return_replacement->CanBeNull()) {
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +00001299 ReferenceTypePropagation(graph_, handles_, /* is_first_run */ false).Run();
David Brazdil4833f5a2015-12-16 10:37:39 +00001300 }
1301 }
1302 } else if (return_replacement->IsInstanceOf()) {
1303 if (do_rtp) {
1304 // Inlining InstanceOf into an If may put a tighter bound on reference types.
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +00001305 ReferenceTypePropagation(graph_, handles_, /* is_first_run */ false).Run();
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001306 }
Calin Juravlecdfed3d2015-10-26 14:05:01 +00001307 }
Calin Juravle2e768302015-07-28 14:41:11 +00001308 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001309}
1310
1311} // namespace art