blob: f203d7f47ec51f7d92ad6a1d53439fac3a400708 [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"
Andreas Gampeb95c74b2017-04-20 19:43:21 -070025#include "dex/inline_method_analyser.h"
Vladimir Markobe10e8e2016-01-22 12:09:44 +000026#include "dex/verified_method.h"
27#include "dex/verification_results.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000028#include "driver/compiler_driver-inl.h"
Calin Juravleec748352015-07-29 13:52:12 +010029#include "driver/compiler_options.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000030#include "driver/dex_compilation_unit.h"
31#include "instruction_simplifier.h"
Scott Wakelingd60a1af2015-07-22 14:32:44 +010032#include "intrinsics.h"
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +000033#include "jit/jit.h"
34#include "jit/jit_code_cache.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000035#include "mirror/class_loader.h"
36#include "mirror/dex_cache.h"
37#include "nodes.h"
Nicolas Geoffray335005e2015-06-25 10:01:47 +010038#include "optimizing_compiler.h"
Nicolas Geoffray454a4812015-06-09 10:37:32 +010039#include "reference_type_propagation.h"
Matthew Gharritye9288852016-07-14 14:08:16 -070040#include "register_allocator_linear_scan.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 Geoffrayf6d46682017-02-28 17:41:45 +000049// Instruction limit to control memory.
50static constexpr size_t kMaximumNumberOfTotalInstructions = 1024;
51
52// Maximum number of instructions for considering a method small,
53// which we will always try to inline if the other non-instruction limits
54// are not reached.
55static constexpr size_t kMaximumNumberOfInstructionsForSmallMethod = 3;
Nicolas Geoffray5949fa02015-12-18 10:57:10 +000056
57// Limit the number of dex registers that we accumulate while inlining
58// to avoid creating large amount of nested environments.
59static constexpr size_t kMaximumNumberOfCumulatedDexRegisters = 64;
60
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +000061// Limit recursive call inlining, which do not benefit from too
62// much inlining compared to code locality.
63static constexpr size_t kMaximumNumberOfRecursiveCalls = 4;
Nicolas Geoffraye418dda2015-08-11 20:03:09 -070064
Calin Juravlee2492d42017-03-20 11:42:13 -070065// Controls the use of inline caches in AOT mode.
Calin Juravle8af70892017-03-28 15:31:44 -070066static constexpr bool kUseAOTInlineCaches = true;
Calin Juravlee2492d42017-03-20 11:42:13 -070067
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +000068// We check for line numbers to make sure the DepthString implementation
69// aligns the output nicely.
70#define LOG_INTERNAL(msg) \
71 static_assert(__LINE__ > 10, "Unhandled line number"); \
72 static_assert(__LINE__ < 10000, "Unhandled line number"); \
73 VLOG(compiler) << DepthString(__LINE__) << msg
74
75#define LOG_TRY() LOG_INTERNAL("Try inlinining call: ")
76#define LOG_NOTE() LOG_INTERNAL("Note: ")
77#define LOG_SUCCESS() LOG_INTERNAL("Success: ")
78#define LOG_FAIL(stat) MaybeRecordStat(stat); LOG_INTERNAL("Fail: ")
79#define LOG_FAIL_NO_STAT() LOG_INTERNAL("Fail: ")
80
81std::string HInliner::DepthString(int line) const {
82 std::string value;
83 // Indent according to the inlining depth.
84 size_t count = depth_;
85 // Line numbers get printed in the log, so add a space if the log's line is less
86 // than 1000, and two if less than 100. 10 cannot be reached as it's the copyright.
87 if (!kIsTargetBuild) {
88 if (line < 100) {
89 value += " ";
90 }
91 if (line < 1000) {
92 value += " ";
93 }
94 // Safeguard if this file reaches more than 10000 lines.
95 DCHECK_LT(line, 10000);
96 }
97 for (size_t i = 0; i < count; ++i) {
98 value += " ";
99 }
100 return value;
101}
102
103static size_t CountNumberOfInstructions(HGraph* graph) {
104 size_t number_of_instructions = 0;
105 for (HBasicBlock* block : graph->GetReversePostOrderSkipEntryBlock()) {
106 for (HInstructionIterator instr_it(block->GetInstructions());
107 !instr_it.Done();
108 instr_it.Advance()) {
109 ++number_of_instructions;
110 }
111 }
112 return number_of_instructions;
113}
114
115void HInliner::UpdateInliningBudget() {
116 if (total_number_of_instructions_ >= kMaximumNumberOfTotalInstructions) {
117 // Always try to inline small methods.
118 inlining_budget_ = kMaximumNumberOfInstructionsForSmallMethod;
119 } else {
120 inlining_budget_ = std::max(
121 kMaximumNumberOfInstructionsForSmallMethod,
122 kMaximumNumberOfTotalInstructions - total_number_of_instructions_);
123 }
124}
125
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000126void HInliner::Run() {
Nicolas Geoffraye50b8d22015-03-13 08:57:42 +0000127 if (graph_->IsDebuggable()) {
128 // For simplicity, we currently never inline when the graph is debuggable. This avoids
129 // doing some logic in the runtime to discover if a method could have been inlined.
130 return;
131 }
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000132
133 // Initialize the number of instructions for the method being compiled. Recursive calls
134 // to HInliner::Run have already updated the instruction count.
135 if (outermost_graph_ == graph_) {
136 total_number_of_instructions_ = CountNumberOfInstructions(graph_);
137 }
138
139 UpdateInliningBudget();
140 DCHECK_NE(total_number_of_instructions_, 0u);
141 DCHECK_NE(inlining_budget_, 0u);
142
Roland Levillain6c3af162017-04-27 11:18:56 +0100143 // If we're compiling with a core image (which is only used for
144 // test purposes), honor inlining directives in method names:
145 // - if a method's name contains the substring "$inline$", ensure
146 // that this method is actually inlined;
147 // - if a method's name contains the substring "$noinline$", do not
148 // inline that method.
149 const bool honor_inlining_directives = IsCompilingWithCoreImage();
150
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +0000151 // Keep a copy of all blocks when starting the visit.
152 ArenaVector<HBasicBlock*> blocks = graph_->GetReversePostOrder();
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100153 DCHECK(!blocks.empty());
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +0000154 // Because we are changing the graph when inlining,
155 // we just iterate over the blocks of the outer method.
156 // This avoids doing the inlining work again on the inlined blocks.
157 for (HBasicBlock* block : blocks) {
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +0000158 for (HInstruction* instruction = block->GetFirstInstruction(); instruction != nullptr;) {
159 HInstruction* next = instruction->GetNext();
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100160 HInvoke* call = instruction->AsInvoke();
Razvan A Lupusoru3e90a962015-03-27 13:44:44 -0700161 // As long as the call is not intrinsified, it is worth trying to inline.
162 if (call != nullptr && call->GetIntrinsic() == Intrinsics::kNone) {
Roland Levillain6c3af162017-04-27 11:18:56 +0100163 if (honor_inlining_directives) {
Nicolas Geoffrayb703d182017-02-14 18:05:28 +0000164 // Debugging case: directives in method names control or assert on inlining.
165 std::string callee_name = outer_compilation_unit_.GetDexFile()->PrettyMethod(
166 call->GetDexMethodIndex(), /* with_signature */ false);
167 // Tests prevent inlining by having $noinline$ in their method names.
168 if (callee_name.find("$noinline$") == std::string::npos) {
169 if (!TryInline(call)) {
170 bool should_have_inlined = (callee_name.find("$inline$") != std::string::npos);
171 CHECK(!should_have_inlined) << "Could not inline " << callee_name;
172 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000173 }
Guillaume "Vermeille" Sancheze918d382015-06-03 15:32:41 +0100174 } else {
Nicolas Geoffrayb703d182017-02-14 18:05:28 +0000175 // Normal case: try to inline.
176 TryInline(call);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000177 }
178 }
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +0000179 instruction = next;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000180 }
181 }
182}
183
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100184static bool IsMethodOrDeclaringClassFinal(ArtMethod* method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700185 REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100186 return method->IsFinal() || method->GetDeclaringClass()->IsFinal();
187}
188
189/**
190 * Given the `resolved_method` looked up in the dex cache, try to find
191 * the actual runtime target of an interface or virtual call.
192 * Return nullptr if the runtime target cannot be proven.
193 */
194static ArtMethod* FindVirtualOrInterfaceTarget(HInvoke* invoke, ArtMethod* resolved_method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700195 REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100196 if (IsMethodOrDeclaringClassFinal(resolved_method)) {
197 // No need to lookup further, the resolved method will be the target.
198 return resolved_method;
199 }
200
201 HInstruction* receiver = invoke->InputAt(0);
202 if (receiver->IsNullCheck()) {
203 // Due to multiple levels of inlining within the same pass, it might be that
204 // null check does not have the reference type of the actual receiver.
205 receiver = receiver->InputAt(0);
206 }
207 ReferenceTypeInfo info = receiver->GetReferenceTypeInfo();
Calin Juravle2e768302015-07-28 14:41:11 +0000208 DCHECK(info.IsValid()) << "Invalid RTI for " << receiver->DebugName();
209 if (!info.IsExact()) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100210 // We currently only support inlining with known receivers.
211 // TODO: Remove this check, we should be able to inline final methods
212 // on unknown receivers.
213 return nullptr;
214 } else if (info.GetTypeHandle()->IsInterface()) {
215 // Statically knowing that the receiver has an interface type cannot
216 // help us find what is the target method.
217 return nullptr;
218 } else if (!resolved_method->GetDeclaringClass()->IsAssignableFrom(info.GetTypeHandle().Get())) {
219 // The method that we're trying to call is not in the receiver's class or super classes.
220 return nullptr;
Nicolas Geoffrayab5327d2016-03-18 11:36:20 +0000221 } else if (info.GetTypeHandle()->IsErroneous()) {
222 // If the type is erroneous, do not go further, as we are going to query the vtable or
223 // imt table, that we can only safely do on non-erroneous classes.
224 return nullptr;
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100225 }
226
227 ClassLinker* cl = Runtime::Current()->GetClassLinker();
Andreas Gampe542451c2016-07-26 09:02:02 -0700228 PointerSize pointer_size = cl->GetImagePointerSize();
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100229 if (invoke->IsInvokeInterface()) {
230 resolved_method = info.GetTypeHandle()->FindVirtualMethodForInterface(
231 resolved_method, pointer_size);
232 } else {
233 DCHECK(invoke->IsInvokeVirtual());
234 resolved_method = info.GetTypeHandle()->FindVirtualMethodForVirtual(
235 resolved_method, pointer_size);
236 }
237
238 if (resolved_method == nullptr) {
239 // The information we had on the receiver was not enough to find
240 // the target method. Since we check above the exact type of the receiver,
241 // the only reason this can happen is an IncompatibleClassChangeError.
242 return nullptr;
Alex Light9139e002015-10-09 15:59:48 -0700243 } else if (!resolved_method->IsInvokable()) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100244 // The information we had on the receiver was not enough to find
245 // the target method. Since we check above the exact type of the receiver,
246 // the only reason this can happen is an IncompatibleClassChangeError.
247 return nullptr;
248 } else if (IsMethodOrDeclaringClassFinal(resolved_method)) {
249 // A final method has to be the target method.
250 return resolved_method;
251 } else if (info.IsExact()) {
252 // If we found a method and the receiver's concrete type is statically
253 // known, we know for sure the target.
254 return resolved_method;
255 } else {
256 // Even if we did find a method, the receiver type was not enough to
257 // statically find the runtime target.
258 return nullptr;
259 }
260}
261
262static uint32_t FindMethodIndexIn(ArtMethod* method,
263 const DexFile& dex_file,
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +0000264 uint32_t name_and_signature_index)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700265 REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100266 if (IsSameDexFile(*method->GetDexFile(), dex_file)) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100267 return method->GetDexMethodIndex();
268 } else {
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +0000269 return method->FindDexMethodIndexInOtherDexFile(dex_file, name_and_signature_index);
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100270 }
271}
272
Andreas Gampea5b09a62016-11-17 15:21:22 -0800273static dex::TypeIndex FindClassIndexIn(mirror::Class* cls,
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000274 const DexCompilationUnit& compilation_unit)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700275 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000276 const DexFile& dex_file = *compilation_unit.GetDexFile();
Andreas Gampea5b09a62016-11-17 15:21:22 -0800277 dex::TypeIndex index;
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100278 if (cls->GetDexCache() == nullptr) {
David Sehr709b0702016-10-13 09:12:37 -0700279 DCHECK(cls->IsArrayClass()) << cls->PrettyClass();
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000280 index = cls->FindTypeIndexInOtherDexFile(dex_file);
Andreas Gampea5b09a62016-11-17 15:21:22 -0800281 } else if (!cls->GetDexTypeIndex().IsValid()) {
David Sehr709b0702016-10-13 09:12:37 -0700282 DCHECK(cls->IsProxyClass()) << cls->PrettyClass();
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100283 // TODO: deal with proxy classes.
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100284 } else if (IsSameDexFile(cls->GetDexFile(), dex_file)) {
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000285 DCHECK_EQ(cls->GetDexCache(), compilation_unit.GetDexCache().Get());
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000286 index = cls->GetDexTypeIndex();
Nicolas Geoffray491617a2016-07-19 17:06:23 +0100287 } else {
288 index = cls->FindTypeIndexInOtherDexFile(dex_file);
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000289 // We cannot guarantee the entry will resolve to the same class,
Nicolas Geoffray491617a2016-07-19 17:06:23 +0100290 // as there may be different class loaders. So only return the index if it's
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000291 // the right class already resolved with the class loader.
292 if (index.IsValid()) {
293 ObjPtr<mirror::Class> resolved = ClassLinker::LookupResolvedType(
294 index, compilation_unit.GetDexCache().Get(), compilation_unit.GetClassLoader().Get());
295 if (resolved != cls) {
296 index = dex::TypeIndex::Invalid();
297 }
Nicolas Geoffray491617a2016-07-19 17:06:23 +0100298 }
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100299 }
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000300
301 return index;
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100302}
303
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000304class ScopedProfilingInfoInlineUse {
305 public:
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000306 explicit ScopedProfilingInfoInlineUse(ArtMethod* method, Thread* self)
307 : method_(method),
308 self_(self),
309 // Fetch the profiling info ahead of using it. If it's null when fetching,
310 // we should not call JitCodeCache::DoneInlining.
311 profiling_info_(
312 Runtime::Current()->GetJit()->GetCodeCache()->NotifyCompilerUse(method, self)) {
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000313 }
314
315 ~ScopedProfilingInfoInlineUse() {
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000316 if (profiling_info_ != nullptr) {
Andreas Gampe542451c2016-07-26 09:02:02 -0700317 PointerSize pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000318 DCHECK_EQ(profiling_info_, method_->GetProfilingInfo(pointer_size));
319 Runtime::Current()->GetJit()->GetCodeCache()->DoneCompilerUse(method_, self_);
320 }
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000321 }
322
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000323 ProfilingInfo* GetProfilingInfo() const { return profiling_info_; }
324
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000325 private:
326 ArtMethod* const method_;
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000327 Thread* const self_;
328 ProfilingInfo* const profiling_info_;
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000329};
330
Calin Juravle13439f02017-02-21 01:17:21 -0800331HInliner::InlineCacheType HInliner::GetInlineCacheType(
332 const Handle<mirror::ObjectArray<mirror::Class>>& classes)
333 REQUIRES_SHARED(Locks::mutator_lock_) {
334 uint8_t number_of_types = 0;
335 for (; number_of_types < InlineCache::kIndividualCacheSize; ++number_of_types) {
336 if (classes->Get(number_of_types) == nullptr) {
337 break;
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000338 }
339 }
Calin Juravle13439f02017-02-21 01:17:21 -0800340
341 if (number_of_types == 0) {
342 return kInlineCacheUninitialized;
343 } else if (number_of_types == 1) {
344 return kInlineCacheMonomorphic;
345 } else if (number_of_types == InlineCache::kIndividualCacheSize) {
346 return kInlineCacheMegamorphic;
347 } else {
348 return kInlineCachePolymorphic;
349 }
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000350}
351
352static mirror::Class* GetMonomorphicType(Handle<mirror::ObjectArray<mirror::Class>> classes)
353 REQUIRES_SHARED(Locks::mutator_lock_) {
354 DCHECK(classes->Get(0) != nullptr);
355 return classes->Get(0);
356}
357
Mingyao Yang063fc772016-08-02 11:02:54 -0700358ArtMethod* HInliner::TryCHADevirtualization(ArtMethod* resolved_method) {
359 if (!resolved_method->HasSingleImplementation()) {
360 return nullptr;
361 }
362 if (Runtime::Current()->IsAotCompiler()) {
363 // No CHA-based devirtulization for AOT compiler (yet).
364 return nullptr;
365 }
366 if (outermost_graph_->IsCompilingOsr()) {
367 // We do not support HDeoptimize in OSR methods.
368 return nullptr;
369 }
Mingyao Yange8fcd012017-01-20 10:43:30 -0800370 PointerSize pointer_size = caller_compilation_unit_.GetClassLinker()->GetImagePointerSize();
Nicolas Geoffray18ea1c92017-03-27 08:00:18 +0000371 ArtMethod* single_impl = resolved_method->GetSingleImplementation(pointer_size);
372 if (single_impl == nullptr) {
373 return nullptr;
374 }
375 if (single_impl->IsProxyMethod()) {
376 // Proxy method is a generic invoker that's not worth
377 // devirtualizing/inlining. It also causes issues when the proxy
378 // method is in another dex file if we try to rewrite invoke-interface to
379 // invoke-virtual because a proxy method doesn't have a real dex file.
380 return nullptr;
381 }
Nicolas Geoffray8e33e842017-04-03 16:55:16 +0100382 if (!single_impl->GetDeclaringClass()->IsResolved()) {
383 // There's a race with the class loading, which updates the CHA info
384 // before setting the class to resolved. So we just bail for this
385 // rare occurence.
386 return nullptr;
387 }
Nicolas Geoffray18ea1c92017-03-27 08:00:18 +0000388 return single_impl;
Mingyao Yang063fc772016-08-02 11:02:54 -0700389}
390
Nicolas Geoffraye418dda2015-08-11 20:03:09 -0700391bool HInliner::TryInline(HInvoke* invoke_instruction) {
Orion Hodsonac141392017-01-13 11:53:47 +0000392 if (invoke_instruction->IsInvokeUnresolved() ||
393 invoke_instruction->IsInvokePolymorphic()) {
394 return false; // Don't bother to move further if we know the method is unresolved or an
395 // invoke-polymorphic.
Calin Juravle175dc732015-08-25 15:42:32 +0100396 }
397
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000398 ScopedObjectAccess soa(Thread::Current());
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +0100399 uint32_t method_index = invoke_instruction->GetDexMethodIndex();
Nicolas Geoffray9437b782015-03-25 10:08:51 +0000400 const DexFile& caller_dex_file = *caller_compilation_unit_.GetDexFile();
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000401 LOG_TRY() << caller_dex_file.PrettyMethod(method_index);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000402
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +0100403 ArtMethod* resolved_method = invoke_instruction->GetResolvedMethod();
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +0100404 if (resolved_method == nullptr) {
405 DCHECK(invoke_instruction->IsInvokeStaticOrDirect());
406 DCHECK(invoke_instruction->AsInvokeStaticOrDirect()->IsStringInit());
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000407 LOG_FAIL_NO_STAT() << "Not inlining a String.<init> method";
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +0100408 return false;
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000409 }
410 ArtMethod* actual_method = nullptr;
411
412 if (invoke_instruction->IsInvokeStaticOrDirect()) {
Andreas Gampefd2140f2015-12-23 16:30:44 -0800413 actual_method = resolved_method;
Vladimir Marko58155012015-08-19 12:49:41 +0000414 } else {
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +0100415 // Check if we can statically find the method.
416 actual_method = FindVirtualOrInterfaceTarget(invoke_instruction, resolved_method);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000417 }
418
Mingyao Yang063fc772016-08-02 11:02:54 -0700419 bool cha_devirtualize = false;
420 if (actual_method == nullptr) {
421 ArtMethod* method = TryCHADevirtualization(resolved_method);
422 if (method != nullptr) {
423 cha_devirtualize = true;
424 actual_method = method;
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000425 LOG_NOTE() << "Try CHA-based inlining of " << actual_method->PrettyMethod();
Mingyao Yang063fc772016-08-02 11:02:54 -0700426 }
427 }
428
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100429 if (actual_method != nullptr) {
Mingyao Yang063fc772016-08-02 11:02:54 -0700430 bool result = TryInlineAndReplace(invoke_instruction,
431 actual_method,
Nicolas Geoffray0f001b72017-01-04 16:46:23 +0000432 ReferenceTypeInfo::CreateInvalid(),
Mingyao Yang063fc772016-08-02 11:02:54 -0700433 /* do_rtp */ true,
434 cha_devirtualize);
Calin Juravle69158982016-03-16 11:53:41 +0000435 if (result && !invoke_instruction->IsInvokeStaticOrDirect()) {
Mingyao Yang063fc772016-08-02 11:02:54 -0700436 if (cha_devirtualize) {
437 // Add dependency due to devirtulization. We've assumed resolved_method
438 // has single implementation.
439 outermost_graph_->AddCHASingleImplementationDependency(resolved_method);
440 MaybeRecordStat(kCHAInline);
441 } else {
442 MaybeRecordStat(kInlinedInvokeVirtualOrInterface);
443 }
Calin Juravle69158982016-03-16 11:53:41 +0000444 }
445 return result;
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100446 }
Andreas Gampefd2140f2015-12-23 16:30:44 -0800447 DCHECK(!invoke_instruction->IsInvokeStaticOrDirect());
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100448
Calin Juravle13439f02017-02-21 01:17:21 -0800449 // Try using inline caches.
450 return TryInlineFromInlineCache(caller_dex_file, invoke_instruction, resolved_method);
451}
452
453static Handle<mirror::ObjectArray<mirror::Class>> AllocateInlineCacheHolder(
454 const DexCompilationUnit& compilation_unit,
455 StackHandleScope<1>* hs)
456 REQUIRES_SHARED(Locks::mutator_lock_) {
457 Thread* self = Thread::Current();
458 ClassLinker* class_linker = compilation_unit.GetClassLinker();
459 Handle<mirror::ObjectArray<mirror::Class>> inline_cache = hs->NewHandle(
460 mirror::ObjectArray<mirror::Class>::Alloc(
461 self,
462 class_linker->GetClassRoot(ClassLinker::kClassArrayClass),
463 InlineCache::kIndividualCacheSize));
464 if (inline_cache == nullptr) {
465 // We got an OOME. Just clear the exception, and don't inline.
466 DCHECK(self->IsExceptionPending());
467 self->ClearException();
468 VLOG(compiler) << "Out of memory in the compiler when trying to inline";
469 }
470 return inline_cache;
471}
472
Calin Juravleaf44e6c2017-05-23 14:24:55 -0700473bool HInliner::UseOnlyPolymorphicInliningWithNoDeopt() {
474 // If we are compiling AOT or OSR, pretend the call using inline caches is polymorphic and
475 // do not generate a deopt.
476 //
477 // For AOT:
478 // Generating a deopt does not ensure that we will actually capture the new types;
479 // and the danger is that we could be stuck in a loop with "forever" deoptimizations.
480 // Take for example the following scenario:
481 // - we capture the inline cache in one run
482 // - the next run, we deoptimize because we miss a type check, but the method
483 // never becomes hot again
484 // In this case, the inline cache will not be updated in the profile and the AOT code
485 // will keep deoptimizing.
486 // Another scenario is if we use profile compilation for a process which is not allowed
487 // to JIT (e.g. system server). If we deoptimize we will run interpreted code for the
488 // rest of the lifetime.
489 // TODO(calin):
490 // This is a compromise because we will most likely never update the inline cache
491 // in the profile (unless there's another reason to deopt). So we might be stuck with
492 // a sub-optimal inline cache.
493 // We could be smarter when capturing inline caches to mitigate this.
494 // (e.g. by having different thresholds for new and old methods).
495 //
496 // For OSR:
497 // We may come from the interpreter and it may have seen different receiver types.
498 return Runtime::Current()->IsAotCompiler() || outermost_graph_->IsCompilingOsr();
499}
Calin Juravle13439f02017-02-21 01:17:21 -0800500bool HInliner::TryInlineFromInlineCache(const DexFile& caller_dex_file,
501 HInvoke* invoke_instruction,
502 ArtMethod* resolved_method)
503 REQUIRES_SHARED(Locks::mutator_lock_) {
Calin Juravlee2492d42017-03-20 11:42:13 -0700504 if (Runtime::Current()->IsAotCompiler() && !kUseAOTInlineCaches) {
505 return false;
506 }
507
Calin Juravle13439f02017-02-21 01:17:21 -0800508 StackHandleScope<1> hs(Thread::Current());
509 Handle<mirror::ObjectArray<mirror::Class>> inline_cache;
510 InlineCacheType inline_cache_type = Runtime::Current()->IsAotCompiler()
511 ? GetInlineCacheAOT(caller_dex_file, invoke_instruction, &hs, &inline_cache)
512 : GetInlineCacheJIT(invoke_instruction, &hs, &inline_cache);
513
514 switch (inline_cache_type) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000515 case kInlineCacheNoData: {
516 LOG_FAIL_NO_STAT()
517 << "Interface or virtual call to "
518 << caller_dex_file.PrettyMethod(invoke_instruction->GetDexMethodIndex())
519 << " could not be statically determined";
Calin Juravle13439f02017-02-21 01:17:21 -0800520 return false;
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000521 }
Calin Juravle13439f02017-02-21 01:17:21 -0800522
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000523 case kInlineCacheUninitialized: {
524 LOG_FAIL_NO_STAT()
525 << "Interface or virtual call to "
526 << caller_dex_file.PrettyMethod(invoke_instruction->GetDexMethodIndex())
527 << " is not hit and not inlined";
528 return false;
529 }
530
531 case kInlineCacheMonomorphic: {
Calin Juravle13439f02017-02-21 01:17:21 -0800532 MaybeRecordStat(kMonomorphicCall);
Calin Juravleaf44e6c2017-05-23 14:24:55 -0700533 if (UseOnlyPolymorphicInliningWithNoDeopt()) {
Calin Juravle13439f02017-02-21 01:17:21 -0800534 return TryInlinePolymorphicCall(invoke_instruction, resolved_method, inline_cache);
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000535 } else {
Calin Juravle13439f02017-02-21 01:17:21 -0800536 return TryInlineMonomorphicCall(invoke_instruction, resolved_method, inline_cache);
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000537 }
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000538 }
Calin Juravle13439f02017-02-21 01:17:21 -0800539
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000540 case kInlineCachePolymorphic: {
Calin Juravle13439f02017-02-21 01:17:21 -0800541 MaybeRecordStat(kPolymorphicCall);
542 return TryInlinePolymorphicCall(invoke_instruction, resolved_method, inline_cache);
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000543 }
Calin Juravle13439f02017-02-21 01:17:21 -0800544
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000545 case kInlineCacheMegamorphic: {
546 LOG_FAIL_NO_STAT()
547 << "Interface or virtual call to "
548 << caller_dex_file.PrettyMethod(invoke_instruction->GetDexMethodIndex())
549 << " is megamorphic and not inlined";
Calin Juravle13439f02017-02-21 01:17:21 -0800550 MaybeRecordStat(kMegamorphicCall);
551 return false;
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000552 }
Calin Juravle13439f02017-02-21 01:17:21 -0800553
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000554 case kInlineCacheMissingTypes: {
555 LOG_FAIL_NO_STAT()
556 << "Interface or virtual call to "
557 << caller_dex_file.PrettyMethod(invoke_instruction->GetDexMethodIndex())
558 << " is missing types and not inlined";
Calin Juravle13439f02017-02-21 01:17:21 -0800559 return false;
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000560 }
Calin Juravle13439f02017-02-21 01:17:21 -0800561 }
562 UNREACHABLE();
563}
564
565HInliner::InlineCacheType HInliner::GetInlineCacheJIT(
566 HInvoke* invoke_instruction,
567 StackHandleScope<1>* hs,
568 /*out*/Handle<mirror::ObjectArray<mirror::Class>>* inline_cache)
569 REQUIRES_SHARED(Locks::mutator_lock_) {
570 DCHECK(Runtime::Current()->UseJitCompilation());
571
572 ArtMethod* caller = graph_->GetArtMethod();
573 // Under JIT, we should always know the caller.
574 DCHECK(caller != nullptr);
575 ScopedProfilingInfoInlineUse spiis(caller, Thread::Current());
576 ProfilingInfo* profiling_info = spiis.GetProfilingInfo();
577
578 if (profiling_info == nullptr) {
579 return kInlineCacheNoData;
580 }
581
582 *inline_cache = AllocateInlineCacheHolder(caller_compilation_unit_, hs);
583 if (inline_cache->Get() == nullptr) {
584 // We can't extract any data if we failed to allocate;
585 return kInlineCacheNoData;
586 } else {
587 Runtime::Current()->GetJit()->GetCodeCache()->CopyInlineCacheInto(
588 *profiling_info->GetInlineCache(invoke_instruction->GetDexPc()),
589 *inline_cache);
590 return GetInlineCacheType(*inline_cache);
591 }
592}
593
594HInliner::InlineCacheType HInliner::GetInlineCacheAOT(
595 const DexFile& caller_dex_file,
596 HInvoke* invoke_instruction,
597 StackHandleScope<1>* hs,
598 /*out*/Handle<mirror::ObjectArray<mirror::Class>>* inline_cache)
599 REQUIRES_SHARED(Locks::mutator_lock_) {
600 DCHECK(Runtime::Current()->IsAotCompiler());
601 const ProfileCompilationInfo* pci = compiler_driver_->GetProfileCompilationInfo();
602 if (pci == nullptr) {
603 return kInlineCacheNoData;
604 }
605
Calin Juravlecc3171a2017-05-19 16:47:53 -0700606 std::unique_ptr<ProfileCompilationInfo::OfflineProfileMethodInfo> offline_profile =
607 pci->GetMethod(caller_dex_file.GetLocation(),
608 caller_dex_file.GetLocationChecksum(),
609 caller_compilation_unit_.GetDexMethodIndex());
610 if (offline_profile == nullptr) {
Calin Juravle13439f02017-02-21 01:17:21 -0800611 return kInlineCacheNoData; // no profile information for this invocation.
612 }
613
614 *inline_cache = AllocateInlineCacheHolder(caller_compilation_unit_, hs);
615 if (inline_cache == nullptr) {
616 // We can't extract any data if we failed to allocate;
617 return kInlineCacheNoData;
618 } else {
619 return ExtractClassesFromOfflineProfile(invoke_instruction,
Calin Juravlecc3171a2017-05-19 16:47:53 -0700620 *(offline_profile.get()),
Calin Juravle13439f02017-02-21 01:17:21 -0800621 *inline_cache);
622 }
623}
624
625HInliner::InlineCacheType HInliner::ExtractClassesFromOfflineProfile(
626 const HInvoke* invoke_instruction,
627 const ProfileCompilationInfo::OfflineProfileMethodInfo& offline_profile,
628 /*out*/Handle<mirror::ObjectArray<mirror::Class>> inline_cache)
629 REQUIRES_SHARED(Locks::mutator_lock_) {
Calin Juravlee6f87cc2017-05-24 17:41:05 -0700630 const auto it = offline_profile.inline_caches->find(invoke_instruction->GetDexPc());
631 if (it == offline_profile.inline_caches->end()) {
Calin Juravle13439f02017-02-21 01:17:21 -0800632 return kInlineCacheUninitialized;
633 }
634
635 const ProfileCompilationInfo::DexPcData& dex_pc_data = it->second;
636
637 if (dex_pc_data.is_missing_types) {
638 return kInlineCacheMissingTypes;
639 }
640 if (dex_pc_data.is_megamorphic) {
641 return kInlineCacheMegamorphic;
642 }
643
644 DCHECK_LE(dex_pc_data.classes.size(), InlineCache::kIndividualCacheSize);
645 Thread* self = Thread::Current();
646 // We need to resolve the class relative to the containing dex file.
647 // So first, build a mapping from the index of dex file in the profile to
648 // its dex cache. This will avoid repeating the lookup when walking over
649 // the inline cache types.
650 std::vector<ObjPtr<mirror::DexCache>> dex_profile_index_to_dex_cache(
651 offline_profile.dex_references.size());
652 for (size_t i = 0; i < offline_profile.dex_references.size(); i++) {
653 bool found = false;
654 for (const DexFile* dex_file : compiler_driver_->GetDexFilesForOatFile()) {
655 if (offline_profile.dex_references[i].MatchesDex(dex_file)) {
656 dex_profile_index_to_dex_cache[i] =
657 caller_compilation_unit_.GetClassLinker()->FindDexCache(self, *dex_file);
658 found = true;
659 }
660 }
661 if (!found) {
662 VLOG(compiler) << "Could not find profiled dex file: "
663 << offline_profile.dex_references[i].dex_location;
664 return kInlineCacheMissingTypes;
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100665 }
666 }
667
Calin Juravle13439f02017-02-21 01:17:21 -0800668 // Walk over the classes and resolve them. If we cannot find a type we return
669 // kInlineCacheMissingTypes.
670 int ic_index = 0;
671 for (const ProfileCompilationInfo::ClassReference& class_ref : dex_pc_data.classes) {
672 ObjPtr<mirror::DexCache> dex_cache =
673 dex_profile_index_to_dex_cache[class_ref.dex_profile_index];
674 DCHECK(dex_cache != nullptr);
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000675 ObjPtr<mirror::Class> clazz = ClassLinker::LookupResolvedType(
676 class_ref.type_index,
677 dex_cache,
678 caller_compilation_unit_.GetClassLoader().Get());
Calin Juravle13439f02017-02-21 01:17:21 -0800679 if (clazz != nullptr) {
680 inline_cache->Set(ic_index++, clazz);
681 } else {
682 VLOG(compiler) << "Could not resolve class from inline cache in AOT mode "
683 << caller_compilation_unit_.GetDexFile()->PrettyMethod(
684 invoke_instruction->GetDexMethodIndex()) << " : "
685 << caller_compilation_unit_
686 .GetDexFile()->StringByTypeIdx(class_ref.type_index);
687 return kInlineCacheMissingTypes;
688 }
689 }
690 return GetInlineCacheType(inline_cache);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100691}
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000692
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000693HInstanceFieldGet* HInliner::BuildGetReceiverClass(ClassLinker* class_linker,
694 HInstruction* receiver,
695 uint32_t dex_pc) const {
696 ArtField* field = class_linker->GetClassRoot(ClassLinker::kJavaLangObject)->GetInstanceField(0);
697 DCHECK_EQ(std::string(field->GetName()), "shadow$_klass_");
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000698 HInstanceFieldGet* result = new (graph_->GetArena()) HInstanceFieldGet(
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000699 receiver,
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +0000700 field,
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000701 Primitive::kPrimNot,
702 field->GetOffset(),
703 field->IsVolatile(),
704 field->GetDexFieldIndex(),
705 field->GetDeclaringClass()->GetDexClassDefIndex(),
706 *field->GetDexFile(),
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000707 dex_pc);
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000708 // The class of a field is effectively final, and does not have any memory dependencies.
709 result->SetSideEffects(SideEffects::None());
710 return result;
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000711}
712
Nicolas Geoffray4c0b4bc2017-03-17 13:08:26 +0000713static ArtMethod* ResolveMethodFromInlineCache(Handle<mirror::Class> klass,
714 ArtMethod* resolved_method,
715 HInstruction* invoke_instruction,
716 PointerSize pointer_size)
717 REQUIRES_SHARED(Locks::mutator_lock_) {
718 if (Runtime::Current()->IsAotCompiler()) {
719 // We can get unrelated types when working with profiles (corruption,
720 // systme updates, or anyone can write to it). So first check if the class
721 // actually implements the declaring class of the method that is being
722 // called in bytecode.
723 // Note: the lookup methods used below require to have assignable types.
724 if (!resolved_method->GetDeclaringClass()->IsAssignableFrom(klass.Get())) {
725 return nullptr;
726 }
727 }
728
729 if (invoke_instruction->IsInvokeInterface()) {
730 resolved_method = klass->FindVirtualMethodForInterface(resolved_method, pointer_size);
731 } else {
732 DCHECK(invoke_instruction->IsInvokeVirtual());
733 resolved_method = klass->FindVirtualMethodForVirtual(resolved_method, pointer_size);
734 }
735 DCHECK(resolved_method != nullptr);
736 return resolved_method;
737}
738
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100739bool HInliner::TryInlineMonomorphicCall(HInvoke* invoke_instruction,
740 ArtMethod* resolved_method,
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000741 Handle<mirror::ObjectArray<mirror::Class>> classes) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000742 DCHECK(invoke_instruction->IsInvokeVirtual() || invoke_instruction->IsInvokeInterface())
743 << invoke_instruction->DebugName();
744
Andreas Gampea5b09a62016-11-17 15:21:22 -0800745 dex::TypeIndex class_index = FindClassIndexIn(
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000746 GetMonomorphicType(classes), caller_compilation_unit_);
Andreas Gampea5b09a62016-11-17 15:21:22 -0800747 if (!class_index.IsValid()) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000748 LOG_FAIL(kNotInlinedDexCache)
749 << "Call to " << ArtMethod::PrettyMethod(resolved_method)
750 << " from inline cache is not inlined because its class is not"
751 << " accessible to the caller";
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100752 return false;
753 }
754
755 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
Andreas Gampe542451c2016-07-26 09:02:02 -0700756 PointerSize pointer_size = class_linker->GetImagePointerSize();
Nicolas Geoffray4c0b4bc2017-03-17 13:08:26 +0000757 Handle<mirror::Class> monomorphic_type = handles_->NewHandle(GetMonomorphicType(classes));
758 resolved_method = ResolveMethodFromInlineCache(
759 monomorphic_type, resolved_method, invoke_instruction, pointer_size);
760
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000761 LOG_NOTE() << "Try inline monomorphic call to " << resolved_method->PrettyMethod();
Nicolas Geoffray4c0b4bc2017-03-17 13:08:26 +0000762 if (resolved_method == nullptr) {
763 // Bogus AOT profile, bail.
764 DCHECK(Runtime::Current()->IsAotCompiler());
765 return false;
766 }
767
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100768 HInstruction* receiver = invoke_instruction->InputAt(0);
769 HInstruction* cursor = invoke_instruction->GetPrevious();
770 HBasicBlock* bb_cursor = invoke_instruction->GetBlock();
Mingyao Yang063fc772016-08-02 11:02:54 -0700771 if (!TryInlineAndReplace(invoke_instruction,
772 resolved_method,
Nicolas Geoffray5247c082017-01-13 14:17:29 +0000773 ReferenceTypeInfo::Create(monomorphic_type, /* is_exact */ true),
Mingyao Yang063fc772016-08-02 11:02:54 -0700774 /* do_rtp */ false,
775 /* cha_devirtualize */ false)) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100776 return false;
777 }
778
779 // We successfully inlined, now add a guard.
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000780 AddTypeGuard(receiver,
781 cursor,
782 bb_cursor,
783 class_index,
Nicolas Geoffray5247c082017-01-13 14:17:29 +0000784 monomorphic_type,
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000785 invoke_instruction,
786 /* with_deoptimization */ true);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100787
788 // Run type propagation to get the guard typed, and eventually propagate the
789 // type of the receiver.
Vladimir Marko456307a2016-04-19 14:12:13 +0000790 ReferenceTypePropagation rtp_fixup(graph_,
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000791 outer_compilation_unit_.GetClassLoader(),
Vladimir Marko456307a2016-04-19 14:12:13 +0000792 outer_compilation_unit_.GetDexCache(),
793 handles_,
794 /* is_first_run */ false);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100795 rtp_fixup.Run();
796
797 MaybeRecordStat(kInlinedMonomorphicCall);
798 return true;
799}
800
Mingyao Yang063fc772016-08-02 11:02:54 -0700801void HInliner::AddCHAGuard(HInstruction* invoke_instruction,
802 uint32_t dex_pc,
803 HInstruction* cursor,
804 HBasicBlock* bb_cursor) {
Mingyao Yangb0b051a2016-11-17 09:04:53 -0800805 HShouldDeoptimizeFlag* deopt_flag = new (graph_->GetArena())
806 HShouldDeoptimizeFlag(graph_->GetArena(), dex_pc);
807 HInstruction* compare = new (graph_->GetArena()) HNotEqual(
Mingyao Yang063fc772016-08-02 11:02:54 -0700808 deopt_flag, graph_->GetIntConstant(0, dex_pc));
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +0000809 HInstruction* deopt = new (graph_->GetArena()) HDeoptimize(
Nicolas Geoffray4e92c3c2017-05-08 09:34:26 +0100810 graph_->GetArena(), compare, DeoptimizationKind::kCHA, dex_pc);
Mingyao Yang063fc772016-08-02 11:02:54 -0700811
812 if (cursor != nullptr) {
813 bb_cursor->InsertInstructionAfter(deopt_flag, cursor);
814 } else {
815 bb_cursor->InsertInstructionBefore(deopt_flag, bb_cursor->GetFirstInstruction());
816 }
Mingyao Yangb0b051a2016-11-17 09:04:53 -0800817 bb_cursor->InsertInstructionAfter(compare, deopt_flag);
818 bb_cursor->InsertInstructionAfter(deopt, compare);
819
820 // Add receiver as input to aid CHA guard optimization later.
821 deopt_flag->AddInput(invoke_instruction->InputAt(0));
822 DCHECK_EQ(deopt_flag->InputCount(), 1u);
Mingyao Yang063fc772016-08-02 11:02:54 -0700823 deopt->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
Mingyao Yangb0b051a2016-11-17 09:04:53 -0800824 outermost_graph_->IncrementNumberOfCHAGuards();
Mingyao Yang063fc772016-08-02 11:02:54 -0700825}
826
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000827HInstruction* HInliner::AddTypeGuard(HInstruction* receiver,
828 HInstruction* cursor,
829 HBasicBlock* bb_cursor,
Andreas Gampea5b09a62016-11-17 15:21:22 -0800830 dex::TypeIndex class_index,
Nicolas Geoffray5247c082017-01-13 14:17:29 +0000831 Handle<mirror::Class> klass,
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000832 HInstruction* invoke_instruction,
833 bool with_deoptimization) {
834 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
835 HInstanceFieldGet* receiver_class = BuildGetReceiverClass(
836 class_linker, receiver, invoke_instruction->GetDexPc());
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000837 if (cursor != nullptr) {
838 bb_cursor->InsertInstructionAfter(receiver_class, cursor);
839 } else {
840 bb_cursor->InsertInstructionBefore(receiver_class, bb_cursor->GetFirstInstruction());
841 }
Nicolas Geoffray56876342016-12-16 16:09:08 +0000842
843 const DexFile& caller_dex_file = *caller_compilation_unit_.GetDexFile();
Calin Juravle07f01df2017-04-28 19:58:01 -0700844 bool is_referrer;
845 ArtMethod* outermost_art_method = outermost_graph_->GetArtMethod();
846 if (outermost_art_method == nullptr) {
847 DCHECK(Runtime::Current()->IsAotCompiler());
848 // We are in AOT mode and we don't have an ART method to determine
849 // if the inlined method belongs to the referrer. Assume it doesn't.
850 is_referrer = false;
851 } else {
852 is_referrer = klass.Get() == outermost_art_method->GetDeclaringClass();
853 }
854
Nicolas Geoffray56876342016-12-16 16:09:08 +0000855 // Note that we will just compare the classes, so we don't need Java semantics access checks.
856 // Note that the type index and the dex file are relative to the method this type guard is
857 // inlined into.
858 HLoadClass* load_class = new (graph_->GetArena()) HLoadClass(graph_->GetCurrentMethod(),
859 class_index,
860 caller_dex_file,
Nicolas Geoffray5247c082017-01-13 14:17:29 +0000861 klass,
Nicolas Geoffray56876342016-12-16 16:09:08 +0000862 is_referrer,
863 invoke_instruction->GetDexPc(),
864 /* needs_access_check */ false);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +0000865 HLoadClass::LoadKind kind = HSharpening::ComputeLoadClassKind(
Nicolas Geoffray83c8e272017-01-31 14:36:37 +0000866 load_class, codegen_, compiler_driver_, caller_compilation_unit_);
867 DCHECK(kind != HLoadClass::LoadKind::kInvalid)
868 << "We should always be able to reference a class for inline caches";
869 // Insert before setting the kind, as setting the kind affects the inputs.
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000870 bb_cursor->InsertInstructionAfter(load_class, receiver_class);
Nicolas Geoffray83c8e272017-01-31 14:36:37 +0000871 load_class->SetLoadKind(kind);
Calin Juravle13439f02017-02-21 01:17:21 -0800872 // In AOT mode, we will most likely load the class from BSS, which will involve a call
873 // to the runtime. In this case, the load instruction will need an environment so copy
874 // it from the invoke instruction.
875 if (load_class->NeedsEnvironment()) {
876 DCHECK(Runtime::Current()->IsAotCompiler());
877 load_class->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
878 }
Nicolas Geoffray56876342016-12-16 16:09:08 +0000879
Nicolas Geoffray56876342016-12-16 16:09:08 +0000880 HNotEqual* compare = new (graph_->GetArena()) HNotEqual(load_class, receiver_class);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000881 bb_cursor->InsertInstructionAfter(compare, load_class);
882 if (with_deoptimization) {
883 HDeoptimize* deoptimize = new (graph_->GetArena()) HDeoptimize(
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +0000884 graph_->GetArena(),
885 compare,
886 receiver,
Nicolas Geoffray4e92c3c2017-05-08 09:34:26 +0100887 Runtime::Current()->IsAotCompiler()
888 ? DeoptimizationKind::kAotInlineCache
889 : DeoptimizationKind::kJitInlineCache,
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +0000890 invoke_instruction->GetDexPc());
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000891 bb_cursor->InsertInstructionAfter(deoptimize, compare);
892 deoptimize->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +0000893 DCHECK_EQ(invoke_instruction->InputAt(0), receiver);
894 receiver->ReplaceUsesDominatedBy(deoptimize, deoptimize);
895 deoptimize->SetReferenceTypeInfo(receiver->GetReferenceTypeInfo());
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000896 }
897 return compare;
898}
899
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000900bool HInliner::TryInlinePolymorphicCall(HInvoke* invoke_instruction,
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100901 ArtMethod* resolved_method,
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000902 Handle<mirror::ObjectArray<mirror::Class>> classes) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000903 DCHECK(invoke_instruction->IsInvokeVirtual() || invoke_instruction->IsInvokeInterface())
904 << invoke_instruction->DebugName();
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000905
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000906 if (TryInlinePolymorphicCallToSameTarget(invoke_instruction, resolved_method, classes)) {
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000907 return true;
908 }
909
910 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
Andreas Gampe542451c2016-07-26 09:02:02 -0700911 PointerSize pointer_size = class_linker->GetImagePointerSize();
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000912
913 bool all_targets_inlined = true;
914 bool one_target_inlined = false;
915 for (size_t i = 0; i < InlineCache::kIndividualCacheSize; ++i) {
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000916 if (classes->Get(i) == nullptr) {
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000917 break;
918 }
919 ArtMethod* method = nullptr;
Nicolas Geoffray0f001b72017-01-04 16:46:23 +0000920
921 Handle<mirror::Class> handle = handles_->NewHandle(classes->Get(i));
Nicolas Geoffray4c0b4bc2017-03-17 13:08:26 +0000922 method = ResolveMethodFromInlineCache(
923 handle, resolved_method, invoke_instruction, pointer_size);
924 if (method == nullptr) {
925 DCHECK(Runtime::Current()->IsAotCompiler());
926 // AOT profile is bogus. This loop expects to iterate over all entries,
927 // so just just continue.
928 all_targets_inlined = false;
929 continue;
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000930 }
931
932 HInstruction* receiver = invoke_instruction->InputAt(0);
933 HInstruction* cursor = invoke_instruction->GetPrevious();
934 HBasicBlock* bb_cursor = invoke_instruction->GetBlock();
935
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000936 dex::TypeIndex class_index = FindClassIndexIn(handle.Get(), caller_compilation_unit_);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000937 HInstruction* return_replacement = nullptr;
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000938 LOG_NOTE() << "Try inline polymorphic call to " << method->PrettyMethod();
Andreas Gampea5b09a62016-11-17 15:21:22 -0800939 if (!class_index.IsValid() ||
Nicolas Geoffray0f001b72017-01-04 16:46:23 +0000940 !TryBuildAndInline(invoke_instruction,
941 method,
942 ReferenceTypeInfo::Create(handle, /* is_exact */ true),
943 &return_replacement)) {
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000944 all_targets_inlined = false;
945 } else {
946 one_target_inlined = true;
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000947
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000948 LOG_SUCCESS() << "Polymorphic call to " << ArtMethod::PrettyMethod(resolved_method)
949 << " has inlined " << ArtMethod::PrettyMethod(method);
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +0000950
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000951 // If we have inlined all targets before, and this receiver is the last seen,
952 // we deoptimize instead of keeping the original invoke instruction.
Calin Juravleaf44e6c2017-05-23 14:24:55 -0700953 bool deoptimize = !UseOnlyPolymorphicInliningWithNoDeopt() &&
954 all_targets_inlined &&
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000955 (i != InlineCache::kIndividualCacheSize - 1) &&
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000956 (classes->Get(i + 1) == nullptr);
Nicolas Geoffray93a18c52016-04-22 13:16:14 +0100957
Nicolas Geoffray56876342016-12-16 16:09:08 +0000958 HInstruction* compare = AddTypeGuard(receiver,
959 cursor,
960 bb_cursor,
961 class_index,
Nicolas Geoffray5247c082017-01-13 14:17:29 +0000962 handle,
Nicolas Geoffray56876342016-12-16 16:09:08 +0000963 invoke_instruction,
964 deoptimize);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000965 if (deoptimize) {
966 if (return_replacement != nullptr) {
967 invoke_instruction->ReplaceWith(return_replacement);
968 }
969 invoke_instruction->GetBlock()->RemoveInstruction(invoke_instruction);
970 // Because the inline cache data can be populated concurrently, we force the end of the
Nicolas Geoffray4c0b4bc2017-03-17 13:08:26 +0000971 // iteration. Otherwise, we could see a new receiver type.
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000972 break;
973 } else {
974 CreateDiamondPatternForPolymorphicInline(compare, return_replacement, invoke_instruction);
975 }
976 }
977 }
978
979 if (!one_target_inlined) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000980 LOG_FAIL_NO_STAT()
981 << "Call to " << ArtMethod::PrettyMethod(resolved_method)
982 << " from inline cache is not inlined because none"
983 << " of its targets could be inlined";
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000984 return false;
985 }
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +0000986
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000987 MaybeRecordStat(kInlinedPolymorphicCall);
988
989 // Run type propagation to get the guards typed.
Vladimir Marko456307a2016-04-19 14:12:13 +0000990 ReferenceTypePropagation rtp_fixup(graph_,
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000991 outer_compilation_unit_.GetClassLoader(),
Vladimir Marko456307a2016-04-19 14:12:13 +0000992 outer_compilation_unit_.GetDexCache(),
993 handles_,
994 /* is_first_run */ false);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000995 rtp_fixup.Run();
996 return true;
997}
998
999void HInliner::CreateDiamondPatternForPolymorphicInline(HInstruction* compare,
1000 HInstruction* return_replacement,
1001 HInstruction* invoke_instruction) {
1002 uint32_t dex_pc = invoke_instruction->GetDexPc();
1003 HBasicBlock* cursor_block = compare->GetBlock();
1004 HBasicBlock* original_invoke_block = invoke_instruction->GetBlock();
1005 ArenaAllocator* allocator = graph_->GetArena();
1006
1007 // Spit the block after the compare: `cursor_block` will now be the start of the diamond,
1008 // and the returned block is the start of the then branch (that could contain multiple blocks).
1009 HBasicBlock* then = cursor_block->SplitAfterForInlining(compare);
1010
1011 // Split the block containing the invoke before and after the invoke. The returned block
1012 // of the split before will contain the invoke and will be the otherwise branch of
1013 // the diamond. The returned block of the split after will be the merge block
1014 // of the diamond.
1015 HBasicBlock* end_then = invoke_instruction->GetBlock();
1016 HBasicBlock* otherwise = end_then->SplitBeforeForInlining(invoke_instruction);
1017 HBasicBlock* merge = otherwise->SplitAfterForInlining(invoke_instruction);
1018
1019 // If the methods we are inlining return a value, we create a phi in the merge block
1020 // that will have the `invoke_instruction and the `return_replacement` as inputs.
1021 if (return_replacement != nullptr) {
1022 HPhi* phi = new (allocator) HPhi(
1023 allocator, kNoRegNumber, 0, HPhi::ToPhiType(invoke_instruction->GetType()), dex_pc);
1024 merge->AddPhi(phi);
1025 invoke_instruction->ReplaceWith(phi);
1026 phi->AddInput(return_replacement);
1027 phi->AddInput(invoke_instruction);
1028 }
1029
1030 // Add the control flow instructions.
1031 otherwise->AddInstruction(new (allocator) HGoto(dex_pc));
1032 end_then->AddInstruction(new (allocator) HGoto(dex_pc));
1033 cursor_block->AddInstruction(new (allocator) HIf(compare, dex_pc));
1034
1035 // Add the newly created blocks to the graph.
1036 graph_->AddBlock(then);
1037 graph_->AddBlock(otherwise);
1038 graph_->AddBlock(merge);
1039
1040 // Set up successor (and implictly predecessor) relations.
1041 cursor_block->AddSuccessor(otherwise);
1042 cursor_block->AddSuccessor(then);
1043 end_then->AddSuccessor(merge);
1044 otherwise->AddSuccessor(merge);
1045
1046 // Set up dominance information.
1047 then->SetDominator(cursor_block);
1048 cursor_block->AddDominatedBlock(then);
1049 otherwise->SetDominator(cursor_block);
1050 cursor_block->AddDominatedBlock(otherwise);
1051 merge->SetDominator(cursor_block);
1052 cursor_block->AddDominatedBlock(merge);
1053
1054 // Update the revert post order.
1055 size_t index = IndexOfElement(graph_->reverse_post_order_, cursor_block);
1056 MakeRoomFor(&graph_->reverse_post_order_, 1, index);
1057 graph_->reverse_post_order_[++index] = then;
1058 index = IndexOfElement(graph_->reverse_post_order_, end_then);
1059 MakeRoomFor(&graph_->reverse_post_order_, 2, index);
1060 graph_->reverse_post_order_[++index] = otherwise;
1061 graph_->reverse_post_order_[++index] = merge;
1062
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001063
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00001064 graph_->UpdateLoopAndTryInformationOfNewBlock(
1065 then, original_invoke_block, /* replace_if_back_edge */ false);
1066 graph_->UpdateLoopAndTryInformationOfNewBlock(
1067 otherwise, original_invoke_block, /* replace_if_back_edge */ false);
1068
1069 // In case the original invoke location was a back edge, we need to update
1070 // the loop to now have the merge block as a back edge.
1071 graph_->UpdateLoopAndTryInformationOfNewBlock(
1072 merge, original_invoke_block, /* replace_if_back_edge */ true);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001073}
1074
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +00001075bool HInliner::TryInlinePolymorphicCallToSameTarget(
1076 HInvoke* invoke_instruction,
1077 ArtMethod* resolved_method,
1078 Handle<mirror::ObjectArray<mirror::Class>> classes) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001079 // This optimization only works under JIT for now.
Calin Juravle13439f02017-02-21 01:17:21 -08001080 if (!Runtime::Current()->UseJitCompilation()) {
1081 return false;
1082 }
1083
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001084 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
Andreas Gampe542451c2016-07-26 09:02:02 -07001085 PointerSize pointer_size = class_linker->GetImagePointerSize();
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001086
1087 DCHECK(resolved_method != nullptr);
1088 ArtMethod* actual_method = nullptr;
Nicolas Geoffray4f97a212016-02-25 16:17:54 +00001089 size_t method_index = invoke_instruction->IsInvokeVirtual()
1090 ? invoke_instruction->AsInvokeVirtual()->GetVTableIndex()
1091 : invoke_instruction->AsInvokeInterface()->GetImtIndex();
1092
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001093 // Check whether we are actually calling the same method among
1094 // the different types seen.
1095 for (size_t i = 0; i < InlineCache::kIndividualCacheSize; ++i) {
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +00001096 if (classes->Get(i) == nullptr) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001097 break;
1098 }
1099 ArtMethod* new_method = nullptr;
1100 if (invoke_instruction->IsInvokeInterface()) {
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +00001101 new_method = classes->Get(i)->GetImt(pointer_size)->Get(
Matthew Gharrity465ecc82016-07-19 21:32:52 +00001102 method_index, pointer_size);
Nicolas Geoffray4f97a212016-02-25 16:17:54 +00001103 if (new_method->IsRuntimeMethod()) {
1104 // Bail out as soon as we see a conflict trampoline in one of the target's
1105 // interface table.
1106 return false;
1107 }
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001108 } else {
1109 DCHECK(invoke_instruction->IsInvokeVirtual());
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +00001110 new_method = classes->Get(i)->GetEmbeddedVTableEntry(method_index, pointer_size);
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001111 }
Nicolas Geoffray4f97a212016-02-25 16:17:54 +00001112 DCHECK(new_method != nullptr);
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001113 if (actual_method == nullptr) {
1114 actual_method = new_method;
1115 } else if (actual_method != new_method) {
1116 // Different methods, bailout.
1117 return false;
1118 }
1119 }
1120
1121 HInstruction* receiver = invoke_instruction->InputAt(0);
1122 HInstruction* cursor = invoke_instruction->GetPrevious();
1123 HBasicBlock* bb_cursor = invoke_instruction->GetBlock();
1124
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01001125 HInstruction* return_replacement = nullptr;
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001126 if (!TryBuildAndInline(invoke_instruction,
1127 actual_method,
1128 ReferenceTypeInfo::CreateInvalid(),
1129 &return_replacement)) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001130 return false;
1131 }
1132
1133 // We successfully inlined, now add a guard.
1134 HInstanceFieldGet* receiver_class = BuildGetReceiverClass(
1135 class_linker, receiver, invoke_instruction->GetDexPc());
1136
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001137 Primitive::Type type = Is64BitInstructionSet(graph_->GetInstructionSet())
1138 ? Primitive::kPrimLong
1139 : Primitive::kPrimInt;
1140 HClassTableGet* class_table_get = new (graph_->GetArena()) HClassTableGet(
1141 receiver_class,
1142 type,
Vladimir Markoa1de9182016-02-25 11:37:38 +00001143 invoke_instruction->IsInvokeVirtual() ? HClassTableGet::TableKind::kVTable
1144 : HClassTableGet::TableKind::kIMTable,
Nicolas Geoffray4f97a212016-02-25 16:17:54 +00001145 method_index,
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001146 invoke_instruction->GetDexPc());
1147
1148 HConstant* constant;
1149 if (type == Primitive::kPrimLong) {
1150 constant = graph_->GetLongConstant(
1151 reinterpret_cast<intptr_t>(actual_method), invoke_instruction->GetDexPc());
1152 } else {
1153 constant = graph_->GetIntConstant(
1154 reinterpret_cast<intptr_t>(actual_method), invoke_instruction->GetDexPc());
1155 }
1156
1157 HNotEqual* compare = new (graph_->GetArena()) HNotEqual(class_table_get, constant);
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001158 if (cursor != nullptr) {
1159 bb_cursor->InsertInstructionAfter(receiver_class, cursor);
1160 } else {
1161 bb_cursor->InsertInstructionBefore(receiver_class, bb_cursor->GetFirstInstruction());
1162 }
1163 bb_cursor->InsertInstructionAfter(class_table_get, receiver_class);
1164 bb_cursor->InsertInstructionAfter(compare, class_table_get);
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01001165
1166 if (outermost_graph_->IsCompilingOsr()) {
1167 CreateDiamondPatternForPolymorphicInline(compare, return_replacement, invoke_instruction);
1168 } else {
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01001169 HDeoptimize* deoptimize = new (graph_->GetArena()) HDeoptimize(
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +00001170 graph_->GetArena(),
1171 compare,
1172 receiver,
Nicolas Geoffray4e92c3c2017-05-08 09:34:26 +01001173 DeoptimizationKind::kJitSameTarget,
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +00001174 invoke_instruction->GetDexPc());
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01001175 bb_cursor->InsertInstructionAfter(deoptimize, compare);
1176 deoptimize->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
1177 if (return_replacement != nullptr) {
1178 invoke_instruction->ReplaceWith(return_replacement);
1179 }
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +00001180 receiver->ReplaceUsesDominatedBy(deoptimize, deoptimize);
Nicolas Geoffray1be7cbd2016-04-29 13:56:01 +01001181 invoke_instruction->GetBlock()->RemoveInstruction(invoke_instruction);
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +00001182 deoptimize->SetReferenceTypeInfo(receiver->GetReferenceTypeInfo());
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01001183 }
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001184
1185 // Run type propagation to get the guard typed.
Vladimir Marko456307a2016-04-19 14:12:13 +00001186 ReferenceTypePropagation rtp_fixup(graph_,
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001187 outer_compilation_unit_.GetClassLoader(),
Vladimir Marko456307a2016-04-19 14:12:13 +00001188 outer_compilation_unit_.GetDexCache(),
1189 handles_,
1190 /* is_first_run */ false);
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001191 rtp_fixup.Run();
1192
1193 MaybeRecordStat(kInlinedPolymorphicCall);
1194
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001195 LOG_SUCCESS() << "Inlined same polymorphic target " << actual_method->PrettyMethod();
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001196 return true;
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001197}
1198
Mingyao Yang063fc772016-08-02 11:02:54 -07001199bool HInliner::TryInlineAndReplace(HInvoke* invoke_instruction,
1200 ArtMethod* method,
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001201 ReferenceTypeInfo receiver_type,
Mingyao Yang063fc772016-08-02 11:02:54 -07001202 bool do_rtp,
1203 bool cha_devirtualize) {
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001204 HInstruction* return_replacement = nullptr;
Mingyao Yang063fc772016-08-02 11:02:54 -07001205 uint32_t dex_pc = invoke_instruction->GetDexPc();
1206 HInstruction* cursor = invoke_instruction->GetPrevious();
1207 HBasicBlock* bb_cursor = invoke_instruction->GetBlock();
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001208 if (!TryBuildAndInline(invoke_instruction, method, receiver_type, &return_replacement)) {
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +00001209 if (invoke_instruction->IsInvokeInterface()) {
Nicolas Geoffray18ea1c92017-03-27 08:00:18 +00001210 DCHECK(!method->IsProxyMethod());
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +00001211 // Turn an invoke-interface into an invoke-virtual. An invoke-virtual is always
1212 // better than an invoke-interface because:
1213 // 1) In the best case, the interface call has one more indirection (to fetch the IMT).
1214 // 2) We will not go to the conflict trampoline with an invoke-virtual.
1215 // TODO: Consider sharpening once it is not dependent on the compiler driver.
Nicolas Geoffray18ea1c92017-03-27 08:00:18 +00001216
1217 if (method->IsDefault() && !method->IsCopied()) {
1218 // Changing to invoke-virtual cannot be done on an original default method
1219 // since it's not in any vtable. Devirtualization by exact type/inline-cache
1220 // always uses a method in the iftable which is never an original default
1221 // method.
1222 // On the other hand, inlining an original default method by CHA is fine.
1223 DCHECK(cha_devirtualize);
1224 return false;
1225 }
1226
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +00001227 const DexFile& caller_dex_file = *caller_compilation_unit_.GetDexFile();
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +01001228 uint32_t dex_method_index = FindMethodIndexIn(
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +00001229 method, caller_dex_file, invoke_instruction->GetDexMethodIndex());
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +01001230 if (dex_method_index == DexFile::kDexNoIndex) {
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +00001231 return false;
1232 }
1233 HInvokeVirtual* new_invoke = new (graph_->GetArena()) HInvokeVirtual(
1234 graph_->GetArena(),
1235 invoke_instruction->GetNumberOfArguments(),
1236 invoke_instruction->GetType(),
1237 invoke_instruction->GetDexPc(),
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +01001238 dex_method_index,
1239 method,
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +00001240 method->GetMethodIndex());
1241 HInputsRef inputs = invoke_instruction->GetInputs();
1242 for (size_t index = 0; index != inputs.size(); ++index) {
1243 new_invoke->SetArgumentAt(index, inputs[index]);
1244 }
1245 invoke_instruction->GetBlock()->InsertInstructionBefore(new_invoke, invoke_instruction);
1246 new_invoke->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
1247 if (invoke_instruction->GetType() == Primitive::kPrimNot) {
1248 new_invoke->SetReferenceTypeInfo(invoke_instruction->GetReferenceTypeInfo());
1249 }
1250 return_replacement = new_invoke;
1251 } else {
1252 // TODO: Consider sharpening an invoke virtual once it is not dependent on the
1253 // compiler driver.
1254 return false;
1255 }
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001256 }
Mingyao Yang063fc772016-08-02 11:02:54 -07001257 if (cha_devirtualize) {
1258 AddCHAGuard(invoke_instruction, dex_pc, cursor, bb_cursor);
1259 }
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001260 if (return_replacement != nullptr) {
1261 invoke_instruction->ReplaceWith(return_replacement);
1262 }
1263 invoke_instruction->GetBlock()->RemoveInstruction(invoke_instruction);
David Brazdil94ab38f2016-06-21 17:48:19 +01001264 FixUpReturnReferenceType(method, return_replacement);
1265 if (do_rtp && ReturnTypeMoreSpecific(invoke_instruction, return_replacement)) {
1266 // Actual return value has a more specific type than the method's declared
1267 // return type. Run RTP again on the outer graph to propagate it.
1268 ReferenceTypePropagation(graph_,
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001269 outer_compilation_unit_.GetClassLoader(),
David Brazdil94ab38f2016-06-21 17:48:19 +01001270 outer_compilation_unit_.GetDexCache(),
1271 handles_,
1272 /* is_first_run */ false).Run();
1273 }
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001274 return true;
1275}
1276
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001277size_t HInliner::CountRecursiveCallsOf(ArtMethod* method) const {
1278 const HInliner* current = this;
1279 size_t count = 0;
1280 do {
1281 if (current->graph_->GetArtMethod() == method) {
1282 ++count;
1283 }
1284 current = current->parent_;
1285 } while (current != nullptr);
1286 return count;
1287}
1288
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001289bool HInliner::TryBuildAndInline(HInvoke* invoke_instruction,
1290 ArtMethod* method,
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001291 ReferenceTypeInfo receiver_type,
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001292 HInstruction** return_replacement) {
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01001293 if (method->IsProxyMethod()) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001294 LOG_FAIL(kNotInlinedProxy)
1295 << "Method " << method->PrettyMethod()
1296 << " is not inlined because of unimplemented inline support for proxy methods.";
1297 return false;
1298 }
1299
1300 if (CountRecursiveCallsOf(method) > kMaximumNumberOfRecursiveCalls) {
1301 LOG_FAIL(kNotInlinedRecursiveBudget)
1302 << "Method "
1303 << method->PrettyMethod()
1304 << " is not inlined because it has reached its recursive call budget.";
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01001305 return false;
1306 }
1307
Jeff Haodcdc85b2015-12-04 14:06:18 -08001308 // Check whether we're allowed to inline. The outermost compilation unit is the relevant
1309 // dex file here (though the transitivity of an inline chain would allow checking the calller).
1310 if (!compiler_driver_->MayInline(method->GetDexFile(),
1311 outer_compilation_unit_.GetDexFile())) {
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001312 if (TryPatternSubstitution(invoke_instruction, method, return_replacement)) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001313 LOG_SUCCESS() << "Successfully replaced pattern of invoke "
1314 << method->PrettyMethod();
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001315 MaybeRecordStat(kReplacedInvokeWithSimplePattern);
1316 return true;
1317 }
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001318 LOG_FAIL(kNotInlinedWont)
1319 << "Won't inline " << method->PrettyMethod() << " in "
1320 << outer_compilation_unit_.GetDexFile()->GetLocation() << " ("
1321 << caller_compilation_unit_.GetDexFile()->GetLocation() << ") from "
1322 << method->GetDexFile()->GetLocation();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001323 return false;
1324 }
1325
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001326 bool same_dex_file = IsSameDexFile(*outer_compilation_unit_.GetDexFile(), *method->GetDexFile());
1327
1328 const DexFile::CodeItem* code_item = method->GetCodeItem();
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001329
1330 if (code_item == nullptr) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001331 LOG_FAIL_NO_STAT()
1332 << "Method " << method->PrettyMethod() << " is not inlined because it is native";
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001333 return false;
1334 }
1335
Calin Juravleec748352015-07-29 13:52:12 +01001336 size_t inline_max_code_units = compiler_driver_->GetCompilerOptions().GetInlineMaxCodeUnits();
1337 if (code_item->insns_size_in_code_units_ > inline_max_code_units) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001338 LOG_FAIL(kNotInlinedCodeItem)
1339 << "Method " << method->PrettyMethod()
1340 << " is not inlined because its code item is too big: "
1341 << code_item->insns_size_in_code_units_
1342 << " > "
1343 << inline_max_code_units;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001344 return false;
1345 }
1346
1347 if (code_item->tries_size_ != 0) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001348 LOG_FAIL(kNotInlinedTryCatch)
1349 << "Method " << method->PrettyMethod() << " is not inlined because of try block";
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001350 return false;
1351 }
1352
Nicolas Geoffray250a3782016-04-20 16:27:53 +01001353 if (!method->IsCompilable()) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001354 LOG_FAIL(kNotInlinedNotVerified)
1355 << "Method " << method->PrettyMethod()
1356 << " has soft failures un-handled by the compiler, so it cannot be inlined";
Nicolas Geoffray250a3782016-04-20 16:27:53 +01001357 }
1358
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001359 if (!method->GetDeclaringClass()->IsVerified()) {
1360 uint16_t class_def_idx = method->GetDeclaringClass()->GetDexClassDefIndex();
Calin Juravleffc87072016-04-20 14:22:09 +01001361 if (Runtime::Current()->UseJitCompilation() ||
Nicolas Geoffray5b82d332016-02-18 14:22:32 +00001362 !compiler_driver_->IsMethodVerifiedWithoutFailures(
1363 method->GetDexMethodIndex(), class_def_idx, *method->GetDexFile())) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001364 LOG_FAIL(kNotInlinedNotVerified)
1365 << "Method " << method->PrettyMethod()
1366 << " couldn't be verified, so it cannot be inlined";
Nicolas Geoffrayccc61972015-10-01 14:34:20 +01001367 return false;
1368 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001369 }
1370
Roland Levillain4c0eb422015-04-24 16:43:49 +01001371 if (invoke_instruction->IsInvokeStaticOrDirect() &&
1372 invoke_instruction->AsInvokeStaticOrDirect()->IsStaticWithImplicitClinitCheck()) {
1373 // Case of a static method that cannot be inlined because it implicitly
1374 // requires an initialization check of its declaring class.
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001375 LOG_FAIL(kNotInlinedDexCache) << "Method " << method->PrettyMethod()
1376 << " is not inlined because it is static and requires a clinit"
1377 << " check that cannot be emitted due to Dex cache limitations";
Roland Levillain4c0eb422015-04-24 16:43:49 +01001378 return false;
1379 }
1380
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001381 if (!TryBuildAndInlineHelper(
1382 invoke_instruction, method, receiver_type, same_dex_file, return_replacement)) {
Nicolas Geoffrayc0365b12015-03-18 18:31:52 +00001383 return false;
1384 }
1385
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001386 LOG_SUCCESS() << method->PrettyMethod();
Nicolas Geoffrayc0365b12015-03-18 18:31:52 +00001387 MaybeRecordStat(kInlinedInvoke);
1388 return true;
1389}
1390
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001391static HInstruction* GetInvokeInputForArgVRegIndex(HInvoke* invoke_instruction,
1392 size_t arg_vreg_index)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001393 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001394 size_t input_index = 0;
1395 for (size_t i = 0; i < arg_vreg_index; ++i, ++input_index) {
1396 DCHECK_LT(input_index, invoke_instruction->GetNumberOfArguments());
1397 if (Primitive::Is64BitType(invoke_instruction->InputAt(input_index)->GetType())) {
1398 ++i;
1399 DCHECK_NE(i, arg_vreg_index);
1400 }
1401 }
1402 DCHECK_LT(input_index, invoke_instruction->GetNumberOfArguments());
1403 return invoke_instruction->InputAt(input_index);
1404}
1405
1406// Try to recognize known simple patterns and replace invoke call with appropriate instructions.
1407bool HInliner::TryPatternSubstitution(HInvoke* invoke_instruction,
1408 ArtMethod* resolved_method,
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001409 HInstruction** return_replacement) {
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001410 InlineMethod inline_method;
1411 if (!InlineMethodAnalyser::AnalyseMethodCode(resolved_method, &inline_method)) {
1412 return false;
1413 }
1414
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001415 switch (inline_method.opcode) {
1416 case kInlineOpNop:
1417 DCHECK_EQ(invoke_instruction->GetType(), Primitive::kPrimVoid);
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001418 *return_replacement = nullptr;
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001419 break;
1420 case kInlineOpReturnArg:
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001421 *return_replacement = GetInvokeInputForArgVRegIndex(invoke_instruction,
1422 inline_method.d.return_data.arg);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001423 break;
1424 case kInlineOpNonWideConst:
1425 if (resolved_method->GetShorty()[0] == 'L') {
1426 DCHECK_EQ(inline_method.d.data, 0u);
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001427 *return_replacement = graph_->GetNullConstant();
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001428 } else {
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001429 *return_replacement = graph_->GetIntConstant(static_cast<int32_t>(inline_method.d.data));
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001430 }
1431 break;
1432 case kInlineOpIGet: {
1433 const InlineIGetIPutData& data = inline_method.d.ifield_data;
1434 if (data.method_is_static || data.object_arg != 0u) {
1435 // TODO: Needs null check.
1436 return false;
1437 }
1438 HInstruction* obj = GetInvokeInputForArgVRegIndex(invoke_instruction, data.object_arg);
Vladimir Markof44d36c2017-03-14 14:18:46 +00001439 HInstanceFieldGet* iget = CreateInstanceFieldGet(data.field_idx, resolved_method, obj);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001440 DCHECK_EQ(iget->GetFieldOffset().Uint32Value(), data.field_offset);
1441 DCHECK_EQ(iget->IsVolatile() ? 1u : 0u, data.is_volatile);
1442 invoke_instruction->GetBlock()->InsertInstructionBefore(iget, invoke_instruction);
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001443 *return_replacement = iget;
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001444 break;
1445 }
1446 case kInlineOpIPut: {
1447 const InlineIGetIPutData& data = inline_method.d.ifield_data;
1448 if (data.method_is_static || data.object_arg != 0u) {
1449 // TODO: Needs null check.
1450 return false;
1451 }
1452 HInstruction* obj = GetInvokeInputForArgVRegIndex(invoke_instruction, data.object_arg);
1453 HInstruction* value = GetInvokeInputForArgVRegIndex(invoke_instruction, data.src_arg);
Vladimir Markof44d36c2017-03-14 14:18:46 +00001454 HInstanceFieldSet* iput = CreateInstanceFieldSet(data.field_idx, resolved_method, obj, value);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001455 DCHECK_EQ(iput->GetFieldOffset().Uint32Value(), data.field_offset);
1456 DCHECK_EQ(iput->IsVolatile() ? 1u : 0u, data.is_volatile);
1457 invoke_instruction->GetBlock()->InsertInstructionBefore(iput, invoke_instruction);
1458 if (data.return_arg_plus1 != 0u) {
1459 size_t return_arg = data.return_arg_plus1 - 1u;
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001460 *return_replacement = GetInvokeInputForArgVRegIndex(invoke_instruction, return_arg);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001461 }
1462 break;
1463 }
Vladimir Marko354efa62016-02-04 19:46:56 +00001464 case kInlineOpConstructor: {
1465 const InlineConstructorData& data = inline_method.d.constructor_data;
1466 // Get the indexes to arrays for easier processing.
1467 uint16_t iput_field_indexes[] = {
1468 data.iput0_field_index, data.iput1_field_index, data.iput2_field_index
1469 };
1470 uint16_t iput_args[] = { data.iput0_arg, data.iput1_arg, data.iput2_arg };
1471 static_assert(arraysize(iput_args) == arraysize(iput_field_indexes), "Size mismatch");
1472 // Count valid field indexes.
1473 size_t number_of_iputs = 0u;
1474 while (number_of_iputs != arraysize(iput_field_indexes) &&
1475 iput_field_indexes[number_of_iputs] != DexFile::kDexNoIndex16) {
1476 // Check that there are no duplicate valid field indexes.
1477 DCHECK_EQ(0, std::count(iput_field_indexes + number_of_iputs + 1,
1478 iput_field_indexes + arraysize(iput_field_indexes),
1479 iput_field_indexes[number_of_iputs]));
1480 ++number_of_iputs;
1481 }
1482 // Check that there are no valid field indexes in the rest of the array.
1483 DCHECK_EQ(0, std::count_if(iput_field_indexes + number_of_iputs,
1484 iput_field_indexes + arraysize(iput_field_indexes),
1485 [](uint16_t index) { return index != DexFile::kDexNoIndex16; }));
1486
1487 // Create HInstanceFieldSet for each IPUT that stores non-zero data.
Vladimir Marko354efa62016-02-04 19:46:56 +00001488 HInstruction* obj = GetInvokeInputForArgVRegIndex(invoke_instruction, /* this */ 0u);
1489 bool needs_constructor_barrier = false;
1490 for (size_t i = 0; i != number_of_iputs; ++i) {
1491 HInstruction* value = GetInvokeInputForArgVRegIndex(invoke_instruction, iput_args[i]);
Roland Levillain1a653882016-03-18 18:05:57 +00001492 if (!value->IsConstant() || !value->AsConstant()->IsZeroBitPattern()) {
Vladimir Marko354efa62016-02-04 19:46:56 +00001493 uint16_t field_index = iput_field_indexes[i];
Vladimir Markof44d36c2017-03-14 14:18:46 +00001494 bool is_final;
1495 HInstanceFieldSet* iput =
1496 CreateInstanceFieldSet(field_index, resolved_method, obj, value, &is_final);
Vladimir Marko354efa62016-02-04 19:46:56 +00001497 invoke_instruction->GetBlock()->InsertInstructionBefore(iput, invoke_instruction);
1498
1499 // Check whether the field is final. If it is, we need to add a barrier.
Vladimir Markof44d36c2017-03-14 14:18:46 +00001500 if (is_final) {
Vladimir Marko354efa62016-02-04 19:46:56 +00001501 needs_constructor_barrier = true;
1502 }
1503 }
1504 }
1505 if (needs_constructor_barrier) {
Igor Murashkind01745e2017-04-05 16:40:31 -07001506 // See CompilerDriver::RequiresConstructorBarrier for more details.
1507 DCHECK(obj != nullptr) << "only non-static methods can have a constructor fence";
1508
1509 HConstructorFence* constructor_fence =
1510 new (graph_->GetArena()) HConstructorFence(obj, kNoDexPc, graph_->GetArena());
1511 invoke_instruction->GetBlock()->InsertInstructionBefore(constructor_fence,
1512 invoke_instruction);
Vladimir Marko354efa62016-02-04 19:46:56 +00001513 }
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001514 *return_replacement = nullptr;
Vladimir Marko354efa62016-02-04 19:46:56 +00001515 break;
1516 }
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001517 default:
1518 LOG(FATAL) << "UNREACHABLE";
1519 UNREACHABLE();
1520 }
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001521 return true;
1522}
1523
Vladimir Markof44d36c2017-03-14 14:18:46 +00001524HInstanceFieldGet* HInliner::CreateInstanceFieldGet(uint32_t field_index,
1525 ArtMethod* referrer,
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001526 HInstruction* obj)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001527 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markof44d36c2017-03-14 14:18:46 +00001528 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1529 ArtField* resolved_field =
1530 class_linker->LookupResolvedField(field_index, referrer, /* is_static */ false);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001531 DCHECK(resolved_field != nullptr);
1532 HInstanceFieldGet* iget = new (graph_->GetArena()) HInstanceFieldGet(
1533 obj,
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00001534 resolved_field,
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001535 resolved_field->GetTypeAsPrimitiveType(),
1536 resolved_field->GetOffset(),
1537 resolved_field->IsVolatile(),
1538 field_index,
1539 resolved_field->GetDeclaringClass()->GetDexClassDefIndex(),
Vladimir Markof44d36c2017-03-14 14:18:46 +00001540 *referrer->GetDexFile(),
Vladimir Markoadda4352016-01-29 10:24:41 +00001541 // Read barrier generates a runtime call in slow path and we need a valid
1542 // dex pc for the associated stack map. 0 is bogus but valid. Bug: 26854537.
1543 /* dex_pc */ 0);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001544 if (iget->GetType() == Primitive::kPrimNot) {
Vladimir Marko456307a2016-04-19 14:12:13 +00001545 // Use the same dex_cache that we used for field lookup as the hint_dex_cache.
Vladimir Markof44d36c2017-03-14 14:18:46 +00001546 Handle<mirror::DexCache> dex_cache = handles_->NewHandle(referrer->GetDexCache());
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001547 ReferenceTypePropagation rtp(graph_,
1548 outer_compilation_unit_.GetClassLoader(),
1549 dex_cache,
1550 handles_,
1551 /* is_first_run */ false);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001552 rtp.Visit(iget);
1553 }
1554 return iget;
1555}
1556
Vladimir Markof44d36c2017-03-14 14:18:46 +00001557HInstanceFieldSet* HInliner::CreateInstanceFieldSet(uint32_t field_index,
1558 ArtMethod* referrer,
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001559 HInstruction* obj,
Vladimir Markof44d36c2017-03-14 14:18:46 +00001560 HInstruction* value,
1561 bool* is_final)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001562 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markof44d36c2017-03-14 14:18:46 +00001563 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1564 ArtField* resolved_field =
1565 class_linker->LookupResolvedField(field_index, referrer, /* is_static */ false);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001566 DCHECK(resolved_field != nullptr);
Vladimir Markof44d36c2017-03-14 14:18:46 +00001567 if (is_final != nullptr) {
1568 // This information is needed only for constructors.
1569 DCHECK(referrer->IsConstructor());
1570 *is_final = resolved_field->IsFinal();
1571 }
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001572 HInstanceFieldSet* iput = new (graph_->GetArena()) HInstanceFieldSet(
1573 obj,
1574 value,
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00001575 resolved_field,
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001576 resolved_field->GetTypeAsPrimitiveType(),
1577 resolved_field->GetOffset(),
1578 resolved_field->IsVolatile(),
1579 field_index,
1580 resolved_field->GetDeclaringClass()->GetDexClassDefIndex(),
Vladimir Markof44d36c2017-03-14 14:18:46 +00001581 *referrer->GetDexFile(),
Vladimir Markoadda4352016-01-29 10:24:41 +00001582 // Read barrier generates a runtime call in slow path and we need a valid
1583 // dex pc for the associated stack map. 0 is bogus but valid. Bug: 26854537.
1584 /* dex_pc */ 0);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001585 return iput;
1586}
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +00001587
Vladimir Markob1d0ee12017-04-20 19:50:32 +01001588template <typename T>
1589static inline Handle<T> NewHandleIfDifferent(T* object,
1590 Handle<T> hint,
1591 VariableSizedHandleScope* handles)
1592 REQUIRES_SHARED(Locks::mutator_lock_) {
1593 return (object != hint.Get()) ? handles->NewHandle(object) : hint;
1594}
1595
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001596bool HInliner::TryBuildAndInlineHelper(HInvoke* invoke_instruction,
1597 ArtMethod* resolved_method,
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001598 ReferenceTypeInfo receiver_type,
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001599 bool same_dex_file,
1600 HInstruction** return_replacement) {
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001601 DCHECK(!(resolved_method->IsStatic() && receiver_type.IsValid()));
Nicolas Geoffrayc0365b12015-03-18 18:31:52 +00001602 ScopedObjectAccess soa(Thread::Current());
1603 const DexFile::CodeItem* code_item = resolved_method->GetCodeItem();
Guillaume "Vermeille" Sanchezae09d2d2015-05-29 10:52:55 +01001604 const DexFile& callee_dex_file = *resolved_method->GetDexFile();
1605 uint32_t method_index = resolved_method->GetDexMethodIndex();
Calin Juravle2e768302015-07-28 14:41:11 +00001606 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
Vladimir Markob1d0ee12017-04-20 19:50:32 +01001607 Handle<mirror::DexCache> dex_cache = NewHandleIfDifferent(resolved_method->GetDexCache(),
1608 caller_compilation_unit_.GetDexCache(),
1609 handles_);
1610 Handle<mirror::ClassLoader> class_loader =
1611 NewHandleIfDifferent(resolved_method->GetDeclaringClass()->GetClassLoader(),
1612 caller_compilation_unit_.GetClassLoader(),
1613 handles_);
Nicolas Geoffrayf1aedb12016-07-28 03:49:14 +01001614
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001615 DexCompilationUnit dex_compilation_unit(
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001616 class_loader,
Nicolas Geoffray5b82d332016-02-18 14:22:32 +00001617 class_linker,
1618 callee_dex_file,
1619 code_item,
1620 resolved_method->GetDeclaringClass()->GetDexClassDefIndex(),
1621 method_index,
1622 resolved_method->GetAccessFlags(),
1623 /* verified_method */ nullptr,
1624 dex_cache);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001625
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +01001626 InvokeType invoke_type = invoke_instruction->GetInvokeType();
Nicolas Geoffray35071052015-06-09 15:43:38 +01001627 if (invoke_type == kInterface) {
1628 // We have statically resolved the dispatch. To please the class linker
1629 // at runtime, we change this call as if it was a virtual call.
1630 invoke_type = kVirtual;
1631 }
David Brazdil3f523062016-02-29 16:53:33 +00001632
1633 const int32_t caller_instruction_counter = graph_->GetCurrentInstructionId();
Nicolas Geoffraye0fe7ae2015-03-09 10:02:49 +00001634 HGraph* callee_graph = new (graph_->GetArena()) HGraph(
Nicolas Geoffray0a23d742015-05-07 11:57:35 +01001635 graph_->GetArena(),
Guillaume "Vermeille" Sanchezae09d2d2015-05-29 10:52:55 +01001636 callee_dex_file,
Nicolas Geoffray0a23d742015-05-07 11:57:35 +01001637 method_index,
Mathieu Chartiere401d142015-04-22 13:56:20 -07001638 compiler_driver_->GetInstructionSet(),
Nicolas Geoffray35071052015-06-09 15:43:38 +01001639 invoke_type,
Nicolas Geoffray0a23d742015-05-07 11:57:35 +01001640 graph_->IsDebuggable(),
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001641 /* osr */ false,
David Brazdil3f523062016-02-29 16:53:33 +00001642 caller_instruction_counter);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001643 callee_graph->SetArtMethod(resolved_method);
David Brazdil5e8b1372015-01-23 14:39:08 +00001644
Vladimir Marko438709f2017-02-23 18:56:13 +00001645 // When they are needed, allocate `inline_stats_` on the Arena instead
Roland Levillaina8013fd2016-04-04 15:34:31 +01001646 // of on the stack, as Clang might produce a stack frame too large
1647 // for this function, that would not fit the requirements of the
1648 // `-Wframe-larger-than` option.
Vladimir Marko438709f2017-02-23 18:56:13 +00001649 if (stats_ != nullptr) {
1650 // Reuse one object for all inline attempts from this caller to keep Arena memory usage low.
1651 if (inline_stats_ == nullptr) {
1652 void* storage = graph_->GetArena()->Alloc<OptimizingCompilerStats>(kArenaAllocMisc);
1653 inline_stats_ = new (storage) OptimizingCompilerStats;
1654 } else {
1655 inline_stats_->Reset();
1656 }
1657 }
David Brazdil5e8b1372015-01-23 14:39:08 +00001658 HGraphBuilder builder(callee_graph,
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001659 &dex_compilation_unit,
1660 &outer_compilation_unit_,
Nicolas Geoffray9437b782015-03-25 10:08:51 +00001661 resolved_method->GetDexFile(),
David Brazdil86ea7ee2016-02-16 09:26:07 +00001662 *code_item,
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001663 compiler_driver_,
Nicolas Geoffray83c8e272017-01-31 14:36:37 +00001664 codegen_,
Vladimir Marko438709f2017-02-23 18:56:13 +00001665 inline_stats_,
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01001666 resolved_method->GetQuickenedInfo(class_linker->GetImagePointerSize()),
David Brazdildee58d62016-04-07 09:54:26 +00001667 dex_cache,
1668 handles_);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001669
David Brazdildee58d62016-04-07 09:54:26 +00001670 if (builder.BuildGraph() != kAnalysisSuccess) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001671 LOG_FAIL(kNotInlinedCannotBuild)
1672 << "Method " << callee_dex_file.PrettyMethod(method_index)
1673 << " could not be built, so cannot be inlined";
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001674 return false;
1675 }
1676
Nicolas Geoffray259136f2014-12-17 23:21:58 +00001677 if (!RegisterAllocator::CanAllocateRegistersFor(*callee_graph,
1678 compiler_driver_->GetInstructionSet())) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001679 LOG_FAIL(kNotInlinedRegisterAllocator)
1680 << "Method " << callee_dex_file.PrettyMethod(method_index)
1681 << " cannot be inlined because of the register allocator";
Nicolas Geoffray259136f2014-12-17 23:21:58 +00001682 return false;
1683 }
1684
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001685 size_t parameter_index = 0;
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001686 bool run_rtp = false;
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001687 for (HInstructionIterator instructions(callee_graph->GetEntryBlock()->GetInstructions());
1688 !instructions.Done();
1689 instructions.Advance()) {
1690 HInstruction* current = instructions.Current();
1691 if (current->IsParameterValue()) {
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001692 HInstruction* argument = invoke_instruction->InputAt(parameter_index);
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001693 if (argument->IsNullConstant()) {
1694 current->ReplaceWith(callee_graph->GetNullConstant());
1695 } else if (argument->IsIntConstant()) {
1696 current->ReplaceWith(callee_graph->GetIntConstant(argument->AsIntConstant()->GetValue()));
1697 } else if (argument->IsLongConstant()) {
1698 current->ReplaceWith(callee_graph->GetLongConstant(argument->AsLongConstant()->GetValue()));
1699 } else if (argument->IsFloatConstant()) {
1700 current->ReplaceWith(
1701 callee_graph->GetFloatConstant(argument->AsFloatConstant()->GetValue()));
1702 } else if (argument->IsDoubleConstant()) {
1703 current->ReplaceWith(
1704 callee_graph->GetDoubleConstant(argument->AsDoubleConstant()->GetValue()));
1705 } else if (argument->GetType() == Primitive::kPrimNot) {
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001706 if (!resolved_method->IsStatic() && parameter_index == 0 && receiver_type.IsValid()) {
1707 run_rtp = true;
1708 current->SetReferenceTypeInfo(receiver_type);
1709 } else {
1710 current->SetReferenceTypeInfo(argument->GetReferenceTypeInfo());
1711 }
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001712 current->AsParameterValue()->SetCanBeNull(argument->CanBeNull());
1713 }
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001714 ++parameter_index;
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001715 }
1716 }
1717
David Brazdil94ab38f2016-06-21 17:48:19 +01001718 // We have replaced formal arguments with actual arguments. If actual types
1719 // are more specific than the declared ones, run RTP again on the inner graph.
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001720 if (run_rtp || ArgumentTypesMoreSpecific(invoke_instruction, resolved_method)) {
David Brazdil94ab38f2016-06-21 17:48:19 +01001721 ReferenceTypePropagation(callee_graph,
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001722 outer_compilation_unit_.GetClassLoader(),
David Brazdil94ab38f2016-06-21 17:48:19 +01001723 dex_compilation_unit.GetDexCache(),
1724 handles_,
1725 /* is_first_run */ false).Run();
1726 }
1727
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001728 RunOptimizations(callee_graph, code_item, dex_compilation_unit);
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +00001729
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001730 HBasicBlock* exit_block = callee_graph->GetExitBlock();
1731 if (exit_block == nullptr) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001732 LOG_FAIL(kNotInlinedInfiniteLoop)
1733 << "Method " << callee_dex_file.PrettyMethod(method_index)
1734 << " could not be inlined because it has an infinite loop";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001735 return false;
1736 }
1737
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00001738 bool has_one_return = false;
Vladimir Marko60584552015-09-03 13:35:12 +00001739 for (HBasicBlock* predecessor : exit_block->GetPredecessors()) {
1740 if (predecessor->GetLastInstruction()->IsThrow()) {
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00001741 if (invoke_instruction->GetBlock()->IsTryBlock()) {
1742 // TODO(ngeoffray): Support adding HTryBoundary in Hgraph::InlineInto.
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001743 LOG_FAIL(kNotInlinedTryCatch)
1744 << "Method " << callee_dex_file.PrettyMethod(method_index)
1745 << " could not be inlined because one branch always throws and"
1746 << " caller is in a try/catch block";
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00001747 return false;
1748 } else if (graph_->GetExitBlock() == nullptr) {
1749 // TODO(ngeoffray): Support adding HExit in the caller graph.
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001750 LOG_FAIL(kNotInlinedInfiniteLoop)
1751 << "Method " << callee_dex_file.PrettyMethod(method_index)
1752 << " could not be inlined because one branch always throws and"
1753 << " caller does not have an exit block";
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00001754 return false;
Nicolas Geoffray1eede6a2017-03-02 16:14:53 +00001755 } else if (graph_->HasIrreducibleLoops()) {
1756 // TODO(ngeoffray): Support re-computing loop information to graphs with
1757 // irreducible loops?
1758 VLOG(compiler) << "Method " << callee_dex_file.PrettyMethod(method_index)
1759 << " could not be inlined because one branch always throws and"
1760 << " caller has irreducible loops";
1761 return false;
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00001762 }
1763 } else {
1764 has_one_return = true;
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001765 }
1766 }
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00001767
1768 if (!has_one_return) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001769 LOG_FAIL(kNotInlinedAlwaysThrows)
1770 << "Method " << callee_dex_file.PrettyMethod(method_index)
1771 << " could not be inlined because it always throws";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001772 return false;
1773 }
1774
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001775 size_t number_of_instructions = 0;
Vladimir Marko2c45bc92016-10-25 16:54:12 +01001776 // Skip the entry block, it does not contain instructions that prevent inlining.
1777 for (HBasicBlock* block : callee_graph->GetReversePostOrderSkipEntryBlock()) {
David Sehrc757dec2016-11-04 15:48:34 -07001778 if (block->IsLoopHeader()) {
1779 if (block->GetLoopInformation()->IsIrreducible()) {
1780 // Don't inline methods with irreducible loops, they could prevent some
1781 // optimizations to run.
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001782 LOG_FAIL(kNotInlinedIrreducibleLoop)
1783 << "Method " << callee_dex_file.PrettyMethod(method_index)
1784 << " could not be inlined because it contains an irreducible loop";
David Sehrc757dec2016-11-04 15:48:34 -07001785 return false;
1786 }
1787 if (!block->GetLoopInformation()->HasExitEdge()) {
1788 // Don't inline methods with loops without exit, since they cause the
1789 // loop information to be computed incorrectly when updating after
1790 // inlining.
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001791 LOG_FAIL(kNotInlinedLoopWithoutExit)
1792 << "Method " << callee_dex_file.PrettyMethod(method_index)
1793 << " could not be inlined because it contains a loop with no exit";
David Sehrc757dec2016-11-04 15:48:34 -07001794 return false;
1795 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001796 }
1797
1798 for (HInstructionIterator instr_it(block->GetInstructions());
1799 !instr_it.Done();
1800 instr_it.Advance()) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001801 if (++number_of_instructions >= inlining_budget_) {
1802 LOG_FAIL(kNotInlinedInstructionBudget)
1803 << "Method " << callee_dex_file.PrettyMethod(method_index)
1804 << " is not inlined because the outer method has reached"
1805 << " its instruction budget limit.";
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001806 return false;
1807 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001808 HInstruction* current = instr_it.Current();
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001809 if (current->NeedsEnvironment() &&
1810 (total_number_of_dex_registers_ >= kMaximumNumberOfCumulatedDexRegisters)) {
1811 LOG_FAIL(kNotInlinedEnvironmentBudget)
1812 << "Method " << callee_dex_file.PrettyMethod(method_index)
1813 << " is not inlined because its caller has reached"
1814 << " its environment budget limit.";
Nicolas Geoffray5949fa02015-12-18 10:57:10 +00001815 return false;
1816 }
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001817
Nicolas Geoffrayfbdfa6d2017-02-03 10:43:13 +00001818 if (current->NeedsEnvironment() &&
1819 !CanEncodeInlinedMethodInStackMap(*caller_compilation_unit_.GetDexFile(),
1820 resolved_method)) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001821 LOG_FAIL(kNotInlinedStackMaps)
1822 << "Method " << callee_dex_file.PrettyMethod(method_index)
1823 << " could not be inlined because " << current->DebugName()
1824 << " needs an environment, is in a different dex file"
1825 << ", and cannot be encoded in the stack maps.";
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001826 return false;
1827 }
Nicolas Geoffray9437b782015-03-25 10:08:51 +00001828
Vladimir Markodc151b22015-10-15 18:02:30 +01001829 if (!same_dex_file && current->NeedsDexCacheOfDeclaringClass()) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001830 LOG_FAIL(kNotInlinedDexCache)
1831 << "Method " << callee_dex_file.PrettyMethod(method_index)
1832 << " could not be inlined because " << current->DebugName()
1833 << " it is in a different dex file and requires access to the dex cache";
Nicolas Geoffray9437b782015-03-25 10:08:51 +00001834 return false;
1835 }
Nicolas Geoffrayd9309292015-10-31 22:21:31 +00001836
Nicolas Geoffrayd9309292015-10-31 22:21:31 +00001837 if (current->IsUnresolvedStaticFieldGet() ||
1838 current->IsUnresolvedInstanceFieldGet() ||
1839 current->IsUnresolvedStaticFieldSet() ||
1840 current->IsUnresolvedInstanceFieldSet()) {
1841 // Entrypoint for unresolved fields does not handle inlined frames.
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001842 LOG_FAIL(kNotInlinedUnresolvedEntrypoint)
1843 << "Method " << callee_dex_file.PrettyMethod(method_index)
1844 << " could not be inlined because it is using an unresolved"
1845 << " entrypoint";
Nicolas Geoffrayd9309292015-10-31 22:21:31 +00001846 return false;
1847 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001848 }
1849 }
David Brazdil3f523062016-02-29 16:53:33 +00001850 DCHECK_EQ(caller_instruction_counter, graph_->GetCurrentInstructionId())
1851 << "No instructions can be added to the outer graph while inner graph is being built";
1852
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001853 // Inline the callee graph inside the caller graph.
David Brazdil3f523062016-02-29 16:53:33 +00001854 const int32_t callee_instruction_counter = callee_graph->GetCurrentInstructionId();
1855 graph_->SetCurrentInstructionId(callee_instruction_counter);
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001856 *return_replacement = callee_graph->InlineInto(graph_, invoke_instruction);
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001857 // Update our budget for other inlining attempts in `caller_graph`.
1858 total_number_of_instructions_ += number_of_instructions;
1859 UpdateInliningBudget();
David Brazdil3f523062016-02-29 16:53:33 +00001860
1861 DCHECK_EQ(callee_instruction_counter, callee_graph->GetCurrentInstructionId())
1862 << "No instructions can be added to the inner graph during inlining into the outer graph";
1863
Vladimir Marko438709f2017-02-23 18:56:13 +00001864 if (stats_ != nullptr) {
1865 DCHECK(inline_stats_ != nullptr);
1866 inline_stats_->AddTo(stats_);
1867 }
1868
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001869 return true;
1870}
Calin Juravle2e768302015-07-28 14:41:11 +00001871
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001872void HInliner::RunOptimizations(HGraph* callee_graph,
1873 const DexFile::CodeItem* code_item,
1874 const DexCompilationUnit& dex_compilation_unit) {
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01001875 // Note: if the outermost_graph_ is being compiled OSR, we should not run any
1876 // optimization that could lead to a HDeoptimize. The following optimizations do not.
Vladimir Marko438709f2017-02-23 18:56:13 +00001877 HDeadCodeElimination dce(callee_graph, inline_stats_, "dead_code_elimination$inliner");
Andreas Gampeca620d72016-11-08 08:09:33 -08001878 HConstantFolding fold(callee_graph, "constant_folding$inliner");
Nicolas Geoffray22384ae2016-12-12 22:33:36 +00001879 HSharpening sharpening(callee_graph, codegen_, dex_compilation_unit, compiler_driver_, handles_);
Vladimir Marko65979462017-05-19 17:25:12 +01001880 InstructionSimplifier simplify(callee_graph, codegen_, compiler_driver_, inline_stats_);
Vladimir Marko438709f2017-02-23 18:56:13 +00001881 IntrinsicsRecognizer intrinsics(callee_graph, inline_stats_);
Roland Levillaina3aef2e2016-04-06 17:45:58 +01001882
1883 HOptimization* optimizations[] = {
1884 &intrinsics,
1885 &sharpening,
1886 &simplify,
1887 &fold,
1888 &dce,
1889 };
1890
1891 for (size_t i = 0; i < arraysize(optimizations); ++i) {
1892 HOptimization* optimization = optimizations[i];
1893 optimization->Run();
1894 }
1895
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001896 // Bail early for pathological cases on the environment (for example recursive calls,
1897 // or too large environment).
1898 if (total_number_of_dex_registers_ >= kMaximumNumberOfCumulatedDexRegisters) {
1899 LOG_NOTE() << "Calls in " << callee_graph->GetArtMethod()->PrettyMethod()
1900 << " will not be inlined because the outer method has reached"
1901 << " its environment budget limit.";
1902 return;
Roland Levillaina3aef2e2016-04-06 17:45:58 +01001903 }
1904
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001905 // Bail early if we know we already are over the limit.
1906 size_t number_of_instructions = CountNumberOfInstructions(callee_graph);
1907 if (number_of_instructions > inlining_budget_) {
1908 LOG_NOTE() << "Calls in " << callee_graph->GetArtMethod()->PrettyMethod()
1909 << " will not be inlined because the outer method has reached"
1910 << " its instruction budget limit. " << number_of_instructions;
1911 return;
1912 }
1913
1914 HInliner inliner(callee_graph,
1915 outermost_graph_,
1916 codegen_,
1917 outer_compilation_unit_,
1918 dex_compilation_unit,
1919 compiler_driver_,
1920 handles_,
1921 inline_stats_,
1922 total_number_of_dex_registers_ + code_item->registers_size_,
1923 total_number_of_instructions_ + number_of_instructions,
1924 this,
1925 depth_ + 1);
1926 inliner.Run();
Roland Levillaina3aef2e2016-04-06 17:45:58 +01001927}
1928
David Brazdil94ab38f2016-06-21 17:48:19 +01001929static bool IsReferenceTypeRefinement(ReferenceTypeInfo declared_rti,
1930 bool declared_can_be_null,
1931 HInstruction* actual_obj)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001932 REQUIRES_SHARED(Locks::mutator_lock_) {
David Brazdil94ab38f2016-06-21 17:48:19 +01001933 if (declared_can_be_null && !actual_obj->CanBeNull()) {
1934 return true;
1935 }
1936
1937 ReferenceTypeInfo actual_rti = actual_obj->GetReferenceTypeInfo();
1938 return (actual_rti.IsExact() && !declared_rti.IsExact()) ||
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001939 declared_rti.IsStrictSupertypeOf(actual_rti);
David Brazdil94ab38f2016-06-21 17:48:19 +01001940}
1941
1942ReferenceTypeInfo HInliner::GetClassRTI(mirror::Class* klass) {
1943 return ReferenceTypePropagation::IsAdmissible(klass)
1944 ? ReferenceTypeInfo::Create(handles_->NewHandle(klass))
1945 : graph_->GetInexactObjectRti();
1946}
1947
1948bool HInliner::ArgumentTypesMoreSpecific(HInvoke* invoke_instruction, ArtMethod* resolved_method) {
1949 // If this is an instance call, test whether the type of the `this` argument
1950 // is more specific than the class which declares the method.
1951 if (!resolved_method->IsStatic()) {
1952 if (IsReferenceTypeRefinement(GetClassRTI(resolved_method->GetDeclaringClass()),
1953 /* declared_can_be_null */ false,
1954 invoke_instruction->InputAt(0u))) {
1955 return true;
1956 }
1957 }
1958
David Brazdil94ab38f2016-06-21 17:48:19 +01001959 // Iterate over the list of parameter types and test whether any of the
1960 // actual inputs has a more specific reference type than the type declared in
1961 // the signature.
1962 const DexFile::TypeList* param_list = resolved_method->GetParameterTypeList();
1963 for (size_t param_idx = 0,
1964 input_idx = resolved_method->IsStatic() ? 0 : 1,
1965 e = (param_list == nullptr ? 0 : param_list->Size());
1966 param_idx < e;
1967 ++param_idx, ++input_idx) {
1968 HInstruction* input = invoke_instruction->InputAt(input_idx);
1969 if (input->GetType() == Primitive::kPrimNot) {
Vladimir Marko942fd312017-01-16 20:52:19 +00001970 mirror::Class* param_cls = resolved_method->GetClassFromTypeIndex(
David Brazdil94ab38f2016-06-21 17:48:19 +01001971 param_list->GetTypeItem(param_idx).type_idx_,
Vladimir Marko942fd312017-01-16 20:52:19 +00001972 /* resolve */ false);
David Brazdil94ab38f2016-06-21 17:48:19 +01001973 if (IsReferenceTypeRefinement(GetClassRTI(param_cls),
1974 /* declared_can_be_null */ true,
1975 input)) {
1976 return true;
1977 }
1978 }
1979 }
1980
1981 return false;
1982}
1983
1984bool HInliner::ReturnTypeMoreSpecific(HInvoke* invoke_instruction,
1985 HInstruction* return_replacement) {
Alex Light68289a52015-12-15 17:30:30 -08001986 // Check the integrity of reference types and run another type propagation if needed.
David Brazdil4833f5a2015-12-16 10:37:39 +00001987 if (return_replacement != nullptr) {
1988 if (return_replacement->GetType() == Primitive::kPrimNot) {
David Brazdil94ab38f2016-06-21 17:48:19 +01001989 // Test if the return type is a refinement of the declared return type.
1990 if (IsReferenceTypeRefinement(invoke_instruction->GetReferenceTypeInfo(),
1991 /* declared_can_be_null */ true,
1992 return_replacement)) {
1993 return true;
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00001994 } else if (return_replacement->IsInstanceFieldGet()) {
1995 HInstanceFieldGet* field_get = return_replacement->AsInstanceFieldGet();
1996 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1997 if (field_get->GetFieldInfo().GetField() ==
1998 class_linker->GetClassRoot(ClassLinker::kJavaLangObject)->GetInstanceField(0)) {
1999 return true;
2000 }
David Brazdil94ab38f2016-06-21 17:48:19 +01002001 }
2002 } else if (return_replacement->IsInstanceOf()) {
2003 // Inlining InstanceOf into an If may put a tighter bound on reference types.
2004 return true;
2005 }
2006 }
2007
2008 return false;
2009}
2010
2011void HInliner::FixUpReturnReferenceType(ArtMethod* resolved_method,
2012 HInstruction* return_replacement) {
2013 if (return_replacement != nullptr) {
2014 if (return_replacement->GetType() == Primitive::kPrimNot) {
David Brazdil4833f5a2015-12-16 10:37:39 +00002015 if (!return_replacement->GetReferenceTypeInfo().IsValid()) {
2016 // Make sure that we have a valid type for the return. We may get an invalid one when
2017 // we inline invokes with multiple branches and create a Phi for the result.
2018 // TODO: we could be more precise by merging the phi inputs but that requires
2019 // some functionality from the reference type propagation.
2020 DCHECK(return_replacement->IsPhi());
Vladimir Marko942fd312017-01-16 20:52:19 +00002021 mirror::Class* cls = resolved_method->GetReturnType(false /* resolve */);
David Brazdil94ab38f2016-06-21 17:48:19 +01002022 return_replacement->SetReferenceTypeInfo(GetClassRTI(cls));
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01002023 }
Calin Juravlecdfed3d2015-10-26 14:05:01 +00002024 }
Calin Juravle2e768302015-07-28 14:41:11 +00002025 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002026}
2027
2028} // namespace art