blob: f1e8239f76ee1950cbfe7fd8e406f18eb4f03cb4 [file] [log] [blame]
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001/*
2 * Copyright (C) 2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "inliner.h"
18
Mathieu Chartiere401d142015-04-22 13:56:20 -070019#include "art_method-inl.h"
Andreas Gampe542451c2016-07-26 09:02:02 -070020#include "base/enums.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000021#include "builder.h"
22#include "class_linker.h"
23#include "constant_folding.h"
24#include "dead_code_elimination.h"
Vladimir Markobe10e8e2016-01-22 12:09:44 +000025#include "dex/verified_method.h"
26#include "dex/verification_results.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000027#include "driver/compiler_driver-inl.h"
Calin Juravleec748352015-07-29 13:52:12 +010028#include "driver/compiler_options.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000029#include "driver/dex_compilation_unit.h"
30#include "instruction_simplifier.h"
Scott Wakelingd60a1af2015-07-22 14:32:44 +010031#include "intrinsics.h"
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +000032#include "jit/jit.h"
33#include "jit/jit_code_cache.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000034#include "mirror/class_loader.h"
35#include "mirror/dex_cache.h"
36#include "nodes.h"
Nicolas Geoffray335005e2015-06-25 10:01:47 +010037#include "optimizing_compiler.h"
Nicolas Geoffray454a4812015-06-09 10:37:32 +010038#include "reference_type_propagation.h"
Matthew Gharritye9288852016-07-14 14:08:16 -070039#include "register_allocator_linear_scan.h"
Vladimir Markobe10e8e2016-01-22 12:09:44 +000040#include "quick/inline_method_analyser.h"
Vladimir Markodc151b22015-10-15 18:02:30 +010041#include "sharpening.h"
David Brazdil4833f5a2015-12-16 10:37:39 +000042#include "ssa_builder.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000043#include "ssa_phi_elimination.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070044#include "scoped_thread_state_change-inl.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000045#include "thread.h"
46
47namespace art {
48
Nicolas Geoffray5949fa02015-12-18 10:57:10 +000049static constexpr size_t kMaximumNumberOfHInstructions = 32;
50
51// Limit the number of dex registers that we accumulate while inlining
52// to avoid creating large amount of nested environments.
53static constexpr size_t kMaximumNumberOfCumulatedDexRegisters = 64;
54
55// Avoid inlining within a huge method due to memory pressure.
56static constexpr size_t kMaximumCodeUnitSize = 4096;
Nicolas Geoffraye418dda2015-08-11 20:03:09 -070057
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 =
David Sehr709b0702016-10-13 09:12:37 -070093 outer_compilation_unit_.GetDexFile()->PrettyMethod(call->GetDexMethodIndex());
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 =
David Sehr709b0702016-10-13 09:12:37 -0700100 outer_compilation_unit_.GetDexFile()->PrettyMethod(call->GetDexMethodIndex());
Guillaume "Vermeille" Sancheze918d382015-06-03 15:32:41 +0100101 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
Andreas Gampea5b09a62016-11-17 15:21:22 -0800200static dex::TypeIndex FindClassIndexIn(mirror::Class* cls,
Mathieu Chartier5812e202017-02-13 18:32:04 -0800201 const DexFile& dex_file,
202 Handle<mirror::DexCache> dex_cache)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700203 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampea5b09a62016-11-17 15:21:22 -0800204 dex::TypeIndex index;
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100205 if (cls->GetDexCache() == nullptr) {
David Sehr709b0702016-10-13 09:12:37 -0700206 DCHECK(cls->IsArrayClass()) << cls->PrettyClass();
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000207 index = cls->FindTypeIndexInOtherDexFile(dex_file);
Andreas Gampea5b09a62016-11-17 15:21:22 -0800208 } else if (!cls->GetDexTypeIndex().IsValid()) {
David Sehr709b0702016-10-13 09:12:37 -0700209 DCHECK(cls->IsProxyClass()) << cls->PrettyClass();
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)) {
Mathieu Chartier5812e202017-02-13 18:32:04 -0800212 DCHECK_EQ(cls->GetDexCache(), dex_cache.Get());
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000213 index = cls->GetDexTypeIndex();
Mathieu Chartier5812e202017-02-13 18:32:04 -0800214 // 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.
218 if (dex_cache->GetResolvedType(index) == nullptr) {
219 dex_cache->SetResolvedType(index, cls);
220 }
Nicolas Geoffray491617a2016-07-19 17:06:23 +0100221 } else {
222 index = cls->FindTypeIndexInOtherDexFile(dex_file);
Mathieu Chartier5812e202017-02-13 18:32:04 -0800223 // We cannot guarantee the entry in the dex cache will resolve to the same class,
Nicolas Geoffray491617a2016-07-19 17:06:23 +0100224 // as there may be different class loaders. So only return the index if it's
Mathieu Chartier5812e202017-02-13 18:32:04 -0800225 // the right class in the dex cache already.
226 if (index.IsValid() && dex_cache->GetResolvedType(index) != cls) {
227 index = dex::TypeIndex::Invalid();
Nicolas Geoffray491617a2016-07-19 17:06:23 +0100228 }
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 Geoffraye51ca8b2016-11-22 14:49:31 +0000261static bool IsMonomorphic(Handle<mirror::ObjectArray<mirror::Class>> classes)
262 REQUIRES_SHARED(Locks::mutator_lock_) {
263 DCHECK_GE(InlineCache::kIndividualCacheSize, 2);
264 return classes->Get(0) != nullptr && classes->Get(1) == nullptr;
265}
266
267static bool IsMegamorphic(Handle<mirror::ObjectArray<mirror::Class>> classes)
268 REQUIRES_SHARED(Locks::mutator_lock_) {
269 for (size_t i = 0; i < InlineCache::kIndividualCacheSize; ++i) {
270 if (classes->Get(i) == nullptr) {
271 return false;
272 }
273 }
274 return true;
275}
276
277static mirror::Class* GetMonomorphicType(Handle<mirror::ObjectArray<mirror::Class>> classes)
278 REQUIRES_SHARED(Locks::mutator_lock_) {
279 DCHECK(classes->Get(0) != nullptr);
280 return classes->Get(0);
281}
282
283static bool IsUninitialized(Handle<mirror::ObjectArray<mirror::Class>> classes)
284 REQUIRES_SHARED(Locks::mutator_lock_) {
285 return classes->Get(0) == nullptr;
286}
287
288static bool IsPolymorphic(Handle<mirror::ObjectArray<mirror::Class>> classes)
289 REQUIRES_SHARED(Locks::mutator_lock_) {
290 DCHECK_GE(InlineCache::kIndividualCacheSize, 3);
291 return classes->Get(1) != nullptr &&
292 classes->Get(InlineCache::kIndividualCacheSize - 1) == nullptr;
293}
294
Mingyao Yang063fc772016-08-02 11:02:54 -0700295ArtMethod* HInliner::TryCHADevirtualization(ArtMethod* resolved_method) {
296 if (!resolved_method->HasSingleImplementation()) {
297 return nullptr;
298 }
299 if (Runtime::Current()->IsAotCompiler()) {
300 // No CHA-based devirtulization for AOT compiler (yet).
301 return nullptr;
302 }
303 if (outermost_graph_->IsCompilingOsr()) {
304 // We do not support HDeoptimize in OSR methods.
305 return nullptr;
306 }
Mingyao Yange8fcd012017-01-20 10:43:30 -0800307 PointerSize pointer_size = caller_compilation_unit_.GetClassLinker()->GetImagePointerSize();
308 return resolved_method->GetSingleImplementation(pointer_size);
Mingyao Yang063fc772016-08-02 11:02:54 -0700309}
310
Nicolas Geoffraye418dda2015-08-11 20:03:09 -0700311bool HInliner::TryInline(HInvoke* invoke_instruction) {
Orion Hodsonac141392017-01-13 11:53:47 +0000312 if (invoke_instruction->IsInvokeUnresolved() ||
313 invoke_instruction->IsInvokePolymorphic()) {
314 return false; // Don't bother to move further if we know the method is unresolved or an
315 // invoke-polymorphic.
Calin Juravle175dc732015-08-25 15:42:32 +0100316 }
317
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000318 ScopedObjectAccess soa(Thread::Current());
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +0100319 uint32_t method_index = invoke_instruction->GetDexMethodIndex();
Nicolas Geoffray9437b782015-03-25 10:08:51 +0000320 const DexFile& caller_dex_file = *caller_compilation_unit_.GetDexFile();
David Sehr709b0702016-10-13 09:12:37 -0700321 VLOG(compiler) << "Try inlining " << caller_dex_file.PrettyMethod(method_index);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000322
Nicolas Geoffray35071052015-06-09 15:43:38 +0100323 // We can query the dex cache directly. The verifier has populated it already.
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +0100324 ArtMethod* resolved_method = invoke_instruction->GetResolvedMethod();
Andreas Gampefd2140f2015-12-23 16:30:44 -0800325 ArtMethod* actual_method = nullptr;
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +0100326 if (resolved_method == nullptr) {
327 DCHECK(invoke_instruction->IsInvokeStaticOrDirect());
328 DCHECK(invoke_instruction->AsInvokeStaticOrDirect()->IsStringInit());
329 VLOG(compiler) << "Not inlining a String.<init> method";
330 return false;
331 } else if (invoke_instruction->IsInvokeStaticOrDirect()) {
Andreas Gampefd2140f2015-12-23 16:30:44 -0800332 actual_method = resolved_method;
Vladimir Marko58155012015-08-19 12:49:41 +0000333 } else {
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +0100334 // Check if we can statically find the method.
335 actual_method = FindVirtualOrInterfaceTarget(invoke_instruction, resolved_method);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000336 }
337
Mingyao Yang063fc772016-08-02 11:02:54 -0700338 bool cha_devirtualize = false;
339 if (actual_method == nullptr) {
340 ArtMethod* method = TryCHADevirtualization(resolved_method);
341 if (method != nullptr) {
342 cha_devirtualize = true;
343 actual_method = method;
344 }
345 }
346
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100347 if (actual_method != nullptr) {
Mingyao Yang063fc772016-08-02 11:02:54 -0700348 bool result = TryInlineAndReplace(invoke_instruction,
349 actual_method,
Nicolas Geoffray0f001b72017-01-04 16:46:23 +0000350 ReferenceTypeInfo::CreateInvalid(),
Mingyao Yang063fc772016-08-02 11:02:54 -0700351 /* do_rtp */ true,
352 cha_devirtualize);
Calin Juravle69158982016-03-16 11:53:41 +0000353 if (result && !invoke_instruction->IsInvokeStaticOrDirect()) {
Mingyao Yang063fc772016-08-02 11:02:54 -0700354 if (cha_devirtualize) {
355 // Add dependency due to devirtulization. We've assumed resolved_method
356 // has single implementation.
357 outermost_graph_->AddCHASingleImplementationDependency(resolved_method);
358 MaybeRecordStat(kCHAInline);
359 } else {
360 MaybeRecordStat(kInlinedInvokeVirtualOrInterface);
361 }
Calin Juravle69158982016-03-16 11:53:41 +0000362 }
363 return result;
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100364 }
Nicolas Geoffray55bd7492016-02-16 15:37:12 +0000365
Andreas Gampefd2140f2015-12-23 16:30:44 -0800366 DCHECK(!invoke_instruction->IsInvokeStaticOrDirect());
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100367
368 // Check if we can use an inline cache.
369 ArtMethod* caller = graph_->GetArtMethod();
Calin Juravleffc87072016-04-20 14:22:09 +0100370 if (Runtime::Current()->UseJitCompilation()) {
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000371 // Under JIT, we should always know the caller.
372 DCHECK(caller != nullptr);
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000373 ScopedProfilingInfoInlineUse spiis(caller, soa.Self());
374 ProfilingInfo* profiling_info = spiis.GetProfilingInfo();
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000375 if (profiling_info != nullptr) {
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000376 StackHandleScope<1> hs(soa.Self());
377 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
378 Handle<mirror::ObjectArray<mirror::Class>> inline_cache = hs.NewHandle(
379 mirror::ObjectArray<mirror::Class>::Alloc(
380 soa.Self(),
381 class_linker->GetClassRoot(ClassLinker::kClassArrayClass),
382 InlineCache::kIndividualCacheSize));
Andreas Gampefa4333d2017-02-14 11:10:34 -0800383 if (inline_cache == nullptr) {
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000384 // We got an OOME. Just clear the exception, and don't inline.
385 DCHECK(soa.Self()->IsExceptionPending());
386 soa.Self()->ClearException();
387 VLOG(compiler) << "Out of memory in the compiler when trying to inline";
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000388 return false;
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000389 } else {
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000390 Runtime::Current()->GetJit()->GetCodeCache()->CopyInlineCacheInto(
391 *profiling_info->GetInlineCache(invoke_instruction->GetDexPc()),
392 inline_cache);
393 if (IsUninitialized(inline_cache)) {
394 VLOG(compiler) << "Interface or virtual call to "
395 << caller_dex_file.PrettyMethod(method_index)
396 << " is not hit and not inlined";
397 return false;
398 } else if (IsMonomorphic(inline_cache)) {
399 MaybeRecordStat(kMonomorphicCall);
400 if (outermost_graph_->IsCompilingOsr()) {
401 // If we are compiling OSR, we pretend this call is polymorphic, as we may come from the
402 // interpreter and it may have seen different receiver types.
403 return TryInlinePolymorphicCall(invoke_instruction, resolved_method, inline_cache);
404 } else {
405 return TryInlineMonomorphicCall(invoke_instruction, resolved_method, inline_cache);
406 }
407 } else if (IsPolymorphic(inline_cache)) {
408 MaybeRecordStat(kPolymorphicCall);
409 return TryInlinePolymorphicCall(invoke_instruction, resolved_method, inline_cache);
410 } else {
411 DCHECK(IsMegamorphic(inline_cache));
412 VLOG(compiler) << "Interface or virtual call to "
413 << caller_dex_file.PrettyMethod(method_index)
414 << " is megamorphic and not inlined";
415 MaybeRecordStat(kMegamorphicCall);
416 return false;
417 }
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000418 }
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100419 }
420 }
421
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100422 VLOG(compiler) << "Interface or virtual call to "
David Sehr709b0702016-10-13 09:12:37 -0700423 << caller_dex_file.PrettyMethod(method_index)
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100424 << " could not be statically determined";
425 return false;
426}
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000427
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000428HInstanceFieldGet* HInliner::BuildGetReceiverClass(ClassLinker* class_linker,
429 HInstruction* receiver,
430 uint32_t dex_pc) const {
431 ArtField* field = class_linker->GetClassRoot(ClassLinker::kJavaLangObject)->GetInstanceField(0);
432 DCHECK_EQ(std::string(field->GetName()), "shadow$_klass_");
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000433 HInstanceFieldGet* result = new (graph_->GetArena()) HInstanceFieldGet(
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000434 receiver,
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +0000435 field,
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000436 Primitive::kPrimNot,
437 field->GetOffset(),
438 field->IsVolatile(),
439 field->GetDexFieldIndex(),
440 field->GetDeclaringClass()->GetDexClassDefIndex(),
441 *field->GetDexFile(),
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000442 dex_pc);
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000443 // The class of a field is effectively final, and does not have any memory dependencies.
444 result->SetSideEffects(SideEffects::None());
445 return result;
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000446}
447
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100448bool HInliner::TryInlineMonomorphicCall(HInvoke* invoke_instruction,
449 ArtMethod* resolved_method,
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000450 Handle<mirror::ObjectArray<mirror::Class>> classes) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000451 DCHECK(invoke_instruction->IsInvokeVirtual() || invoke_instruction->IsInvokeInterface())
452 << invoke_instruction->DebugName();
453
Mathieu Chartier5812e202017-02-13 18:32:04 -0800454 const DexFile& caller_dex_file = *caller_compilation_unit_.GetDexFile();
Andreas Gampea5b09a62016-11-17 15:21:22 -0800455 dex::TypeIndex class_index = FindClassIndexIn(
Mathieu Chartier5812e202017-02-13 18:32:04 -0800456 GetMonomorphicType(classes), caller_dex_file, caller_compilation_unit_.GetDexCache());
Andreas Gampea5b09a62016-11-17 15:21:22 -0800457 if (!class_index.IsValid()) {
David Sehr709b0702016-10-13 09:12:37 -0700458 VLOG(compiler) << "Call to " << ArtMethod::PrettyMethod(resolved_method)
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100459 << " from inline cache is not inlined because its class is not"
460 << " accessible to the caller";
461 return false;
462 }
463
464 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
Andreas Gampe542451c2016-07-26 09:02:02 -0700465 PointerSize pointer_size = class_linker->GetImagePointerSize();
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100466 if (invoke_instruction->IsInvokeInterface()) {
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000467 resolved_method = GetMonomorphicType(classes)->FindVirtualMethodForInterface(
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100468 resolved_method, pointer_size);
469 } else {
470 DCHECK(invoke_instruction->IsInvokeVirtual());
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000471 resolved_method = GetMonomorphicType(classes)->FindVirtualMethodForVirtual(
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100472 resolved_method, pointer_size);
473 }
474 DCHECK(resolved_method != nullptr);
475 HInstruction* receiver = invoke_instruction->InputAt(0);
476 HInstruction* cursor = invoke_instruction->GetPrevious();
477 HBasicBlock* bb_cursor = invoke_instruction->GetBlock();
Nicolas Geoffray5247c082017-01-13 14:17:29 +0000478 Handle<mirror::Class> monomorphic_type = handles_->NewHandle(GetMonomorphicType(classes));
Mingyao Yang063fc772016-08-02 11:02:54 -0700479 if (!TryInlineAndReplace(invoke_instruction,
480 resolved_method,
Nicolas Geoffray5247c082017-01-13 14:17:29 +0000481 ReferenceTypeInfo::Create(monomorphic_type, /* is_exact */ true),
Mingyao Yang063fc772016-08-02 11:02:54 -0700482 /* do_rtp */ false,
483 /* cha_devirtualize */ false)) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100484 return false;
485 }
486
487 // We successfully inlined, now add a guard.
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000488 AddTypeGuard(receiver,
489 cursor,
490 bb_cursor,
491 class_index,
Nicolas Geoffray5247c082017-01-13 14:17:29 +0000492 monomorphic_type,
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000493 invoke_instruction,
494 /* with_deoptimization */ true);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100495
496 // Run type propagation to get the guard typed, and eventually propagate the
497 // type of the receiver.
Vladimir Marko456307a2016-04-19 14:12:13 +0000498 ReferenceTypePropagation rtp_fixup(graph_,
499 outer_compilation_unit_.GetDexCache(),
500 handles_,
501 /* is_first_run */ false);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100502 rtp_fixup.Run();
503
504 MaybeRecordStat(kInlinedMonomorphicCall);
505 return true;
506}
507
Mingyao Yang063fc772016-08-02 11:02:54 -0700508void HInliner::AddCHAGuard(HInstruction* invoke_instruction,
509 uint32_t dex_pc,
510 HInstruction* cursor,
511 HBasicBlock* bb_cursor) {
Mingyao Yangb0b051a2016-11-17 09:04:53 -0800512 HShouldDeoptimizeFlag* deopt_flag = new (graph_->GetArena())
513 HShouldDeoptimizeFlag(graph_->GetArena(), dex_pc);
514 HInstruction* compare = new (graph_->GetArena()) HNotEqual(
Mingyao Yang063fc772016-08-02 11:02:54 -0700515 deopt_flag, graph_->GetIntConstant(0, dex_pc));
Mingyao Yangb0b051a2016-11-17 09:04:53 -0800516 HInstruction* deopt = new (graph_->GetArena()) HDeoptimize(compare, dex_pc);
Mingyao Yang063fc772016-08-02 11:02:54 -0700517
518 if (cursor != nullptr) {
519 bb_cursor->InsertInstructionAfter(deopt_flag, cursor);
520 } else {
521 bb_cursor->InsertInstructionBefore(deopt_flag, bb_cursor->GetFirstInstruction());
522 }
Mingyao Yangb0b051a2016-11-17 09:04:53 -0800523 bb_cursor->InsertInstructionAfter(compare, deopt_flag);
524 bb_cursor->InsertInstructionAfter(deopt, compare);
525
526 // Add receiver as input to aid CHA guard optimization later.
527 deopt_flag->AddInput(invoke_instruction->InputAt(0));
528 DCHECK_EQ(deopt_flag->InputCount(), 1u);
Mingyao Yang063fc772016-08-02 11:02:54 -0700529 deopt->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
Mingyao Yangb0b051a2016-11-17 09:04:53 -0800530 outermost_graph_->IncrementNumberOfCHAGuards();
Mingyao Yang063fc772016-08-02 11:02:54 -0700531}
532
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000533HInstruction* HInliner::AddTypeGuard(HInstruction* receiver,
534 HInstruction* cursor,
535 HBasicBlock* bb_cursor,
Andreas Gampea5b09a62016-11-17 15:21:22 -0800536 dex::TypeIndex class_index,
Nicolas Geoffray5247c082017-01-13 14:17:29 +0000537 Handle<mirror::Class> klass,
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000538 HInstruction* invoke_instruction,
539 bool with_deoptimization) {
540 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
541 HInstanceFieldGet* receiver_class = BuildGetReceiverClass(
542 class_linker, receiver, invoke_instruction->GetDexPc());
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000543 if (cursor != nullptr) {
544 bb_cursor->InsertInstructionAfter(receiver_class, cursor);
545 } else {
546 bb_cursor->InsertInstructionBefore(receiver_class, bb_cursor->GetFirstInstruction());
547 }
Nicolas Geoffray56876342016-12-16 16:09:08 +0000548
549 const DexFile& caller_dex_file = *caller_compilation_unit_.GetDexFile();
Nicolas Geoffray5247c082017-01-13 14:17:29 +0000550 bool is_referrer = (klass.Get() == outermost_graph_->GetArtMethod()->GetDeclaringClass());
Nicolas Geoffray56876342016-12-16 16:09:08 +0000551 // Note that we will just compare the classes, so we don't need Java semantics access checks.
552 // Note that the type index and the dex file are relative to the method this type guard is
553 // inlined into.
554 HLoadClass* load_class = new (graph_->GetArena()) HLoadClass(graph_->GetCurrentMethod(),
555 class_index,
556 caller_dex_file,
Nicolas Geoffray5247c082017-01-13 14:17:29 +0000557 klass,
Nicolas Geoffray56876342016-12-16 16:09:08 +0000558 is_referrer,
559 invoke_instruction->GetDexPc(),
560 /* needs_access_check */ false);
Nicolas Geoffray83c8e272017-01-31 14:36:37 +0000561 HLoadClass::LoadKind kind = HSharpening::SharpenClass(
562 load_class, codegen_, compiler_driver_, caller_compilation_unit_);
563 DCHECK(kind != HLoadClass::LoadKind::kInvalid)
564 << "We should always be able to reference a class for inline caches";
565 // Insert before setting the kind, as setting the kind affects the inputs.
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000566 bb_cursor->InsertInstructionAfter(load_class, receiver_class);
Nicolas Geoffray83c8e272017-01-31 14:36:37 +0000567 load_class->SetLoadKind(kind);
Nicolas Geoffray56876342016-12-16 16:09:08 +0000568
569 // TODO: Extend reference type propagation to understand the guard.
570 HNotEqual* compare = new (graph_->GetArena()) HNotEqual(load_class, receiver_class);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000571 bb_cursor->InsertInstructionAfter(compare, load_class);
572 if (with_deoptimization) {
573 HDeoptimize* deoptimize = new (graph_->GetArena()) HDeoptimize(
574 compare, invoke_instruction->GetDexPc());
575 bb_cursor->InsertInstructionAfter(deoptimize, compare);
576 deoptimize->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
577 }
578 return compare;
579}
580
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000581bool HInliner::TryInlinePolymorphicCall(HInvoke* invoke_instruction,
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100582 ArtMethod* resolved_method,
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000583 Handle<mirror::ObjectArray<mirror::Class>> classes) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000584 DCHECK(invoke_instruction->IsInvokeVirtual() || invoke_instruction->IsInvokeInterface())
585 << invoke_instruction->DebugName();
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000586
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000587 if (TryInlinePolymorphicCallToSameTarget(invoke_instruction, resolved_method, classes)) {
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000588 return true;
589 }
590
591 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
Andreas Gampe542451c2016-07-26 09:02:02 -0700592 PointerSize pointer_size = class_linker->GetImagePointerSize();
Mathieu Chartier5812e202017-02-13 18:32:04 -0800593 const DexFile& caller_dex_file = *caller_compilation_unit_.GetDexFile();
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000594
595 bool all_targets_inlined = true;
596 bool one_target_inlined = false;
597 for (size_t i = 0; i < InlineCache::kIndividualCacheSize; ++i) {
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000598 if (classes->Get(i) == nullptr) {
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000599 break;
600 }
601 ArtMethod* method = nullptr;
Nicolas Geoffray0f001b72017-01-04 16:46:23 +0000602
603 Handle<mirror::Class> handle = handles_->NewHandle(classes->Get(i));
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000604 if (invoke_instruction->IsInvokeInterface()) {
Nicolas Geoffray0f001b72017-01-04 16:46:23 +0000605 method = handle->FindVirtualMethodForInterface(resolved_method, pointer_size);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000606 } else {
607 DCHECK(invoke_instruction->IsInvokeVirtual());
Nicolas Geoffray0f001b72017-01-04 16:46:23 +0000608 method = handle->FindVirtualMethodForVirtual(resolved_method, pointer_size);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000609 }
610
611 HInstruction* receiver = invoke_instruction->InputAt(0);
612 HInstruction* cursor = invoke_instruction->GetPrevious();
613 HBasicBlock* bb_cursor = invoke_instruction->GetBlock();
614
Mathieu Chartier5812e202017-02-13 18:32:04 -0800615 dex::TypeIndex class_index = FindClassIndexIn(
616 handle.Get(), caller_dex_file, caller_compilation_unit_.GetDexCache());
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000617 HInstruction* return_replacement = nullptr;
Andreas Gampea5b09a62016-11-17 15:21:22 -0800618 if (!class_index.IsValid() ||
Nicolas Geoffray0f001b72017-01-04 16:46:23 +0000619 !TryBuildAndInline(invoke_instruction,
620 method,
621 ReferenceTypeInfo::Create(handle, /* is_exact */ true),
622 &return_replacement)) {
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000623 all_targets_inlined = false;
624 } else {
625 one_target_inlined = true;
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000626
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +0000627 VLOG(compiler) << "Polymorphic call to " << ArtMethod::PrettyMethod(resolved_method)
628 << " has inlined " << ArtMethod::PrettyMethod(method);
629
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000630 // If we have inlined all targets before, and this receiver is the last seen,
631 // we deoptimize instead of keeping the original invoke instruction.
632 bool deoptimize = all_targets_inlined &&
633 (i != InlineCache::kIndividualCacheSize - 1) &&
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000634 (classes->Get(i + 1) == nullptr);
Nicolas Geoffray93a18c52016-04-22 13:16:14 +0100635
636 if (outermost_graph_->IsCompilingOsr()) {
637 // We do not support HDeoptimize in OSR methods.
638 deoptimize = false;
639 }
Nicolas Geoffray56876342016-12-16 16:09:08 +0000640 HInstruction* compare = AddTypeGuard(receiver,
641 cursor,
642 bb_cursor,
643 class_index,
Nicolas Geoffray5247c082017-01-13 14:17:29 +0000644 handle,
Nicolas Geoffray56876342016-12-16 16:09:08 +0000645 invoke_instruction,
646 deoptimize);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000647 if (deoptimize) {
648 if (return_replacement != nullptr) {
649 invoke_instruction->ReplaceWith(return_replacement);
650 }
651 invoke_instruction->GetBlock()->RemoveInstruction(invoke_instruction);
652 // Because the inline cache data can be populated concurrently, we force the end of the
653 // iteration. Otherhwise, we could see a new receiver type.
654 break;
655 } else {
656 CreateDiamondPatternForPolymorphicInline(compare, return_replacement, invoke_instruction);
657 }
658 }
659 }
660
661 if (!one_target_inlined) {
David Sehr709b0702016-10-13 09:12:37 -0700662 VLOG(compiler) << "Call to " << ArtMethod::PrettyMethod(resolved_method)
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000663 << " from inline cache is not inlined because none"
664 << " of its targets could be inlined";
665 return false;
666 }
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +0000667
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000668 MaybeRecordStat(kInlinedPolymorphicCall);
669
670 // Run type propagation to get the guards typed.
Vladimir Marko456307a2016-04-19 14:12:13 +0000671 ReferenceTypePropagation rtp_fixup(graph_,
672 outer_compilation_unit_.GetDexCache(),
673 handles_,
674 /* is_first_run */ false);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000675 rtp_fixup.Run();
676 return true;
677}
678
679void HInliner::CreateDiamondPatternForPolymorphicInline(HInstruction* compare,
680 HInstruction* return_replacement,
681 HInstruction* invoke_instruction) {
682 uint32_t dex_pc = invoke_instruction->GetDexPc();
683 HBasicBlock* cursor_block = compare->GetBlock();
684 HBasicBlock* original_invoke_block = invoke_instruction->GetBlock();
685 ArenaAllocator* allocator = graph_->GetArena();
686
687 // Spit the block after the compare: `cursor_block` will now be the start of the diamond,
688 // and the returned block is the start of the then branch (that could contain multiple blocks).
689 HBasicBlock* then = cursor_block->SplitAfterForInlining(compare);
690
691 // Split the block containing the invoke before and after the invoke. The returned block
692 // of the split before will contain the invoke and will be the otherwise branch of
693 // the diamond. The returned block of the split after will be the merge block
694 // of the diamond.
695 HBasicBlock* end_then = invoke_instruction->GetBlock();
696 HBasicBlock* otherwise = end_then->SplitBeforeForInlining(invoke_instruction);
697 HBasicBlock* merge = otherwise->SplitAfterForInlining(invoke_instruction);
698
699 // If the methods we are inlining return a value, we create a phi in the merge block
700 // that will have the `invoke_instruction and the `return_replacement` as inputs.
701 if (return_replacement != nullptr) {
702 HPhi* phi = new (allocator) HPhi(
703 allocator, kNoRegNumber, 0, HPhi::ToPhiType(invoke_instruction->GetType()), dex_pc);
704 merge->AddPhi(phi);
705 invoke_instruction->ReplaceWith(phi);
706 phi->AddInput(return_replacement);
707 phi->AddInput(invoke_instruction);
708 }
709
710 // Add the control flow instructions.
711 otherwise->AddInstruction(new (allocator) HGoto(dex_pc));
712 end_then->AddInstruction(new (allocator) HGoto(dex_pc));
713 cursor_block->AddInstruction(new (allocator) HIf(compare, dex_pc));
714
715 // Add the newly created blocks to the graph.
716 graph_->AddBlock(then);
717 graph_->AddBlock(otherwise);
718 graph_->AddBlock(merge);
719
720 // Set up successor (and implictly predecessor) relations.
721 cursor_block->AddSuccessor(otherwise);
722 cursor_block->AddSuccessor(then);
723 end_then->AddSuccessor(merge);
724 otherwise->AddSuccessor(merge);
725
726 // Set up dominance information.
727 then->SetDominator(cursor_block);
728 cursor_block->AddDominatedBlock(then);
729 otherwise->SetDominator(cursor_block);
730 cursor_block->AddDominatedBlock(otherwise);
731 merge->SetDominator(cursor_block);
732 cursor_block->AddDominatedBlock(merge);
733
734 // Update the revert post order.
735 size_t index = IndexOfElement(graph_->reverse_post_order_, cursor_block);
736 MakeRoomFor(&graph_->reverse_post_order_, 1, index);
737 graph_->reverse_post_order_[++index] = then;
738 index = IndexOfElement(graph_->reverse_post_order_, end_then);
739 MakeRoomFor(&graph_->reverse_post_order_, 2, index);
740 graph_->reverse_post_order_[++index] = otherwise;
741 graph_->reverse_post_order_[++index] = merge;
742
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000743
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +0000744 graph_->UpdateLoopAndTryInformationOfNewBlock(
745 then, original_invoke_block, /* replace_if_back_edge */ false);
746 graph_->UpdateLoopAndTryInformationOfNewBlock(
747 otherwise, original_invoke_block, /* replace_if_back_edge */ false);
748
749 // In case the original invoke location was a back edge, we need to update
750 // the loop to now have the merge block as a back edge.
751 graph_->UpdateLoopAndTryInformationOfNewBlock(
752 merge, original_invoke_block, /* replace_if_back_edge */ true);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000753}
754
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000755bool HInliner::TryInlinePolymorphicCallToSameTarget(
756 HInvoke* invoke_instruction,
757 ArtMethod* resolved_method,
758 Handle<mirror::ObjectArray<mirror::Class>> classes) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000759 // This optimization only works under JIT for now.
Calin Juravleffc87072016-04-20 14:22:09 +0100760 DCHECK(Runtime::Current()->UseJitCompilation());
Roland Levillain2aba7cd2016-02-03 12:27:20 +0000761 if (graph_->GetInstructionSet() == kMips64) {
762 // TODO: Support HClassTableGet for mips64.
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000763 return false;
764 }
765 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
Andreas Gampe542451c2016-07-26 09:02:02 -0700766 PointerSize pointer_size = class_linker->GetImagePointerSize();
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000767
768 DCHECK(resolved_method != nullptr);
769 ArtMethod* actual_method = nullptr;
Nicolas Geoffray4f97a212016-02-25 16:17:54 +0000770 size_t method_index = invoke_instruction->IsInvokeVirtual()
771 ? invoke_instruction->AsInvokeVirtual()->GetVTableIndex()
772 : invoke_instruction->AsInvokeInterface()->GetImtIndex();
773
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000774 // Check whether we are actually calling the same method among
775 // the different types seen.
776 for (size_t i = 0; i < InlineCache::kIndividualCacheSize; ++i) {
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000777 if (classes->Get(i) == nullptr) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000778 break;
779 }
780 ArtMethod* new_method = nullptr;
781 if (invoke_instruction->IsInvokeInterface()) {
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000782 new_method = classes->Get(i)->GetImt(pointer_size)->Get(
Matthew Gharrity465ecc82016-07-19 21:32:52 +0000783 method_index, pointer_size);
Nicolas Geoffray4f97a212016-02-25 16:17:54 +0000784 if (new_method->IsRuntimeMethod()) {
785 // Bail out as soon as we see a conflict trampoline in one of the target's
786 // interface table.
787 return false;
788 }
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000789 } else {
790 DCHECK(invoke_instruction->IsInvokeVirtual());
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000791 new_method = classes->Get(i)->GetEmbeddedVTableEntry(method_index, pointer_size);
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000792 }
Nicolas Geoffray4f97a212016-02-25 16:17:54 +0000793 DCHECK(new_method != nullptr);
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000794 if (actual_method == nullptr) {
795 actual_method = new_method;
796 } else if (actual_method != new_method) {
797 // Different methods, bailout.
David Sehr709b0702016-10-13 09:12:37 -0700798 VLOG(compiler) << "Call to " << ArtMethod::PrettyMethod(resolved_method)
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +0000799 << " from inline cache is not inlined because it resolves"
800 << " to different methods";
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000801 return false;
802 }
803 }
804
805 HInstruction* receiver = invoke_instruction->InputAt(0);
806 HInstruction* cursor = invoke_instruction->GetPrevious();
807 HBasicBlock* bb_cursor = invoke_instruction->GetBlock();
808
Nicolas Geoffray93a18c52016-04-22 13:16:14 +0100809 HInstruction* return_replacement = nullptr;
Nicolas Geoffray0f001b72017-01-04 16:46:23 +0000810 if (!TryBuildAndInline(invoke_instruction,
811 actual_method,
812 ReferenceTypeInfo::CreateInvalid(),
813 &return_replacement)) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000814 return false;
815 }
816
817 // We successfully inlined, now add a guard.
818 HInstanceFieldGet* receiver_class = BuildGetReceiverClass(
819 class_linker, receiver, invoke_instruction->GetDexPc());
820
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000821 Primitive::Type type = Is64BitInstructionSet(graph_->GetInstructionSet())
822 ? Primitive::kPrimLong
823 : Primitive::kPrimInt;
824 HClassTableGet* class_table_get = new (graph_->GetArena()) HClassTableGet(
825 receiver_class,
826 type,
Vladimir Markoa1de9182016-02-25 11:37:38 +0000827 invoke_instruction->IsInvokeVirtual() ? HClassTableGet::TableKind::kVTable
828 : HClassTableGet::TableKind::kIMTable,
Nicolas Geoffray4f97a212016-02-25 16:17:54 +0000829 method_index,
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000830 invoke_instruction->GetDexPc());
831
832 HConstant* constant;
833 if (type == Primitive::kPrimLong) {
834 constant = graph_->GetLongConstant(
835 reinterpret_cast<intptr_t>(actual_method), invoke_instruction->GetDexPc());
836 } else {
837 constant = graph_->GetIntConstant(
838 reinterpret_cast<intptr_t>(actual_method), invoke_instruction->GetDexPc());
839 }
840
841 HNotEqual* compare = new (graph_->GetArena()) HNotEqual(class_table_get, constant);
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000842 if (cursor != nullptr) {
843 bb_cursor->InsertInstructionAfter(receiver_class, cursor);
844 } else {
845 bb_cursor->InsertInstructionBefore(receiver_class, bb_cursor->GetFirstInstruction());
846 }
847 bb_cursor->InsertInstructionAfter(class_table_get, receiver_class);
848 bb_cursor->InsertInstructionAfter(compare, class_table_get);
Nicolas Geoffray93a18c52016-04-22 13:16:14 +0100849
850 if (outermost_graph_->IsCompilingOsr()) {
851 CreateDiamondPatternForPolymorphicInline(compare, return_replacement, invoke_instruction);
852 } else {
853 // TODO: Extend reference type propagation to understand the guard.
854 HDeoptimize* deoptimize = new (graph_->GetArena()) HDeoptimize(
855 compare, invoke_instruction->GetDexPc());
856 bb_cursor->InsertInstructionAfter(deoptimize, compare);
857 deoptimize->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
858 if (return_replacement != nullptr) {
859 invoke_instruction->ReplaceWith(return_replacement);
860 }
Nicolas Geoffray1be7cbd2016-04-29 13:56:01 +0100861 invoke_instruction->GetBlock()->RemoveInstruction(invoke_instruction);
Nicolas Geoffray93a18c52016-04-22 13:16:14 +0100862 }
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000863
864 // Run type propagation to get the guard typed.
Vladimir Marko456307a2016-04-19 14:12:13 +0000865 ReferenceTypePropagation rtp_fixup(graph_,
866 outer_compilation_unit_.GetDexCache(),
867 handles_,
868 /* is_first_run */ false);
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000869 rtp_fixup.Run();
870
871 MaybeRecordStat(kInlinedPolymorphicCall);
872
873 return true;
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100874}
875
Mingyao Yang063fc772016-08-02 11:02:54 -0700876bool HInliner::TryInlineAndReplace(HInvoke* invoke_instruction,
877 ArtMethod* method,
Nicolas Geoffray0f001b72017-01-04 16:46:23 +0000878 ReferenceTypeInfo receiver_type,
Mingyao Yang063fc772016-08-02 11:02:54 -0700879 bool do_rtp,
880 bool cha_devirtualize) {
Nicolas Geoffray55bd7492016-02-16 15:37:12 +0000881 HInstruction* return_replacement = nullptr;
Mingyao Yang063fc772016-08-02 11:02:54 -0700882 uint32_t dex_pc = invoke_instruction->GetDexPc();
883 HInstruction* cursor = invoke_instruction->GetPrevious();
884 HBasicBlock* bb_cursor = invoke_instruction->GetBlock();
Nicolas Geoffray0f001b72017-01-04 16:46:23 +0000885 if (!TryBuildAndInline(invoke_instruction, method, receiver_type, &return_replacement)) {
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +0000886 if (invoke_instruction->IsInvokeInterface()) {
887 // Turn an invoke-interface into an invoke-virtual. An invoke-virtual is always
888 // better than an invoke-interface because:
889 // 1) In the best case, the interface call has one more indirection (to fetch the IMT).
890 // 2) We will not go to the conflict trampoline with an invoke-virtual.
891 // TODO: Consider sharpening once it is not dependent on the compiler driver.
892 const DexFile& caller_dex_file = *caller_compilation_unit_.GetDexFile();
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +0100893 uint32_t dex_method_index = FindMethodIndexIn(
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +0000894 method, caller_dex_file, invoke_instruction->GetDexMethodIndex());
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +0100895 if (dex_method_index == DexFile::kDexNoIndex) {
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +0000896 return false;
897 }
898 HInvokeVirtual* new_invoke = new (graph_->GetArena()) HInvokeVirtual(
899 graph_->GetArena(),
900 invoke_instruction->GetNumberOfArguments(),
901 invoke_instruction->GetType(),
902 invoke_instruction->GetDexPc(),
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +0100903 dex_method_index,
904 method,
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +0000905 method->GetMethodIndex());
906 HInputsRef inputs = invoke_instruction->GetInputs();
907 for (size_t index = 0; index != inputs.size(); ++index) {
908 new_invoke->SetArgumentAt(index, inputs[index]);
909 }
910 invoke_instruction->GetBlock()->InsertInstructionBefore(new_invoke, invoke_instruction);
911 new_invoke->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
912 if (invoke_instruction->GetType() == Primitive::kPrimNot) {
913 new_invoke->SetReferenceTypeInfo(invoke_instruction->GetReferenceTypeInfo());
914 }
915 return_replacement = new_invoke;
916 } else {
917 // TODO: Consider sharpening an invoke virtual once it is not dependent on the
918 // compiler driver.
919 return false;
920 }
Nicolas Geoffray55bd7492016-02-16 15:37:12 +0000921 }
Mingyao Yang063fc772016-08-02 11:02:54 -0700922 if (cha_devirtualize) {
923 AddCHAGuard(invoke_instruction, dex_pc, cursor, bb_cursor);
924 }
Nicolas Geoffray55bd7492016-02-16 15:37:12 +0000925 if (return_replacement != nullptr) {
926 invoke_instruction->ReplaceWith(return_replacement);
927 }
928 invoke_instruction->GetBlock()->RemoveInstruction(invoke_instruction);
David Brazdil94ab38f2016-06-21 17:48:19 +0100929 FixUpReturnReferenceType(method, return_replacement);
930 if (do_rtp && ReturnTypeMoreSpecific(invoke_instruction, return_replacement)) {
931 // Actual return value has a more specific type than the method's declared
932 // return type. Run RTP again on the outer graph to propagate it.
933 ReferenceTypePropagation(graph_,
934 outer_compilation_unit_.GetDexCache(),
935 handles_,
936 /* is_first_run */ false).Run();
937 }
Nicolas Geoffray55bd7492016-02-16 15:37:12 +0000938 return true;
939}
940
941bool HInliner::TryBuildAndInline(HInvoke* invoke_instruction,
942 ArtMethod* method,
Nicolas Geoffray0f001b72017-01-04 16:46:23 +0000943 ReferenceTypeInfo receiver_type,
Nicolas Geoffray55bd7492016-02-16 15:37:12 +0000944 HInstruction** return_replacement) {
Nicolas Geoffray93a18c52016-04-22 13:16:14 +0100945 if (method->IsProxyMethod()) {
David Sehr709b0702016-10-13 09:12:37 -0700946 VLOG(compiler) << "Method " << method->PrettyMethod()
Nicolas Geoffray93a18c52016-04-22 13:16:14 +0100947 << " is not inlined because of unimplemented inline support for proxy methods.";
948 return false;
949 }
950
Jeff Haodcdc85b2015-12-04 14:06:18 -0800951 // Check whether we're allowed to inline. The outermost compilation unit is the relevant
952 // dex file here (though the transitivity of an inline chain would allow checking the calller).
953 if (!compiler_driver_->MayInline(method->GetDexFile(),
954 outer_compilation_unit_.GetDexFile())) {
Nicolas Geoffray55bd7492016-02-16 15:37:12 +0000955 if (TryPatternSubstitution(invoke_instruction, method, return_replacement)) {
David Sehr709b0702016-10-13 09:12:37 -0700956 VLOG(compiler) << "Successfully replaced pattern of invoke "
957 << method->PrettyMethod();
Vladimir Markobe10e8e2016-01-22 12:09:44 +0000958 MaybeRecordStat(kReplacedInvokeWithSimplePattern);
959 return true;
960 }
David Sehr709b0702016-10-13 09:12:37 -0700961 VLOG(compiler) << "Won't inline " << method->PrettyMethod() << " in "
Jeff Haodcdc85b2015-12-04 14:06:18 -0800962 << outer_compilation_unit_.GetDexFile()->GetLocation() << " ("
963 << caller_compilation_unit_.GetDexFile()->GetLocation() << ") from "
964 << method->GetDexFile()->GetLocation();
965 return false;
966 }
967
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100968 bool same_dex_file = IsSameDexFile(*outer_compilation_unit_.GetDexFile(), *method->GetDexFile());
969
970 const DexFile::CodeItem* code_item = method->GetCodeItem();
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000971
972 if (code_item == nullptr) {
David Sehr709b0702016-10-13 09:12:37 -0700973 VLOG(compiler) << "Method " << method->PrettyMethod()
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000974 << " is not inlined because it is native";
975 return false;
976 }
977
Calin Juravleec748352015-07-29 13:52:12 +0100978 size_t inline_max_code_units = compiler_driver_->GetCompilerOptions().GetInlineMaxCodeUnits();
979 if (code_item->insns_size_in_code_units_ > inline_max_code_units) {
David Sehr709b0702016-10-13 09:12:37 -0700980 VLOG(compiler) << "Method " << method->PrettyMethod()
Nicolas Geoffray788f2f02016-01-22 12:41:38 +0000981 << " is too big to inline: "
982 << code_item->insns_size_in_code_units_
983 << " > "
984 << inline_max_code_units;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000985 return false;
986 }
987
988 if (code_item->tries_size_ != 0) {
David Sehr709b0702016-10-13 09:12:37 -0700989 VLOG(compiler) << "Method " << method->PrettyMethod()
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000990 << " is not inlined because of try block";
991 return false;
992 }
993
Nicolas Geoffray250a3782016-04-20 16:27:53 +0100994 if (!method->IsCompilable()) {
David Sehr709b0702016-10-13 09:12:37 -0700995 VLOG(compiler) << "Method " << method->PrettyMethod()
Nicolas Geoffray250a3782016-04-20 16:27:53 +0100996 << " has soft failures un-handled by the compiler, so it cannot be inlined";
997 }
998
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100999 if (!method->GetDeclaringClass()->IsVerified()) {
1000 uint16_t class_def_idx = method->GetDeclaringClass()->GetDexClassDefIndex();
Calin Juravleffc87072016-04-20 14:22:09 +01001001 if (Runtime::Current()->UseJitCompilation() ||
Nicolas Geoffray5b82d332016-02-18 14:22:32 +00001002 !compiler_driver_->IsMethodVerifiedWithoutFailures(
1003 method->GetDexMethodIndex(), class_def_idx, *method->GetDexFile())) {
David Sehr709b0702016-10-13 09:12:37 -07001004 VLOG(compiler) << "Method " << method->PrettyMethod()
Nicolas Geoffrayccc61972015-10-01 14:34:20 +01001005 << " couldn't be verified, so it cannot be inlined";
1006 return false;
1007 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001008 }
1009
Roland Levillain4c0eb422015-04-24 16:43:49 +01001010 if (invoke_instruction->IsInvokeStaticOrDirect() &&
1011 invoke_instruction->AsInvokeStaticOrDirect()->IsStaticWithImplicitClinitCheck()) {
1012 // Case of a static method that cannot be inlined because it implicitly
1013 // requires an initialization check of its declaring class.
David Sehr709b0702016-10-13 09:12:37 -07001014 VLOG(compiler) << "Method " << method->PrettyMethod()
Roland Levillain4c0eb422015-04-24 16:43:49 +01001015 << " is not inlined because it is static and requires a clinit"
1016 << " check that cannot be emitted due to Dex cache limitations";
1017 return false;
1018 }
1019
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001020 if (!TryBuildAndInlineHelper(
1021 invoke_instruction, method, receiver_type, same_dex_file, return_replacement)) {
Nicolas Geoffrayc0365b12015-03-18 18:31:52 +00001022 return false;
1023 }
1024
David Sehr709b0702016-10-13 09:12:37 -07001025 VLOG(compiler) << "Successfully inlined " << method->PrettyMethod();
Nicolas Geoffrayc0365b12015-03-18 18:31:52 +00001026 MaybeRecordStat(kInlinedInvoke);
1027 return true;
1028}
1029
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001030static HInstruction* GetInvokeInputForArgVRegIndex(HInvoke* invoke_instruction,
1031 size_t arg_vreg_index)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001032 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001033 size_t input_index = 0;
1034 for (size_t i = 0; i < arg_vreg_index; ++i, ++input_index) {
1035 DCHECK_LT(input_index, invoke_instruction->GetNumberOfArguments());
1036 if (Primitive::Is64BitType(invoke_instruction->InputAt(input_index)->GetType())) {
1037 ++i;
1038 DCHECK_NE(i, arg_vreg_index);
1039 }
1040 }
1041 DCHECK_LT(input_index, invoke_instruction->GetNumberOfArguments());
1042 return invoke_instruction->InputAt(input_index);
1043}
1044
1045// Try to recognize known simple patterns and replace invoke call with appropriate instructions.
1046bool HInliner::TryPatternSubstitution(HInvoke* invoke_instruction,
1047 ArtMethod* resolved_method,
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001048 HInstruction** return_replacement) {
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001049 InlineMethod inline_method;
1050 if (!InlineMethodAnalyser::AnalyseMethodCode(resolved_method, &inline_method)) {
1051 return false;
1052 }
1053
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001054 switch (inline_method.opcode) {
1055 case kInlineOpNop:
1056 DCHECK_EQ(invoke_instruction->GetType(), Primitive::kPrimVoid);
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001057 *return_replacement = nullptr;
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001058 break;
1059 case kInlineOpReturnArg:
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001060 *return_replacement = GetInvokeInputForArgVRegIndex(invoke_instruction,
1061 inline_method.d.return_data.arg);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001062 break;
1063 case kInlineOpNonWideConst:
1064 if (resolved_method->GetShorty()[0] == 'L') {
1065 DCHECK_EQ(inline_method.d.data, 0u);
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001066 *return_replacement = graph_->GetNullConstant();
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001067 } else {
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001068 *return_replacement = graph_->GetIntConstant(static_cast<int32_t>(inline_method.d.data));
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001069 }
1070 break;
1071 case kInlineOpIGet: {
1072 const InlineIGetIPutData& data = inline_method.d.ifield_data;
1073 if (data.method_is_static || data.object_arg != 0u) {
1074 // TODO: Needs null check.
1075 return false;
1076 }
Vladimir Marko354efa62016-02-04 19:46:56 +00001077 Handle<mirror::DexCache> dex_cache(handles_->NewHandle(resolved_method->GetDexCache()));
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001078 HInstruction* obj = GetInvokeInputForArgVRegIndex(invoke_instruction, data.object_arg);
Vladimir Marko354efa62016-02-04 19:46:56 +00001079 HInstanceFieldGet* iget = CreateInstanceFieldGet(dex_cache, data.field_idx, obj);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001080 DCHECK_EQ(iget->GetFieldOffset().Uint32Value(), data.field_offset);
1081 DCHECK_EQ(iget->IsVolatile() ? 1u : 0u, data.is_volatile);
1082 invoke_instruction->GetBlock()->InsertInstructionBefore(iget, invoke_instruction);
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001083 *return_replacement = iget;
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001084 break;
1085 }
1086 case kInlineOpIPut: {
1087 const InlineIGetIPutData& data = inline_method.d.ifield_data;
1088 if (data.method_is_static || data.object_arg != 0u) {
1089 // TODO: Needs null check.
1090 return false;
1091 }
Vladimir Marko354efa62016-02-04 19:46:56 +00001092 Handle<mirror::DexCache> dex_cache(handles_->NewHandle(resolved_method->GetDexCache()));
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001093 HInstruction* obj = GetInvokeInputForArgVRegIndex(invoke_instruction, data.object_arg);
1094 HInstruction* value = GetInvokeInputForArgVRegIndex(invoke_instruction, data.src_arg);
Vladimir Marko354efa62016-02-04 19:46:56 +00001095 HInstanceFieldSet* iput = CreateInstanceFieldSet(dex_cache, data.field_idx, obj, value);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001096 DCHECK_EQ(iput->GetFieldOffset().Uint32Value(), data.field_offset);
1097 DCHECK_EQ(iput->IsVolatile() ? 1u : 0u, data.is_volatile);
1098 invoke_instruction->GetBlock()->InsertInstructionBefore(iput, invoke_instruction);
1099 if (data.return_arg_plus1 != 0u) {
1100 size_t return_arg = data.return_arg_plus1 - 1u;
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001101 *return_replacement = GetInvokeInputForArgVRegIndex(invoke_instruction, return_arg);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001102 }
1103 break;
1104 }
Vladimir Marko354efa62016-02-04 19:46:56 +00001105 case kInlineOpConstructor: {
1106 const InlineConstructorData& data = inline_method.d.constructor_data;
1107 // Get the indexes to arrays for easier processing.
1108 uint16_t iput_field_indexes[] = {
1109 data.iput0_field_index, data.iput1_field_index, data.iput2_field_index
1110 };
1111 uint16_t iput_args[] = { data.iput0_arg, data.iput1_arg, data.iput2_arg };
1112 static_assert(arraysize(iput_args) == arraysize(iput_field_indexes), "Size mismatch");
1113 // Count valid field indexes.
1114 size_t number_of_iputs = 0u;
1115 while (number_of_iputs != arraysize(iput_field_indexes) &&
1116 iput_field_indexes[number_of_iputs] != DexFile::kDexNoIndex16) {
1117 // Check that there are no duplicate valid field indexes.
1118 DCHECK_EQ(0, std::count(iput_field_indexes + number_of_iputs + 1,
1119 iput_field_indexes + arraysize(iput_field_indexes),
1120 iput_field_indexes[number_of_iputs]));
1121 ++number_of_iputs;
1122 }
1123 // Check that there are no valid field indexes in the rest of the array.
1124 DCHECK_EQ(0, std::count_if(iput_field_indexes + number_of_iputs,
1125 iput_field_indexes + arraysize(iput_field_indexes),
1126 [](uint16_t index) { return index != DexFile::kDexNoIndex16; }));
1127
1128 // Create HInstanceFieldSet for each IPUT that stores non-zero data.
1129 Handle<mirror::DexCache> dex_cache;
1130 HInstruction* obj = GetInvokeInputForArgVRegIndex(invoke_instruction, /* this */ 0u);
1131 bool needs_constructor_barrier = false;
1132 for (size_t i = 0; i != number_of_iputs; ++i) {
1133 HInstruction* value = GetInvokeInputForArgVRegIndex(invoke_instruction, iput_args[i]);
Roland Levillain1a653882016-03-18 18:05:57 +00001134 if (!value->IsConstant() || !value->AsConstant()->IsZeroBitPattern()) {
Vladimir Marko354efa62016-02-04 19:46:56 +00001135 if (dex_cache.GetReference() == nullptr) {
1136 dex_cache = handles_->NewHandle(resolved_method->GetDexCache());
1137 }
1138 uint16_t field_index = iput_field_indexes[i];
1139 HInstanceFieldSet* iput = CreateInstanceFieldSet(dex_cache, field_index, obj, value);
1140 invoke_instruction->GetBlock()->InsertInstructionBefore(iput, invoke_instruction);
1141
1142 // Check whether the field is final. If it is, we need to add a barrier.
Andreas Gampe542451c2016-07-26 09:02:02 -07001143 PointerSize pointer_size = InstructionSetPointerSize(codegen_->GetInstructionSet());
Vladimir Marko354efa62016-02-04 19:46:56 +00001144 ArtField* resolved_field = dex_cache->GetResolvedField(field_index, pointer_size);
1145 DCHECK(resolved_field != nullptr);
1146 if (resolved_field->IsFinal()) {
1147 needs_constructor_barrier = true;
1148 }
1149 }
1150 }
1151 if (needs_constructor_barrier) {
1152 HMemoryBarrier* barrier = new (graph_->GetArena()) HMemoryBarrier(kStoreStore, kNoDexPc);
1153 invoke_instruction->GetBlock()->InsertInstructionBefore(barrier, invoke_instruction);
1154 }
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001155 *return_replacement = nullptr;
Vladimir Marko354efa62016-02-04 19:46:56 +00001156 break;
1157 }
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001158 default:
1159 LOG(FATAL) << "UNREACHABLE";
1160 UNREACHABLE();
1161 }
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001162 return true;
1163}
1164
Vladimir Marko354efa62016-02-04 19:46:56 +00001165HInstanceFieldGet* HInliner::CreateInstanceFieldGet(Handle<mirror::DexCache> dex_cache,
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001166 uint32_t field_index,
1167 HInstruction* obj)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001168 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe542451c2016-07-26 09:02:02 -07001169 PointerSize pointer_size = InstructionSetPointerSize(codegen_->GetInstructionSet());
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001170 ArtField* resolved_field = dex_cache->GetResolvedField(field_index, pointer_size);
1171 DCHECK(resolved_field != nullptr);
1172 HInstanceFieldGet* iget = new (graph_->GetArena()) HInstanceFieldGet(
1173 obj,
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00001174 resolved_field,
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001175 resolved_field->GetTypeAsPrimitiveType(),
1176 resolved_field->GetOffset(),
1177 resolved_field->IsVolatile(),
1178 field_index,
1179 resolved_field->GetDeclaringClass()->GetDexClassDefIndex(),
Vladimir Marko354efa62016-02-04 19:46:56 +00001180 *dex_cache->GetDexFile(),
Vladimir Markoadda4352016-01-29 10:24:41 +00001181 // Read barrier generates a runtime call in slow path and we need a valid
1182 // dex pc for the associated stack map. 0 is bogus but valid. Bug: 26854537.
1183 /* dex_pc */ 0);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001184 if (iget->GetType() == Primitive::kPrimNot) {
Vladimir Marko456307a2016-04-19 14:12:13 +00001185 // Use the same dex_cache that we used for field lookup as the hint_dex_cache.
Mathieu Chartier5812e202017-02-13 18:32:04 -08001186 ReferenceTypePropagation rtp(graph_, dex_cache, handles_, /* is_first_run */ false);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001187 rtp.Visit(iget);
1188 }
1189 return iget;
1190}
1191
Vladimir Marko354efa62016-02-04 19:46:56 +00001192HInstanceFieldSet* HInliner::CreateInstanceFieldSet(Handle<mirror::DexCache> dex_cache,
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001193 uint32_t field_index,
1194 HInstruction* obj,
1195 HInstruction* value)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001196 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe542451c2016-07-26 09:02:02 -07001197 PointerSize pointer_size = InstructionSetPointerSize(codegen_->GetInstructionSet());
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001198 ArtField* resolved_field = dex_cache->GetResolvedField(field_index, pointer_size);
1199 DCHECK(resolved_field != nullptr);
1200 HInstanceFieldSet* iput = new (graph_->GetArena()) HInstanceFieldSet(
1201 obj,
1202 value,
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00001203 resolved_field,
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001204 resolved_field->GetTypeAsPrimitiveType(),
1205 resolved_field->GetOffset(),
1206 resolved_field->IsVolatile(),
1207 field_index,
1208 resolved_field->GetDeclaringClass()->GetDexClassDefIndex(),
Vladimir Marko354efa62016-02-04 19:46:56 +00001209 *dex_cache->GetDexFile(),
Vladimir Markoadda4352016-01-29 10:24:41 +00001210 // Read barrier generates a runtime call in slow path and we need a valid
1211 // dex pc for the associated stack map. 0 is bogus but valid. Bug: 26854537.
1212 /* dex_pc */ 0);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001213 return iput;
1214}
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +00001215
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001216bool HInliner::TryBuildAndInlineHelper(HInvoke* invoke_instruction,
1217 ArtMethod* resolved_method,
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001218 ReferenceTypeInfo receiver_type,
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001219 bool same_dex_file,
1220 HInstruction** return_replacement) {
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001221 DCHECK(!(resolved_method->IsStatic() && receiver_type.IsValid()));
Nicolas Geoffrayc0365b12015-03-18 18:31:52 +00001222 ScopedObjectAccess soa(Thread::Current());
1223 const DexFile::CodeItem* code_item = resolved_method->GetCodeItem();
Guillaume "Vermeille" Sanchezae09d2d2015-05-29 10:52:55 +01001224 const DexFile& callee_dex_file = *resolved_method->GetDexFile();
1225 uint32_t method_index = resolved_method->GetDexMethodIndex();
Calin Juravle2e768302015-07-28 14:41:11 +00001226 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
Mathieu Chartier736b5602015-09-02 14:54:11 -07001227 Handle<mirror::DexCache> dex_cache(handles_->NewHandle(resolved_method->GetDexCache()));
Nicolas Geoffrayf1aedb12016-07-28 03:49:14 +01001228 Handle<mirror::ClassLoader> class_loader(handles_->NewHandle(
1229 resolved_method->GetDeclaringClass()->GetClassLoader()));
1230
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001231 DexCompilationUnit dex_compilation_unit(
Mathieu Chartier5812e202017-02-13 18:32:04 -08001232 class_loader.ToJObject(),
Nicolas Geoffray5b82d332016-02-18 14:22:32 +00001233 class_linker,
1234 callee_dex_file,
1235 code_item,
1236 resolved_method->GetDeclaringClass()->GetDexClassDefIndex(),
1237 method_index,
1238 resolved_method->GetAccessFlags(),
1239 /* verified_method */ nullptr,
1240 dex_cache);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001241
Calin Juravle3cd4fc82015-05-14 15:15:42 +01001242 bool requires_ctor_barrier = false;
1243
1244 if (dex_compilation_unit.IsConstructor()) {
1245 // If it's a super invocation and we already generate a barrier there's no need
1246 // to generate another one.
1247 // We identify super calls by looking at the "this" pointer. If its value is the
1248 // same as the local "this" pointer then we must have a super invocation.
1249 bool is_super_invocation = invoke_instruction->InputAt(0)->IsParameterValue()
1250 && invoke_instruction->InputAt(0)->AsParameterValue()->IsThis();
1251 if (is_super_invocation && graph_->ShouldGenerateConstructorBarrier()) {
1252 requires_ctor_barrier = false;
1253 } else {
1254 Thread* self = Thread::Current();
1255 requires_ctor_barrier = compiler_driver_->RequiresConstructorBarrier(self,
1256 dex_compilation_unit.GetDexFile(),
1257 dex_compilation_unit.GetClassDefIndex());
1258 }
1259 }
1260
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +01001261 InvokeType invoke_type = invoke_instruction->GetInvokeType();
Nicolas Geoffray35071052015-06-09 15:43:38 +01001262 if (invoke_type == kInterface) {
1263 // We have statically resolved the dispatch. To please the class linker
1264 // at runtime, we change this call as if it was a virtual call.
1265 invoke_type = kVirtual;
1266 }
David Brazdil3f523062016-02-29 16:53:33 +00001267
1268 const int32_t caller_instruction_counter = graph_->GetCurrentInstructionId();
Nicolas Geoffraye0fe7ae2015-03-09 10:02:49 +00001269 HGraph* callee_graph = new (graph_->GetArena()) HGraph(
Nicolas Geoffray0a23d742015-05-07 11:57:35 +01001270 graph_->GetArena(),
Guillaume "Vermeille" Sanchezae09d2d2015-05-29 10:52:55 +01001271 callee_dex_file,
Nicolas Geoffray0a23d742015-05-07 11:57:35 +01001272 method_index,
Calin Juravle3cd4fc82015-05-14 15:15:42 +01001273 requires_ctor_barrier,
Mathieu Chartiere401d142015-04-22 13:56:20 -07001274 compiler_driver_->GetInstructionSet(),
Nicolas Geoffray35071052015-06-09 15:43:38 +01001275 invoke_type,
Nicolas Geoffray0a23d742015-05-07 11:57:35 +01001276 graph_->IsDebuggable(),
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001277 /* osr */ false,
David Brazdil3f523062016-02-29 16:53:33 +00001278 caller_instruction_counter);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001279 callee_graph->SetArtMethod(resolved_method);
David Brazdil5e8b1372015-01-23 14:39:08 +00001280
Roland Levillaina8013fd2016-04-04 15:34:31 +01001281 // When they are needed, allocate `inline_stats` on the heap instead
1282 // of on the stack, as Clang might produce a stack frame too large
1283 // for this function, that would not fit the requirements of the
1284 // `-Wframe-larger-than` option.
1285 std::unique_ptr<OptimizingCompilerStats> inline_stats =
1286 (stats_ == nullptr) ? nullptr : MakeUnique<OptimizingCompilerStats>();
David Brazdil5e8b1372015-01-23 14:39:08 +00001287 HGraphBuilder builder(callee_graph,
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001288 &dex_compilation_unit,
1289 &outer_compilation_unit_,
Nicolas Geoffray9437b782015-03-25 10:08:51 +00001290 resolved_method->GetDexFile(),
David Brazdil86ea7ee2016-02-16 09:26:07 +00001291 *code_item,
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001292 compiler_driver_,
Nicolas Geoffray83c8e272017-01-31 14:36:37 +00001293 codegen_,
Roland Levillaina8013fd2016-04-04 15:34:31 +01001294 inline_stats.get(),
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01001295 resolved_method->GetQuickenedInfo(class_linker->GetImagePointerSize()),
David Brazdildee58d62016-04-07 09:54:26 +00001296 dex_cache,
1297 handles_);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001298
David Brazdildee58d62016-04-07 09:54:26 +00001299 if (builder.BuildGraph() != kAnalysisSuccess) {
David Sehr709b0702016-10-13 09:12:37 -07001300 VLOG(compiler) << "Method " << callee_dex_file.PrettyMethod(method_index)
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001301 << " could not be built, so cannot be inlined";
1302 return false;
1303 }
1304
Nicolas Geoffray259136f2014-12-17 23:21:58 +00001305 if (!RegisterAllocator::CanAllocateRegistersFor(*callee_graph,
1306 compiler_driver_->GetInstructionSet())) {
David Sehr709b0702016-10-13 09:12:37 -07001307 VLOG(compiler) << "Method " << callee_dex_file.PrettyMethod(method_index)
Nicolas Geoffray259136f2014-12-17 23:21:58 +00001308 << " cannot be inlined because of the register allocator";
1309 return false;
1310 }
1311
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001312 size_t parameter_index = 0;
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001313 bool run_rtp = false;
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001314 for (HInstructionIterator instructions(callee_graph->GetEntryBlock()->GetInstructions());
1315 !instructions.Done();
1316 instructions.Advance()) {
1317 HInstruction* current = instructions.Current();
1318 if (current->IsParameterValue()) {
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001319 HInstruction* argument = invoke_instruction->InputAt(parameter_index);
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001320 if (argument->IsNullConstant()) {
1321 current->ReplaceWith(callee_graph->GetNullConstant());
1322 } else if (argument->IsIntConstant()) {
1323 current->ReplaceWith(callee_graph->GetIntConstant(argument->AsIntConstant()->GetValue()));
1324 } else if (argument->IsLongConstant()) {
1325 current->ReplaceWith(callee_graph->GetLongConstant(argument->AsLongConstant()->GetValue()));
1326 } else if (argument->IsFloatConstant()) {
1327 current->ReplaceWith(
1328 callee_graph->GetFloatConstant(argument->AsFloatConstant()->GetValue()));
1329 } else if (argument->IsDoubleConstant()) {
1330 current->ReplaceWith(
1331 callee_graph->GetDoubleConstant(argument->AsDoubleConstant()->GetValue()));
1332 } else if (argument->GetType() == Primitive::kPrimNot) {
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001333 if (!resolved_method->IsStatic() && parameter_index == 0 && receiver_type.IsValid()) {
1334 run_rtp = true;
1335 current->SetReferenceTypeInfo(receiver_type);
1336 } else {
1337 current->SetReferenceTypeInfo(argument->GetReferenceTypeInfo());
1338 }
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001339 current->AsParameterValue()->SetCanBeNull(argument->CanBeNull());
1340 }
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001341 ++parameter_index;
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001342 }
1343 }
1344
David Brazdil94ab38f2016-06-21 17:48:19 +01001345 // We have replaced formal arguments with actual arguments. If actual types
1346 // are more specific than the declared ones, run RTP again on the inner graph.
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001347 if (run_rtp || ArgumentTypesMoreSpecific(invoke_instruction, resolved_method)) {
David Brazdil94ab38f2016-06-21 17:48:19 +01001348 ReferenceTypePropagation(callee_graph,
1349 dex_compilation_unit.GetDexCache(),
1350 handles_,
1351 /* is_first_run */ false).Run();
1352 }
1353
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001354 size_t number_of_instructions_budget = kMaximumNumberOfHInstructions;
Roland Levillaina3aef2e2016-04-06 17:45:58 +01001355 size_t number_of_inlined_instructions =
1356 RunOptimizations(callee_graph, code_item, dex_compilation_unit);
1357 number_of_instructions_budget += number_of_inlined_instructions;
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +00001358
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001359 // TODO: We should abort only if all predecessors throw. However,
1360 // HGraph::InlineInto currently does not handle an exit block with
1361 // a throw predecessor.
1362 HBasicBlock* exit_block = callee_graph->GetExitBlock();
1363 if (exit_block == nullptr) {
David Sehr709b0702016-10-13 09:12:37 -07001364 VLOG(compiler) << "Method " << callee_dex_file.PrettyMethod(method_index)
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001365 << " could not be inlined because it has an infinite loop";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001366 return false;
1367 }
1368
1369 bool has_throw_predecessor = false;
Vladimir Marko60584552015-09-03 13:35:12 +00001370 for (HBasicBlock* predecessor : exit_block->GetPredecessors()) {
1371 if (predecessor->GetLastInstruction()->IsThrow()) {
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001372 has_throw_predecessor = true;
1373 break;
1374 }
1375 }
1376 if (has_throw_predecessor) {
David Sehr709b0702016-10-13 09:12:37 -07001377 VLOG(compiler) << "Method " << callee_dex_file.PrettyMethod(method_index)
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001378 << " could not be inlined because one branch always throws";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001379 return false;
1380 }
1381
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001382 size_t number_of_instructions = 0;
Nicolas Geoffray5949fa02015-12-18 10:57:10 +00001383
1384 bool can_inline_environment =
1385 total_number_of_dex_registers_ < kMaximumNumberOfCumulatedDexRegisters;
1386
Vladimir Marko2c45bc92016-10-25 16:54:12 +01001387 // Skip the entry block, it does not contain instructions that prevent inlining.
1388 for (HBasicBlock* block : callee_graph->GetReversePostOrderSkipEntryBlock()) {
David Sehrc757dec2016-11-04 15:48:34 -07001389 if (block->IsLoopHeader()) {
1390 if (block->GetLoopInformation()->IsIrreducible()) {
1391 // Don't inline methods with irreducible loops, they could prevent some
1392 // optimizations to run.
1393 VLOG(compiler) << "Method " << callee_dex_file.PrettyMethod(method_index)
1394 << " could not be inlined because it contains an irreducible loop";
1395 return false;
1396 }
1397 if (!block->GetLoopInformation()->HasExitEdge()) {
1398 // Don't inline methods with loops without exit, since they cause the
1399 // loop information to be computed incorrectly when updating after
1400 // inlining.
1401 VLOG(compiler) << "Method " << callee_dex_file.PrettyMethod(method_index)
1402 << " could not be inlined because it contains a loop with no exit";
1403 return false;
1404 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001405 }
1406
1407 for (HInstructionIterator instr_it(block->GetInstructions());
1408 !instr_it.Done();
1409 instr_it.Advance()) {
Roland Levillaina3aef2e2016-04-06 17:45:58 +01001410 if (number_of_instructions++ == number_of_instructions_budget) {
David Sehr709b0702016-10-13 09:12:37 -07001411 VLOG(compiler) << "Method " << callee_dex_file.PrettyMethod(method_index)
Nicolas Geoffray5949fa02015-12-18 10:57:10 +00001412 << " is not inlined because its caller has reached"
1413 << " its instruction budget limit.";
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001414 return false;
1415 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001416 HInstruction* current = instr_it.Current();
Nicolas Geoffray5949fa02015-12-18 10:57:10 +00001417 if (!can_inline_environment && current->NeedsEnvironment()) {
David Sehr709b0702016-10-13 09:12:37 -07001418 VLOG(compiler) << "Method " << callee_dex_file.PrettyMethod(method_index)
Nicolas Geoffray5949fa02015-12-18 10:57:10 +00001419 << " is not inlined because its caller has reached"
1420 << " its environment budget limit.";
1421 return false;
1422 }
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001423
Nicolas Geoffrayfbdfa6d2017-02-03 10:43:13 +00001424 if (current->NeedsEnvironment() &&
1425 !CanEncodeInlinedMethodInStackMap(*caller_compilation_unit_.GetDexFile(),
1426 resolved_method)) {
David Sehr709b0702016-10-13 09:12:37 -07001427 VLOG(compiler) << "Method " << callee_dex_file.PrettyMethod(method_index)
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001428 << " could not be inlined because " << current->DebugName()
Nicolas Geoffrayfbdfa6d2017-02-03 10:43:13 +00001429 << " needs an environment, is in a different dex file"
1430 << ", and cannot be encoded in the stack maps.";
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001431 return false;
1432 }
Nicolas Geoffray9437b782015-03-25 10:08:51 +00001433
Vladimir Markodc151b22015-10-15 18:02:30 +01001434 if (!same_dex_file && current->NeedsDexCacheOfDeclaringClass()) {
David Sehr709b0702016-10-13 09:12:37 -07001435 VLOG(compiler) << "Method " << callee_dex_file.PrettyMethod(method_index)
Nicolas Geoffray9437b782015-03-25 10:08:51 +00001436 << " could not be inlined because " << current->DebugName()
1437 << " it is in a different dex file and requires access to the dex cache";
1438 return false;
1439 }
Nicolas Geoffrayd9309292015-10-31 22:21:31 +00001440
Nicolas Geoffrayd9309292015-10-31 22:21:31 +00001441 if (current->IsUnresolvedStaticFieldGet() ||
1442 current->IsUnresolvedInstanceFieldGet() ||
1443 current->IsUnresolvedStaticFieldSet() ||
1444 current->IsUnresolvedInstanceFieldSet()) {
1445 // Entrypoint for unresolved fields does not handle inlined frames.
David Sehr709b0702016-10-13 09:12:37 -07001446 VLOG(compiler) << "Method " << callee_dex_file.PrettyMethod(method_index)
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +00001447 << " could not be inlined because it is using an unresolved"
1448 << " entrypoint";
Nicolas Geoffrayd9309292015-10-31 22:21:31 +00001449 return false;
1450 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001451 }
1452 }
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001453 number_of_inlined_instructions_ += number_of_instructions;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001454
David Brazdil3f523062016-02-29 16:53:33 +00001455 DCHECK_EQ(caller_instruction_counter, graph_->GetCurrentInstructionId())
1456 << "No instructions can be added to the outer graph while inner graph is being built";
1457
1458 const int32_t callee_instruction_counter = callee_graph->GetCurrentInstructionId();
1459 graph_->SetCurrentInstructionId(callee_instruction_counter);
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001460 *return_replacement = callee_graph->InlineInto(graph_, invoke_instruction);
David Brazdil3f523062016-02-29 16:53:33 +00001461
1462 DCHECK_EQ(callee_instruction_counter, callee_graph->GetCurrentInstructionId())
1463 << "No instructions can be added to the inner graph during inlining into the outer graph";
1464
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001465 return true;
1466}
Calin Juravle2e768302015-07-28 14:41:11 +00001467
Roland Levillaina3aef2e2016-04-06 17:45:58 +01001468size_t HInliner::RunOptimizations(HGraph* callee_graph,
1469 const DexFile::CodeItem* code_item,
1470 const DexCompilationUnit& dex_compilation_unit) {
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01001471 // Note: if the outermost_graph_ is being compiled OSR, we should not run any
1472 // optimization that could lead to a HDeoptimize. The following optimizations do not.
Andreas Gampeca620d72016-11-08 08:09:33 -08001473 HDeadCodeElimination dce(callee_graph, stats_, "dead_code_elimination$inliner");
1474 HConstantFolding fold(callee_graph, "constant_folding$inliner");
Nicolas Geoffray22384ae2016-12-12 22:33:36 +00001475 HSharpening sharpening(callee_graph, codegen_, dex_compilation_unit, compiler_driver_, handles_);
Roland Levillaina3aef2e2016-04-06 17:45:58 +01001476 InstructionSimplifier simplify(callee_graph, stats_);
Nicolas Geoffray762869d2016-07-15 15:28:35 +01001477 IntrinsicsRecognizer intrinsics(callee_graph, stats_);
Roland Levillaina3aef2e2016-04-06 17:45:58 +01001478
1479 HOptimization* optimizations[] = {
1480 &intrinsics,
1481 &sharpening,
1482 &simplify,
1483 &fold,
1484 &dce,
1485 };
1486
1487 for (size_t i = 0; i < arraysize(optimizations); ++i) {
1488 HOptimization* optimization = optimizations[i];
1489 optimization->Run();
1490 }
1491
1492 size_t number_of_inlined_instructions = 0u;
1493 if (depth_ + 1 < compiler_driver_->GetCompilerOptions().GetInlineDepthLimit()) {
1494 HInliner inliner(callee_graph,
1495 outermost_graph_,
1496 codegen_,
1497 outer_compilation_unit_,
1498 dex_compilation_unit,
1499 compiler_driver_,
1500 handles_,
1501 stats_,
1502 total_number_of_dex_registers_ + code_item->registers_size_,
1503 depth_ + 1);
1504 inliner.Run();
1505 number_of_inlined_instructions += inliner.number_of_inlined_instructions_;
1506 }
1507
1508 return number_of_inlined_instructions;
1509}
1510
David Brazdil94ab38f2016-06-21 17:48:19 +01001511static bool IsReferenceTypeRefinement(ReferenceTypeInfo declared_rti,
1512 bool declared_can_be_null,
1513 HInstruction* actual_obj)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001514 REQUIRES_SHARED(Locks::mutator_lock_) {
David Brazdil94ab38f2016-06-21 17:48:19 +01001515 if (declared_can_be_null && !actual_obj->CanBeNull()) {
1516 return true;
1517 }
1518
1519 ReferenceTypeInfo actual_rti = actual_obj->GetReferenceTypeInfo();
1520 return (actual_rti.IsExact() && !declared_rti.IsExact()) ||
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001521 declared_rti.IsStrictSupertypeOf(actual_rti);
David Brazdil94ab38f2016-06-21 17:48:19 +01001522}
1523
1524ReferenceTypeInfo HInliner::GetClassRTI(mirror::Class* klass) {
1525 return ReferenceTypePropagation::IsAdmissible(klass)
1526 ? ReferenceTypeInfo::Create(handles_->NewHandle(klass))
1527 : graph_->GetInexactObjectRti();
1528}
1529
1530bool HInliner::ArgumentTypesMoreSpecific(HInvoke* invoke_instruction, ArtMethod* resolved_method) {
1531 // If this is an instance call, test whether the type of the `this` argument
1532 // is more specific than the class which declares the method.
1533 if (!resolved_method->IsStatic()) {
1534 if (IsReferenceTypeRefinement(GetClassRTI(resolved_method->GetDeclaringClass()),
1535 /* declared_can_be_null */ false,
1536 invoke_instruction->InputAt(0u))) {
1537 return true;
1538 }
1539 }
1540
David Brazdil94ab38f2016-06-21 17:48:19 +01001541 // Iterate over the list of parameter types and test whether any of the
1542 // actual inputs has a more specific reference type than the type declared in
1543 // the signature.
1544 const DexFile::TypeList* param_list = resolved_method->GetParameterTypeList();
1545 for (size_t param_idx = 0,
1546 input_idx = resolved_method->IsStatic() ? 0 : 1,
1547 e = (param_list == nullptr ? 0 : param_list->Size());
1548 param_idx < e;
1549 ++param_idx, ++input_idx) {
1550 HInstruction* input = invoke_instruction->InputAt(input_idx);
1551 if (input->GetType() == Primitive::kPrimNot) {
Vladimir Marko942fd312017-01-16 20:52:19 +00001552 mirror::Class* param_cls = resolved_method->GetClassFromTypeIndex(
David Brazdil94ab38f2016-06-21 17:48:19 +01001553 param_list->GetTypeItem(param_idx).type_idx_,
Vladimir Marko942fd312017-01-16 20:52:19 +00001554 /* resolve */ false);
David Brazdil94ab38f2016-06-21 17:48:19 +01001555 if (IsReferenceTypeRefinement(GetClassRTI(param_cls),
1556 /* declared_can_be_null */ true,
1557 input)) {
1558 return true;
1559 }
1560 }
1561 }
1562
1563 return false;
1564}
1565
1566bool HInliner::ReturnTypeMoreSpecific(HInvoke* invoke_instruction,
1567 HInstruction* return_replacement) {
Alex Light68289a52015-12-15 17:30:30 -08001568 // Check the integrity of reference types and run another type propagation if needed.
David Brazdil4833f5a2015-12-16 10:37:39 +00001569 if (return_replacement != nullptr) {
1570 if (return_replacement->GetType() == Primitive::kPrimNot) {
David Brazdil94ab38f2016-06-21 17:48:19 +01001571 // Test if the return type is a refinement of the declared return type.
1572 if (IsReferenceTypeRefinement(invoke_instruction->GetReferenceTypeInfo(),
1573 /* declared_can_be_null */ true,
1574 return_replacement)) {
1575 return true;
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00001576 } else if (return_replacement->IsInstanceFieldGet()) {
1577 HInstanceFieldGet* field_get = return_replacement->AsInstanceFieldGet();
1578 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1579 if (field_get->GetFieldInfo().GetField() ==
1580 class_linker->GetClassRoot(ClassLinker::kJavaLangObject)->GetInstanceField(0)) {
1581 return true;
1582 }
David Brazdil94ab38f2016-06-21 17:48:19 +01001583 }
1584 } else if (return_replacement->IsInstanceOf()) {
1585 // Inlining InstanceOf into an If may put a tighter bound on reference types.
1586 return true;
1587 }
1588 }
1589
1590 return false;
1591}
1592
1593void HInliner::FixUpReturnReferenceType(ArtMethod* resolved_method,
1594 HInstruction* return_replacement) {
1595 if (return_replacement != nullptr) {
1596 if (return_replacement->GetType() == Primitive::kPrimNot) {
David Brazdil4833f5a2015-12-16 10:37:39 +00001597 if (!return_replacement->GetReferenceTypeInfo().IsValid()) {
1598 // Make sure that we have a valid type for the return. We may get an invalid one when
1599 // we inline invokes with multiple branches and create a Phi for the result.
1600 // TODO: we could be more precise by merging the phi inputs but that requires
1601 // some functionality from the reference type propagation.
1602 DCHECK(return_replacement->IsPhi());
Vladimir Marko942fd312017-01-16 20:52:19 +00001603 mirror::Class* cls = resolved_method->GetReturnType(false /* resolve */);
David Brazdil94ab38f2016-06-21 17:48:19 +01001604 return_replacement->SetReferenceTypeInfo(GetClassRTI(cls));
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001605 }
Calin Juravlecdfed3d2015-10-26 14:05:01 +00001606 }
Calin Juravle2e768302015-07-28 14:41:11 +00001607 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001608}
1609
1610} // namespace art