• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2015 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 "sharpening.h"
18 
19 #include "base/casts.h"
20 #include "class_linker.h"
21 #include "code_generator.h"
22 #include "driver/dex_compilation_unit.h"
23 #include "utils/dex_cache_arrays_layout-inl.h"
24 #include "driver/compiler_driver.h"
25 #include "gc/heap.h"
26 #include "gc/space/image_space.h"
27 #include "handle_scope-inl.h"
28 #include "mirror/dex_cache.h"
29 #include "mirror/string.h"
30 #include "nodes.h"
31 #include "runtime.h"
32 #include "scoped_thread_state_change.h"
33 
34 namespace art {
35 
Run()36 void HSharpening::Run() {
37   // We don't care about the order of the blocks here.
38   for (HBasicBlock* block : graph_->GetReversePostOrder()) {
39     for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
40       HInstruction* instruction = it.Current();
41       if (instruction->IsInvokeStaticOrDirect()) {
42         ProcessInvokeStaticOrDirect(instruction->AsInvokeStaticOrDirect());
43       } else if (instruction->IsLoadString()) {
44         ProcessLoadString(instruction->AsLoadString());
45       }
46       // TODO: Move the sharpening of invoke-virtual/-interface/-super from HGraphBuilder
47       //       here. Rewrite it to avoid the CompilerDriver's reliance on verifier data
48       //       because we know the type better when inlining.
49       // TODO: HLoadClass - select better load kind if available.
50     }
51   }
52 }
53 
ProcessInvokeStaticOrDirect(HInvokeStaticOrDirect * invoke)54 void HSharpening::ProcessInvokeStaticOrDirect(HInvokeStaticOrDirect* invoke) {
55   if (invoke->IsStringInit()) {
56     // Not using the dex cache arrays. But we could still try to use a better dispatch...
57     // TODO: Use direct_method and direct_code for the appropriate StringFactory method.
58     return;
59   }
60 
61   // TODO: Avoid CompilerDriver.
62   InvokeType original_invoke_type = invoke->GetOriginalInvokeType();
63   InvokeType optimized_invoke_type = original_invoke_type;
64   MethodReference target_method(&graph_->GetDexFile(), invoke->GetDexMethodIndex());
65   int vtable_idx;
66   uintptr_t direct_code, direct_method;
67   bool success = compiler_driver_->ComputeInvokeInfo(
68       &compilation_unit_,
69       invoke->GetDexPc(),
70       false /* update_stats: already updated in builder */,
71       true /* enable_devirtualization */,
72       &optimized_invoke_type,
73       &target_method,
74       &vtable_idx,
75       &direct_code,
76       &direct_method);
77   if (!success) {
78     // TODO: try using kDexCachePcRelative. It's always a valid method load
79     // kind as long as it's supported by the codegen
80     return;
81   }
82   invoke->SetOptimizedInvokeType(optimized_invoke_type);
83   invoke->SetTargetMethod(target_method);
84 
85   HInvokeStaticOrDirect::MethodLoadKind method_load_kind;
86   HInvokeStaticOrDirect::CodePtrLocation code_ptr_location;
87   uint64_t method_load_data = 0u;
88   uint64_t direct_code_ptr = 0u;
89 
90   HGraph* outer_graph = codegen_->GetGraph();
91   if (target_method.dex_file == &outer_graph->GetDexFile() &&
92       target_method.dex_method_index == outer_graph->GetMethodIdx()) {
93     method_load_kind = HInvokeStaticOrDirect::MethodLoadKind::kRecursive;
94     code_ptr_location = HInvokeStaticOrDirect::CodePtrLocation::kCallSelf;
95   } else {
96     bool use_pc_relative_instructions =
97         ((direct_method == 0u || direct_code == static_cast<uintptr_t>(-1))) &&
98         ContainsElement(compiler_driver_->GetDexFilesForOatFile(), target_method.dex_file);
99     if (direct_method != 0u) {  // Should we use a direct pointer to the method?
100       // Note: For JIT, kDirectAddressWithFixup doesn't make sense at all and while
101       // kDirectAddress would be fine for image methods, we don't support it at the moment.
102       DCHECK(!Runtime::Current()->UseJitCompilation());
103       if (direct_method != static_cast<uintptr_t>(-1)) {  // Is the method pointer known now?
104         method_load_kind = HInvokeStaticOrDirect::MethodLoadKind::kDirectAddress;
105         method_load_data = direct_method;
106       } else {  // The direct pointer will be known at link time.
107         method_load_kind = HInvokeStaticOrDirect::MethodLoadKind::kDirectAddressWithFixup;
108       }
109     } else {  // Use dex cache.
110       DCHECK_EQ(target_method.dex_file, &graph_->GetDexFile());
111       if (use_pc_relative_instructions) {  // Can we use PC-relative access to the dex cache arrays?
112         DCHECK(!Runtime::Current()->UseJitCompilation());
113         method_load_kind = HInvokeStaticOrDirect::MethodLoadKind::kDexCachePcRelative;
114         DexCacheArraysLayout layout(GetInstructionSetPointerSize(codegen_->GetInstructionSet()),
115                                     &graph_->GetDexFile());
116         method_load_data = layout.MethodOffset(target_method.dex_method_index);
117       } else {  // We must go through the ArtMethod's pointer to resolved methods.
118         method_load_kind = HInvokeStaticOrDirect::MethodLoadKind::kDexCacheViaMethod;
119       }
120     }
121     if (direct_code != 0u) {  // Should we use a direct pointer to the code?
122       // Note: For JIT, kCallPCRelative and kCallDirectWithFixup don't make sense at all and
123       // while kCallDirect would be fine for image methods, we don't support it at the moment.
124       DCHECK(!Runtime::Current()->UseJitCompilation());
125       if (direct_code != static_cast<uintptr_t>(-1)) {  // Is the code pointer known now?
126         code_ptr_location = HInvokeStaticOrDirect::CodePtrLocation::kCallDirect;
127         direct_code_ptr = direct_code;
128       } else if (use_pc_relative_instructions) {
129         // Use PC-relative calls for invokes within a multi-dex oat file.
130         code_ptr_location = HInvokeStaticOrDirect::CodePtrLocation::kCallPCRelative;
131       } else {  // The direct pointer will be known at link time.
132         // NOTE: This is used for app->boot calls when compiling an app against
133         // a relocatable but not yet relocated image.
134         code_ptr_location = HInvokeStaticOrDirect::CodePtrLocation::kCallDirectWithFixup;
135       }
136     } else {  // We must use the code pointer from the ArtMethod.
137       code_ptr_location = HInvokeStaticOrDirect::CodePtrLocation::kCallArtMethod;
138     }
139   }
140 
141   if (graph_->IsDebuggable()) {
142     // For debuggable apps always use the code pointer from ArtMethod
143     // so that we don't circumvent instrumentation stubs if installed.
144     code_ptr_location = HInvokeStaticOrDirect::CodePtrLocation::kCallArtMethod;
145   }
146 
147   HInvokeStaticOrDirect::DispatchInfo desired_dispatch_info = {
148       method_load_kind, code_ptr_location, method_load_data, direct_code_ptr
149   };
150   HInvokeStaticOrDirect::DispatchInfo dispatch_info =
151       codegen_->GetSupportedInvokeStaticOrDirectDispatch(desired_dispatch_info,
152                                                          invoke->GetTargetMethod());
153   invoke->SetDispatchInfo(dispatch_info);
154 }
155 
ProcessLoadString(HLoadString * load_string)156 void HSharpening::ProcessLoadString(HLoadString* load_string) {
157   DCHECK_EQ(load_string->GetLoadKind(), HLoadString::LoadKind::kDexCacheViaMethod);
158   DCHECK(!load_string->IsInDexCache());
159 
160   const DexFile& dex_file = load_string->GetDexFile();
161   uint32_t string_index = load_string->GetStringIndex();
162 
163   bool is_in_dex_cache = false;
164   HLoadString::LoadKind desired_load_kind;
165   uint64_t address = 0u;  // String or dex cache element address.
166   {
167     Runtime* runtime = Runtime::Current();
168     ClassLinker* class_linker = runtime->GetClassLinker();
169     ScopedObjectAccess soa(Thread::Current());
170     StackHandleScope<1> hs(soa.Self());
171     Handle<mirror::DexCache> dex_cache = IsSameDexFile(dex_file, *compilation_unit_.GetDexFile())
172         ? compilation_unit_.GetDexCache()
173         : hs.NewHandle(class_linker->FindDexCache(soa.Self(), dex_file));
174 
175     if (compiler_driver_->IsBootImage()) {
176       // Compiling boot image. Resolve the string and allocate it if needed.
177       DCHECK(!runtime->UseJitCompilation());
178       mirror::String* string = class_linker->ResolveString(dex_file, string_index, dex_cache);
179       CHECK(string != nullptr);
180       if (!compiler_driver_->GetSupportBootImageFixup()) {
181         // MIPS/MIPS64 or compiler_driver_test. Do not sharpen.
182         desired_load_kind = HLoadString::LoadKind::kDexCacheViaMethod;
183       } else {
184         DCHECK(ContainsElement(compiler_driver_->GetDexFilesForOatFile(), &dex_file));
185         is_in_dex_cache = true;
186         desired_load_kind = codegen_->GetCompilerOptions().GetCompilePic()
187             ? HLoadString::LoadKind::kBootImageLinkTimePcRelative
188             : HLoadString::LoadKind::kBootImageLinkTimeAddress;
189       }
190     } else if (runtime->UseJitCompilation()) {
191       // TODO: Make sure we don't set the "compile PIC" flag for JIT as that's bogus.
192       // DCHECK(!codegen_->GetCompilerOptions().GetCompilePic());
193       mirror::String* string = dex_cache->GetResolvedString(string_index);
194       is_in_dex_cache = (string != nullptr);
195       if (string != nullptr && runtime->GetHeap()->ObjectIsInBootImageSpace(string)) {
196         desired_load_kind = HLoadString::LoadKind::kBootImageAddress;
197         address = reinterpret_cast64<uint64_t>(string);
198       } else {
199         // Note: If the string is not in the dex cache, the instruction needs environment
200         // and will not be inlined across dex files. Within a dex file, the slow-path helper
201         // loads the correct string and inlined frames are used correctly for OOM stack trace.
202         // TODO: Write a test for this.
203         desired_load_kind = HLoadString::LoadKind::kDexCacheAddress;
204         void* dex_cache_element_address = &dex_cache->GetStrings()[string_index];
205         address = reinterpret_cast64<uint64_t>(dex_cache_element_address);
206       }
207     } else {
208       // AOT app compilation. Try to lookup the string without allocating if not found.
209       mirror::String* string = class_linker->LookupString(dex_file, string_index, dex_cache);
210       if (string != nullptr && runtime->GetHeap()->ObjectIsInBootImageSpace(string)) {
211         if (codegen_->GetCompilerOptions().GetCompilePic()) {
212           // Use PC-relative load from the dex cache if the dex file belongs
213           // to the oat file that we're currently compiling.
214           desired_load_kind = ContainsElement(compiler_driver_->GetDexFilesForOatFile(), &dex_file)
215               ? HLoadString::LoadKind::kDexCachePcRelative
216               : HLoadString::LoadKind::kDexCacheViaMethod;
217         } else {
218           desired_load_kind = HLoadString::LoadKind::kBootImageAddress;
219           address = reinterpret_cast64<uint64_t>(string);
220         }
221       } else {
222         // Not JIT and the string is not in boot image.
223         desired_load_kind = HLoadString::LoadKind::kDexCachePcRelative;
224       }
225     }
226   }
227   if (is_in_dex_cache) {
228     load_string->MarkInDexCache();
229   }
230 
231   HLoadString::LoadKind load_kind = codegen_->GetSupportedLoadStringKind(desired_load_kind);
232   switch (load_kind) {
233     case HLoadString::LoadKind::kBootImageLinkTimeAddress:
234     case HLoadString::LoadKind::kBootImageLinkTimePcRelative:
235     case HLoadString::LoadKind::kDexCacheViaMethod:
236       load_string->SetLoadKindWithStringReference(load_kind, dex_file, string_index);
237       break;
238     case HLoadString::LoadKind::kBootImageAddress:
239     case HLoadString::LoadKind::kDexCacheAddress:
240       DCHECK_NE(address, 0u);
241       load_string->SetLoadKindWithAddress(load_kind, address);
242       break;
243     case HLoadString::LoadKind::kDexCachePcRelative: {
244       size_t pointer_size = InstructionSetPointerSize(codegen_->GetInstructionSet());
245       DexCacheArraysLayout layout(pointer_size, &dex_file);
246       size_t element_index = layout.StringOffset(string_index);
247       load_string->SetLoadKindWithDexCacheReference(load_kind, dex_file, element_index);
248       break;
249     }
250   }
251 }
252 
253 }  // namespace art
254