blob: e1cf2485ab19ed32d08bca91a31962928ba6fb33 [file] [log] [blame]
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001/*
2 * Copyright (C) 2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "inliner.h"
18
Mathieu Chartiere401d142015-04-22 13:56:20 -070019#include "art_method-inl.h"
Andreas Gampe542451c2016-07-26 09:02:02 -070020#include "base/enums.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000021#include "builder.h"
22#include "class_linker.h"
23#include "constant_folding.h"
24#include "dead_code_elimination.h"
Vladimir Markobe10e8e2016-01-22 12:09:44 +000025#include "dex/verified_method.h"
26#include "dex/verification_results.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000027#include "driver/compiler_driver-inl.h"
Calin Juravleec748352015-07-29 13:52:12 +010028#include "driver/compiler_options.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000029#include "driver/dex_compilation_unit.h"
30#include "instruction_simplifier.h"
Scott Wakelingd60a1af2015-07-22 14:32:44 +010031#include "intrinsics.h"
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +000032#include "jit/jit.h"
33#include "jit/jit_code_cache.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000034#include "mirror/class_loader.h"
35#include "mirror/dex_cache.h"
36#include "nodes.h"
Nicolas Geoffray335005e2015-06-25 10:01:47 +010037#include "optimizing_compiler.h"
Nicolas Geoffray454a4812015-06-09 10:37:32 +010038#include "reference_type_propagation.h"
Matthew Gharritye9288852016-07-14 14:08:16 -070039#include "register_allocator_linear_scan.h"
Vladimir Markobe10e8e2016-01-22 12:09:44 +000040#include "quick/inline_method_analyser.h"
Vladimir Markodc151b22015-10-15 18:02:30 +010041#include "sharpening.h"
David Brazdil4833f5a2015-12-16 10:37:39 +000042#include "ssa_builder.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000043#include "ssa_phi_elimination.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070044#include "scoped_thread_state_change-inl.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000045#include "thread.h"
46
47namespace art {
48
Nicolas 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.
66static constexpr bool kUseAOTInlineCaches = false;
67
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
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +0000143 // Keep a copy of all blocks when starting the visit.
144 ArenaVector<HBasicBlock*> blocks = graph_->GetReversePostOrder();
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100145 DCHECK(!blocks.empty());
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +0000146 // Because we are changing the graph when inlining,
147 // we just iterate over the blocks of the outer method.
148 // This avoids doing the inlining work again on the inlined blocks.
149 for (HBasicBlock* block : blocks) {
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +0000150 for (HInstruction* instruction = block->GetFirstInstruction(); instruction != nullptr;) {
151 HInstruction* next = instruction->GetNext();
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100152 HInvoke* call = instruction->AsInvoke();
Razvan A Lupusoru3e90a962015-03-27 13:44:44 -0700153 // As long as the call is not intrinsified, it is worth trying to inline.
154 if (call != nullptr && call->GetIntrinsic() == Intrinsics::kNone) {
Nicolas Geoffrayb703d182017-02-14 18:05:28 +0000155 if (kIsDebugBuild && IsCompilingWithCoreImage()) {
156 // Debugging case: directives in method names control or assert on inlining.
157 std::string callee_name = outer_compilation_unit_.GetDexFile()->PrettyMethod(
158 call->GetDexMethodIndex(), /* with_signature */ false);
159 // Tests prevent inlining by having $noinline$ in their method names.
160 if (callee_name.find("$noinline$") == std::string::npos) {
161 if (!TryInline(call)) {
162 bool should_have_inlined = (callee_name.find("$inline$") != std::string::npos);
163 CHECK(!should_have_inlined) << "Could not inline " << callee_name;
164 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000165 }
Guillaume "Vermeille" Sancheze918d382015-06-03 15:32:41 +0100166 } else {
Nicolas Geoffrayb703d182017-02-14 18:05:28 +0000167 // Normal case: try to inline.
168 TryInline(call);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000169 }
170 }
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +0000171 instruction = next;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000172 }
173 }
174}
175
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100176static bool IsMethodOrDeclaringClassFinal(ArtMethod* method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700177 REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100178 return method->IsFinal() || method->GetDeclaringClass()->IsFinal();
179}
180
181/**
182 * Given the `resolved_method` looked up in the dex cache, try to find
183 * the actual runtime target of an interface or virtual call.
184 * Return nullptr if the runtime target cannot be proven.
185 */
186static ArtMethod* FindVirtualOrInterfaceTarget(HInvoke* invoke, ArtMethod* resolved_method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700187 REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100188 if (IsMethodOrDeclaringClassFinal(resolved_method)) {
189 // No need to lookup further, the resolved method will be the target.
190 return resolved_method;
191 }
192
193 HInstruction* receiver = invoke->InputAt(0);
194 if (receiver->IsNullCheck()) {
195 // Due to multiple levels of inlining within the same pass, it might be that
196 // null check does not have the reference type of the actual receiver.
197 receiver = receiver->InputAt(0);
198 }
199 ReferenceTypeInfo info = receiver->GetReferenceTypeInfo();
Calin Juravle2e768302015-07-28 14:41:11 +0000200 DCHECK(info.IsValid()) << "Invalid RTI for " << receiver->DebugName();
201 if (!info.IsExact()) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100202 // We currently only support inlining with known receivers.
203 // TODO: Remove this check, we should be able to inline final methods
204 // on unknown receivers.
205 return nullptr;
206 } else if (info.GetTypeHandle()->IsInterface()) {
207 // Statically knowing that the receiver has an interface type cannot
208 // help us find what is the target method.
209 return nullptr;
210 } else if (!resolved_method->GetDeclaringClass()->IsAssignableFrom(info.GetTypeHandle().Get())) {
211 // The method that we're trying to call is not in the receiver's class or super classes.
212 return nullptr;
Nicolas Geoffrayab5327d2016-03-18 11:36:20 +0000213 } else if (info.GetTypeHandle()->IsErroneous()) {
214 // If the type is erroneous, do not go further, as we are going to query the vtable or
215 // imt table, that we can only safely do on non-erroneous classes.
216 return nullptr;
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100217 }
218
219 ClassLinker* cl = Runtime::Current()->GetClassLinker();
Andreas Gampe542451c2016-07-26 09:02:02 -0700220 PointerSize pointer_size = cl->GetImagePointerSize();
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100221 if (invoke->IsInvokeInterface()) {
222 resolved_method = info.GetTypeHandle()->FindVirtualMethodForInterface(
223 resolved_method, pointer_size);
224 } else {
225 DCHECK(invoke->IsInvokeVirtual());
226 resolved_method = info.GetTypeHandle()->FindVirtualMethodForVirtual(
227 resolved_method, pointer_size);
228 }
229
230 if (resolved_method == nullptr) {
231 // The information we had on the receiver was not enough to find
232 // the target method. Since we check above the exact type of the receiver,
233 // the only reason this can happen is an IncompatibleClassChangeError.
234 return nullptr;
Alex Light9139e002015-10-09 15:59:48 -0700235 } else if (!resolved_method->IsInvokable()) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100236 // The information we had on the receiver was not enough to find
237 // the target method. Since we check above the exact type of the receiver,
238 // the only reason this can happen is an IncompatibleClassChangeError.
239 return nullptr;
240 } else if (IsMethodOrDeclaringClassFinal(resolved_method)) {
241 // A final method has to be the target method.
242 return resolved_method;
243 } else if (info.IsExact()) {
244 // If we found a method and the receiver's concrete type is statically
245 // known, we know for sure the target.
246 return resolved_method;
247 } else {
248 // Even if we did find a method, the receiver type was not enough to
249 // statically find the runtime target.
250 return nullptr;
251 }
252}
253
254static uint32_t FindMethodIndexIn(ArtMethod* method,
255 const DexFile& dex_file,
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +0000256 uint32_t name_and_signature_index)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700257 REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100258 if (IsSameDexFile(*method->GetDexFile(), dex_file)) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100259 return method->GetDexMethodIndex();
260 } else {
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +0000261 return method->FindDexMethodIndexInOtherDexFile(dex_file, name_and_signature_index);
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100262 }
263}
264
Andreas Gampea5b09a62016-11-17 15:21:22 -0800265static dex::TypeIndex FindClassIndexIn(mirror::Class* cls,
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000266 const DexCompilationUnit& compilation_unit)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700267 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000268 const DexFile& dex_file = *compilation_unit.GetDexFile();
Andreas Gampea5b09a62016-11-17 15:21:22 -0800269 dex::TypeIndex index;
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100270 if (cls->GetDexCache() == nullptr) {
David Sehr709b0702016-10-13 09:12:37 -0700271 DCHECK(cls->IsArrayClass()) << cls->PrettyClass();
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000272 index = cls->FindTypeIndexInOtherDexFile(dex_file);
Andreas Gampea5b09a62016-11-17 15:21:22 -0800273 } else if (!cls->GetDexTypeIndex().IsValid()) {
David Sehr709b0702016-10-13 09:12:37 -0700274 DCHECK(cls->IsProxyClass()) << cls->PrettyClass();
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100275 // TODO: deal with proxy classes.
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100276 } else if (IsSameDexFile(cls->GetDexFile(), dex_file)) {
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000277 DCHECK_EQ(cls->GetDexCache(), compilation_unit.GetDexCache().Get());
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000278 index = cls->GetDexTypeIndex();
Nicolas Geoffray491617a2016-07-19 17:06:23 +0100279 } else {
280 index = cls->FindTypeIndexInOtherDexFile(dex_file);
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000281 // We cannot guarantee the entry will resolve to the same class,
Nicolas Geoffray491617a2016-07-19 17:06:23 +0100282 // as there may be different class loaders. So only return the index if it's
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000283 // the right class already resolved with the class loader.
284 if (index.IsValid()) {
285 ObjPtr<mirror::Class> resolved = ClassLinker::LookupResolvedType(
286 index, compilation_unit.GetDexCache().Get(), compilation_unit.GetClassLoader().Get());
287 if (resolved != cls) {
288 index = dex::TypeIndex::Invalid();
289 }
Nicolas Geoffray491617a2016-07-19 17:06:23 +0100290 }
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100291 }
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000292
293 return index;
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100294}
295
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000296class ScopedProfilingInfoInlineUse {
297 public:
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000298 explicit ScopedProfilingInfoInlineUse(ArtMethod* method, Thread* self)
299 : method_(method),
300 self_(self),
301 // Fetch the profiling info ahead of using it. If it's null when fetching,
302 // we should not call JitCodeCache::DoneInlining.
303 profiling_info_(
304 Runtime::Current()->GetJit()->GetCodeCache()->NotifyCompilerUse(method, self)) {
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000305 }
306
307 ~ScopedProfilingInfoInlineUse() {
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000308 if (profiling_info_ != nullptr) {
Andreas Gampe542451c2016-07-26 09:02:02 -0700309 PointerSize pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000310 DCHECK_EQ(profiling_info_, method_->GetProfilingInfo(pointer_size));
311 Runtime::Current()->GetJit()->GetCodeCache()->DoneCompilerUse(method_, self_);
312 }
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000313 }
314
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000315 ProfilingInfo* GetProfilingInfo() const { return profiling_info_; }
316
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000317 private:
318 ArtMethod* const method_;
Nicolas Geoffray07e3ca92016-03-11 09:57:57 +0000319 Thread* const self_;
320 ProfilingInfo* const profiling_info_;
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000321};
322
Calin Juravle13439f02017-02-21 01:17:21 -0800323HInliner::InlineCacheType HInliner::GetInlineCacheType(
324 const Handle<mirror::ObjectArray<mirror::Class>>& classes)
325 REQUIRES_SHARED(Locks::mutator_lock_) {
326 uint8_t number_of_types = 0;
327 for (; number_of_types < InlineCache::kIndividualCacheSize; ++number_of_types) {
328 if (classes->Get(number_of_types) == nullptr) {
329 break;
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000330 }
331 }
Calin Juravle13439f02017-02-21 01:17:21 -0800332
333 if (number_of_types == 0) {
334 return kInlineCacheUninitialized;
335 } else if (number_of_types == 1) {
336 return kInlineCacheMonomorphic;
337 } else if (number_of_types == InlineCache::kIndividualCacheSize) {
338 return kInlineCacheMegamorphic;
339 } else {
340 return kInlineCachePolymorphic;
341 }
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000342}
343
344static mirror::Class* GetMonomorphicType(Handle<mirror::ObjectArray<mirror::Class>> classes)
345 REQUIRES_SHARED(Locks::mutator_lock_) {
346 DCHECK(classes->Get(0) != nullptr);
347 return classes->Get(0);
348}
349
Mingyao Yang063fc772016-08-02 11:02:54 -0700350ArtMethod* HInliner::TryCHADevirtualization(ArtMethod* resolved_method) {
351 if (!resolved_method->HasSingleImplementation()) {
352 return nullptr;
353 }
354 if (Runtime::Current()->IsAotCompiler()) {
355 // No CHA-based devirtulization for AOT compiler (yet).
356 return nullptr;
357 }
358 if (outermost_graph_->IsCompilingOsr()) {
359 // We do not support HDeoptimize in OSR methods.
360 return nullptr;
361 }
Mingyao Yange8fcd012017-01-20 10:43:30 -0800362 PointerSize pointer_size = caller_compilation_unit_.GetClassLinker()->GetImagePointerSize();
Nicolas Geoffray18ea1c92017-03-27 08:00:18 +0000363 ArtMethod* single_impl = resolved_method->GetSingleImplementation(pointer_size);
364 if (single_impl == nullptr) {
365 return nullptr;
366 }
367 if (single_impl->IsProxyMethod()) {
368 // Proxy method is a generic invoker that's not worth
369 // devirtualizing/inlining. It also causes issues when the proxy
370 // method is in another dex file if we try to rewrite invoke-interface to
371 // invoke-virtual because a proxy method doesn't have a real dex file.
372 return nullptr;
373 }
374 return single_impl;
Mingyao Yang063fc772016-08-02 11:02:54 -0700375}
376
Nicolas Geoffraye418dda2015-08-11 20:03:09 -0700377bool HInliner::TryInline(HInvoke* invoke_instruction) {
Orion Hodsonac141392017-01-13 11:53:47 +0000378 if (invoke_instruction->IsInvokeUnresolved() ||
379 invoke_instruction->IsInvokePolymorphic()) {
380 return false; // Don't bother to move further if we know the method is unresolved or an
381 // invoke-polymorphic.
Calin Juravle175dc732015-08-25 15:42:32 +0100382 }
383
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000384 ScopedObjectAccess soa(Thread::Current());
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +0100385 uint32_t method_index = invoke_instruction->GetDexMethodIndex();
Nicolas Geoffray9437b782015-03-25 10:08:51 +0000386 const DexFile& caller_dex_file = *caller_compilation_unit_.GetDexFile();
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000387 LOG_TRY() << caller_dex_file.PrettyMethod(method_index);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000388
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +0100389 ArtMethod* resolved_method = invoke_instruction->GetResolvedMethod();
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +0100390 if (resolved_method == nullptr) {
391 DCHECK(invoke_instruction->IsInvokeStaticOrDirect());
392 DCHECK(invoke_instruction->AsInvokeStaticOrDirect()->IsStringInit());
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000393 LOG_FAIL_NO_STAT() << "Not inlining a String.<init> method";
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +0100394 return false;
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000395 }
396 ArtMethod* actual_method = nullptr;
397
398 if (invoke_instruction->IsInvokeStaticOrDirect()) {
Andreas Gampefd2140f2015-12-23 16:30:44 -0800399 actual_method = resolved_method;
Vladimir Marko58155012015-08-19 12:49:41 +0000400 } else {
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +0100401 // Check if we can statically find the method.
402 actual_method = FindVirtualOrInterfaceTarget(invoke_instruction, resolved_method);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000403 }
404
Mingyao Yang063fc772016-08-02 11:02:54 -0700405 bool cha_devirtualize = false;
406 if (actual_method == nullptr) {
407 ArtMethod* method = TryCHADevirtualization(resolved_method);
408 if (method != nullptr) {
409 cha_devirtualize = true;
410 actual_method = method;
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000411 LOG_NOTE() << "Try CHA-based inlining of " << actual_method->PrettyMethod();
Mingyao Yang063fc772016-08-02 11:02:54 -0700412 }
413 }
414
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100415 if (actual_method != nullptr) {
Mingyao Yang063fc772016-08-02 11:02:54 -0700416 bool result = TryInlineAndReplace(invoke_instruction,
417 actual_method,
Nicolas Geoffray0f001b72017-01-04 16:46:23 +0000418 ReferenceTypeInfo::CreateInvalid(),
Mingyao Yang063fc772016-08-02 11:02:54 -0700419 /* do_rtp */ true,
420 cha_devirtualize);
Calin Juravle69158982016-03-16 11:53:41 +0000421 if (result && !invoke_instruction->IsInvokeStaticOrDirect()) {
Mingyao Yang063fc772016-08-02 11:02:54 -0700422 if (cha_devirtualize) {
423 // Add dependency due to devirtulization. We've assumed resolved_method
424 // has single implementation.
425 outermost_graph_->AddCHASingleImplementationDependency(resolved_method);
426 MaybeRecordStat(kCHAInline);
427 } else {
428 MaybeRecordStat(kInlinedInvokeVirtualOrInterface);
429 }
Calin Juravle69158982016-03-16 11:53:41 +0000430 }
431 return result;
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100432 }
Andreas Gampefd2140f2015-12-23 16:30:44 -0800433 DCHECK(!invoke_instruction->IsInvokeStaticOrDirect());
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100434
Calin Juravle13439f02017-02-21 01:17:21 -0800435 // Try using inline caches.
436 return TryInlineFromInlineCache(caller_dex_file, invoke_instruction, resolved_method);
437}
438
439static Handle<mirror::ObjectArray<mirror::Class>> AllocateInlineCacheHolder(
440 const DexCompilationUnit& compilation_unit,
441 StackHandleScope<1>* hs)
442 REQUIRES_SHARED(Locks::mutator_lock_) {
443 Thread* self = Thread::Current();
444 ClassLinker* class_linker = compilation_unit.GetClassLinker();
445 Handle<mirror::ObjectArray<mirror::Class>> inline_cache = hs->NewHandle(
446 mirror::ObjectArray<mirror::Class>::Alloc(
447 self,
448 class_linker->GetClassRoot(ClassLinker::kClassArrayClass),
449 InlineCache::kIndividualCacheSize));
450 if (inline_cache == nullptr) {
451 // We got an OOME. Just clear the exception, and don't inline.
452 DCHECK(self->IsExceptionPending());
453 self->ClearException();
454 VLOG(compiler) << "Out of memory in the compiler when trying to inline";
455 }
456 return inline_cache;
457}
458
459bool HInliner::TryInlineFromInlineCache(const DexFile& caller_dex_file,
460 HInvoke* invoke_instruction,
461 ArtMethod* resolved_method)
462 REQUIRES_SHARED(Locks::mutator_lock_) {
Calin Juravlee2492d42017-03-20 11:42:13 -0700463 if (Runtime::Current()->IsAotCompiler() && !kUseAOTInlineCaches) {
464 return false;
465 }
466
Calin Juravle13439f02017-02-21 01:17:21 -0800467 StackHandleScope<1> hs(Thread::Current());
468 Handle<mirror::ObjectArray<mirror::Class>> inline_cache;
469 InlineCacheType inline_cache_type = Runtime::Current()->IsAotCompiler()
470 ? GetInlineCacheAOT(caller_dex_file, invoke_instruction, &hs, &inline_cache)
471 : GetInlineCacheJIT(invoke_instruction, &hs, &inline_cache);
472
473 switch (inline_cache_type) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000474 case kInlineCacheNoData: {
475 LOG_FAIL_NO_STAT()
476 << "Interface or virtual call to "
477 << caller_dex_file.PrettyMethod(invoke_instruction->GetDexMethodIndex())
478 << " could not be statically determined";
Calin Juravle13439f02017-02-21 01:17:21 -0800479 return false;
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000480 }
Calin Juravle13439f02017-02-21 01:17:21 -0800481
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000482 case kInlineCacheUninitialized: {
483 LOG_FAIL_NO_STAT()
484 << "Interface or virtual call to "
485 << caller_dex_file.PrettyMethod(invoke_instruction->GetDexMethodIndex())
486 << " is not hit and not inlined";
487 return false;
488 }
489
490 case kInlineCacheMonomorphic: {
Calin Juravle13439f02017-02-21 01:17:21 -0800491 MaybeRecordStat(kMonomorphicCall);
492 if (outermost_graph_->IsCompilingOsr()) {
493 // If we are compiling OSR, we pretend this call is polymorphic, as we may come from the
494 // interpreter and it may have seen different receiver types.
495 return TryInlinePolymorphicCall(invoke_instruction, resolved_method, inline_cache);
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000496 } else {
Calin Juravle13439f02017-02-21 01:17:21 -0800497 return TryInlineMonomorphicCall(invoke_instruction, resolved_method, inline_cache);
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +0000498 }
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000499 }
Calin Juravle13439f02017-02-21 01:17:21 -0800500
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000501 case kInlineCachePolymorphic: {
Calin Juravle13439f02017-02-21 01:17:21 -0800502 MaybeRecordStat(kPolymorphicCall);
503 return TryInlinePolymorphicCall(invoke_instruction, resolved_method, inline_cache);
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000504 }
Calin Juravle13439f02017-02-21 01:17:21 -0800505
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000506 case kInlineCacheMegamorphic: {
507 LOG_FAIL_NO_STAT()
508 << "Interface or virtual call to "
509 << caller_dex_file.PrettyMethod(invoke_instruction->GetDexMethodIndex())
510 << " is megamorphic and not inlined";
Calin Juravle13439f02017-02-21 01:17:21 -0800511 MaybeRecordStat(kMegamorphicCall);
512 return false;
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000513 }
Calin Juravle13439f02017-02-21 01:17:21 -0800514
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000515 case kInlineCacheMissingTypes: {
516 LOG_FAIL_NO_STAT()
517 << "Interface or virtual call to "
518 << caller_dex_file.PrettyMethod(invoke_instruction->GetDexMethodIndex())
519 << " is missing types and not inlined";
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 }
523 UNREACHABLE();
524}
525
526HInliner::InlineCacheType HInliner::GetInlineCacheJIT(
527 HInvoke* invoke_instruction,
528 StackHandleScope<1>* hs,
529 /*out*/Handle<mirror::ObjectArray<mirror::Class>>* inline_cache)
530 REQUIRES_SHARED(Locks::mutator_lock_) {
531 DCHECK(Runtime::Current()->UseJitCompilation());
532
533 ArtMethod* caller = graph_->GetArtMethod();
534 // Under JIT, we should always know the caller.
535 DCHECK(caller != nullptr);
536 ScopedProfilingInfoInlineUse spiis(caller, Thread::Current());
537 ProfilingInfo* profiling_info = spiis.GetProfilingInfo();
538
539 if (profiling_info == nullptr) {
540 return kInlineCacheNoData;
541 }
542
543 *inline_cache = AllocateInlineCacheHolder(caller_compilation_unit_, hs);
544 if (inline_cache->Get() == nullptr) {
545 // We can't extract any data if we failed to allocate;
546 return kInlineCacheNoData;
547 } else {
548 Runtime::Current()->GetJit()->GetCodeCache()->CopyInlineCacheInto(
549 *profiling_info->GetInlineCache(invoke_instruction->GetDexPc()),
550 *inline_cache);
551 return GetInlineCacheType(*inline_cache);
552 }
553}
554
555HInliner::InlineCacheType HInliner::GetInlineCacheAOT(
556 const DexFile& caller_dex_file,
557 HInvoke* invoke_instruction,
558 StackHandleScope<1>* hs,
559 /*out*/Handle<mirror::ObjectArray<mirror::Class>>* inline_cache)
560 REQUIRES_SHARED(Locks::mutator_lock_) {
561 DCHECK(Runtime::Current()->IsAotCompiler());
562 const ProfileCompilationInfo* pci = compiler_driver_->GetProfileCompilationInfo();
563 if (pci == nullptr) {
564 return kInlineCacheNoData;
565 }
566
567 ProfileCompilationInfo::OfflineProfileMethodInfo offline_profile;
568 bool found = pci->GetMethod(caller_dex_file.GetLocation(),
569 caller_dex_file.GetLocationChecksum(),
570 caller_compilation_unit_.GetDexMethodIndex(),
571 &offline_profile);
572 if (!found) {
573 return kInlineCacheNoData; // no profile information for this invocation.
574 }
575
576 *inline_cache = AllocateInlineCacheHolder(caller_compilation_unit_, hs);
577 if (inline_cache == nullptr) {
578 // We can't extract any data if we failed to allocate;
579 return kInlineCacheNoData;
580 } else {
581 return ExtractClassesFromOfflineProfile(invoke_instruction,
582 offline_profile,
583 *inline_cache);
584 }
585}
586
587HInliner::InlineCacheType HInliner::ExtractClassesFromOfflineProfile(
588 const HInvoke* invoke_instruction,
589 const ProfileCompilationInfo::OfflineProfileMethodInfo& offline_profile,
590 /*out*/Handle<mirror::ObjectArray<mirror::Class>> inline_cache)
591 REQUIRES_SHARED(Locks::mutator_lock_) {
592 const auto it = offline_profile.inline_caches.find(invoke_instruction->GetDexPc());
593 if (it == offline_profile.inline_caches.end()) {
594 return kInlineCacheUninitialized;
595 }
596
597 const ProfileCompilationInfo::DexPcData& dex_pc_data = it->second;
598
599 if (dex_pc_data.is_missing_types) {
600 return kInlineCacheMissingTypes;
601 }
602 if (dex_pc_data.is_megamorphic) {
603 return kInlineCacheMegamorphic;
604 }
605
606 DCHECK_LE(dex_pc_data.classes.size(), InlineCache::kIndividualCacheSize);
607 Thread* self = Thread::Current();
608 // We need to resolve the class relative to the containing dex file.
609 // So first, build a mapping from the index of dex file in the profile to
610 // its dex cache. This will avoid repeating the lookup when walking over
611 // the inline cache types.
612 std::vector<ObjPtr<mirror::DexCache>> dex_profile_index_to_dex_cache(
613 offline_profile.dex_references.size());
614 for (size_t i = 0; i < offline_profile.dex_references.size(); i++) {
615 bool found = false;
616 for (const DexFile* dex_file : compiler_driver_->GetDexFilesForOatFile()) {
617 if (offline_profile.dex_references[i].MatchesDex(dex_file)) {
618 dex_profile_index_to_dex_cache[i] =
619 caller_compilation_unit_.GetClassLinker()->FindDexCache(self, *dex_file);
620 found = true;
621 }
622 }
623 if (!found) {
624 VLOG(compiler) << "Could not find profiled dex file: "
625 << offline_profile.dex_references[i].dex_location;
626 return kInlineCacheMissingTypes;
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100627 }
628 }
629
Calin Juravle13439f02017-02-21 01:17:21 -0800630 // Walk over the classes and resolve them. If we cannot find a type we return
631 // kInlineCacheMissingTypes.
632 int ic_index = 0;
633 for (const ProfileCompilationInfo::ClassReference& class_ref : dex_pc_data.classes) {
634 ObjPtr<mirror::DexCache> dex_cache =
635 dex_profile_index_to_dex_cache[class_ref.dex_profile_index];
636 DCHECK(dex_cache != nullptr);
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000637 ObjPtr<mirror::Class> clazz = ClassLinker::LookupResolvedType(
638 class_ref.type_index,
639 dex_cache,
640 caller_compilation_unit_.GetClassLoader().Get());
Calin Juravle13439f02017-02-21 01:17:21 -0800641 if (clazz != nullptr) {
642 inline_cache->Set(ic_index++, clazz);
643 } else {
644 VLOG(compiler) << "Could not resolve class from inline cache in AOT mode "
645 << caller_compilation_unit_.GetDexFile()->PrettyMethod(
646 invoke_instruction->GetDexMethodIndex()) << " : "
647 << caller_compilation_unit_
648 .GetDexFile()->StringByTypeIdx(class_ref.type_index);
649 return kInlineCacheMissingTypes;
650 }
651 }
652 return GetInlineCacheType(inline_cache);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100653}
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000654
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000655HInstanceFieldGet* HInliner::BuildGetReceiverClass(ClassLinker* class_linker,
656 HInstruction* receiver,
657 uint32_t dex_pc) const {
658 ArtField* field = class_linker->GetClassRoot(ClassLinker::kJavaLangObject)->GetInstanceField(0);
659 DCHECK_EQ(std::string(field->GetName()), "shadow$_klass_");
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000660 HInstanceFieldGet* result = new (graph_->GetArena()) HInstanceFieldGet(
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000661 receiver,
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +0000662 field,
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000663 Primitive::kPrimNot,
664 field->GetOffset(),
665 field->IsVolatile(),
666 field->GetDexFieldIndex(),
667 field->GetDeclaringClass()->GetDexClassDefIndex(),
668 *field->GetDexFile(),
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000669 dex_pc);
Nicolas Geoffraye4084a52016-02-18 14:43:42 +0000670 // The class of a field is effectively final, and does not have any memory dependencies.
671 result->SetSideEffects(SideEffects::None());
672 return result;
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000673}
674
Nicolas Geoffray4c0b4bc2017-03-17 13:08:26 +0000675static ArtMethod* ResolveMethodFromInlineCache(Handle<mirror::Class> klass,
676 ArtMethod* resolved_method,
677 HInstruction* invoke_instruction,
678 PointerSize pointer_size)
679 REQUIRES_SHARED(Locks::mutator_lock_) {
680 if (Runtime::Current()->IsAotCompiler()) {
681 // We can get unrelated types when working with profiles (corruption,
682 // systme updates, or anyone can write to it). So first check if the class
683 // actually implements the declaring class of the method that is being
684 // called in bytecode.
685 // Note: the lookup methods used below require to have assignable types.
686 if (!resolved_method->GetDeclaringClass()->IsAssignableFrom(klass.Get())) {
687 return nullptr;
688 }
689 }
690
691 if (invoke_instruction->IsInvokeInterface()) {
692 resolved_method = klass->FindVirtualMethodForInterface(resolved_method, pointer_size);
693 } else {
694 DCHECK(invoke_instruction->IsInvokeVirtual());
695 resolved_method = klass->FindVirtualMethodForVirtual(resolved_method, pointer_size);
696 }
697 DCHECK(resolved_method != nullptr);
698 return resolved_method;
699}
700
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100701bool HInliner::TryInlineMonomorphicCall(HInvoke* invoke_instruction,
702 ArtMethod* resolved_method,
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000703 Handle<mirror::ObjectArray<mirror::Class>> classes) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000704 DCHECK(invoke_instruction->IsInvokeVirtual() || invoke_instruction->IsInvokeInterface())
705 << invoke_instruction->DebugName();
706
Andreas Gampea5b09a62016-11-17 15:21:22 -0800707 dex::TypeIndex class_index = FindClassIndexIn(
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000708 GetMonomorphicType(classes), caller_compilation_unit_);
Andreas Gampea5b09a62016-11-17 15:21:22 -0800709 if (!class_index.IsValid()) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000710 LOG_FAIL(kNotInlinedDexCache)
711 << "Call to " << ArtMethod::PrettyMethod(resolved_method)
712 << " from inline cache is not inlined because its class is not"
713 << " accessible to the caller";
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100714 return false;
715 }
716
717 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
Andreas Gampe542451c2016-07-26 09:02:02 -0700718 PointerSize pointer_size = class_linker->GetImagePointerSize();
Nicolas Geoffray4c0b4bc2017-03-17 13:08:26 +0000719 Handle<mirror::Class> monomorphic_type = handles_->NewHandle(GetMonomorphicType(classes));
720 resolved_method = ResolveMethodFromInlineCache(
721 monomorphic_type, resolved_method, invoke_instruction, pointer_size);
722
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000723 LOG_NOTE() << "Try inline monomorphic call to " << resolved_method->PrettyMethod();
Nicolas Geoffray4c0b4bc2017-03-17 13:08:26 +0000724 if (resolved_method == nullptr) {
725 // Bogus AOT profile, bail.
726 DCHECK(Runtime::Current()->IsAotCompiler());
727 return false;
728 }
729
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100730 HInstruction* receiver = invoke_instruction->InputAt(0);
731 HInstruction* cursor = invoke_instruction->GetPrevious();
732 HBasicBlock* bb_cursor = invoke_instruction->GetBlock();
Mingyao Yang063fc772016-08-02 11:02:54 -0700733 if (!TryInlineAndReplace(invoke_instruction,
734 resolved_method,
Nicolas Geoffray5247c082017-01-13 14:17:29 +0000735 ReferenceTypeInfo::Create(monomorphic_type, /* is_exact */ true),
Mingyao Yang063fc772016-08-02 11:02:54 -0700736 /* do_rtp */ false,
737 /* cha_devirtualize */ false)) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100738 return false;
739 }
740
741 // We successfully inlined, now add a guard.
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000742 AddTypeGuard(receiver,
743 cursor,
744 bb_cursor,
745 class_index,
Nicolas Geoffray5247c082017-01-13 14:17:29 +0000746 monomorphic_type,
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000747 invoke_instruction,
748 /* with_deoptimization */ true);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100749
750 // Run type propagation to get the guard typed, and eventually propagate the
751 // type of the receiver.
Vladimir Marko456307a2016-04-19 14:12:13 +0000752 ReferenceTypePropagation rtp_fixup(graph_,
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000753 outer_compilation_unit_.GetClassLoader(),
Vladimir Marko456307a2016-04-19 14:12:13 +0000754 outer_compilation_unit_.GetDexCache(),
755 handles_,
756 /* is_first_run */ false);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100757 rtp_fixup.Run();
758
759 MaybeRecordStat(kInlinedMonomorphicCall);
760 return true;
761}
762
Mingyao Yang063fc772016-08-02 11:02:54 -0700763void HInliner::AddCHAGuard(HInstruction* invoke_instruction,
764 uint32_t dex_pc,
765 HInstruction* cursor,
766 HBasicBlock* bb_cursor) {
Mingyao Yangb0b051a2016-11-17 09:04:53 -0800767 HShouldDeoptimizeFlag* deopt_flag = new (graph_->GetArena())
768 HShouldDeoptimizeFlag(graph_->GetArena(), dex_pc);
769 HInstruction* compare = new (graph_->GetArena()) HNotEqual(
Mingyao Yang063fc772016-08-02 11:02:54 -0700770 deopt_flag, graph_->GetIntConstant(0, dex_pc));
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +0000771 HInstruction* deopt = new (graph_->GetArena()) HDeoptimize(
772 graph_->GetArena(), compare, HDeoptimize::Kind::kInline, dex_pc);
Mingyao Yang063fc772016-08-02 11:02:54 -0700773
774 if (cursor != nullptr) {
775 bb_cursor->InsertInstructionAfter(deopt_flag, cursor);
776 } else {
777 bb_cursor->InsertInstructionBefore(deopt_flag, bb_cursor->GetFirstInstruction());
778 }
Mingyao Yangb0b051a2016-11-17 09:04:53 -0800779 bb_cursor->InsertInstructionAfter(compare, deopt_flag);
780 bb_cursor->InsertInstructionAfter(deopt, compare);
781
782 // Add receiver as input to aid CHA guard optimization later.
783 deopt_flag->AddInput(invoke_instruction->InputAt(0));
784 DCHECK_EQ(deopt_flag->InputCount(), 1u);
Mingyao Yang063fc772016-08-02 11:02:54 -0700785 deopt->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
Mingyao Yangb0b051a2016-11-17 09:04:53 -0800786 outermost_graph_->IncrementNumberOfCHAGuards();
Mingyao Yang063fc772016-08-02 11:02:54 -0700787}
788
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000789HInstruction* HInliner::AddTypeGuard(HInstruction* receiver,
790 HInstruction* cursor,
791 HBasicBlock* bb_cursor,
Andreas Gampea5b09a62016-11-17 15:21:22 -0800792 dex::TypeIndex class_index,
Nicolas Geoffray5247c082017-01-13 14:17:29 +0000793 Handle<mirror::Class> klass,
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000794 HInstruction* invoke_instruction,
795 bool with_deoptimization) {
796 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
797 HInstanceFieldGet* receiver_class = BuildGetReceiverClass(
798 class_linker, receiver, invoke_instruction->GetDexPc());
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000799 if (cursor != nullptr) {
800 bb_cursor->InsertInstructionAfter(receiver_class, cursor);
801 } else {
802 bb_cursor->InsertInstructionBefore(receiver_class, bb_cursor->GetFirstInstruction());
803 }
Nicolas Geoffray56876342016-12-16 16:09:08 +0000804
805 const DexFile& caller_dex_file = *caller_compilation_unit_.GetDexFile();
Nicolas Geoffray5247c082017-01-13 14:17:29 +0000806 bool is_referrer = (klass.Get() == outermost_graph_->GetArtMethod()->GetDeclaringClass());
Nicolas Geoffray56876342016-12-16 16:09:08 +0000807 // Note that we will just compare the classes, so we don't need Java semantics access checks.
808 // Note that the type index and the dex file are relative to the method this type guard is
809 // inlined into.
810 HLoadClass* load_class = new (graph_->GetArena()) HLoadClass(graph_->GetCurrentMethod(),
811 class_index,
812 caller_dex_file,
Nicolas Geoffray5247c082017-01-13 14:17:29 +0000813 klass,
Nicolas Geoffray56876342016-12-16 16:09:08 +0000814 is_referrer,
815 invoke_instruction->GetDexPc(),
816 /* needs_access_check */ false);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +0000817 HLoadClass::LoadKind kind = HSharpening::ComputeLoadClassKind(
Nicolas Geoffray83c8e272017-01-31 14:36:37 +0000818 load_class, codegen_, compiler_driver_, caller_compilation_unit_);
819 DCHECK(kind != HLoadClass::LoadKind::kInvalid)
820 << "We should always be able to reference a class for inline caches";
821 // Insert before setting the kind, as setting the kind affects the inputs.
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000822 bb_cursor->InsertInstructionAfter(load_class, receiver_class);
Nicolas Geoffray83c8e272017-01-31 14:36:37 +0000823 load_class->SetLoadKind(kind);
Calin Juravle13439f02017-02-21 01:17:21 -0800824 // In AOT mode, we will most likely load the class from BSS, which will involve a call
825 // to the runtime. In this case, the load instruction will need an environment so copy
826 // it from the invoke instruction.
827 if (load_class->NeedsEnvironment()) {
828 DCHECK(Runtime::Current()->IsAotCompiler());
829 load_class->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
830 }
Nicolas Geoffray56876342016-12-16 16:09:08 +0000831
Nicolas Geoffray56876342016-12-16 16:09:08 +0000832 HNotEqual* compare = new (graph_->GetArena()) HNotEqual(load_class, receiver_class);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000833 bb_cursor->InsertInstructionAfter(compare, load_class);
834 if (with_deoptimization) {
835 HDeoptimize* deoptimize = new (graph_->GetArena()) HDeoptimize(
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +0000836 graph_->GetArena(),
837 compare,
838 receiver,
839 HDeoptimize::Kind::kInline,
840 invoke_instruction->GetDexPc());
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000841 bb_cursor->InsertInstructionAfter(deoptimize, compare);
842 deoptimize->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +0000843 DCHECK_EQ(invoke_instruction->InputAt(0), receiver);
844 receiver->ReplaceUsesDominatedBy(deoptimize, deoptimize);
845 deoptimize->SetReferenceTypeInfo(receiver->GetReferenceTypeInfo());
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000846 }
847 return compare;
848}
849
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000850bool HInliner::TryInlinePolymorphicCall(HInvoke* invoke_instruction,
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100851 ArtMethod* resolved_method,
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000852 Handle<mirror::ObjectArray<mirror::Class>> classes) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000853 DCHECK(invoke_instruction->IsInvokeVirtual() || invoke_instruction->IsInvokeInterface())
854 << invoke_instruction->DebugName();
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000855
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000856 if (TryInlinePolymorphicCallToSameTarget(invoke_instruction, resolved_method, classes)) {
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000857 return true;
858 }
859
860 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
Andreas Gampe542451c2016-07-26 09:02:02 -0700861 PointerSize pointer_size = class_linker->GetImagePointerSize();
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000862
863 bool all_targets_inlined = true;
864 bool one_target_inlined = false;
865 for (size_t i = 0; i < InlineCache::kIndividualCacheSize; ++i) {
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000866 if (classes->Get(i) == nullptr) {
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000867 break;
868 }
869 ArtMethod* method = nullptr;
Nicolas Geoffray0f001b72017-01-04 16:46:23 +0000870
871 Handle<mirror::Class> handle = handles_->NewHandle(classes->Get(i));
Nicolas Geoffray4c0b4bc2017-03-17 13:08:26 +0000872 method = ResolveMethodFromInlineCache(
873 handle, resolved_method, invoke_instruction, pointer_size);
874 if (method == nullptr) {
875 DCHECK(Runtime::Current()->IsAotCompiler());
876 // AOT profile is bogus. This loop expects to iterate over all entries,
877 // so just just continue.
878 all_targets_inlined = false;
879 continue;
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000880 }
881
882 HInstruction* receiver = invoke_instruction->InputAt(0);
883 HInstruction* cursor = invoke_instruction->GetPrevious();
884 HBasicBlock* bb_cursor = invoke_instruction->GetBlock();
885
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000886 dex::TypeIndex class_index = FindClassIndexIn(handle.Get(), caller_compilation_unit_);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000887 HInstruction* return_replacement = nullptr;
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000888 LOG_NOTE() << "Try inline polymorphic call to " << method->PrettyMethod();
Andreas Gampea5b09a62016-11-17 15:21:22 -0800889 if (!class_index.IsValid() ||
Nicolas Geoffray0f001b72017-01-04 16:46:23 +0000890 !TryBuildAndInline(invoke_instruction,
891 method,
892 ReferenceTypeInfo::Create(handle, /* is_exact */ true),
893 &return_replacement)) {
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000894 all_targets_inlined = false;
895 } else {
896 one_target_inlined = true;
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000897
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000898 LOG_SUCCESS() << "Polymorphic call to " << ArtMethod::PrettyMethod(resolved_method)
899 << " has inlined " << ArtMethod::PrettyMethod(method);
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +0000900
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000901 // If we have inlined all targets before, and this receiver is the last seen,
902 // we deoptimize instead of keeping the original invoke instruction.
903 bool deoptimize = all_targets_inlined &&
904 (i != InlineCache::kIndividualCacheSize - 1) &&
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +0000905 (classes->Get(i + 1) == nullptr);
Nicolas Geoffray93a18c52016-04-22 13:16:14 +0100906
907 if (outermost_graph_->IsCompilingOsr()) {
908 // We do not support HDeoptimize in OSR methods.
909 deoptimize = false;
910 }
Nicolas Geoffray56876342016-12-16 16:09:08 +0000911 HInstruction* compare = AddTypeGuard(receiver,
912 cursor,
913 bb_cursor,
914 class_index,
Nicolas Geoffray5247c082017-01-13 14:17:29 +0000915 handle,
Nicolas Geoffray56876342016-12-16 16:09:08 +0000916 invoke_instruction,
917 deoptimize);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000918 if (deoptimize) {
919 if (return_replacement != nullptr) {
920 invoke_instruction->ReplaceWith(return_replacement);
921 }
922 invoke_instruction->GetBlock()->RemoveInstruction(invoke_instruction);
923 // Because the inline cache data can be populated concurrently, we force the end of the
Nicolas Geoffray4c0b4bc2017-03-17 13:08:26 +0000924 // iteration. Otherwise, we could see a new receiver type.
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000925 break;
926 } else {
927 CreateDiamondPatternForPolymorphicInline(compare, return_replacement, invoke_instruction);
928 }
929 }
930 }
931
932 if (!one_target_inlined) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +0000933 LOG_FAIL_NO_STAT()
934 << "Call to " << ArtMethod::PrettyMethod(resolved_method)
935 << " from inline cache is not inlined because none"
936 << " of its targets could be inlined";
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000937 return false;
938 }
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +0000939
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000940 MaybeRecordStat(kInlinedPolymorphicCall);
941
942 // Run type propagation to get the guards typed.
Vladimir Marko456307a2016-04-19 14:12:13 +0000943 ReferenceTypePropagation rtp_fixup(graph_,
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000944 outer_compilation_unit_.GetClassLoader(),
Vladimir Marko456307a2016-04-19 14:12:13 +0000945 outer_compilation_unit_.GetDexCache(),
946 handles_,
947 /* is_first_run */ false);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +0000948 rtp_fixup.Run();
949 return true;
950}
951
952void HInliner::CreateDiamondPatternForPolymorphicInline(HInstruction* compare,
953 HInstruction* return_replacement,
954 HInstruction* invoke_instruction) {
955 uint32_t dex_pc = invoke_instruction->GetDexPc();
956 HBasicBlock* cursor_block = compare->GetBlock();
957 HBasicBlock* original_invoke_block = invoke_instruction->GetBlock();
958 ArenaAllocator* allocator = graph_->GetArena();
959
960 // Spit the block after the compare: `cursor_block` will now be the start of the diamond,
961 // and the returned block is the start of the then branch (that could contain multiple blocks).
962 HBasicBlock* then = cursor_block->SplitAfterForInlining(compare);
963
964 // Split the block containing the invoke before and after the invoke. The returned block
965 // of the split before will contain the invoke and will be the otherwise branch of
966 // the diamond. The returned block of the split after will be the merge block
967 // of the diamond.
968 HBasicBlock* end_then = invoke_instruction->GetBlock();
969 HBasicBlock* otherwise = end_then->SplitBeforeForInlining(invoke_instruction);
970 HBasicBlock* merge = otherwise->SplitAfterForInlining(invoke_instruction);
971
972 // If the methods we are inlining return a value, we create a phi in the merge block
973 // that will have the `invoke_instruction and the `return_replacement` as inputs.
974 if (return_replacement != nullptr) {
975 HPhi* phi = new (allocator) HPhi(
976 allocator, kNoRegNumber, 0, HPhi::ToPhiType(invoke_instruction->GetType()), dex_pc);
977 merge->AddPhi(phi);
978 invoke_instruction->ReplaceWith(phi);
979 phi->AddInput(return_replacement);
980 phi->AddInput(invoke_instruction);
981 }
982
983 // Add the control flow instructions.
984 otherwise->AddInstruction(new (allocator) HGoto(dex_pc));
985 end_then->AddInstruction(new (allocator) HGoto(dex_pc));
986 cursor_block->AddInstruction(new (allocator) HIf(compare, dex_pc));
987
988 // Add the newly created blocks to the graph.
989 graph_->AddBlock(then);
990 graph_->AddBlock(otherwise);
991 graph_->AddBlock(merge);
992
993 // Set up successor (and implictly predecessor) relations.
994 cursor_block->AddSuccessor(otherwise);
995 cursor_block->AddSuccessor(then);
996 end_then->AddSuccessor(merge);
997 otherwise->AddSuccessor(merge);
998
999 // Set up dominance information.
1000 then->SetDominator(cursor_block);
1001 cursor_block->AddDominatedBlock(then);
1002 otherwise->SetDominator(cursor_block);
1003 cursor_block->AddDominatedBlock(otherwise);
1004 merge->SetDominator(cursor_block);
1005 cursor_block->AddDominatedBlock(merge);
1006
1007 // Update the revert post order.
1008 size_t index = IndexOfElement(graph_->reverse_post_order_, cursor_block);
1009 MakeRoomFor(&graph_->reverse_post_order_, 1, index);
1010 graph_->reverse_post_order_[++index] = then;
1011 index = IndexOfElement(graph_->reverse_post_order_, end_then);
1012 MakeRoomFor(&graph_->reverse_post_order_, 2, index);
1013 graph_->reverse_post_order_[++index] = otherwise;
1014 graph_->reverse_post_order_[++index] = merge;
1015
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001016
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00001017 graph_->UpdateLoopAndTryInformationOfNewBlock(
1018 then, original_invoke_block, /* replace_if_back_edge */ false);
1019 graph_->UpdateLoopAndTryInformationOfNewBlock(
1020 otherwise, original_invoke_block, /* replace_if_back_edge */ false);
1021
1022 // In case the original invoke location was a back edge, we need to update
1023 // the loop to now have the merge block as a back edge.
1024 graph_->UpdateLoopAndTryInformationOfNewBlock(
1025 merge, original_invoke_block, /* replace_if_back_edge */ true);
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001026}
1027
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +00001028bool HInliner::TryInlinePolymorphicCallToSameTarget(
1029 HInvoke* invoke_instruction,
1030 ArtMethod* resolved_method,
1031 Handle<mirror::ObjectArray<mirror::Class>> classes) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001032 // This optimization only works under JIT for now.
Calin Juravle13439f02017-02-21 01:17:21 -08001033 if (!Runtime::Current()->UseJitCompilation()) {
1034 return false;
1035 }
1036
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001037 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
Andreas Gampe542451c2016-07-26 09:02:02 -07001038 PointerSize pointer_size = class_linker->GetImagePointerSize();
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001039
1040 DCHECK(resolved_method != nullptr);
1041 ArtMethod* actual_method = nullptr;
Nicolas Geoffray4f97a212016-02-25 16:17:54 +00001042 size_t method_index = invoke_instruction->IsInvokeVirtual()
1043 ? invoke_instruction->AsInvokeVirtual()->GetVTableIndex()
1044 : invoke_instruction->AsInvokeInterface()->GetImtIndex();
1045
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001046 // Check whether we are actually calling the same method among
1047 // the different types seen.
1048 for (size_t i = 0; i < InlineCache::kIndividualCacheSize; ++i) {
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +00001049 if (classes->Get(i) == nullptr) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001050 break;
1051 }
1052 ArtMethod* new_method = nullptr;
1053 if (invoke_instruction->IsInvokeInterface()) {
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +00001054 new_method = classes->Get(i)->GetImt(pointer_size)->Get(
Matthew Gharrity465ecc82016-07-19 21:32:52 +00001055 method_index, pointer_size);
Nicolas Geoffray4f97a212016-02-25 16:17:54 +00001056 if (new_method->IsRuntimeMethod()) {
1057 // Bail out as soon as we see a conflict trampoline in one of the target's
1058 // interface table.
1059 return false;
1060 }
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001061 } else {
1062 DCHECK(invoke_instruction->IsInvokeVirtual());
Nicolas Geoffraye51ca8b2016-11-22 14:49:31 +00001063 new_method = classes->Get(i)->GetEmbeddedVTableEntry(method_index, pointer_size);
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001064 }
Nicolas Geoffray4f97a212016-02-25 16:17:54 +00001065 DCHECK(new_method != nullptr);
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001066 if (actual_method == nullptr) {
1067 actual_method = new_method;
1068 } else if (actual_method != new_method) {
1069 // Different methods, bailout.
1070 return false;
1071 }
1072 }
1073
1074 HInstruction* receiver = invoke_instruction->InputAt(0);
1075 HInstruction* cursor = invoke_instruction->GetPrevious();
1076 HBasicBlock* bb_cursor = invoke_instruction->GetBlock();
1077
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01001078 HInstruction* return_replacement = nullptr;
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001079 if (!TryBuildAndInline(invoke_instruction,
1080 actual_method,
1081 ReferenceTypeInfo::CreateInvalid(),
1082 &return_replacement)) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001083 return false;
1084 }
1085
1086 // We successfully inlined, now add a guard.
1087 HInstanceFieldGet* receiver_class = BuildGetReceiverClass(
1088 class_linker, receiver, invoke_instruction->GetDexPc());
1089
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001090 Primitive::Type type = Is64BitInstructionSet(graph_->GetInstructionSet())
1091 ? Primitive::kPrimLong
1092 : Primitive::kPrimInt;
1093 HClassTableGet* class_table_get = new (graph_->GetArena()) HClassTableGet(
1094 receiver_class,
1095 type,
Vladimir Markoa1de9182016-02-25 11:37:38 +00001096 invoke_instruction->IsInvokeVirtual() ? HClassTableGet::TableKind::kVTable
1097 : HClassTableGet::TableKind::kIMTable,
Nicolas Geoffray4f97a212016-02-25 16:17:54 +00001098 method_index,
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001099 invoke_instruction->GetDexPc());
1100
1101 HConstant* constant;
1102 if (type == Primitive::kPrimLong) {
1103 constant = graph_->GetLongConstant(
1104 reinterpret_cast<intptr_t>(actual_method), invoke_instruction->GetDexPc());
1105 } else {
1106 constant = graph_->GetIntConstant(
1107 reinterpret_cast<intptr_t>(actual_method), invoke_instruction->GetDexPc());
1108 }
1109
1110 HNotEqual* compare = new (graph_->GetArena()) HNotEqual(class_table_get, constant);
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001111 if (cursor != nullptr) {
1112 bb_cursor->InsertInstructionAfter(receiver_class, cursor);
1113 } else {
1114 bb_cursor->InsertInstructionBefore(receiver_class, bb_cursor->GetFirstInstruction());
1115 }
1116 bb_cursor->InsertInstructionAfter(class_table_get, receiver_class);
1117 bb_cursor->InsertInstructionAfter(compare, class_table_get);
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01001118
1119 if (outermost_graph_->IsCompilingOsr()) {
1120 CreateDiamondPatternForPolymorphicInline(compare, return_replacement, invoke_instruction);
1121 } else {
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01001122 HDeoptimize* deoptimize = new (graph_->GetArena()) HDeoptimize(
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +00001123 graph_->GetArena(),
1124 compare,
1125 receiver,
1126 HDeoptimize::Kind::kInline,
1127 invoke_instruction->GetDexPc());
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01001128 bb_cursor->InsertInstructionAfter(deoptimize, compare);
1129 deoptimize->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
1130 if (return_replacement != nullptr) {
1131 invoke_instruction->ReplaceWith(return_replacement);
1132 }
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +00001133 receiver->ReplaceUsesDominatedBy(deoptimize, deoptimize);
Nicolas Geoffray1be7cbd2016-04-29 13:56:01 +01001134 invoke_instruction->GetBlock()->RemoveInstruction(invoke_instruction);
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +00001135 deoptimize->SetReferenceTypeInfo(receiver->GetReferenceTypeInfo());
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01001136 }
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001137
1138 // Run type propagation to get the guard typed.
Vladimir Marko456307a2016-04-19 14:12:13 +00001139 ReferenceTypePropagation rtp_fixup(graph_,
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001140 outer_compilation_unit_.GetClassLoader(),
Vladimir Marko456307a2016-04-19 14:12:13 +00001141 outer_compilation_unit_.GetDexCache(),
1142 handles_,
1143 /* is_first_run */ false);
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001144 rtp_fixup.Run();
1145
1146 MaybeRecordStat(kInlinedPolymorphicCall);
1147
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001148 LOG_SUCCESS() << "Inlined same polymorphic target " << actual_method->PrettyMethod();
Nicolas Geoffraya42363f2015-12-17 14:57:09 +00001149 return true;
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001150}
1151
Mingyao Yang063fc772016-08-02 11:02:54 -07001152bool HInliner::TryInlineAndReplace(HInvoke* invoke_instruction,
1153 ArtMethod* method,
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001154 ReferenceTypeInfo receiver_type,
Mingyao Yang063fc772016-08-02 11:02:54 -07001155 bool do_rtp,
1156 bool cha_devirtualize) {
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001157 HInstruction* return_replacement = nullptr;
Mingyao Yang063fc772016-08-02 11:02:54 -07001158 uint32_t dex_pc = invoke_instruction->GetDexPc();
1159 HInstruction* cursor = invoke_instruction->GetPrevious();
1160 HBasicBlock* bb_cursor = invoke_instruction->GetBlock();
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001161 if (!TryBuildAndInline(invoke_instruction, method, receiver_type, &return_replacement)) {
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +00001162 if (invoke_instruction->IsInvokeInterface()) {
Nicolas Geoffray18ea1c92017-03-27 08:00:18 +00001163 DCHECK(!method->IsProxyMethod());
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +00001164 // Turn an invoke-interface into an invoke-virtual. An invoke-virtual is always
1165 // better than an invoke-interface because:
1166 // 1) In the best case, the interface call has one more indirection (to fetch the IMT).
1167 // 2) We will not go to the conflict trampoline with an invoke-virtual.
1168 // TODO: Consider sharpening once it is not dependent on the compiler driver.
Nicolas Geoffray18ea1c92017-03-27 08:00:18 +00001169
1170 if (method->IsDefault() && !method->IsCopied()) {
1171 // Changing to invoke-virtual cannot be done on an original default method
1172 // since it's not in any vtable. Devirtualization by exact type/inline-cache
1173 // always uses a method in the iftable which is never an original default
1174 // method.
1175 // On the other hand, inlining an original default method by CHA is fine.
1176 DCHECK(cha_devirtualize);
1177 return false;
1178 }
1179
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +00001180 const DexFile& caller_dex_file = *caller_compilation_unit_.GetDexFile();
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +01001181 uint32_t dex_method_index = FindMethodIndexIn(
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +00001182 method, caller_dex_file, invoke_instruction->GetDexMethodIndex());
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +01001183 if (dex_method_index == DexFile::kDexNoIndex) {
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +00001184 return false;
1185 }
1186 HInvokeVirtual* new_invoke = new (graph_->GetArena()) HInvokeVirtual(
1187 graph_->GetArena(),
1188 invoke_instruction->GetNumberOfArguments(),
1189 invoke_instruction->GetType(),
1190 invoke_instruction->GetDexPc(),
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +01001191 dex_method_index,
1192 method,
Nicolas Geoffray5bf7bac2016-07-06 14:18:23 +00001193 method->GetMethodIndex());
1194 HInputsRef inputs = invoke_instruction->GetInputs();
1195 for (size_t index = 0; index != inputs.size(); ++index) {
1196 new_invoke->SetArgumentAt(index, inputs[index]);
1197 }
1198 invoke_instruction->GetBlock()->InsertInstructionBefore(new_invoke, invoke_instruction);
1199 new_invoke->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
1200 if (invoke_instruction->GetType() == Primitive::kPrimNot) {
1201 new_invoke->SetReferenceTypeInfo(invoke_instruction->GetReferenceTypeInfo());
1202 }
1203 return_replacement = new_invoke;
1204 } else {
1205 // TODO: Consider sharpening an invoke virtual once it is not dependent on the
1206 // compiler driver.
1207 return false;
1208 }
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001209 }
Mingyao Yang063fc772016-08-02 11:02:54 -07001210 if (cha_devirtualize) {
1211 AddCHAGuard(invoke_instruction, dex_pc, cursor, bb_cursor);
1212 }
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001213 if (return_replacement != nullptr) {
1214 invoke_instruction->ReplaceWith(return_replacement);
1215 }
1216 invoke_instruction->GetBlock()->RemoveInstruction(invoke_instruction);
David Brazdil94ab38f2016-06-21 17:48:19 +01001217 FixUpReturnReferenceType(method, return_replacement);
1218 if (do_rtp && ReturnTypeMoreSpecific(invoke_instruction, return_replacement)) {
1219 // Actual return value has a more specific type than the method's declared
1220 // return type. Run RTP again on the outer graph to propagate it.
1221 ReferenceTypePropagation(graph_,
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001222 outer_compilation_unit_.GetClassLoader(),
David Brazdil94ab38f2016-06-21 17:48:19 +01001223 outer_compilation_unit_.GetDexCache(),
1224 handles_,
1225 /* is_first_run */ false).Run();
1226 }
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001227 return true;
1228}
1229
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001230size_t HInliner::CountRecursiveCallsOf(ArtMethod* method) const {
1231 const HInliner* current = this;
1232 size_t count = 0;
1233 do {
1234 if (current->graph_->GetArtMethod() == method) {
1235 ++count;
1236 }
1237 current = current->parent_;
1238 } while (current != nullptr);
1239 return count;
1240}
1241
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001242bool HInliner::TryBuildAndInline(HInvoke* invoke_instruction,
1243 ArtMethod* method,
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001244 ReferenceTypeInfo receiver_type,
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001245 HInstruction** return_replacement) {
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01001246 if (method->IsProxyMethod()) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001247 LOG_FAIL(kNotInlinedProxy)
1248 << "Method " << method->PrettyMethod()
1249 << " is not inlined because of unimplemented inline support for proxy methods.";
1250 return false;
1251 }
1252
1253 if (CountRecursiveCallsOf(method) > kMaximumNumberOfRecursiveCalls) {
1254 LOG_FAIL(kNotInlinedRecursiveBudget)
1255 << "Method "
1256 << method->PrettyMethod()
1257 << " is not inlined because it has reached its recursive call budget.";
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01001258 return false;
1259 }
1260
Jeff Haodcdc85b2015-12-04 14:06:18 -08001261 // Check whether we're allowed to inline. The outermost compilation unit is the relevant
1262 // dex file here (though the transitivity of an inline chain would allow checking the calller).
1263 if (!compiler_driver_->MayInline(method->GetDexFile(),
1264 outer_compilation_unit_.GetDexFile())) {
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001265 if (TryPatternSubstitution(invoke_instruction, method, return_replacement)) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001266 LOG_SUCCESS() << "Successfully replaced pattern of invoke "
1267 << method->PrettyMethod();
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001268 MaybeRecordStat(kReplacedInvokeWithSimplePattern);
1269 return true;
1270 }
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001271 LOG_FAIL(kNotInlinedWont)
1272 << "Won't inline " << method->PrettyMethod() << " in "
1273 << outer_compilation_unit_.GetDexFile()->GetLocation() << " ("
1274 << caller_compilation_unit_.GetDexFile()->GetLocation() << ") from "
1275 << method->GetDexFile()->GetLocation();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001276 return false;
1277 }
1278
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001279 bool same_dex_file = IsSameDexFile(*outer_compilation_unit_.GetDexFile(), *method->GetDexFile());
1280
1281 const DexFile::CodeItem* code_item = method->GetCodeItem();
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001282
1283 if (code_item == nullptr) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001284 LOG_FAIL_NO_STAT()
1285 << "Method " << method->PrettyMethod() << " is not inlined because it is native";
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001286 return false;
1287 }
1288
Calin Juravleec748352015-07-29 13:52:12 +01001289 size_t inline_max_code_units = compiler_driver_->GetCompilerOptions().GetInlineMaxCodeUnits();
1290 if (code_item->insns_size_in_code_units_ > inline_max_code_units) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001291 LOG_FAIL(kNotInlinedCodeItem)
1292 << "Method " << method->PrettyMethod()
1293 << " is not inlined because its code item is too big: "
1294 << code_item->insns_size_in_code_units_
1295 << " > "
1296 << inline_max_code_units;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001297 return false;
1298 }
1299
1300 if (code_item->tries_size_ != 0) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001301 LOG_FAIL(kNotInlinedTryCatch)
1302 << "Method " << method->PrettyMethod() << " is not inlined because of try block";
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001303 return false;
1304 }
1305
Nicolas Geoffray250a3782016-04-20 16:27:53 +01001306 if (!method->IsCompilable()) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001307 LOG_FAIL(kNotInlinedNotVerified)
1308 << "Method " << method->PrettyMethod()
1309 << " has soft failures un-handled by the compiler, so it cannot be inlined";
Nicolas Geoffray250a3782016-04-20 16:27:53 +01001310 }
1311
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001312 if (!method->GetDeclaringClass()->IsVerified()) {
1313 uint16_t class_def_idx = method->GetDeclaringClass()->GetDexClassDefIndex();
Calin Juravleffc87072016-04-20 14:22:09 +01001314 if (Runtime::Current()->UseJitCompilation() ||
Nicolas Geoffray5b82d332016-02-18 14:22:32 +00001315 !compiler_driver_->IsMethodVerifiedWithoutFailures(
1316 method->GetDexMethodIndex(), class_def_idx, *method->GetDexFile())) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001317 LOG_FAIL(kNotInlinedNotVerified)
1318 << "Method " << method->PrettyMethod()
1319 << " couldn't be verified, so it cannot be inlined";
Nicolas Geoffrayccc61972015-10-01 14:34:20 +01001320 return false;
1321 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001322 }
1323
Roland Levillain4c0eb422015-04-24 16:43:49 +01001324 if (invoke_instruction->IsInvokeStaticOrDirect() &&
1325 invoke_instruction->AsInvokeStaticOrDirect()->IsStaticWithImplicitClinitCheck()) {
1326 // Case of a static method that cannot be inlined because it implicitly
1327 // requires an initialization check of its declaring class.
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001328 LOG_FAIL(kNotInlinedDexCache) << "Method " << method->PrettyMethod()
1329 << " is not inlined because it is static and requires a clinit"
1330 << " check that cannot be emitted due to Dex cache limitations";
Roland Levillain4c0eb422015-04-24 16:43:49 +01001331 return false;
1332 }
1333
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001334 if (!TryBuildAndInlineHelper(
1335 invoke_instruction, method, receiver_type, same_dex_file, return_replacement)) {
Nicolas Geoffrayc0365b12015-03-18 18:31:52 +00001336 return false;
1337 }
1338
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001339 LOG_SUCCESS() << method->PrettyMethod();
Nicolas Geoffrayc0365b12015-03-18 18:31:52 +00001340 MaybeRecordStat(kInlinedInvoke);
1341 return true;
1342}
1343
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001344static HInstruction* GetInvokeInputForArgVRegIndex(HInvoke* invoke_instruction,
1345 size_t arg_vreg_index)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001346 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001347 size_t input_index = 0;
1348 for (size_t i = 0; i < arg_vreg_index; ++i, ++input_index) {
1349 DCHECK_LT(input_index, invoke_instruction->GetNumberOfArguments());
1350 if (Primitive::Is64BitType(invoke_instruction->InputAt(input_index)->GetType())) {
1351 ++i;
1352 DCHECK_NE(i, arg_vreg_index);
1353 }
1354 }
1355 DCHECK_LT(input_index, invoke_instruction->GetNumberOfArguments());
1356 return invoke_instruction->InputAt(input_index);
1357}
1358
1359// Try to recognize known simple patterns and replace invoke call with appropriate instructions.
1360bool HInliner::TryPatternSubstitution(HInvoke* invoke_instruction,
1361 ArtMethod* resolved_method,
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001362 HInstruction** return_replacement) {
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001363 InlineMethod inline_method;
1364 if (!InlineMethodAnalyser::AnalyseMethodCode(resolved_method, &inline_method)) {
1365 return false;
1366 }
1367
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001368 switch (inline_method.opcode) {
1369 case kInlineOpNop:
1370 DCHECK_EQ(invoke_instruction->GetType(), Primitive::kPrimVoid);
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001371 *return_replacement = nullptr;
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001372 break;
1373 case kInlineOpReturnArg:
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001374 *return_replacement = GetInvokeInputForArgVRegIndex(invoke_instruction,
1375 inline_method.d.return_data.arg);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001376 break;
1377 case kInlineOpNonWideConst:
1378 if (resolved_method->GetShorty()[0] == 'L') {
1379 DCHECK_EQ(inline_method.d.data, 0u);
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001380 *return_replacement = graph_->GetNullConstant();
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001381 } else {
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001382 *return_replacement = graph_->GetIntConstant(static_cast<int32_t>(inline_method.d.data));
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001383 }
1384 break;
1385 case kInlineOpIGet: {
1386 const InlineIGetIPutData& data = inline_method.d.ifield_data;
1387 if (data.method_is_static || data.object_arg != 0u) {
1388 // TODO: Needs null check.
1389 return false;
1390 }
1391 HInstruction* obj = GetInvokeInputForArgVRegIndex(invoke_instruction, data.object_arg);
Vladimir Markof44d36c2017-03-14 14:18:46 +00001392 HInstanceFieldGet* iget = CreateInstanceFieldGet(data.field_idx, resolved_method, obj);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001393 DCHECK_EQ(iget->GetFieldOffset().Uint32Value(), data.field_offset);
1394 DCHECK_EQ(iget->IsVolatile() ? 1u : 0u, data.is_volatile);
1395 invoke_instruction->GetBlock()->InsertInstructionBefore(iget, invoke_instruction);
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001396 *return_replacement = iget;
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001397 break;
1398 }
1399 case kInlineOpIPut: {
1400 const InlineIGetIPutData& data = inline_method.d.ifield_data;
1401 if (data.method_is_static || data.object_arg != 0u) {
1402 // TODO: Needs null check.
1403 return false;
1404 }
1405 HInstruction* obj = GetInvokeInputForArgVRegIndex(invoke_instruction, data.object_arg);
1406 HInstruction* value = GetInvokeInputForArgVRegIndex(invoke_instruction, data.src_arg);
Vladimir Markof44d36c2017-03-14 14:18:46 +00001407 HInstanceFieldSet* iput = CreateInstanceFieldSet(data.field_idx, resolved_method, obj, value);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001408 DCHECK_EQ(iput->GetFieldOffset().Uint32Value(), data.field_offset);
1409 DCHECK_EQ(iput->IsVolatile() ? 1u : 0u, data.is_volatile);
1410 invoke_instruction->GetBlock()->InsertInstructionBefore(iput, invoke_instruction);
1411 if (data.return_arg_plus1 != 0u) {
1412 size_t return_arg = data.return_arg_plus1 - 1u;
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001413 *return_replacement = GetInvokeInputForArgVRegIndex(invoke_instruction, return_arg);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001414 }
1415 break;
1416 }
Vladimir Marko354efa62016-02-04 19:46:56 +00001417 case kInlineOpConstructor: {
1418 const InlineConstructorData& data = inline_method.d.constructor_data;
1419 // Get the indexes to arrays for easier processing.
1420 uint16_t iput_field_indexes[] = {
1421 data.iput0_field_index, data.iput1_field_index, data.iput2_field_index
1422 };
1423 uint16_t iput_args[] = { data.iput0_arg, data.iput1_arg, data.iput2_arg };
1424 static_assert(arraysize(iput_args) == arraysize(iput_field_indexes), "Size mismatch");
1425 // Count valid field indexes.
1426 size_t number_of_iputs = 0u;
1427 while (number_of_iputs != arraysize(iput_field_indexes) &&
1428 iput_field_indexes[number_of_iputs] != DexFile::kDexNoIndex16) {
1429 // Check that there are no duplicate valid field indexes.
1430 DCHECK_EQ(0, std::count(iput_field_indexes + number_of_iputs + 1,
1431 iput_field_indexes + arraysize(iput_field_indexes),
1432 iput_field_indexes[number_of_iputs]));
1433 ++number_of_iputs;
1434 }
1435 // Check that there are no valid field indexes in the rest of the array.
1436 DCHECK_EQ(0, std::count_if(iput_field_indexes + number_of_iputs,
1437 iput_field_indexes + arraysize(iput_field_indexes),
1438 [](uint16_t index) { return index != DexFile::kDexNoIndex16; }));
1439
1440 // Create HInstanceFieldSet for each IPUT that stores non-zero data.
Vladimir Marko354efa62016-02-04 19:46:56 +00001441 HInstruction* obj = GetInvokeInputForArgVRegIndex(invoke_instruction, /* this */ 0u);
1442 bool needs_constructor_barrier = false;
1443 for (size_t i = 0; i != number_of_iputs; ++i) {
1444 HInstruction* value = GetInvokeInputForArgVRegIndex(invoke_instruction, iput_args[i]);
Roland Levillain1a653882016-03-18 18:05:57 +00001445 if (!value->IsConstant() || !value->AsConstant()->IsZeroBitPattern()) {
Vladimir Marko354efa62016-02-04 19:46:56 +00001446 uint16_t field_index = iput_field_indexes[i];
Vladimir Markof44d36c2017-03-14 14:18:46 +00001447 bool is_final;
1448 HInstanceFieldSet* iput =
1449 CreateInstanceFieldSet(field_index, resolved_method, obj, value, &is_final);
Vladimir Marko354efa62016-02-04 19:46:56 +00001450 invoke_instruction->GetBlock()->InsertInstructionBefore(iput, invoke_instruction);
1451
1452 // Check whether the field is final. If it is, we need to add a barrier.
Vladimir Markof44d36c2017-03-14 14:18:46 +00001453 if (is_final) {
Vladimir Marko354efa62016-02-04 19:46:56 +00001454 needs_constructor_barrier = true;
1455 }
1456 }
1457 }
1458 if (needs_constructor_barrier) {
1459 HMemoryBarrier* barrier = new (graph_->GetArena()) HMemoryBarrier(kStoreStore, kNoDexPc);
1460 invoke_instruction->GetBlock()->InsertInstructionBefore(barrier, invoke_instruction);
1461 }
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001462 *return_replacement = nullptr;
Vladimir Marko354efa62016-02-04 19:46:56 +00001463 break;
1464 }
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001465 default:
1466 LOG(FATAL) << "UNREACHABLE";
1467 UNREACHABLE();
1468 }
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001469 return true;
1470}
1471
Vladimir Markof44d36c2017-03-14 14:18:46 +00001472HInstanceFieldGet* HInliner::CreateInstanceFieldGet(uint32_t field_index,
1473 ArtMethod* referrer,
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001474 HInstruction* obj)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001475 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markof44d36c2017-03-14 14:18:46 +00001476 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1477 ArtField* resolved_field =
1478 class_linker->LookupResolvedField(field_index, referrer, /* is_static */ false);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001479 DCHECK(resolved_field != nullptr);
1480 HInstanceFieldGet* iget = new (graph_->GetArena()) HInstanceFieldGet(
1481 obj,
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00001482 resolved_field,
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001483 resolved_field->GetTypeAsPrimitiveType(),
1484 resolved_field->GetOffset(),
1485 resolved_field->IsVolatile(),
1486 field_index,
1487 resolved_field->GetDeclaringClass()->GetDexClassDefIndex(),
Vladimir Markof44d36c2017-03-14 14:18:46 +00001488 *referrer->GetDexFile(),
Vladimir Markoadda4352016-01-29 10:24:41 +00001489 // Read barrier generates a runtime call in slow path and we need a valid
1490 // dex pc for the associated stack map. 0 is bogus but valid. Bug: 26854537.
1491 /* dex_pc */ 0);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001492 if (iget->GetType() == Primitive::kPrimNot) {
Vladimir Marko456307a2016-04-19 14:12:13 +00001493 // Use the same dex_cache that we used for field lookup as the hint_dex_cache.
Vladimir Markof44d36c2017-03-14 14:18:46 +00001494 Handle<mirror::DexCache> dex_cache = handles_->NewHandle(referrer->GetDexCache());
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001495 ReferenceTypePropagation rtp(graph_,
1496 outer_compilation_unit_.GetClassLoader(),
1497 dex_cache,
1498 handles_,
1499 /* is_first_run */ false);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001500 rtp.Visit(iget);
1501 }
1502 return iget;
1503}
1504
Vladimir Markof44d36c2017-03-14 14:18:46 +00001505HInstanceFieldSet* HInliner::CreateInstanceFieldSet(uint32_t field_index,
1506 ArtMethod* referrer,
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001507 HInstruction* obj,
Vladimir Markof44d36c2017-03-14 14:18:46 +00001508 HInstruction* value,
1509 bool* is_final)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001510 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markof44d36c2017-03-14 14:18:46 +00001511 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1512 ArtField* resolved_field =
1513 class_linker->LookupResolvedField(field_index, referrer, /* is_static */ false);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001514 DCHECK(resolved_field != nullptr);
Vladimir Markof44d36c2017-03-14 14:18:46 +00001515 if (is_final != nullptr) {
1516 // This information is needed only for constructors.
1517 DCHECK(referrer->IsConstructor());
1518 *is_final = resolved_field->IsFinal();
1519 }
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001520 HInstanceFieldSet* iput = new (graph_->GetArena()) HInstanceFieldSet(
1521 obj,
1522 value,
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00001523 resolved_field,
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001524 resolved_field->GetTypeAsPrimitiveType(),
1525 resolved_field->GetOffset(),
1526 resolved_field->IsVolatile(),
1527 field_index,
1528 resolved_field->GetDeclaringClass()->GetDexClassDefIndex(),
Vladimir Markof44d36c2017-03-14 14:18:46 +00001529 *referrer->GetDexFile(),
Vladimir Markoadda4352016-01-29 10:24:41 +00001530 // Read barrier generates a runtime call in slow path and we need a valid
1531 // dex pc for the associated stack map. 0 is bogus but valid. Bug: 26854537.
1532 /* dex_pc */ 0);
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001533 return iput;
1534}
Nicolas Geoffrayd9994f02016-02-11 17:35:55 +00001535
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001536bool HInliner::TryBuildAndInlineHelper(HInvoke* invoke_instruction,
1537 ArtMethod* resolved_method,
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001538 ReferenceTypeInfo receiver_type,
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001539 bool same_dex_file,
1540 HInstruction** return_replacement) {
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001541 DCHECK(!(resolved_method->IsStatic() && receiver_type.IsValid()));
Nicolas Geoffrayc0365b12015-03-18 18:31:52 +00001542 ScopedObjectAccess soa(Thread::Current());
1543 const DexFile::CodeItem* code_item = resolved_method->GetCodeItem();
Guillaume "Vermeille" Sanchezae09d2d2015-05-29 10:52:55 +01001544 const DexFile& callee_dex_file = *resolved_method->GetDexFile();
1545 uint32_t method_index = resolved_method->GetDexMethodIndex();
Calin Juravle2e768302015-07-28 14:41:11 +00001546 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
Mathieu Chartier736b5602015-09-02 14:54:11 -07001547 Handle<mirror::DexCache> dex_cache(handles_->NewHandle(resolved_method->GetDexCache()));
Nicolas Geoffrayf1aedb12016-07-28 03:49:14 +01001548 Handle<mirror::ClassLoader> class_loader(handles_->NewHandle(
1549 resolved_method->GetDeclaringClass()->GetClassLoader()));
1550
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001551 DexCompilationUnit dex_compilation_unit(
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001552 class_loader,
Nicolas Geoffray5b82d332016-02-18 14:22:32 +00001553 class_linker,
1554 callee_dex_file,
1555 code_item,
1556 resolved_method->GetDeclaringClass()->GetDexClassDefIndex(),
1557 method_index,
1558 resolved_method->GetAccessFlags(),
1559 /* verified_method */ nullptr,
1560 dex_cache);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001561
Calin Juravle3cd4fc82015-05-14 15:15:42 +01001562 bool requires_ctor_barrier = false;
1563
1564 if (dex_compilation_unit.IsConstructor()) {
1565 // If it's a super invocation and we already generate a barrier there's no need
1566 // to generate another one.
1567 // We identify super calls by looking at the "this" pointer. If its value is the
1568 // same as the local "this" pointer then we must have a super invocation.
1569 bool is_super_invocation = invoke_instruction->InputAt(0)->IsParameterValue()
1570 && invoke_instruction->InputAt(0)->AsParameterValue()->IsThis();
1571 if (is_super_invocation && graph_->ShouldGenerateConstructorBarrier()) {
1572 requires_ctor_barrier = false;
1573 } else {
1574 Thread* self = Thread::Current();
1575 requires_ctor_barrier = compiler_driver_->RequiresConstructorBarrier(self,
1576 dex_compilation_unit.GetDexFile(),
1577 dex_compilation_unit.GetClassDefIndex());
1578 }
1579 }
1580
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +01001581 InvokeType invoke_type = invoke_instruction->GetInvokeType();
Nicolas Geoffray35071052015-06-09 15:43:38 +01001582 if (invoke_type == kInterface) {
1583 // We have statically resolved the dispatch. To please the class linker
1584 // at runtime, we change this call as if it was a virtual call.
1585 invoke_type = kVirtual;
1586 }
David Brazdil3f523062016-02-29 16:53:33 +00001587
1588 const int32_t caller_instruction_counter = graph_->GetCurrentInstructionId();
Nicolas Geoffraye0fe7ae2015-03-09 10:02:49 +00001589 HGraph* callee_graph = new (graph_->GetArena()) HGraph(
Nicolas Geoffray0a23d742015-05-07 11:57:35 +01001590 graph_->GetArena(),
Guillaume "Vermeille" Sanchezae09d2d2015-05-29 10:52:55 +01001591 callee_dex_file,
Nicolas Geoffray0a23d742015-05-07 11:57:35 +01001592 method_index,
Calin Juravle3cd4fc82015-05-14 15:15:42 +01001593 requires_ctor_barrier,
Mathieu Chartiere401d142015-04-22 13:56:20 -07001594 compiler_driver_->GetInstructionSet(),
Nicolas Geoffray35071052015-06-09 15:43:38 +01001595 invoke_type,
Nicolas Geoffray0a23d742015-05-07 11:57:35 +01001596 graph_->IsDebuggable(),
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001597 /* osr */ false,
David Brazdil3f523062016-02-29 16:53:33 +00001598 caller_instruction_counter);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001599 callee_graph->SetArtMethod(resolved_method);
David Brazdil5e8b1372015-01-23 14:39:08 +00001600
Vladimir Marko438709f2017-02-23 18:56:13 +00001601 // When they are needed, allocate `inline_stats_` on the Arena instead
Roland Levillaina8013fd2016-04-04 15:34:31 +01001602 // of on the stack, as Clang might produce a stack frame too large
1603 // for this function, that would not fit the requirements of the
1604 // `-Wframe-larger-than` option.
Vladimir Marko438709f2017-02-23 18:56:13 +00001605 if (stats_ != nullptr) {
1606 // Reuse one object for all inline attempts from this caller to keep Arena memory usage low.
1607 if (inline_stats_ == nullptr) {
1608 void* storage = graph_->GetArena()->Alloc<OptimizingCompilerStats>(kArenaAllocMisc);
1609 inline_stats_ = new (storage) OptimizingCompilerStats;
1610 } else {
1611 inline_stats_->Reset();
1612 }
1613 }
David Brazdil5e8b1372015-01-23 14:39:08 +00001614 HGraphBuilder builder(callee_graph,
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001615 &dex_compilation_unit,
1616 &outer_compilation_unit_,
Nicolas Geoffray9437b782015-03-25 10:08:51 +00001617 resolved_method->GetDexFile(),
David Brazdil86ea7ee2016-02-16 09:26:07 +00001618 *code_item,
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001619 compiler_driver_,
Nicolas Geoffray83c8e272017-01-31 14:36:37 +00001620 codegen_,
Vladimir Marko438709f2017-02-23 18:56:13 +00001621 inline_stats_,
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01001622 resolved_method->GetQuickenedInfo(class_linker->GetImagePointerSize()),
David Brazdildee58d62016-04-07 09:54:26 +00001623 dex_cache,
1624 handles_);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001625
David Brazdildee58d62016-04-07 09:54:26 +00001626 if (builder.BuildGraph() != kAnalysisSuccess) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001627 LOG_FAIL(kNotInlinedCannotBuild)
1628 << "Method " << callee_dex_file.PrettyMethod(method_index)
1629 << " could not be built, so cannot be inlined";
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001630 return false;
1631 }
1632
Nicolas Geoffray259136f2014-12-17 23:21:58 +00001633 if (!RegisterAllocator::CanAllocateRegistersFor(*callee_graph,
1634 compiler_driver_->GetInstructionSet())) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001635 LOG_FAIL(kNotInlinedRegisterAllocator)
1636 << "Method " << callee_dex_file.PrettyMethod(method_index)
1637 << " cannot be inlined because of the register allocator";
Nicolas Geoffray259136f2014-12-17 23:21:58 +00001638 return false;
1639 }
1640
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001641 size_t parameter_index = 0;
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001642 bool run_rtp = false;
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001643 for (HInstructionIterator instructions(callee_graph->GetEntryBlock()->GetInstructions());
1644 !instructions.Done();
1645 instructions.Advance()) {
1646 HInstruction* current = instructions.Current();
1647 if (current->IsParameterValue()) {
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001648 HInstruction* argument = invoke_instruction->InputAt(parameter_index);
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001649 if (argument->IsNullConstant()) {
1650 current->ReplaceWith(callee_graph->GetNullConstant());
1651 } else if (argument->IsIntConstant()) {
1652 current->ReplaceWith(callee_graph->GetIntConstant(argument->AsIntConstant()->GetValue()));
1653 } else if (argument->IsLongConstant()) {
1654 current->ReplaceWith(callee_graph->GetLongConstant(argument->AsLongConstant()->GetValue()));
1655 } else if (argument->IsFloatConstant()) {
1656 current->ReplaceWith(
1657 callee_graph->GetFloatConstant(argument->AsFloatConstant()->GetValue()));
1658 } else if (argument->IsDoubleConstant()) {
1659 current->ReplaceWith(
1660 callee_graph->GetDoubleConstant(argument->AsDoubleConstant()->GetValue()));
1661 } else if (argument->GetType() == Primitive::kPrimNot) {
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001662 if (!resolved_method->IsStatic() && parameter_index == 0 && receiver_type.IsValid()) {
1663 run_rtp = true;
1664 current->SetReferenceTypeInfo(receiver_type);
1665 } else {
1666 current->SetReferenceTypeInfo(argument->GetReferenceTypeInfo());
1667 }
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001668 current->AsParameterValue()->SetCanBeNull(argument->CanBeNull());
1669 }
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001670 ++parameter_index;
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001671 }
1672 }
1673
David Brazdil94ab38f2016-06-21 17:48:19 +01001674 // We have replaced formal arguments with actual arguments. If actual types
1675 // are more specific than the declared ones, run RTP again on the inner graph.
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001676 if (run_rtp || ArgumentTypesMoreSpecific(invoke_instruction, resolved_method)) {
David Brazdil94ab38f2016-06-21 17:48:19 +01001677 ReferenceTypePropagation(callee_graph,
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001678 outer_compilation_unit_.GetClassLoader(),
David Brazdil94ab38f2016-06-21 17:48:19 +01001679 dex_compilation_unit.GetDexCache(),
1680 handles_,
1681 /* is_first_run */ false).Run();
1682 }
1683
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001684 RunOptimizations(callee_graph, code_item, dex_compilation_unit);
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +00001685
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001686 HBasicBlock* exit_block = callee_graph->GetExitBlock();
1687 if (exit_block == nullptr) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001688 LOG_FAIL(kNotInlinedInfiniteLoop)
1689 << "Method " << callee_dex_file.PrettyMethod(method_index)
1690 << " could not be inlined because it has an infinite loop";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001691 return false;
1692 }
1693
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00001694 bool has_one_return = false;
Vladimir Marko60584552015-09-03 13:35:12 +00001695 for (HBasicBlock* predecessor : exit_block->GetPredecessors()) {
1696 if (predecessor->GetLastInstruction()->IsThrow()) {
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00001697 if (invoke_instruction->GetBlock()->IsTryBlock()) {
1698 // TODO(ngeoffray): Support adding HTryBoundary in Hgraph::InlineInto.
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001699 LOG_FAIL(kNotInlinedTryCatch)
1700 << "Method " << callee_dex_file.PrettyMethod(method_index)
1701 << " could not be inlined because one branch always throws and"
1702 << " caller is in a try/catch block";
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00001703 return false;
1704 } else if (graph_->GetExitBlock() == nullptr) {
1705 // TODO(ngeoffray): Support adding HExit in the caller graph.
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001706 LOG_FAIL(kNotInlinedInfiniteLoop)
1707 << "Method " << callee_dex_file.PrettyMethod(method_index)
1708 << " could not be inlined because one branch always throws and"
1709 << " caller does not have an exit block";
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00001710 return false;
Nicolas Geoffray1eede6a2017-03-02 16:14:53 +00001711 } else if (graph_->HasIrreducibleLoops()) {
1712 // TODO(ngeoffray): Support re-computing loop information to graphs with
1713 // irreducible loops?
1714 VLOG(compiler) << "Method " << callee_dex_file.PrettyMethod(method_index)
1715 << " could not be inlined because one branch always throws and"
1716 << " caller has irreducible loops";
1717 return false;
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00001718 }
1719 } else {
1720 has_one_return = true;
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001721 }
1722 }
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00001723
1724 if (!has_one_return) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001725 LOG_FAIL(kNotInlinedAlwaysThrows)
1726 << "Method " << callee_dex_file.PrettyMethod(method_index)
1727 << " could not be inlined because it always throws";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001728 return false;
1729 }
1730
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001731 size_t number_of_instructions = 0;
Vladimir Marko2c45bc92016-10-25 16:54:12 +01001732 // Skip the entry block, it does not contain instructions that prevent inlining.
1733 for (HBasicBlock* block : callee_graph->GetReversePostOrderSkipEntryBlock()) {
David Sehrc757dec2016-11-04 15:48:34 -07001734 if (block->IsLoopHeader()) {
1735 if (block->GetLoopInformation()->IsIrreducible()) {
1736 // Don't inline methods with irreducible loops, they could prevent some
1737 // optimizations to run.
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001738 LOG_FAIL(kNotInlinedIrreducibleLoop)
1739 << "Method " << callee_dex_file.PrettyMethod(method_index)
1740 << " could not be inlined because it contains an irreducible loop";
David Sehrc757dec2016-11-04 15:48:34 -07001741 return false;
1742 }
1743 if (!block->GetLoopInformation()->HasExitEdge()) {
1744 // Don't inline methods with loops without exit, since they cause the
1745 // loop information to be computed incorrectly when updating after
1746 // inlining.
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001747 LOG_FAIL(kNotInlinedLoopWithoutExit)
1748 << "Method " << callee_dex_file.PrettyMethod(method_index)
1749 << " could not be inlined because it contains a loop with no exit";
David Sehrc757dec2016-11-04 15:48:34 -07001750 return false;
1751 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001752 }
1753
1754 for (HInstructionIterator instr_it(block->GetInstructions());
1755 !instr_it.Done();
1756 instr_it.Advance()) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001757 if (++number_of_instructions >= inlining_budget_) {
1758 LOG_FAIL(kNotInlinedInstructionBudget)
1759 << "Method " << callee_dex_file.PrettyMethod(method_index)
1760 << " is not inlined because the outer method has reached"
1761 << " its instruction budget limit.";
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001762 return false;
1763 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001764 HInstruction* current = instr_it.Current();
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001765 if (current->NeedsEnvironment() &&
1766 (total_number_of_dex_registers_ >= kMaximumNumberOfCumulatedDexRegisters)) {
1767 LOG_FAIL(kNotInlinedEnvironmentBudget)
1768 << "Method " << callee_dex_file.PrettyMethod(method_index)
1769 << " is not inlined because its caller has reached"
1770 << " its environment budget limit.";
Nicolas Geoffray5949fa02015-12-18 10:57:10 +00001771 return false;
1772 }
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001773
Nicolas Geoffrayfbdfa6d2017-02-03 10:43:13 +00001774 if (current->NeedsEnvironment() &&
1775 !CanEncodeInlinedMethodInStackMap(*caller_compilation_unit_.GetDexFile(),
1776 resolved_method)) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001777 LOG_FAIL(kNotInlinedStackMaps)
1778 << "Method " << callee_dex_file.PrettyMethod(method_index)
1779 << " could not be inlined because " << current->DebugName()
1780 << " needs an environment, is in a different dex file"
1781 << ", and cannot be encoded in the stack maps.";
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001782 return false;
1783 }
Nicolas Geoffray9437b782015-03-25 10:08:51 +00001784
Vladimir Markodc151b22015-10-15 18:02:30 +01001785 if (!same_dex_file && current->NeedsDexCacheOfDeclaringClass()) {
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001786 LOG_FAIL(kNotInlinedDexCache)
1787 << "Method " << callee_dex_file.PrettyMethod(method_index)
1788 << " could not be inlined because " << current->DebugName()
1789 << " it is in a different dex file and requires access to the dex cache";
Nicolas Geoffray9437b782015-03-25 10:08:51 +00001790 return false;
1791 }
Nicolas Geoffrayd9309292015-10-31 22:21:31 +00001792
Nicolas Geoffrayd9309292015-10-31 22:21:31 +00001793 if (current->IsUnresolvedStaticFieldGet() ||
1794 current->IsUnresolvedInstanceFieldGet() ||
1795 current->IsUnresolvedStaticFieldSet() ||
1796 current->IsUnresolvedInstanceFieldSet()) {
1797 // Entrypoint for unresolved fields does not handle inlined frames.
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001798 LOG_FAIL(kNotInlinedUnresolvedEntrypoint)
1799 << "Method " << callee_dex_file.PrettyMethod(method_index)
1800 << " could not be inlined because it is using an unresolved"
1801 << " entrypoint";
Nicolas Geoffrayd9309292015-10-31 22:21:31 +00001802 return false;
1803 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001804 }
1805 }
David Brazdil3f523062016-02-29 16:53:33 +00001806 DCHECK_EQ(caller_instruction_counter, graph_->GetCurrentInstructionId())
1807 << "No instructions can be added to the outer graph while inner graph is being built";
1808
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001809 // Inline the callee graph inside the caller graph.
David Brazdil3f523062016-02-29 16:53:33 +00001810 const int32_t callee_instruction_counter = callee_graph->GetCurrentInstructionId();
1811 graph_->SetCurrentInstructionId(callee_instruction_counter);
Nicolas Geoffray55bd7492016-02-16 15:37:12 +00001812 *return_replacement = callee_graph->InlineInto(graph_, invoke_instruction);
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001813 // Update our budget for other inlining attempts in `caller_graph`.
1814 total_number_of_instructions_ += number_of_instructions;
1815 UpdateInliningBudget();
David Brazdil3f523062016-02-29 16:53:33 +00001816
1817 DCHECK_EQ(callee_instruction_counter, callee_graph->GetCurrentInstructionId())
1818 << "No instructions can be added to the inner graph during inlining into the outer graph";
1819
Vladimir Marko438709f2017-02-23 18:56:13 +00001820 if (stats_ != nullptr) {
1821 DCHECK(inline_stats_ != nullptr);
1822 inline_stats_->AddTo(stats_);
1823 }
1824
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001825 return true;
1826}
Calin Juravle2e768302015-07-28 14:41:11 +00001827
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001828void HInliner::RunOptimizations(HGraph* callee_graph,
1829 const DexFile::CodeItem* code_item,
1830 const DexCompilationUnit& dex_compilation_unit) {
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01001831 // Note: if the outermost_graph_ is being compiled OSR, we should not run any
1832 // optimization that could lead to a HDeoptimize. The following optimizations do not.
Vladimir Marko438709f2017-02-23 18:56:13 +00001833 HDeadCodeElimination dce(callee_graph, inline_stats_, "dead_code_elimination$inliner");
Andreas Gampeca620d72016-11-08 08:09:33 -08001834 HConstantFolding fold(callee_graph, "constant_folding$inliner");
Nicolas Geoffray22384ae2016-12-12 22:33:36 +00001835 HSharpening sharpening(callee_graph, codegen_, dex_compilation_unit, compiler_driver_, handles_);
Nicolas Geoffrayc4aa82c2017-03-06 14:38:52 +00001836 InstructionSimplifier simplify(callee_graph, codegen_, inline_stats_);
Vladimir Marko438709f2017-02-23 18:56:13 +00001837 IntrinsicsRecognizer intrinsics(callee_graph, inline_stats_);
Roland Levillaina3aef2e2016-04-06 17:45:58 +01001838
1839 HOptimization* optimizations[] = {
1840 &intrinsics,
1841 &sharpening,
1842 &simplify,
1843 &fold,
1844 &dce,
1845 };
1846
1847 for (size_t i = 0; i < arraysize(optimizations); ++i) {
1848 HOptimization* optimization = optimizations[i];
1849 optimization->Run();
1850 }
1851
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001852 // Bail early for pathological cases on the environment (for example recursive calls,
1853 // or too large environment).
1854 if (total_number_of_dex_registers_ >= kMaximumNumberOfCumulatedDexRegisters) {
1855 LOG_NOTE() << "Calls in " << callee_graph->GetArtMethod()->PrettyMethod()
1856 << " will not be inlined because the outer method has reached"
1857 << " its environment budget limit.";
1858 return;
Roland Levillaina3aef2e2016-04-06 17:45:58 +01001859 }
1860
Nicolas Geoffrayf6d46682017-02-28 17:41:45 +00001861 // Bail early if we know we already are over the limit.
1862 size_t number_of_instructions = CountNumberOfInstructions(callee_graph);
1863 if (number_of_instructions > inlining_budget_) {
1864 LOG_NOTE() << "Calls in " << callee_graph->GetArtMethod()->PrettyMethod()
1865 << " will not be inlined because the outer method has reached"
1866 << " its instruction budget limit. " << number_of_instructions;
1867 return;
1868 }
1869
1870 HInliner inliner(callee_graph,
1871 outermost_graph_,
1872 codegen_,
1873 outer_compilation_unit_,
1874 dex_compilation_unit,
1875 compiler_driver_,
1876 handles_,
1877 inline_stats_,
1878 total_number_of_dex_registers_ + code_item->registers_size_,
1879 total_number_of_instructions_ + number_of_instructions,
1880 this,
1881 depth_ + 1);
1882 inliner.Run();
Roland Levillaina3aef2e2016-04-06 17:45:58 +01001883}
1884
David Brazdil94ab38f2016-06-21 17:48:19 +01001885static bool IsReferenceTypeRefinement(ReferenceTypeInfo declared_rti,
1886 bool declared_can_be_null,
1887 HInstruction* actual_obj)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001888 REQUIRES_SHARED(Locks::mutator_lock_) {
David Brazdil94ab38f2016-06-21 17:48:19 +01001889 if (declared_can_be_null && !actual_obj->CanBeNull()) {
1890 return true;
1891 }
1892
1893 ReferenceTypeInfo actual_rti = actual_obj->GetReferenceTypeInfo();
1894 return (actual_rti.IsExact() && !declared_rti.IsExact()) ||
Nicolas Geoffray0f001b72017-01-04 16:46:23 +00001895 declared_rti.IsStrictSupertypeOf(actual_rti);
David Brazdil94ab38f2016-06-21 17:48:19 +01001896}
1897
1898ReferenceTypeInfo HInliner::GetClassRTI(mirror::Class* klass) {
1899 return ReferenceTypePropagation::IsAdmissible(klass)
1900 ? ReferenceTypeInfo::Create(handles_->NewHandle(klass))
1901 : graph_->GetInexactObjectRti();
1902}
1903
1904bool HInliner::ArgumentTypesMoreSpecific(HInvoke* invoke_instruction, ArtMethod* resolved_method) {
1905 // If this is an instance call, test whether the type of the `this` argument
1906 // is more specific than the class which declares the method.
1907 if (!resolved_method->IsStatic()) {
1908 if (IsReferenceTypeRefinement(GetClassRTI(resolved_method->GetDeclaringClass()),
1909 /* declared_can_be_null */ false,
1910 invoke_instruction->InputAt(0u))) {
1911 return true;
1912 }
1913 }
1914
David Brazdil94ab38f2016-06-21 17:48:19 +01001915 // Iterate over the list of parameter types and test whether any of the
1916 // actual inputs has a more specific reference type than the type declared in
1917 // the signature.
1918 const DexFile::TypeList* param_list = resolved_method->GetParameterTypeList();
1919 for (size_t param_idx = 0,
1920 input_idx = resolved_method->IsStatic() ? 0 : 1,
1921 e = (param_list == nullptr ? 0 : param_list->Size());
1922 param_idx < e;
1923 ++param_idx, ++input_idx) {
1924 HInstruction* input = invoke_instruction->InputAt(input_idx);
1925 if (input->GetType() == Primitive::kPrimNot) {
Vladimir Marko942fd312017-01-16 20:52:19 +00001926 mirror::Class* param_cls = resolved_method->GetClassFromTypeIndex(
David Brazdil94ab38f2016-06-21 17:48:19 +01001927 param_list->GetTypeItem(param_idx).type_idx_,
Vladimir Marko942fd312017-01-16 20:52:19 +00001928 /* resolve */ false);
David Brazdil94ab38f2016-06-21 17:48:19 +01001929 if (IsReferenceTypeRefinement(GetClassRTI(param_cls),
1930 /* declared_can_be_null */ true,
1931 input)) {
1932 return true;
1933 }
1934 }
1935 }
1936
1937 return false;
1938}
1939
1940bool HInliner::ReturnTypeMoreSpecific(HInvoke* invoke_instruction,
1941 HInstruction* return_replacement) {
Alex Light68289a52015-12-15 17:30:30 -08001942 // Check the integrity of reference types and run another type propagation if needed.
David Brazdil4833f5a2015-12-16 10:37:39 +00001943 if (return_replacement != nullptr) {
1944 if (return_replacement->GetType() == Primitive::kPrimNot) {
David Brazdil94ab38f2016-06-21 17:48:19 +01001945 // Test if the return type is a refinement of the declared return type.
1946 if (IsReferenceTypeRefinement(invoke_instruction->GetReferenceTypeInfo(),
1947 /* declared_can_be_null */ true,
1948 return_replacement)) {
1949 return true;
Nicolas Geoffrayc52b26d2016-12-19 09:18:07 +00001950 } else if (return_replacement->IsInstanceFieldGet()) {
1951 HInstanceFieldGet* field_get = return_replacement->AsInstanceFieldGet();
1952 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1953 if (field_get->GetFieldInfo().GetField() ==
1954 class_linker->GetClassRoot(ClassLinker::kJavaLangObject)->GetInstanceField(0)) {
1955 return true;
1956 }
David Brazdil94ab38f2016-06-21 17:48:19 +01001957 }
1958 } else if (return_replacement->IsInstanceOf()) {
1959 // Inlining InstanceOf into an If may put a tighter bound on reference types.
1960 return true;
1961 }
1962 }
1963
1964 return false;
1965}
1966
1967void HInliner::FixUpReturnReferenceType(ArtMethod* resolved_method,
1968 HInstruction* return_replacement) {
1969 if (return_replacement != nullptr) {
1970 if (return_replacement->GetType() == Primitive::kPrimNot) {
David Brazdil4833f5a2015-12-16 10:37:39 +00001971 if (!return_replacement->GetReferenceTypeInfo().IsValid()) {
1972 // Make sure that we have a valid type for the return. We may get an invalid one when
1973 // we inline invokes with multiple branches and create a Phi for the result.
1974 // TODO: we could be more precise by merging the phi inputs but that requires
1975 // some functionality from the reference type propagation.
1976 DCHECK(return_replacement->IsPhi());
Vladimir Marko942fd312017-01-16 20:52:19 +00001977 mirror::Class* cls = resolved_method->GetReturnType(false /* resolve */);
David Brazdil94ab38f2016-06-21 17:48:19 +01001978 return_replacement->SetReferenceTypeInfo(GetClassRTI(cls));
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001979 }
Calin Juravlecdfed3d2015-10-26 14:05:01 +00001980 }
Calin Juravle2e768302015-07-28 14:41:11 +00001981 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001982}
1983
1984} // namespace art