blob: a839d2dee86583dc34ad24b7ee091a4f867d28a9 [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());
395 if (graph_->GetInstructionSet() == kMips || graph_->GetInstructionSet() == kMips64) {
396 // TODO: Support HClassTableGet for mips and mips64.
397 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 }
615 HInstruction* obj = GetInvokeInputForArgVRegIndex(invoke_instruction, data.object_arg);
616 HInstanceFieldGet* iget = CreateInstanceFieldGet(resolved_method, data.field_idx, obj);
617 DCHECK_EQ(iget->GetFieldOffset().Uint32Value(), data.field_offset);
618 DCHECK_EQ(iget->IsVolatile() ? 1u : 0u, data.is_volatile);
619 invoke_instruction->GetBlock()->InsertInstructionBefore(iget, invoke_instruction);
620 return_replacement = iget;
621 break;
622 }
623 case kInlineOpIPut: {
624 const InlineIGetIPutData& data = inline_method.d.ifield_data;
625 if (data.method_is_static || data.object_arg != 0u) {
626 // TODO: Needs null check.
627 return false;
628 }
629 HInstruction* obj = GetInvokeInputForArgVRegIndex(invoke_instruction, data.object_arg);
630 HInstruction* value = GetInvokeInputForArgVRegIndex(invoke_instruction, data.src_arg);
631 HInstanceFieldSet* iput = CreateInstanceFieldSet(resolved_method, data.field_idx, obj, value);
632 DCHECK_EQ(iput->GetFieldOffset().Uint32Value(), data.field_offset);
633 DCHECK_EQ(iput->IsVolatile() ? 1u : 0u, data.is_volatile);
634 invoke_instruction->GetBlock()->InsertInstructionBefore(iput, invoke_instruction);
635 if (data.return_arg_plus1 != 0u) {
636 size_t return_arg = data.return_arg_plus1 - 1u;
637 return_replacement = GetInvokeInputForArgVRegIndex(invoke_instruction, return_arg);
638 }
639 break;
640 }
641 default:
642 LOG(FATAL) << "UNREACHABLE";
643 UNREACHABLE();
644 }
645
646 if (return_replacement != nullptr) {
647 invoke_instruction->ReplaceWith(return_replacement);
648 }
649 invoke_instruction->GetBlock()->RemoveInstruction(invoke_instruction);
650
651 FixUpReturnReferenceType(resolved_method, invoke_instruction, return_replacement, do_rtp);
652 return true;
653}
654
655HInstanceFieldGet* HInliner::CreateInstanceFieldGet(ArtMethod* resolved_method,
656 uint32_t field_index,
657 HInstruction* obj)
658 SHARED_REQUIRES(Locks::mutator_lock_) {
659 Handle<mirror::DexCache> dex_cache(handles_->NewHandle(resolved_method->GetDexCache()));
660 size_t pointer_size = InstructionSetPointerSize(codegen_->GetInstructionSet());
661 ArtField* resolved_field = dex_cache->GetResolvedField(field_index, pointer_size);
662 DCHECK(resolved_field != nullptr);
663 HInstanceFieldGet* iget = new (graph_->GetArena()) HInstanceFieldGet(
664 obj,
665 resolved_field->GetTypeAsPrimitiveType(),
666 resolved_field->GetOffset(),
667 resolved_field->IsVolatile(),
668 field_index,
669 resolved_field->GetDeclaringClass()->GetDexClassDefIndex(),
670 *resolved_method->GetDexFile(),
671 dex_cache,
Vladimir Markoadda4352016-01-29 10:24:41 +0000672 // Read barrier generates a runtime call in slow path and we need a valid
673 // dex pc for the associated stack map. 0 is bogus but valid. Bug: 26854537.
674 /* dex_pc */ 0);
Vladimir Markobe10e8e2016-01-22 12:09:44 +0000675 if (iget->GetType() == Primitive::kPrimNot) {
676 ReferenceTypePropagation rtp(graph_, handles_);
677 rtp.Visit(iget);
678 }
679 return iget;
680}
681
682HInstanceFieldSet* HInliner::CreateInstanceFieldSet(ArtMethod* resolved_method,
683 uint32_t field_index,
684 HInstruction* obj,
685 HInstruction* value)
686 SHARED_REQUIRES(Locks::mutator_lock_) {
687 Handle<mirror::DexCache> dex_cache(handles_->NewHandle(resolved_method->GetDexCache()));
688 size_t pointer_size = InstructionSetPointerSize(codegen_->GetInstructionSet());
689 ArtField* resolved_field = dex_cache->GetResolvedField(field_index, pointer_size);
690 DCHECK(resolved_field != nullptr);
691 HInstanceFieldSet* iput = new (graph_->GetArena()) HInstanceFieldSet(
692 obj,
693 value,
694 resolved_field->GetTypeAsPrimitiveType(),
695 resolved_field->GetOffset(),
696 resolved_field->IsVolatile(),
697 field_index,
698 resolved_field->GetDeclaringClass()->GetDexClassDefIndex(),
699 *resolved_method->GetDexFile(),
700 dex_cache,
Vladimir Markoadda4352016-01-29 10:24:41 +0000701 // Read barrier generates a runtime call in slow path and we need a valid
702 // dex pc for the associated stack map. 0 is bogus but valid. Bug: 26854537.
703 /* dex_pc */ 0);
Vladimir Markobe10e8e2016-01-22 12:09:44 +0000704 return iput;
705}
Mathieu Chartiere401d142015-04-22 13:56:20 -0700706bool HInliner::TryBuildAndInline(ArtMethod* resolved_method,
Nicolas Geoffrayc0365b12015-03-18 18:31:52 +0000707 HInvoke* invoke_instruction,
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100708 bool same_dex_file,
709 bool do_rtp) {
Nicolas Geoffrayc0365b12015-03-18 18:31:52 +0000710 ScopedObjectAccess soa(Thread::Current());
711 const DexFile::CodeItem* code_item = resolved_method->GetCodeItem();
Guillaume "Vermeille" Sanchezae09d2d2015-05-29 10:52:55 +0100712 const DexFile& callee_dex_file = *resolved_method->GetDexFile();
713 uint32_t method_index = resolved_method->GetDexMethodIndex();
Calin Juravle2e768302015-07-28 14:41:11 +0000714 ClassLinker* class_linker = caller_compilation_unit_.GetClassLinker();
Mathieu Chartier736b5602015-09-02 14:54:11 -0700715 Handle<mirror::DexCache> dex_cache(handles_->NewHandle(resolved_method->GetDexCache()));
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000716 DexCompilationUnit dex_compilation_unit(
717 nullptr,
Nicolas Geoffray9437b782015-03-25 10:08:51 +0000718 caller_compilation_unit_.GetClassLoader(),
Calin Juravle2e768302015-07-28 14:41:11 +0000719 class_linker,
Nicolas Geoffray8dbf0cf2015-08-11 02:14:38 +0000720 callee_dex_file,
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000721 code_item,
722 resolved_method->GetDeclaringClass()->GetDexClassDefIndex(),
Nicolas Geoffray8dbf0cf2015-08-11 02:14:38 +0000723 method_index,
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000724 resolved_method->GetAccessFlags(),
Mathieu Chartier736b5602015-09-02 14:54:11 -0700725 compiler_driver_->GetVerifiedMethod(&callee_dex_file, method_index),
726 dex_cache);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000727
Calin Juravle3cd4fc82015-05-14 15:15:42 +0100728 bool requires_ctor_barrier = false;
729
730 if (dex_compilation_unit.IsConstructor()) {
731 // If it's a super invocation and we already generate a barrier there's no need
732 // to generate another one.
733 // We identify super calls by looking at the "this" pointer. If its value is the
734 // same as the local "this" pointer then we must have a super invocation.
735 bool is_super_invocation = invoke_instruction->InputAt(0)->IsParameterValue()
736 && invoke_instruction->InputAt(0)->AsParameterValue()->IsThis();
737 if (is_super_invocation && graph_->ShouldGenerateConstructorBarrier()) {
738 requires_ctor_barrier = false;
739 } else {
740 Thread* self = Thread::Current();
741 requires_ctor_barrier = compiler_driver_->RequiresConstructorBarrier(self,
742 dex_compilation_unit.GetDexFile(),
743 dex_compilation_unit.GetClassDefIndex());
744 }
745 }
746
Nicolas Geoffray35071052015-06-09 15:43:38 +0100747 InvokeType invoke_type = invoke_instruction->GetOriginalInvokeType();
748 if (invoke_type == kInterface) {
749 // We have statically resolved the dispatch. To please the class linker
750 // at runtime, we change this call as if it was a virtual call.
751 invoke_type = kVirtual;
752 }
Nicolas Geoffraye0fe7ae2015-03-09 10:02:49 +0000753 HGraph* callee_graph = new (graph_->GetArena()) HGraph(
Nicolas Geoffray0a23d742015-05-07 11:57:35 +0100754 graph_->GetArena(),
Guillaume "Vermeille" Sanchezae09d2d2015-05-29 10:52:55 +0100755 callee_dex_file,
Nicolas Geoffray0a23d742015-05-07 11:57:35 +0100756 method_index,
Calin Juravle3cd4fc82015-05-14 15:15:42 +0100757 requires_ctor_barrier,
Mathieu Chartiere401d142015-04-22 13:56:20 -0700758 compiler_driver_->GetInstructionSet(),
Nicolas Geoffray35071052015-06-09 15:43:38 +0100759 invoke_type,
Nicolas Geoffray0a23d742015-05-07 11:57:35 +0100760 graph_->IsDebuggable(),
761 graph_->GetCurrentInstructionId());
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100762 callee_graph->SetArtMethod(resolved_method);
David Brazdil5e8b1372015-01-23 14:39:08 +0000763
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000764 OptimizingCompilerStats inline_stats;
David Brazdil5e8b1372015-01-23 14:39:08 +0000765 HGraphBuilder builder(callee_graph,
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000766 &dex_compilation_unit,
767 &outer_compilation_unit_,
Nicolas Geoffray9437b782015-03-25 10:08:51 +0000768 resolved_method->GetDexFile(),
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000769 compiler_driver_,
Nicolas Geoffray9523a3e2015-07-17 11:51:28 +0000770 &inline_stats,
Mathieu Chartier736b5602015-09-02 14:54:11 -0700771 resolved_method->GetQuickenedInfo(),
772 dex_cache);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000773
David Brazdil5e8b1372015-01-23 14:39:08 +0000774 if (!builder.BuildGraph(*code_item)) {
Guillaume "Vermeille" Sanchezae09d2d2015-05-29 10:52:55 +0100775 VLOG(compiler) << "Method " << PrettyMethod(method_index, callee_dex_file)
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000776 << " could not be built, so cannot be inlined";
777 return false;
778 }
779
Nicolas Geoffray259136f2014-12-17 23:21:58 +0000780 if (!RegisterAllocator::CanAllocateRegistersFor(*callee_graph,
781 compiler_driver_->GetInstructionSet())) {
Guillaume "Vermeille" Sanchezae09d2d2015-05-29 10:52:55 +0100782 VLOG(compiler) << "Method " << PrettyMethod(method_index, callee_dex_file)
Nicolas Geoffray259136f2014-12-17 23:21:58 +0000783 << " cannot be inlined because of the register allocator";
784 return false;
785 }
786
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000787 if (callee_graph->TryBuildingSsa(handles_) != kAnalysisSuccess) {
Guillaume "Vermeille" Sanchezae09d2d2015-05-29 10:52:55 +0100788 VLOG(compiler) << "Method " << PrettyMethod(method_index, callee_dex_file)
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000789 << " could not be transformed to SSA";
790 return false;
791 }
792
Nicolas Geoffraye418dda2015-08-11 20:03:09 -0700793 size_t parameter_index = 0;
794 for (HInstructionIterator instructions(callee_graph->GetEntryBlock()->GetInstructions());
795 !instructions.Done();
796 instructions.Advance()) {
797 HInstruction* current = instructions.Current();
798 if (current->IsParameterValue()) {
799 HInstruction* argument = invoke_instruction->InputAt(parameter_index++);
800 if (argument->IsNullConstant()) {
801 current->ReplaceWith(callee_graph->GetNullConstant());
802 } else if (argument->IsIntConstant()) {
803 current->ReplaceWith(callee_graph->GetIntConstant(argument->AsIntConstant()->GetValue()));
804 } else if (argument->IsLongConstant()) {
805 current->ReplaceWith(callee_graph->GetLongConstant(argument->AsLongConstant()->GetValue()));
806 } else if (argument->IsFloatConstant()) {
807 current->ReplaceWith(
808 callee_graph->GetFloatConstant(argument->AsFloatConstant()->GetValue()));
809 } else if (argument->IsDoubleConstant()) {
810 current->ReplaceWith(
811 callee_graph->GetDoubleConstant(argument->AsDoubleConstant()->GetValue()));
812 } else if (argument->GetType() == Primitive::kPrimNot) {
813 current->SetReferenceTypeInfo(argument->GetReferenceTypeInfo());
814 current->AsParameterValue()->SetCanBeNull(argument->CanBeNull());
815 }
816 }
817 }
818
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +0000819 // Run simple optimizations on the graph.
Calin Juravle7a9c8852015-04-21 14:07:50 +0100820 HDeadCodeElimination dce(callee_graph, stats_);
Nicolas Geoffraye34648d2015-11-23 08:59:07 +0000821 HConstantFolding fold(callee_graph);
Vladimir Markodc151b22015-10-15 18:02:30 +0100822 HSharpening sharpening(callee_graph, codegen_, dex_compilation_unit, compiler_driver_);
Calin Juravleacf735c2015-02-12 15:25:22 +0000823 InstructionSimplifier simplify(callee_graph, stats_);
Nicolas Geoffraye34648d2015-11-23 08:59:07 +0000824 IntrinsicsRecognizer intrinsics(callee_graph, compiler_driver_);
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +0000825
826 HOptimization* optimizations[] = {
Scott Wakelingd60a1af2015-07-22 14:32:44 +0100827 &intrinsics,
Vladimir Markodc151b22015-10-15 18:02:30 +0100828 &sharpening,
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +0000829 &simplify,
Nicolas Geoffraye418dda2015-08-11 20:03:09 -0700830 &fold,
Vladimir Marko9e23df52015-11-10 17:14:35 +0000831 &dce,
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +0000832 };
833
834 for (size_t i = 0; i < arraysize(optimizations); ++i) {
835 HOptimization* optimization = optimizations[i];
836 optimization->Run();
837 }
838
Nicolas Geoffraye418dda2015-08-11 20:03:09 -0700839 size_t number_of_instructions_budget = kMaximumNumberOfHInstructions;
Calin Juravleec748352015-07-29 13:52:12 +0100840 if (depth_ + 1 < compiler_driver_->GetCompilerOptions().GetInlineDepthLimit()) {
Nicolas Geoffray9437b782015-03-25 10:08:51 +0000841 HInliner inliner(callee_graph,
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100842 outermost_graph_,
Vladimir Markodc151b22015-10-15 18:02:30 +0100843 codegen_,
Nicolas Geoffray9437b782015-03-25 10:08:51 +0000844 outer_compilation_unit_,
845 dex_compilation_unit,
846 compiler_driver_,
Nicolas Geoffray454a4812015-06-09 10:37:32 +0100847 handles_,
Nicolas Geoffray9437b782015-03-25 10:08:51 +0000848 stats_,
Nicolas Geoffray5949fa02015-12-18 10:57:10 +0000849 total_number_of_dex_registers_ + code_item->registers_size_,
Nicolas Geoffray9437b782015-03-25 10:08:51 +0000850 depth_ + 1);
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +0000851 inliner.Run();
Nicolas Geoffraye418dda2015-08-11 20:03:09 -0700852 number_of_instructions_budget += inliner.number_of_inlined_instructions_;
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +0000853 }
854
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +0100855 // TODO: We should abort only if all predecessors throw. However,
856 // HGraph::InlineInto currently does not handle an exit block with
857 // a throw predecessor.
858 HBasicBlock* exit_block = callee_graph->GetExitBlock();
859 if (exit_block == nullptr) {
Guillaume "Vermeille" Sanchezae09d2d2015-05-29 10:52:55 +0100860 VLOG(compiler) << "Method " << PrettyMethod(method_index, callee_dex_file)
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +0100861 << " could not be inlined because it has an infinite loop";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +0100862 return false;
863 }
864
865 bool has_throw_predecessor = false;
Vladimir Marko60584552015-09-03 13:35:12 +0000866 for (HBasicBlock* predecessor : exit_block->GetPredecessors()) {
867 if (predecessor->GetLastInstruction()->IsThrow()) {
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +0100868 has_throw_predecessor = true;
869 break;
870 }
871 }
872 if (has_throw_predecessor) {
Guillaume "Vermeille" Sanchezae09d2d2015-05-29 10:52:55 +0100873 VLOG(compiler) << "Method " << PrettyMethod(method_index, callee_dex_file)
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +0100874 << " could not be inlined because one branch always throws";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +0100875 return false;
876 }
877
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000878 HReversePostOrderIterator it(*callee_graph);
Nicolas Geoffrayef87c5d2015-01-30 12:41:14 +0000879 it.Advance(); // Past the entry block, it does not contain instructions that prevent inlining.
Nicolas Geoffraye418dda2015-08-11 20:03:09 -0700880 size_t number_of_instructions = 0;
Nicolas Geoffray5949fa02015-12-18 10:57:10 +0000881
882 bool can_inline_environment =
883 total_number_of_dex_registers_ < kMaximumNumberOfCumulatedDexRegisters;
884
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000885 for (; !it.Done(); it.Advance()) {
886 HBasicBlock* block = it.Current();
Nicolas Geoffray788f2f02016-01-22 12:41:38 +0000887
888 if (block->IsLoopHeader() && block->GetLoopInformation()->IsIrreducible()) {
889 // Don't inline methods with irreducible loops, they could prevent some
890 // optimizations to run.
Guillaume "Vermeille" Sanchezae09d2d2015-05-29 10:52:55 +0100891 VLOG(compiler) << "Method " << PrettyMethod(method_index, callee_dex_file)
Nicolas Geoffray788f2f02016-01-22 12:41:38 +0000892 << " could not be inlined because it contains an irreducible loop";
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000893 return false;
894 }
895
896 for (HInstructionIterator instr_it(block->GetInstructions());
897 !instr_it.Done();
898 instr_it.Advance()) {
Nicolas Geoffraye418dda2015-08-11 20:03:09 -0700899 if (number_of_instructions++ == number_of_instructions_budget) {
900 VLOG(compiler) << "Method " << PrettyMethod(method_index, callee_dex_file)
Nicolas Geoffray5949fa02015-12-18 10:57:10 +0000901 << " is not inlined because its caller has reached"
902 << " its instruction budget limit.";
Nicolas Geoffraye418dda2015-08-11 20:03:09 -0700903 return false;
904 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000905 HInstruction* current = instr_it.Current();
Nicolas Geoffray5949fa02015-12-18 10:57:10 +0000906 if (!can_inline_environment && current->NeedsEnvironment()) {
907 VLOG(compiler) << "Method " << PrettyMethod(method_index, callee_dex_file)
908 << " is not inlined because its caller has reached"
909 << " its environment budget limit.";
910 return false;
911 }
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000912
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +0100913 if (current->IsInvokeInterface()) {
914 // Disable inlining of interface calls. The cost in case of entering the
915 // resolution conflict is currently too high.
Guillaume "Vermeille" Sanchezae09d2d2015-05-29 10:52:55 +0100916 VLOG(compiler) << "Method " << PrettyMethod(method_index, callee_dex_file)
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +0100917 << " could not be inlined because it has an interface call.";
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000918 return false;
919 }
920
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +0100921 if (!same_dex_file && current->NeedsEnvironment()) {
Guillaume "Vermeille" Sanchezae09d2d2015-05-29 10:52:55 +0100922 VLOG(compiler) << "Method " << PrettyMethod(method_index, callee_dex_file)
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000923 << " could not be inlined because " << current->DebugName()
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +0100924 << " needs an environment and is in a different dex file";
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000925 return false;
926 }
Nicolas Geoffray9437b782015-03-25 10:08:51 +0000927
Vladimir Markodc151b22015-10-15 18:02:30 +0100928 if (!same_dex_file && current->NeedsDexCacheOfDeclaringClass()) {
Guillaume "Vermeille" Sanchezae09d2d2015-05-29 10:52:55 +0100929 VLOG(compiler) << "Method " << PrettyMethod(method_index, callee_dex_file)
Nicolas Geoffray9437b782015-03-25 10:08:51 +0000930 << " could not be inlined because " << current->DebugName()
931 << " it is in a different dex file and requires access to the dex cache";
932 return false;
933 }
Nicolas Geoffrayd9309292015-10-31 22:21:31 +0000934
935 if (current->IsNewInstance() &&
936 (current->AsNewInstance()->GetEntrypoint() == kQuickAllocObjectWithAccessCheck)) {
937 // Allocation entrypoint does not handle inlined frames.
938 return false;
939 }
940
941 if (current->IsNewArray() &&
942 (current->AsNewArray()->GetEntrypoint() == kQuickAllocArrayWithAccessCheck)) {
943 // Allocation entrypoint does not handle inlined frames.
944 return false;
945 }
946
947 if (current->IsUnresolvedStaticFieldGet() ||
948 current->IsUnresolvedInstanceFieldGet() ||
949 current->IsUnresolvedStaticFieldSet() ||
950 current->IsUnresolvedInstanceFieldSet()) {
951 // Entrypoint for unresolved fields does not handle inlined frames.
952 return false;
953 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000954 }
955 }
Nicolas Geoffraye418dda2015-08-11 20:03:09 -0700956 number_of_inlined_instructions_ += number_of_instructions;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000957
Calin Juravle2e768302015-07-28 14:41:11 +0000958 HInstruction* return_replacement = callee_graph->InlineInto(graph_, invoke_instruction);
Calin Juravle214bbcd2015-10-20 14:54:07 +0100959 if (return_replacement != nullptr) {
960 DCHECK_EQ(graph_, return_replacement->GetBlock()->GetGraph());
961 }
Vladimir Markobe10e8e2016-01-22 12:09:44 +0000962 FixUpReturnReferenceType(resolved_method, invoke_instruction, return_replacement, do_rtp);
963 return true;
964}
Calin Juravle2e768302015-07-28 14:41:11 +0000965
Vladimir Markobe10e8e2016-01-22 12:09:44 +0000966void HInliner::FixUpReturnReferenceType(ArtMethod* resolved_method,
967 HInvoke* invoke_instruction,
968 HInstruction* return_replacement,
969 bool do_rtp) {
Alex Light68289a52015-12-15 17:30:30 -0800970 // Check the integrity of reference types and run another type propagation if needed.
David Brazdil4833f5a2015-12-16 10:37:39 +0000971 if (return_replacement != nullptr) {
972 if (return_replacement->GetType() == Primitive::kPrimNot) {
973 if (!return_replacement->GetReferenceTypeInfo().IsValid()) {
974 // Make sure that we have a valid type for the return. We may get an invalid one when
975 // we inline invokes with multiple branches and create a Phi for the result.
976 // TODO: we could be more precise by merging the phi inputs but that requires
977 // some functionality from the reference type propagation.
978 DCHECK(return_replacement->IsPhi());
979 size_t pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
980 ReferenceTypeInfo::TypeHandle return_handle =
981 handles_->NewHandle(resolved_method->GetReturnType(true /* resolve */, pointer_size));
982 return_replacement->SetReferenceTypeInfo(ReferenceTypeInfo::Create(
983 return_handle, return_handle->CannotBeAssignedFromOtherTypes() /* is_exact */));
984 }
Alex Light68289a52015-12-15 17:30:30 -0800985
David Brazdil4833f5a2015-12-16 10:37:39 +0000986 if (do_rtp) {
987 // If the return type is a refinement of the declared type run the type propagation again.
988 ReferenceTypeInfo return_rti = return_replacement->GetReferenceTypeInfo();
989 ReferenceTypeInfo invoke_rti = invoke_instruction->GetReferenceTypeInfo();
990 if (invoke_rti.IsStrictSupertypeOf(return_rti)
991 || (return_rti.IsExact() && !invoke_rti.IsExact())
992 || !return_replacement->CanBeNull()) {
993 ReferenceTypePropagation(graph_, handles_).Run();
994 }
995 }
996 } else if (return_replacement->IsInstanceOf()) {
997 if (do_rtp) {
998 // Inlining InstanceOf into an If may put a tighter bound on reference types.
999 ReferenceTypePropagation(graph_, handles_).Run();
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001000 }
Calin Juravlecdfed3d2015-10-26 14:05:01 +00001001 }
Calin Juravle2e768302015-07-28 14:41:11 +00001002 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001003}
1004
1005} // namespace art