blob: 34a5e34acc2a4a0b4bca85b2b4601585cdb113c1 [file] [log] [blame]
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001/*
2 * Copyright (C) 2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "inliner.h"
18
Mathieu Chartiere401d142015-04-22 13:56:20 -070019#include "art_method-inl.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000020#include "builder.h"
21#include "class_linker.h"
22#include "constant_folding.h"
23#include "dead_code_elimination.h"
Vladimir Markobe10e8e2016-01-22 12:09:44 +000024#include "dex/verified_method.h"
25#include "dex/verification_results.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000026#include "driver/compiler_driver-inl.h"
Calin Juravleec748352015-07-29 13:52:12 +010027#include "driver/compiler_options.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000028#include "driver/dex_compilation_unit.h"
29#include "instruction_simplifier.h"
Scott Wakelingd60a1af2015-07-22 14:32:44 +010030#include "intrinsics.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000031#include "mirror/class_loader.h"
32#include "mirror/dex_cache.h"
33#include "nodes.h"
Nicolas Geoffray335005e2015-06-25 10:01:47 +010034#include "optimizing_compiler.h"
Nicolas Geoffray454a4812015-06-09 10:37:32 +010035#include "reference_type_propagation.h"
Nicolas Geoffray259136f2014-12-17 23:21:58 +000036#include "register_allocator.h"
Vladimir Markobe10e8e2016-01-22 12:09:44 +000037#include "quick/inline_method_analyser.h"
Vladimir Markodc151b22015-10-15 18:02:30 +010038#include "sharpening.h"
David Brazdil4833f5a2015-12-16 10:37:39 +000039#include "ssa_builder.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000040#include "ssa_phi_elimination.h"
41#include "scoped_thread_state_change.h"
42#include "thread.h"
43
44namespace art {
45
Nicolas Geoffray5949fa02015-12-18 10:57:10 +000046static constexpr size_t kMaximumNumberOfHInstructions = 32;
47
48// Limit the number of dex registers that we accumulate while inlining
49// to avoid creating large amount of nested environments.
50static constexpr size_t kMaximumNumberOfCumulatedDexRegisters = 64;
51
52// Avoid inlining within a huge method due to memory pressure.
53static constexpr size_t kMaximumCodeUnitSize = 4096;
Nicolas Geoffraye418dda2015-08-11 20:03:09 -070054
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000055void HInliner::Run() {
Calin Juravle8f96df82015-07-29 15:58:48 +010056 const CompilerOptions& compiler_options = compiler_driver_->GetCompilerOptions();
57 if ((compiler_options.GetInlineDepthLimit() == 0)
58 || (compiler_options.GetInlineMaxCodeUnits() == 0)) {
59 return;
60 }
Nicolas Geoffray5949fa02015-12-18 10:57:10 +000061 if (caller_compilation_unit_.GetCodeItem()->insns_size_in_code_units_ > kMaximumCodeUnitSize) {
62 return;
63 }
Nicolas Geoffraye50b8d22015-03-13 08:57:42 +000064 if (graph_->IsDebuggable()) {
65 // For simplicity, we currently never inline when the graph is debuggable. This avoids
66 // doing some logic in the runtime to discover if a method could have been inlined.
67 return;
68 }
Vladimir Markofa6b93c2015-09-15 10:15:55 +010069 const ArenaVector<HBasicBlock*>& blocks = graph_->GetReversePostOrder();
70 DCHECK(!blocks.empty());
71 HBasicBlock* next_block = blocks[0];
72 for (size_t i = 0; i < blocks.size(); ++i) {
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +010073 // Because we are changing the graph when inlining, we need to remember the next block.
74 // This avoids doing the inlining work again on the inlined blocks.
Vladimir Markofa6b93c2015-09-15 10:15:55 +010075 if (blocks[i] != next_block) {
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +010076 continue;
77 }
78 HBasicBlock* block = next_block;
Vladimir Markofa6b93c2015-09-15 10:15:55 +010079 next_block = (i == blocks.size() - 1) ? nullptr : blocks[i + 1];
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +000080 for (HInstruction* instruction = block->GetFirstInstruction(); instruction != nullptr;) {
81 HInstruction* next = instruction->GetNext();
Nicolas Geoffray454a4812015-06-09 10:37:32 +010082 HInvoke* call = instruction->AsInvoke();
Razvan A Lupusoru3e90a962015-03-27 13:44:44 -070083 // As long as the call is not intrinsified, it is worth trying to inline.
84 if (call != nullptr && call->GetIntrinsic() == Intrinsics::kNone) {
Nicolas Geoffray79041292015-03-26 10:05:54 +000085 // We use the original invoke type to ensure the resolution of the called method
86 // works properly.
Vladimir Marko58155012015-08-19 12:49:41 +000087 if (!TryInline(call)) {
Nicolas Geoffray335005e2015-06-25 10:01:47 +010088 if (kIsDebugBuild && IsCompilingWithCoreImage()) {
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000089 std::string callee_name =
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +000090 PrettyMethod(call->GetDexMethodIndex(), *outer_compilation_unit_.GetDexFile());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000091 bool should_inline = callee_name.find("$inline$") != std::string::npos;
92 CHECK(!should_inline) << "Could not inline " << callee_name;
93 }
Guillaume "Vermeille" Sancheze918d382015-06-03 15:32:41 +010094 } else {
Nicolas Geoffray335005e2015-06-25 10:01:47 +010095 if (kIsDebugBuild && IsCompilingWithCoreImage()) {
Guillaume "Vermeille" Sancheze918d382015-06-03 15:32:41 +010096 std::string callee_name =
97 PrettyMethod(call->GetDexMethodIndex(), *outer_compilation_unit_.GetDexFile());
98 bool must_not_inline = callee_name.find("$noinline$") != std::string::npos;
99 CHECK(!must_not_inline) << "Should not have inlined " << callee_name;
100 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000101 }
102 }
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +0000103 instruction = next;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000104 }
105 }
106}
107
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100108static bool IsMethodOrDeclaringClassFinal(ArtMethod* method)
Mathieu Chartier90443472015-07-16 20:32:27 -0700109 SHARED_REQUIRES(Locks::mutator_lock_) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100110 return method->IsFinal() || method->GetDeclaringClass()->IsFinal();
111}
112
113/**
114 * Given the `resolved_method` looked up in the dex cache, try to find
115 * the actual runtime target of an interface or virtual call.
116 * Return nullptr if the runtime target cannot be proven.
117 */
118static ArtMethod* FindVirtualOrInterfaceTarget(HInvoke* invoke, ArtMethod* resolved_method)
Mathieu Chartier90443472015-07-16 20:32:27 -0700119 SHARED_REQUIRES(Locks::mutator_lock_) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100120 if (IsMethodOrDeclaringClassFinal(resolved_method)) {
121 // No need to lookup further, the resolved method will be the target.
122 return resolved_method;
123 }
124
125 HInstruction* receiver = invoke->InputAt(0);
126 if (receiver->IsNullCheck()) {
127 // Due to multiple levels of inlining within the same pass, it might be that
128 // null check does not have the reference type of the actual receiver.
129 receiver = receiver->InputAt(0);
130 }
131 ReferenceTypeInfo info = receiver->GetReferenceTypeInfo();
Calin Juravle2e768302015-07-28 14:41:11 +0000132 DCHECK(info.IsValid()) << "Invalid RTI for " << receiver->DebugName();
133 if (!info.IsExact()) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100134 // We currently only support inlining with known receivers.
135 // TODO: Remove this check, we should be able to inline final methods
136 // on unknown receivers.
137 return nullptr;
138 } else if (info.GetTypeHandle()->IsInterface()) {
139 // Statically knowing that the receiver has an interface type cannot
140 // help us find what is the target method.
141 return nullptr;
142 } else if (!resolved_method->GetDeclaringClass()->IsAssignableFrom(info.GetTypeHandle().Get())) {
143 // The method that we're trying to call is not in the receiver's class or super classes.
144 return nullptr;
145 }
146
147 ClassLinker* cl = Runtime::Current()->GetClassLinker();
148 size_t pointer_size = cl->GetImagePointerSize();
149 if (invoke->IsInvokeInterface()) {
150 resolved_method = info.GetTypeHandle()->FindVirtualMethodForInterface(
151 resolved_method, pointer_size);
152 } else {
153 DCHECK(invoke->IsInvokeVirtual());
154 resolved_method = info.GetTypeHandle()->FindVirtualMethodForVirtual(
155 resolved_method, pointer_size);
156 }
157
158 if (resolved_method == nullptr) {
159 // The information we had on the receiver was not enough to find
160 // the target method. Since we check above the exact type of the receiver,
161 // the only reason this can happen is an IncompatibleClassChangeError.
162 return nullptr;
Alex Light9139e002015-10-09 15:59:48 -0700163 } else if (!resolved_method->IsInvokable()) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100164 // The information we had on the receiver was not enough to find
165 // the target method. Since we check above the exact type of the receiver,
166 // the only reason this can happen is an IncompatibleClassChangeError.
167 return nullptr;
168 } else if (IsMethodOrDeclaringClassFinal(resolved_method)) {
169 // A final method has to be the target method.
170 return resolved_method;
171 } else if (info.IsExact()) {
172 // If we found a method and the receiver's concrete type is statically
173 // known, we know for sure the target.
174 return resolved_method;
175 } else {
176 // Even if we did find a method, the receiver type was not enough to
177 // statically find the runtime target.
178 return nullptr;
179 }
180}
181
182static uint32_t FindMethodIndexIn(ArtMethod* method,
183 const DexFile& dex_file,
184 uint32_t referrer_index)
Mathieu Chartier90443472015-07-16 20:32:27 -0700185 SHARED_REQUIRES(Locks::mutator_lock_) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100186 if (IsSameDexFile(*method->GetDexFile(), dex_file)) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100187 return method->GetDexMethodIndex();
188 } else {
189 return method->FindDexMethodIndexInOtherDexFile(dex_file, referrer_index);
190 }
191}
192
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100193static uint32_t FindClassIndexIn(mirror::Class* cls, const DexFile& dex_file)
194 SHARED_REQUIRES(Locks::mutator_lock_) {
195 if (cls->GetDexCache() == nullptr) {
196 DCHECK(cls->IsArrayClass());
197 // TODO: find the class in `dex_file`.
198 return DexFile::kDexNoIndex;
199 } else if (cls->GetDexTypeIndex() == DexFile::kDexNoIndex16) {
200 // TODO: deal with proxy classes.
201 return DexFile::kDexNoIndex;
202 } else if (IsSameDexFile(cls->GetDexFile(), dex_file)) {
203 // Update the dex cache to ensure the class is in. The generated code will
204 // consider it is. We make it safe by updating the dex cache, as other
205 // dex files might also load the class, and there is no guarantee the dex
206 // cache of the dex file of the class will be updated.
207 if (cls->GetDexCache()->GetResolvedType(cls->GetDexTypeIndex()) == nullptr) {
208 cls->GetDexCache()->SetResolvedType(cls->GetDexTypeIndex(), cls);
209 }
210 return cls->GetDexTypeIndex();
211 } else {
212 // TODO: find the class in `dex_file`.
213 return DexFile::kDexNoIndex;
214 }
215}
216
Nicolas Geoffraye418dda2015-08-11 20:03:09 -0700217bool HInliner::TryInline(HInvoke* invoke_instruction) {
Calin Juravle175dc732015-08-25 15:42:32 +0100218 if (invoke_instruction->IsInvokeUnresolved()) {
219 return false; // Don't bother to move further if we know the method is unresolved.
220 }
221
Vladimir Marko58155012015-08-19 12:49:41 +0000222 uint32_t method_index = invoke_instruction->GetDexMethodIndex();
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000223 ScopedObjectAccess soa(Thread::Current());
Nicolas Geoffray9437b782015-03-25 10:08:51 +0000224 const DexFile& caller_dex_file = *caller_compilation_unit_.GetDexFile();
225 VLOG(compiler) << "Try inlining " << PrettyMethod(method_index, caller_dex_file);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000226
Nicolas Geoffray35071052015-06-09 15:43:38 +0100227 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
228 // We can query the dex cache directly. The verifier has populated it already.
Vladimir Marko58155012015-08-19 12:49:41 +0000229 ArtMethod* resolved_method;
Andreas Gampefd2140f2015-12-23 16:30:44 -0800230 ArtMethod* actual_method = nullptr;
Vladimir Marko58155012015-08-19 12:49:41 +0000231 if (invoke_instruction->IsInvokeStaticOrDirect()) {
Nicolas Geoffraye5234232015-12-02 09:06:11 +0000232 if (invoke_instruction->AsInvokeStaticOrDirect()->IsStringInit()) {
233 VLOG(compiler) << "Not inlining a String.<init> method";
234 return false;
235 }
Vladimir Marko58155012015-08-19 12:49:41 +0000236 MethodReference ref = invoke_instruction->AsInvokeStaticOrDirect()->GetTargetMethod();
Mathieu Chartier736b5602015-09-02 14:54:11 -0700237 mirror::DexCache* const dex_cache = (&caller_dex_file == ref.dex_file)
238 ? caller_compilation_unit_.GetDexCache().Get()
239 : class_linker->FindDexCache(soa.Self(), *ref.dex_file);
240 resolved_method = dex_cache->GetResolvedMethod(
Vladimir Marko58155012015-08-19 12:49:41 +0000241 ref.dex_method_index, class_linker->GetImagePointerSize());
Andreas Gampefd2140f2015-12-23 16:30:44 -0800242 // actual_method == resolved_method for direct or static calls.
243 actual_method = resolved_method;
Vladimir Marko58155012015-08-19 12:49:41 +0000244 } else {
Mathieu Chartier736b5602015-09-02 14:54:11 -0700245 resolved_method = caller_compilation_unit_.GetDexCache().Get()->GetResolvedMethod(
Vladimir Marko58155012015-08-19 12:49:41 +0000246 method_index, class_linker->GetImagePointerSize());
Andreas Gampefd2140f2015-12-23 16:30:44 -0800247 if (resolved_method != nullptr) {
248 // Check if we can statically find the method.
249 actual_method = FindVirtualOrInterfaceTarget(invoke_instruction, resolved_method);
250 }
Vladimir Marko58155012015-08-19 12:49:41 +0000251 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000252
Mathieu Chartiere401d142015-04-22 13:56:20 -0700253 if (resolved_method == nullptr) {
Calin Juravle175dc732015-08-25 15:42:32 +0100254 // TODO: Can this still happen?
Nicolas Geoffray35071052015-06-09 15:43:38 +0100255 // Method cannot be resolved if it is in another dex file we do not have access to.
Nicolas Geoffray9437b782015-03-25 10:08:51 +0000256 VLOG(compiler) << "Method cannot be resolved " << PrettyMethod(method_index, caller_dex_file);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000257 return false;
258 }
259
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100260 if (actual_method != nullptr) {
261 return TryInline(invoke_instruction, actual_method);
262 }
Andreas Gampefd2140f2015-12-23 16:30:44 -0800263 DCHECK(!invoke_instruction->IsInvokeStaticOrDirect());
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100264
265 // Check if we can use an inline cache.
266 ArtMethod* caller = graph_->GetArtMethod();
267 size_t pointer_size = class_linker->GetImagePointerSize();
268 // Under JIT, we should always know the caller.
269 DCHECK(!Runtime::Current()->UseJit() || (caller != nullptr));
270 if (caller != nullptr && caller->GetProfilingInfo(pointer_size) != nullptr) {
271 ProfilingInfo* profiling_info = caller->GetProfilingInfo(pointer_size);
272 const InlineCache& ic = *profiling_info->GetInlineCache(invoke_instruction->GetDexPc());
273 if (ic.IsUnitialized()) {
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100274 VLOG(compiler) << "Interface or virtual call to "
275 << PrettyMethod(method_index, caller_dex_file)
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100276 << " is not hit and not inlined";
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100277 return false;
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100278 } else if (ic.IsMonomorphic()) {
279 MaybeRecordStat(kMonomorphicCall);
280 return TryInlineMonomorphicCall(invoke_instruction, resolved_method, ic);
281 } else if (ic.IsPolymorphic()) {
282 MaybeRecordStat(kPolymorphicCall);
283 return TryInlinePolymorphicCall(invoke_instruction, resolved_method, ic);
284 } else {
285 DCHECK(ic.IsMegamorphic());
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100286 VLOG(compiler) << "Interface or virtual call to "
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100287 << PrettyMethod(method_index, caller_dex_file)
288 << " is megamorphic and not inlined";
289 MaybeRecordStat(kMegamorphicCall);
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100290 return false;
291 }
292 }
293
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100294 VLOG(compiler) << "Interface or virtual call to "
295 << PrettyMethod(method_index, caller_dex_file)
296 << " could not be statically determined";
297 return false;
298}
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000299
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000300HInstanceFieldGet* HInliner::BuildGetReceiverClass(ClassLinker* class_linker,
301 HInstruction* receiver,
302 uint32_t dex_pc) const {
303 ArtField* field = class_linker->GetClassRoot(ClassLinker::kJavaLangObject)->GetInstanceField(0);
304 DCHECK_EQ(std::string(field->GetName()), "shadow$_klass_");
305 return new (graph_->GetArena()) HInstanceFieldGet(
306 receiver,
307 Primitive::kPrimNot,
308 field->GetOffset(),
309 field->IsVolatile(),
310 field->GetDexFieldIndex(),
311 field->GetDeclaringClass()->GetDexClassDefIndex(),
312 *field->GetDexFile(),
313 handles_->NewHandle(field->GetDexCache()),
314 dex_pc);
315}
316
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100317bool HInliner::TryInlineMonomorphicCall(HInvoke* invoke_instruction,
318 ArtMethod* resolved_method,
319 const InlineCache& ic) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000320 DCHECK(invoke_instruction->IsInvokeVirtual() || invoke_instruction->IsInvokeInterface())
321 << invoke_instruction->DebugName();
322
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100323 const DexFile& caller_dex_file = *caller_compilation_unit_.GetDexFile();
324 uint32_t class_index = FindClassIndexIn(ic.GetMonomorphicType(), caller_dex_file);
325 if (class_index == DexFile::kDexNoIndex) {
326 VLOG(compiler) << "Call to " << PrettyMethod(resolved_method)
327 << " from inline cache is not inlined because its class is not"
328 << " accessible to the caller";
329 return false;
330 }
331
332 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
333 size_t pointer_size = class_linker->GetImagePointerSize();
334 if (invoke_instruction->IsInvokeInterface()) {
335 resolved_method = ic.GetMonomorphicType()->FindVirtualMethodForInterface(
336 resolved_method, pointer_size);
337 } else {
338 DCHECK(invoke_instruction->IsInvokeVirtual());
339 resolved_method = ic.GetMonomorphicType()->FindVirtualMethodForVirtual(
340 resolved_method, pointer_size);
341 }
342 DCHECK(resolved_method != nullptr);
343 HInstruction* receiver = invoke_instruction->InputAt(0);
344 HInstruction* cursor = invoke_instruction->GetPrevious();
345 HBasicBlock* bb_cursor = invoke_instruction->GetBlock();
346
347 if (!TryInline(invoke_instruction, resolved_method, /* do_rtp */ false)) {
348 return false;
349 }
350
351 // We successfully inlined, now add a guard.
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000352 HInstanceFieldGet* receiver_class = BuildGetReceiverClass(
353 class_linker, receiver, invoke_instruction->GetDexPc());
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100354
355 bool is_referrer =
356 (ic.GetMonomorphicType() == outermost_graph_->GetArtMethod()->GetDeclaringClass());
357 HLoadClass* load_class = new (graph_->GetArena()) HLoadClass(graph_->GetCurrentMethod(),
358 class_index,
359 caller_dex_file,
360 is_referrer,
361 invoke_instruction->GetDexPc(),
362 /* needs_access_check */ false,
363 /* is_in_dex_cache */ true);
364
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000365 HNotEqual* compare = new (graph_->GetArena()) HNotEqual(load_class, receiver_class);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100366 HDeoptimize* deoptimize = new (graph_->GetArena()) HDeoptimize(
367 compare, invoke_instruction->GetDexPc());
368 // TODO: Extend reference type propagation to understand the guard.
369 if (cursor != nullptr) {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000370 bb_cursor->InsertInstructionAfter(receiver_class, cursor);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100371 } else {
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000372 bb_cursor->InsertInstructionBefore(receiver_class, bb_cursor->GetFirstInstruction());
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100373 }
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000374 bb_cursor->InsertInstructionAfter(load_class, receiver_class);
Nicolas Geoffray7c0f2e52016-01-18 15:24:53 +0000375 bb_cursor->InsertInstructionAfter(compare, load_class);
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100376 bb_cursor->InsertInstructionAfter(deoptimize, compare);
377 deoptimize->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
378
379 // Run type propagation to get the guard typed, and eventually propagate the
380 // type of the receiver.
381 ReferenceTypePropagation rtp_fixup(graph_, handles_);
382 rtp_fixup.Run();
383
384 MaybeRecordStat(kInlinedMonomorphicCall);
385 return true;
386}
387
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000388bool HInliner::TryInlinePolymorphicCall(HInvoke* invoke_instruction,
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100389 ArtMethod* resolved_method,
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000390 const InlineCache& ic) {
391 DCHECK(invoke_instruction->IsInvokeVirtual() || invoke_instruction->IsInvokeInterface())
392 << invoke_instruction->DebugName();
393 // This optimization only works under JIT for now.
394 DCHECK(Runtime::Current()->UseJit());
Roland Levillain2aba7cd2016-02-03 12:27:20 +0000395 if (graph_->GetInstructionSet() == kMips64) {
396 // TODO: Support HClassTableGet for mips64.
Nicolas Geoffraya42363f2015-12-17 14:57:09 +0000397 return false;
398 }
399 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
400 size_t pointer_size = class_linker->GetImagePointerSize();
401
402 DCHECK(resolved_method != nullptr);
403 ArtMethod* actual_method = nullptr;
404 // Check whether we are actually calling the same method among
405 // the different types seen.
406 for (size_t i = 0; i < InlineCache::kIndividualCacheSize; ++i) {
407 if (ic.GetTypeAt(i) == nullptr) {
408 break;
409 }
410 ArtMethod* new_method = nullptr;
411 if (invoke_instruction->IsInvokeInterface()) {
412 new_method = ic.GetTypeAt(i)->FindVirtualMethodForInterface(
413 resolved_method, pointer_size);
414 } else {
415 DCHECK(invoke_instruction->IsInvokeVirtual());
416 new_method = ic.GetTypeAt(i)->FindVirtualMethodForVirtual(
417 resolved_method, pointer_size);
418 }
419 if (actual_method == nullptr) {
420 actual_method = new_method;
421 } else if (actual_method != new_method) {
422 // Different methods, bailout.
423 return false;
424 }
425 }
426
427 HInstruction* receiver = invoke_instruction->InputAt(0);
428 HInstruction* cursor = invoke_instruction->GetPrevious();
429 HBasicBlock* bb_cursor = invoke_instruction->GetBlock();
430
431 if (!TryInline(invoke_instruction, actual_method, /* do_rtp */ false)) {
432 return false;
433 }
434
435 // We successfully inlined, now add a guard.
436 HInstanceFieldGet* receiver_class = BuildGetReceiverClass(
437 class_linker, receiver, invoke_instruction->GetDexPc());
438
439 size_t method_offset = invoke_instruction->IsInvokeVirtual()
440 ? actual_method->GetVtableIndex()
441 : invoke_instruction->AsInvokeInterface()->GetImtIndex();
442
443 Primitive::Type type = Is64BitInstructionSet(graph_->GetInstructionSet())
444 ? Primitive::kPrimLong
445 : Primitive::kPrimInt;
446 HClassTableGet* class_table_get = new (graph_->GetArena()) HClassTableGet(
447 receiver_class,
448 type,
449 invoke_instruction->IsInvokeVirtual() ? HClassTableGet::kVTable : HClassTableGet::kIMTable,
450 method_offset,
451 invoke_instruction->GetDexPc());
452
453 HConstant* constant;
454 if (type == Primitive::kPrimLong) {
455 constant = graph_->GetLongConstant(
456 reinterpret_cast<intptr_t>(actual_method), invoke_instruction->GetDexPc());
457 } else {
458 constant = graph_->GetIntConstant(
459 reinterpret_cast<intptr_t>(actual_method), invoke_instruction->GetDexPc());
460 }
461
462 HNotEqual* compare = new (graph_->GetArena()) HNotEqual(class_table_get, constant);
463 HDeoptimize* deoptimize = new (graph_->GetArena()) HDeoptimize(
464 compare, invoke_instruction->GetDexPc());
465 // TODO: Extend reference type propagation to understand the guard.
466 if (cursor != nullptr) {
467 bb_cursor->InsertInstructionAfter(receiver_class, cursor);
468 } else {
469 bb_cursor->InsertInstructionBefore(receiver_class, bb_cursor->GetFirstInstruction());
470 }
471 bb_cursor->InsertInstructionAfter(class_table_get, receiver_class);
472 bb_cursor->InsertInstructionAfter(compare, class_table_get);
473 bb_cursor->InsertInstructionAfter(deoptimize, compare);
474 deoptimize->CopyEnvironmentFrom(invoke_instruction->GetEnvironment());
475
476 // Run type propagation to get the guard typed.
477 ReferenceTypePropagation rtp_fixup(graph_, handles_);
478 rtp_fixup.Run();
479
480 MaybeRecordStat(kInlinedPolymorphicCall);
481
482 return true;
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100483}
484
485bool HInliner::TryInline(HInvoke* invoke_instruction, ArtMethod* method, bool do_rtp) {
486 const DexFile& caller_dex_file = *caller_compilation_unit_.GetDexFile();
Jeff Haodcdc85b2015-12-04 14:06:18 -0800487
488 // Check whether we're allowed to inline. The outermost compilation unit is the relevant
489 // dex file here (though the transitivity of an inline chain would allow checking the calller).
490 if (!compiler_driver_->MayInline(method->GetDexFile(),
491 outer_compilation_unit_.GetDexFile())) {
Vladimir Markobe10e8e2016-01-22 12:09:44 +0000492 if (TryPatternSubstitution(invoke_instruction, method, do_rtp)) {
493 VLOG(compiler) << "Successfully replaced pattern of invoke " << PrettyMethod(method);
494 MaybeRecordStat(kReplacedInvokeWithSimplePattern);
495 return true;
496 }
Jeff Haodcdc85b2015-12-04 14:06:18 -0800497 VLOG(compiler) << "Won't inline " << PrettyMethod(method) << " in "
498 << outer_compilation_unit_.GetDexFile()->GetLocation() << " ("
499 << caller_compilation_unit_.GetDexFile()->GetLocation() << ") from "
500 << method->GetDexFile()->GetLocation();
501 return false;
502 }
503
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100504 uint32_t method_index = FindMethodIndexIn(
505 method, caller_dex_file, invoke_instruction->GetDexMethodIndex());
506 if (method_index == DexFile::kDexNoIndex) {
507 VLOG(compiler) << "Call to "
508 << PrettyMethod(method)
509 << " cannot be inlined because unaccessible to caller";
510 return false;
511 }
512
513 bool same_dex_file = IsSameDexFile(*outer_compilation_unit_.GetDexFile(), *method->GetDexFile());
514
515 const DexFile::CodeItem* code_item = method->GetCodeItem();
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000516
517 if (code_item == nullptr) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100518 VLOG(compiler) << "Method " << PrettyMethod(method)
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000519 << " is not inlined because it is native";
520 return false;
521 }
522
Calin Juravleec748352015-07-29 13:52:12 +0100523 size_t inline_max_code_units = compiler_driver_->GetCompilerOptions().GetInlineMaxCodeUnits();
524 if (code_item->insns_size_in_code_units_ > inline_max_code_units) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100525 VLOG(compiler) << "Method " << PrettyMethod(method)
Nicolas Geoffray788f2f02016-01-22 12:41:38 +0000526 << " is too big to inline: "
527 << code_item->insns_size_in_code_units_
528 << " > "
529 << inline_max_code_units;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000530 return false;
531 }
532
533 if (code_item->tries_size_ != 0) {
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100534 VLOG(compiler) << "Method " << PrettyMethod(method)
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000535 << " is not inlined because of try block";
536 return false;
537 }
538
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100539 if (!method->GetDeclaringClass()->IsVerified()) {
540 uint16_t class_def_idx = method->GetDeclaringClass()->GetDexClassDefIndex();
Nicolas Geoffrayccc61972015-10-01 14:34:20 +0100541 if (!compiler_driver_->IsMethodVerifiedWithoutFailures(
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100542 method->GetDexMethodIndex(), class_def_idx, *method->GetDexFile())) {
Nicolas Geoffrayccc61972015-10-01 14:34:20 +0100543 VLOG(compiler) << "Method " << PrettyMethod(method_index, caller_dex_file)
544 << " couldn't be verified, so it cannot be inlined";
545 return false;
546 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000547 }
548
Roland Levillain4c0eb422015-04-24 16:43:49 +0100549 if (invoke_instruction->IsInvokeStaticOrDirect() &&
550 invoke_instruction->AsInvokeStaticOrDirect()->IsStaticWithImplicitClinitCheck()) {
551 // Case of a static method that cannot be inlined because it implicitly
552 // requires an initialization check of its declaring class.
553 VLOG(compiler) << "Method " << PrettyMethod(method_index, caller_dex_file)
554 << " is not inlined because it is static and requires a clinit"
555 << " check that cannot be emitted due to Dex cache limitations";
556 return false;
557 }
558
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100559 if (!TryBuildAndInline(method, invoke_instruction, same_dex_file, do_rtp)) {
Nicolas Geoffrayc0365b12015-03-18 18:31:52 +0000560 return false;
561 }
562
Nicolas Geoffray9437b782015-03-25 10:08:51 +0000563 VLOG(compiler) << "Successfully inlined " << PrettyMethod(method_index, caller_dex_file);
Nicolas Geoffrayc0365b12015-03-18 18:31:52 +0000564 MaybeRecordStat(kInlinedInvoke);
565 return true;
566}
567
Vladimir Markobe10e8e2016-01-22 12:09:44 +0000568static HInstruction* GetInvokeInputForArgVRegIndex(HInvoke* invoke_instruction,
569 size_t arg_vreg_index)
570 SHARED_REQUIRES(Locks::mutator_lock_) {
571 size_t input_index = 0;
572 for (size_t i = 0; i < arg_vreg_index; ++i, ++input_index) {
573 DCHECK_LT(input_index, invoke_instruction->GetNumberOfArguments());
574 if (Primitive::Is64BitType(invoke_instruction->InputAt(input_index)->GetType())) {
575 ++i;
576 DCHECK_NE(i, arg_vreg_index);
577 }
578 }
579 DCHECK_LT(input_index, invoke_instruction->GetNumberOfArguments());
580 return invoke_instruction->InputAt(input_index);
581}
582
583// Try to recognize known simple patterns and replace invoke call with appropriate instructions.
584bool HInliner::TryPatternSubstitution(HInvoke* invoke_instruction,
585 ArtMethod* resolved_method,
586 bool do_rtp) {
587 InlineMethod inline_method;
588 if (!InlineMethodAnalyser::AnalyseMethodCode(resolved_method, &inline_method)) {
589 return false;
590 }
591
592 HInstruction* return_replacement = nullptr;
593 switch (inline_method.opcode) {
594 case kInlineOpNop:
595 DCHECK_EQ(invoke_instruction->GetType(), Primitive::kPrimVoid);
596 break;
597 case kInlineOpReturnArg:
598 return_replacement = GetInvokeInputForArgVRegIndex(invoke_instruction,
599 inline_method.d.return_data.arg);
600 break;
601 case kInlineOpNonWideConst:
602 if (resolved_method->GetShorty()[0] == 'L') {
603 DCHECK_EQ(inline_method.d.data, 0u);
604 return_replacement = graph_->GetNullConstant();
605 } else {
606 return_replacement = graph_->GetIntConstant(static_cast<int32_t>(inline_method.d.data));
607 }
608 break;
609 case kInlineOpIGet: {
610 const InlineIGetIPutData& data = inline_method.d.ifield_data;
611 if (data.method_is_static || data.object_arg != 0u) {
612 // TODO: Needs null check.
613 return false;
614 }
Vladimir Marko354efa62016-02-04 19:46:56 +0000615 Handle<mirror::DexCache> dex_cache(handles_->NewHandle(resolved_method->GetDexCache()));
Vladimir Markobe10e8e2016-01-22 12:09:44 +0000616 HInstruction* obj = GetInvokeInputForArgVRegIndex(invoke_instruction, data.object_arg);
Vladimir Marko354efa62016-02-04 19:46:56 +0000617 HInstanceFieldGet* iget = CreateInstanceFieldGet(dex_cache, data.field_idx, obj);
Vladimir Markobe10e8e2016-01-22 12:09:44 +0000618 DCHECK_EQ(iget->GetFieldOffset().Uint32Value(), data.field_offset);
619 DCHECK_EQ(iget->IsVolatile() ? 1u : 0u, data.is_volatile);
620 invoke_instruction->GetBlock()->InsertInstructionBefore(iget, invoke_instruction);
621 return_replacement = iget;
622 break;
623 }
624 case kInlineOpIPut: {
625 const InlineIGetIPutData& data = inline_method.d.ifield_data;
626 if (data.method_is_static || data.object_arg != 0u) {
627 // TODO: Needs null check.
628 return false;
629 }
Vladimir Marko354efa62016-02-04 19:46:56 +0000630 Handle<mirror::DexCache> dex_cache(handles_->NewHandle(resolved_method->GetDexCache()));
Vladimir Markobe10e8e2016-01-22 12:09:44 +0000631 HInstruction* obj = GetInvokeInputForArgVRegIndex(invoke_instruction, data.object_arg);
632 HInstruction* value = GetInvokeInputForArgVRegIndex(invoke_instruction, data.src_arg);
Vladimir Marko354efa62016-02-04 19:46:56 +0000633 HInstanceFieldSet* iput = CreateInstanceFieldSet(dex_cache, data.field_idx, obj, value);
Vladimir Markobe10e8e2016-01-22 12:09:44 +0000634 DCHECK_EQ(iput->GetFieldOffset().Uint32Value(), data.field_offset);
635 DCHECK_EQ(iput->IsVolatile() ? 1u : 0u, data.is_volatile);
636 invoke_instruction->GetBlock()->InsertInstructionBefore(iput, invoke_instruction);
637 if (data.return_arg_plus1 != 0u) {
638 size_t return_arg = data.return_arg_plus1 - 1u;
639 return_replacement = GetInvokeInputForArgVRegIndex(invoke_instruction, return_arg);
640 }
641 break;
642 }
Vladimir Marko354efa62016-02-04 19:46:56 +0000643 case kInlineOpConstructor: {
644 const InlineConstructorData& data = inline_method.d.constructor_data;
645 // Get the indexes to arrays for easier processing.
646 uint16_t iput_field_indexes[] = {
647 data.iput0_field_index, data.iput1_field_index, data.iput2_field_index
648 };
649 uint16_t iput_args[] = { data.iput0_arg, data.iput1_arg, data.iput2_arg };
650 static_assert(arraysize(iput_args) == arraysize(iput_field_indexes), "Size mismatch");
651 // Count valid field indexes.
652 size_t number_of_iputs = 0u;
653 while (number_of_iputs != arraysize(iput_field_indexes) &&
654 iput_field_indexes[number_of_iputs] != DexFile::kDexNoIndex16) {
655 // Check that there are no duplicate valid field indexes.
656 DCHECK_EQ(0, std::count(iput_field_indexes + number_of_iputs + 1,
657 iput_field_indexes + arraysize(iput_field_indexes),
658 iput_field_indexes[number_of_iputs]));
659 ++number_of_iputs;
660 }
661 // Check that there are no valid field indexes in the rest of the array.
662 DCHECK_EQ(0, std::count_if(iput_field_indexes + number_of_iputs,
663 iput_field_indexes + arraysize(iput_field_indexes),
664 [](uint16_t index) { return index != DexFile::kDexNoIndex16; }));
665
666 // Create HInstanceFieldSet for each IPUT that stores non-zero data.
667 Handle<mirror::DexCache> dex_cache;
668 HInstruction* obj = GetInvokeInputForArgVRegIndex(invoke_instruction, /* this */ 0u);
669 bool needs_constructor_barrier = false;
670 for (size_t i = 0; i != number_of_iputs; ++i) {
671 HInstruction* value = GetInvokeInputForArgVRegIndex(invoke_instruction, iput_args[i]);
672 if (!value->IsConstant() ||
673 (!value->AsConstant()->IsZero() && !value->IsNullConstant())) {
674 if (dex_cache.GetReference() == nullptr) {
675 dex_cache = handles_->NewHandle(resolved_method->GetDexCache());
676 }
677 uint16_t field_index = iput_field_indexes[i];
678 HInstanceFieldSet* iput = CreateInstanceFieldSet(dex_cache, field_index, obj, value);
679 invoke_instruction->GetBlock()->InsertInstructionBefore(iput, invoke_instruction);
680
681 // Check whether the field is final. If it is, we need to add a barrier.
682 size_t pointer_size = InstructionSetPointerSize(codegen_->GetInstructionSet());
683 ArtField* resolved_field = dex_cache->GetResolvedField(field_index, pointer_size);
684 DCHECK(resolved_field != nullptr);
685 if (resolved_field->IsFinal()) {
686 needs_constructor_barrier = true;
687 }
688 }
689 }
690 if (needs_constructor_barrier) {
691 HMemoryBarrier* barrier = new (graph_->GetArena()) HMemoryBarrier(kStoreStore, kNoDexPc);
692 invoke_instruction->GetBlock()->InsertInstructionBefore(barrier, invoke_instruction);
693 }
694 break;
695 }
Vladimir Markobe10e8e2016-01-22 12:09:44 +0000696 default:
697 LOG(FATAL) << "UNREACHABLE";
698 UNREACHABLE();
699 }
700
701 if (return_replacement != nullptr) {
702 invoke_instruction->ReplaceWith(return_replacement);
703 }
704 invoke_instruction->GetBlock()->RemoveInstruction(invoke_instruction);
705
706 FixUpReturnReferenceType(resolved_method, invoke_instruction, return_replacement, do_rtp);
707 return true;
708}
709
Vladimir Marko354efa62016-02-04 19:46:56 +0000710HInstanceFieldGet* HInliner::CreateInstanceFieldGet(Handle<mirror::DexCache> dex_cache,
Vladimir Markobe10e8e2016-01-22 12:09:44 +0000711 uint32_t field_index,
712 HInstruction* obj)
713 SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Markobe10e8e2016-01-22 12:09:44 +0000714 size_t pointer_size = InstructionSetPointerSize(codegen_->GetInstructionSet());
715 ArtField* resolved_field = dex_cache->GetResolvedField(field_index, pointer_size);
716 DCHECK(resolved_field != nullptr);
717 HInstanceFieldGet* iget = new (graph_->GetArena()) HInstanceFieldGet(
718 obj,
719 resolved_field->GetTypeAsPrimitiveType(),
720 resolved_field->GetOffset(),
721 resolved_field->IsVolatile(),
722 field_index,
723 resolved_field->GetDeclaringClass()->GetDexClassDefIndex(),
Vladimir Marko354efa62016-02-04 19:46:56 +0000724 *dex_cache->GetDexFile(),
Vladimir Markobe10e8e2016-01-22 12:09:44 +0000725 dex_cache,
Vladimir Markoadda4352016-01-29 10:24:41 +0000726 // Read barrier generates a runtime call in slow path and we need a valid
727 // dex pc for the associated stack map. 0 is bogus but valid. Bug: 26854537.
728 /* dex_pc */ 0);
Vladimir Markobe10e8e2016-01-22 12:09:44 +0000729 if (iget->GetType() == Primitive::kPrimNot) {
730 ReferenceTypePropagation rtp(graph_, handles_);
731 rtp.Visit(iget);
732 }
733 return iget;
734}
735
Vladimir Marko354efa62016-02-04 19:46:56 +0000736HInstanceFieldSet* HInliner::CreateInstanceFieldSet(Handle<mirror::DexCache> dex_cache,
Vladimir Markobe10e8e2016-01-22 12:09:44 +0000737 uint32_t field_index,
738 HInstruction* obj,
739 HInstruction* value)
740 SHARED_REQUIRES(Locks::mutator_lock_) {
Vladimir Markobe10e8e2016-01-22 12:09:44 +0000741 size_t pointer_size = InstructionSetPointerSize(codegen_->GetInstructionSet());
742 ArtField* resolved_field = dex_cache->GetResolvedField(field_index, pointer_size);
743 DCHECK(resolved_field != nullptr);
744 HInstanceFieldSet* iput = new (graph_->GetArena()) HInstanceFieldSet(
745 obj,
746 value,
747 resolved_field->GetTypeAsPrimitiveType(),
748 resolved_field->GetOffset(),
749 resolved_field->IsVolatile(),
750 field_index,
751 resolved_field->GetDeclaringClass()->GetDexClassDefIndex(),
Vladimir Marko354efa62016-02-04 19:46:56 +0000752 *dex_cache->GetDexFile(),
Vladimir Markobe10e8e2016-01-22 12:09:44 +0000753 dex_cache,
Vladimir Markoadda4352016-01-29 10:24:41 +0000754 // Read barrier generates a runtime call in slow path and we need a valid
755 // dex pc for the associated stack map. 0 is bogus but valid. Bug: 26854537.
756 /* dex_pc */ 0);
Vladimir Markobe10e8e2016-01-22 12:09:44 +0000757 return iput;
758}
Mathieu Chartiere401d142015-04-22 13:56:20 -0700759bool HInliner::TryBuildAndInline(ArtMethod* resolved_method,
Nicolas Geoffrayc0365b12015-03-18 18:31:52 +0000760 HInvoke* invoke_instruction,
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100761 bool same_dex_file,
762 bool do_rtp) {
Nicolas Geoffrayc0365b12015-03-18 18:31:52 +0000763 ScopedObjectAccess soa(Thread::Current());
764 const DexFile::CodeItem* code_item = resolved_method->GetCodeItem();
Guillaume "Vermeille" Sanchezae09d2d2015-05-29 10:52:55 +0100765 const DexFile& callee_dex_file = *resolved_method->GetDexFile();
766 uint32_t method_index = resolved_method->GetDexMethodIndex();
Calin Juravle2e768302015-07-28 14:41:11 +0000767 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
Mathieu Chartier736b5602015-09-02 14:54:11 -0700768 Handle<mirror::DexCache> dex_cache(handles_->NewHandle(resolved_method->GetDexCache()));
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000769 DexCompilationUnit dex_compilation_unit(
770 nullptr,
Nicolas Geoffray9437b782015-03-25 10:08:51 +0000771 caller_compilation_unit_.GetClassLoader(),
Calin Juravle2e768302015-07-28 14:41:11 +0000772 class_linker,
Nicolas Geoffray8dbf0cf2015-08-11 02:14:38 +0000773 callee_dex_file,
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000774 code_item,
775 resolved_method->GetDeclaringClass()->GetDexClassDefIndex(),
Nicolas Geoffray8dbf0cf2015-08-11 02:14:38 +0000776 method_index,
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000777 resolved_method->GetAccessFlags(),
Mathieu Chartier736b5602015-09-02 14:54:11 -0700778 compiler_driver_->GetVerifiedMethod(&callee_dex_file, method_index),
779 dex_cache);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000780
Calin Juravle3cd4fc82015-05-14 15:15:42 +0100781 bool requires_ctor_barrier = false;
782
783 if (dex_compilation_unit.IsConstructor()) {
784 // If it's a super invocation and we already generate a barrier there's no need
785 // to generate another one.
786 // We identify super calls by looking at the "this" pointer. If its value is the
787 // same as the local "this" pointer then we must have a super invocation.
788 bool is_super_invocation = invoke_instruction->InputAt(0)->IsParameterValue()
789 && invoke_instruction->InputAt(0)->AsParameterValue()->IsThis();
790 if (is_super_invocation && graph_->ShouldGenerateConstructorBarrier()) {
791 requires_ctor_barrier = false;
792 } else {
793 Thread* self = Thread::Current();
794 requires_ctor_barrier = compiler_driver_->RequiresConstructorBarrier(self,
795 dex_compilation_unit.GetDexFile(),
796 dex_compilation_unit.GetClassDefIndex());
797 }
798 }
799
Nicolas Geoffray35071052015-06-09 15:43:38 +0100800 InvokeType invoke_type = invoke_instruction->GetOriginalInvokeType();
801 if (invoke_type == kInterface) {
802 // We have statically resolved the dispatch. To please the class linker
803 // at runtime, we change this call as if it was a virtual call.
804 invoke_type = kVirtual;
805 }
Nicolas Geoffraye0fe7ae2015-03-09 10:02:49 +0000806 HGraph* callee_graph = new (graph_->GetArena()) HGraph(
Nicolas Geoffray0a23d742015-05-07 11:57:35 +0100807 graph_->GetArena(),
Guillaume "Vermeille" Sanchezae09d2d2015-05-29 10:52:55 +0100808 callee_dex_file,
Nicolas Geoffray0a23d742015-05-07 11:57:35 +0100809 method_index,
Calin Juravle3cd4fc82015-05-14 15:15:42 +0100810 requires_ctor_barrier,
Mathieu Chartiere401d142015-04-22 13:56:20 -0700811 compiler_driver_->GetInstructionSet(),
Nicolas Geoffray35071052015-06-09 15:43:38 +0100812 invoke_type,
Nicolas Geoffray0a23d742015-05-07 11:57:35 +0100813 graph_->IsDebuggable(),
814 graph_->GetCurrentInstructionId());
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100815 callee_graph->SetArtMethod(resolved_method);
David Brazdil5e8b1372015-01-23 14:39:08 +0000816
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000817 OptimizingCompilerStats inline_stats;
David Brazdil5e8b1372015-01-23 14:39:08 +0000818 HGraphBuilder builder(callee_graph,
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000819 &dex_compilation_unit,
820 &outer_compilation_unit_,
Nicolas Geoffray9437b782015-03-25 10:08:51 +0000821 resolved_method->GetDexFile(),
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000822 compiler_driver_,
Nicolas Geoffray9523a3e2015-07-17 11:51:28 +0000823 &inline_stats,
Mathieu Chartier736b5602015-09-02 14:54:11 -0700824 resolved_method->GetQuickenedInfo(),
825 dex_cache);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000826
David Brazdil5e8b1372015-01-23 14:39:08 +0000827 if (!builder.BuildGraph(*code_item)) {
Guillaume "Vermeille" Sanchezae09d2d2015-05-29 10:52:55 +0100828 VLOG(compiler) << "Method " << PrettyMethod(method_index, callee_dex_file)
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000829 << " could not be built, so cannot be inlined";
830 return false;
831 }
832
Nicolas Geoffray259136f2014-12-17 23:21:58 +0000833 if (!RegisterAllocator::CanAllocateRegistersFor(*callee_graph,
834 compiler_driver_->GetInstructionSet())) {
Guillaume "Vermeille" Sanchezae09d2d2015-05-29 10:52:55 +0100835 VLOG(compiler) << "Method " << PrettyMethod(method_index, callee_dex_file)
Nicolas Geoffray259136f2014-12-17 23:21:58 +0000836 << " cannot be inlined because of the register allocator";
837 return false;
838 }
839
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000840 if (callee_graph->TryBuildingSsa(handles_) != kAnalysisSuccess) {
Guillaume "Vermeille" Sanchezae09d2d2015-05-29 10:52:55 +0100841 VLOG(compiler) << "Method " << PrettyMethod(method_index, callee_dex_file)
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000842 << " could not be transformed to SSA";
843 return false;
844 }
845
Nicolas Geoffraye418dda2015-08-11 20:03:09 -0700846 size_t parameter_index = 0;
847 for (HInstructionIterator instructions(callee_graph->GetEntryBlock()->GetInstructions());
848 !instructions.Done();
849 instructions.Advance()) {
850 HInstruction* current = instructions.Current();
851 if (current->IsParameterValue()) {
852 HInstruction* argument = invoke_instruction->InputAt(parameter_index++);
853 if (argument->IsNullConstant()) {
854 current->ReplaceWith(callee_graph->GetNullConstant());
855 } else if (argument->IsIntConstant()) {
856 current->ReplaceWith(callee_graph->GetIntConstant(argument->AsIntConstant()->GetValue()));
857 } else if (argument->IsLongConstant()) {
858 current->ReplaceWith(callee_graph->GetLongConstant(argument->AsLongConstant()->GetValue()));
859 } else if (argument->IsFloatConstant()) {
860 current->ReplaceWith(
861 callee_graph->GetFloatConstant(argument->AsFloatConstant()->GetValue()));
862 } else if (argument->IsDoubleConstant()) {
863 current->ReplaceWith(
864 callee_graph->GetDoubleConstant(argument->AsDoubleConstant()->GetValue()));
865 } else if (argument->GetType() == Primitive::kPrimNot) {
866 current->SetReferenceTypeInfo(argument->GetReferenceTypeInfo());
867 current->AsParameterValue()->SetCanBeNull(argument->CanBeNull());
868 }
869 }
870 }
871
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +0000872 // Run simple optimizations on the graph.
Calin Juravle7a9c8852015-04-21 14:07:50 +0100873 HDeadCodeElimination dce(callee_graph, stats_);
Nicolas Geoffraye34648d2015-11-23 08:59:07 +0000874 HConstantFolding fold(callee_graph);
Vladimir Markodc151b22015-10-15 18:02:30 +0100875 HSharpening sharpening(callee_graph, codegen_, dex_compilation_unit, compiler_driver_);
Calin Juravleacf735c2015-02-12 15:25:22 +0000876 InstructionSimplifier simplify(callee_graph, stats_);
Nicolas Geoffraye34648d2015-11-23 08:59:07 +0000877 IntrinsicsRecognizer intrinsics(callee_graph, compiler_driver_);
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +0000878
879 HOptimization* optimizations[] = {
Scott Wakelingd60a1af2015-07-22 14:32:44 +0100880 &intrinsics,
Vladimir Markodc151b22015-10-15 18:02:30 +0100881 &sharpening,
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +0000882 &simplify,
Nicolas Geoffraye418dda2015-08-11 20:03:09 -0700883 &fold,
Vladimir Marko9e23df52015-11-10 17:14:35 +0000884 &dce,
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +0000885 };
886
887 for (size_t i = 0; i < arraysize(optimizations); ++i) {
888 HOptimization* optimization = optimizations[i];
889 optimization->Run();
890 }
891
Nicolas Geoffraye418dda2015-08-11 20:03:09 -0700892 size_t number_of_instructions_budget = kMaximumNumberOfHInstructions;
Calin Juravleec748352015-07-29 13:52:12 +0100893 if (depth_ + 1 < compiler_driver_->GetCompilerOptions().GetInlineDepthLimit()) {
Nicolas Geoffray9437b782015-03-25 10:08:51 +0000894 HInliner inliner(callee_graph,
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100895 outermost_graph_,
Vladimir Markodc151b22015-10-15 18:02:30 +0100896 codegen_,
Nicolas Geoffray9437b782015-03-25 10:08:51 +0000897 outer_compilation_unit_,
898 dex_compilation_unit,
899 compiler_driver_,
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100900 handles_,
Nicolas Geoffray9437b782015-03-25 10:08:51 +0000901 stats_,
Nicolas Geoffray5949fa02015-12-18 10:57:10 +0000902 total_number_of_dex_registers_ + code_item->registers_size_,
Nicolas Geoffray9437b782015-03-25 10:08:51 +0000903 depth_ + 1);
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +0000904 inliner.Run();
Nicolas Geoffraye418dda2015-08-11 20:03:09 -0700905 number_of_instructions_budget += inliner.number_of_inlined_instructions_;
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +0000906 }
907
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +0100908 // TODO: We should abort only if all predecessors throw. However,
909 // HGraph::InlineInto currently does not handle an exit block with
910 // a throw predecessor.
911 HBasicBlock* exit_block = callee_graph->GetExitBlock();
912 if (exit_block == nullptr) {
Guillaume "Vermeille" Sanchezae09d2d2015-05-29 10:52:55 +0100913 VLOG(compiler) << "Method " << PrettyMethod(method_index, callee_dex_file)
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +0100914 << " could not be inlined because it has an infinite loop";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +0100915 return false;
916 }
917
918 bool has_throw_predecessor = false;
Vladimir Marko60584552015-09-03 13:35:12 +0000919 for (HBasicBlock* predecessor : exit_block->GetPredecessors()) {
920 if (predecessor->GetLastInstruction()->IsThrow()) {
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +0100921 has_throw_predecessor = true;
922 break;
923 }
924 }
925 if (has_throw_predecessor) {
Guillaume "Vermeille" Sanchezae09d2d2015-05-29 10:52:55 +0100926 VLOG(compiler) << "Method " << PrettyMethod(method_index, callee_dex_file)
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +0100927 << " could not be inlined because one branch always throws";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +0100928 return false;
929 }
930
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000931 HReversePostOrderIterator it(*callee_graph);
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +0000932 it.Advance(); // Past the entry block, it does not contain instructions that prevent inlining.
Nicolas Geoffraye418dda2015-08-11 20:03:09 -0700933 size_t number_of_instructions = 0;
Nicolas Geoffray5949fa02015-12-18 10:57:10 +0000934
935 bool can_inline_environment =
936 total_number_of_dex_registers_ < kMaximumNumberOfCumulatedDexRegisters;
937
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000938 for (; !it.Done(); it.Advance()) {
939 HBasicBlock* block = it.Current();
Nicolas Geoffray788f2f02016-01-22 12:41:38 +0000940
941 if (block->IsLoopHeader() && block->GetLoopInformation()->IsIrreducible()) {
942 // Don't inline methods with irreducible loops, they could prevent some
943 // optimizations to run.
Guillaume "Vermeille" Sanchezae09d2d2015-05-29 10:52:55 +0100944 VLOG(compiler) << "Method " << PrettyMethod(method_index, callee_dex_file)
Nicolas Geoffray788f2f02016-01-22 12:41:38 +0000945 << " could not be inlined because it contains an irreducible loop";
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000946 return false;
947 }
948
949 for (HInstructionIterator instr_it(block->GetInstructions());
950 !instr_it.Done();
951 instr_it.Advance()) {
Nicolas Geoffraye418dda2015-08-11 20:03:09 -0700952 if (number_of_instructions++ == number_of_instructions_budget) {
953 VLOG(compiler) << "Method " << PrettyMethod(method_index, callee_dex_file)
Nicolas Geoffray5949fa02015-12-18 10:57:10 +0000954 << " is not inlined because its caller has reached"
955 << " its instruction budget limit.";
Nicolas Geoffraye418dda2015-08-11 20:03:09 -0700956 return false;
957 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000958 HInstruction* current = instr_it.Current();
Nicolas Geoffray5949fa02015-12-18 10:57:10 +0000959 if (!can_inline_environment && current->NeedsEnvironment()) {
960 VLOG(compiler) << "Method " << PrettyMethod(method_index, callee_dex_file)
961 << " is not inlined because its caller has reached"
962 << " its environment budget limit.";
963 return false;
964 }
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000965
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +0100966 if (current->IsInvokeInterface()) {
967 // Disable inlining of interface calls. The cost in case of entering the
968 // resolution conflict is currently too high.
Guillaume "Vermeille" Sanchezae09d2d2015-05-29 10:52:55 +0100969 VLOG(compiler) << "Method " << PrettyMethod(method_index, callee_dex_file)
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +0100970 << " could not be inlined because it has an interface call.";
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000971 return false;
972 }
973
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +0100974 if (!same_dex_file && current->NeedsEnvironment()) {
Guillaume "Vermeille" Sanchezae09d2d2015-05-29 10:52:55 +0100975 VLOG(compiler) << "Method " << PrettyMethod(method_index, callee_dex_file)
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000976 << " could not be inlined because " << current->DebugName()
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +0100977 << " needs an environment and is in a different dex file";
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000978 return false;
979 }
Nicolas Geoffray9437b782015-03-25 10:08:51 +0000980
Vladimir Markodc151b22015-10-15 18:02:30 +0100981 if (!same_dex_file && current->NeedsDexCacheOfDeclaringClass()) {
Guillaume "Vermeille" Sanchezae09d2d2015-05-29 10:52:55 +0100982 VLOG(compiler) << "Method " << PrettyMethod(method_index, callee_dex_file)
Nicolas Geoffray9437b782015-03-25 10:08:51 +0000983 << " could not be inlined because " << current->DebugName()
984 << " it is in a different dex file and requires access to the dex cache";
985 return false;
986 }
Nicolas Geoffrayd9309292015-10-31 22:21:31 +0000987
988 if (current->IsNewInstance() &&
989 (current->AsNewInstance()->GetEntrypoint() == kQuickAllocObjectWithAccessCheck)) {
990 // Allocation entrypoint does not handle inlined frames.
991 return false;
992 }
993
994 if (current->IsNewArray() &&
995 (current->AsNewArray()->GetEntrypoint() == kQuickAllocArrayWithAccessCheck)) {
996 // Allocation entrypoint does not handle inlined frames.
997 return false;
998 }
999
1000 if (current->IsUnresolvedStaticFieldGet() ||
1001 current->IsUnresolvedInstanceFieldGet() ||
1002 current->IsUnresolvedStaticFieldSet() ||
1003 current->IsUnresolvedInstanceFieldSet()) {
1004 // Entrypoint for unresolved fields does not handle inlined frames.
1005 return false;
1006 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001007 }
1008 }
Nicolas Geoffraye418dda2015-08-11 20:03:09 -07001009 number_of_inlined_instructions_ += number_of_instructions;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001010
Calin Juravle2e768302015-07-28 14:41:11 +00001011 HInstruction* return_replacement = callee_graph->InlineInto(graph_, invoke_instruction);
Calin Juravle214bbcd2015-10-20 14:54:07 +01001012 if (return_replacement != nullptr) {
1013 DCHECK_EQ(graph_, return_replacement->GetBlock()->GetGraph());
1014 }
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001015 FixUpReturnReferenceType(resolved_method, invoke_instruction, return_replacement, do_rtp);
1016 return true;
1017}
Calin Juravle2e768302015-07-28 14:41:11 +00001018
Vladimir Markobe10e8e2016-01-22 12:09:44 +00001019void HInliner::FixUpReturnReferenceType(ArtMethod* resolved_method,
1020 HInvoke* invoke_instruction,
1021 HInstruction* return_replacement,
1022 bool do_rtp) {
Alex Light68289a52015-12-15 17:30:30 -08001023 // Check the integrity of reference types and run another type propagation if needed.
David Brazdil4833f5a2015-12-16 10:37:39 +00001024 if (return_replacement != nullptr) {
1025 if (return_replacement->GetType() == Primitive::kPrimNot) {
1026 if (!return_replacement->GetReferenceTypeInfo().IsValid()) {
1027 // Make sure that we have a valid type for the return. We may get an invalid one when
1028 // we inline invokes with multiple branches and create a Phi for the result.
1029 // TODO: we could be more precise by merging the phi inputs but that requires
1030 // some functionality from the reference type propagation.
1031 DCHECK(return_replacement->IsPhi());
1032 size_t pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
1033 ReferenceTypeInfo::TypeHandle return_handle =
1034 handles_->NewHandle(resolved_method->GetReturnType(true /* resolve */, pointer_size));
1035 return_replacement->SetReferenceTypeInfo(ReferenceTypeInfo::Create(
1036 return_handle, return_handle->CannotBeAssignedFromOtherTypes() /* is_exact */));
1037 }
Alex Light68289a52015-12-15 17:30:30 -08001038
David Brazdil4833f5a2015-12-16 10:37:39 +00001039 if (do_rtp) {
1040 // If the return type is a refinement of the declared type run the type propagation again.
1041 ReferenceTypeInfo return_rti = return_replacement->GetReferenceTypeInfo();
1042 ReferenceTypeInfo invoke_rti = invoke_instruction->GetReferenceTypeInfo();
1043 if (invoke_rti.IsStrictSupertypeOf(return_rti)
1044 || (return_rti.IsExact() && !invoke_rti.IsExact())
1045 || !return_replacement->CanBeNull()) {
1046 ReferenceTypePropagation(graph_, handles_).Run();
1047 }
1048 }
1049 } else if (return_replacement->IsInstanceOf()) {
1050 if (do_rtp) {
1051 // Inlining InstanceOf into an If may put a tighter bound on reference types.
1052 ReferenceTypePropagation(graph_, handles_).Run();
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001053 }
Calin Juravlecdfed3d2015-10-26 14:05:01 +00001054 }
Calin Juravle2e768302015-07-28 14:41:11 +00001055 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001056}
1057
1058} // namespace art