blob: 4d98d610924397d8ef2306514578884ccb0d0657 [file] [log] [blame]
Elliott Hughes2faa5f12012-01-30 14:42:07 -08001/*
2 * Copyright (C) 2011 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 */
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -070016
17#include "compiler.h"
18
Elliott Hughesd9c67be2012-02-02 19:54:06 -080019#include <vector>
20
Elliott Hughesb3bd5f02012-03-08 21:05:27 -080021#include <dlfcn.h>
Elliott Hughesd9c67be2012-02-02 19:54:06 -080022#include <unistd.h>
Brian Carlstrom27ec9612011-09-19 20:20:38 -070023
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -070024#include "class_linker.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -070025#include "class_loader.h"
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -070026#include "dex_cache.h"
Brian Carlstrom9baa4ae2011-09-01 21:14:14 -070027#include "jni_internal.h"
Logan Chien4dd96f52012-02-29 01:26:58 +080028#include "oat_compilation_unit.h"
Brian Carlstrom3320cf42011-10-04 14:58:28 -070029#include "oat_file.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080030#include "object_utils.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -070031#include "runtime.h"
Elliott Hughesb3bd5f02012-03-08 21:05:27 -080032#include "space.h"
Brian Carlstrom3320cf42011-10-04 14:58:28 -070033#include "stl_util.h"
Elliott Hughes601a1232012-02-02 17:47:38 -080034#include "timing_logger.h"
Ian Rogers776ac1f2012-04-13 23:36:36 -070035#include "verifier/method_verifier.h"
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -070036
Elliott Hughes059d5c12012-03-12 17:39:18 -070037#if defined(__APPLE__)
38#include <mach-o/dyld.h>
39#endif
40
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -070041namespace art {
42
Shih-wei Liaoc486c112011-09-13 16:43:52 -070043namespace arm {
Ian Rogersbdb03912011-09-14 00:55:44 -070044 ByteArray* CreateAbstractMethodErrorStub();
Ian Rogers1cb0a1d2011-10-06 15:24:35 -070045 ByteArray* ArmCreateResolutionTrampoline(Runtime::TrampolineType type);
Elliott Hughes8add92d2012-01-18 18:18:43 -080046 ByteArray* CreateJniDlsymLookupStub();
Shih-wei Liaoc486c112011-09-13 16:43:52 -070047}
Shih-wei Liaoc486c112011-09-13 16:43:52 -070048namespace x86 {
Ian Rogersbdb03912011-09-14 00:55:44 -070049 ByteArray* CreateAbstractMethodErrorStub();
Ian Rogers1cb0a1d2011-10-06 15:24:35 -070050 ByteArray* X86CreateResolutionTrampoline(Runtime::TrampolineType type);
Elliott Hughes8add92d2012-01-18 18:18:43 -080051 ByteArray* CreateJniDlsymLookupStub();
Brian Carlstrome24fa612011-09-29 00:53:55 -070052}
53
Ian Rogers996cc582012-02-14 22:23:29 -080054static double Percentage(size_t x, size_t y) {
Elliott Hughes398f64b2012-03-26 18:05:48 -070055 return 100.0 * (static_cast<double>(x)) / (static_cast<double>(x + y));
Ian Rogers996cc582012-02-14 22:23:29 -080056}
57
58static void DumpStat(size_t x, size_t y, const char* str) {
59 if (x == 0 && y == 0) {
60 return;
61 }
62 LOG(INFO) << Percentage(x, y) << "% of " << str << " for " << (x + y) << " cases";
63}
64
Ian Rogersc8b306f2012-02-17 21:34:44 -080065class AOTCompilationStats {
66 public:
67 AOTCompilationStats() : stats_lock_("AOT compilation statistics lock"),
68 types_in_dex_cache_(0), types_not_in_dex_cache_(0),
69 strings_in_dex_cache_(0), strings_not_in_dex_cache_(0),
70 resolved_types_(0), unresolved_types_(0),
71 resolved_instance_fields_(0), unresolved_instance_fields_(0),
Ian Rogers2ed3b952012-03-17 11:49:39 -070072 resolved_local_static_fields_(0), resolved_static_fields_(0), unresolved_static_fields_(0) {
73 for (size_t i = 0; i <= kMaxInvokeType; i++) {
Ian Rogersc8b306f2012-02-17 21:34:44 -080074 resolved_methods_[i] = 0;
75 unresolved_methods_[i] = 0;
Ian Rogers2ed3b952012-03-17 11:49:39 -070076 virtual_made_direct_[i] = 0;
77 direct_calls_to_boot_[i] = 0;
78 direct_methods_to_boot_[i] = 0;
Elliott Hughesb25c3f62012-03-26 16:35:06 -070079 }
Ian Rogersc8b306f2012-02-17 21:34:44 -080080 }
81
82 void Dump() {
83 DumpStat(types_in_dex_cache_, types_not_in_dex_cache_, "types known to be in dex cache");
84 DumpStat(strings_in_dex_cache_, strings_not_in_dex_cache_, "strings known to be in dex cache");
85 DumpStat(resolved_types_, unresolved_types_, "types resolved");
86 DumpStat(resolved_instance_fields_, unresolved_instance_fields_, "instance fields resolved");
87 DumpStat(resolved_local_static_fields_ + resolved_static_fields_, unresolved_static_fields_,
88 "static fields resolved");
89 DumpStat(resolved_local_static_fields_, resolved_static_fields_ + unresolved_static_fields_,
90 "static fields local to a class");
91
Ian Rogers2ed3b952012-03-17 11:49:39 -070092 for (size_t i = 0; i <= kMaxInvokeType; i++) {
Ian Rogersc8b306f2012-02-17 21:34:44 -080093 std::ostringstream oss;
Ian Rogers2ed3b952012-03-17 11:49:39 -070094 oss << static_cast<InvokeType>(i) << " methods were AOT resolved";
Ian Rogersc8b306f2012-02-17 21:34:44 -080095 DumpStat(resolved_methods_[i], unresolved_methods_[i], oss.str().c_str());
Ian Rogers2ed3b952012-03-17 11:49:39 -070096 if (virtual_made_direct_[i] > 0) {
97 std::ostringstream oss2;
98 oss2 << static_cast<InvokeType>(i) << " methods made direct";
99 DumpStat(virtual_made_direct_[i],
100 resolved_methods_[i] + unresolved_methods_[i] - virtual_made_direct_[i],
101 oss2.str().c_str());
102 }
103 if (direct_calls_to_boot_[i] > 0) {
104 std::ostringstream oss2;
105 oss2 << static_cast<InvokeType>(i) << " method calls are direct into boot";
106 DumpStat(direct_calls_to_boot_[i],
107 resolved_methods_[i] + unresolved_methods_[i] - direct_calls_to_boot_[i],
108 oss2.str().c_str());
109 }
110 if (direct_methods_to_boot_[i] > 0) {
111 std::ostringstream oss2;
112 oss2 << static_cast<InvokeType>(i) << " method calls have methods in boot";
113 DumpStat(direct_methods_to_boot_[i],
114 resolved_methods_[i] + unresolved_methods_[i] - direct_methods_to_boot_[i],
115 oss2.str().c_str());
116 }
Ian Rogersc8b306f2012-02-17 21:34:44 -0800117 }
118 }
Ian Rogers996cc582012-02-14 22:23:29 -0800119
120// Allow lossy statistics in non-debug builds
121#ifndef NDEBUG
122#define STATS_LOCK() MutexLock mu(stats_lock_)
123#else
124#define STATS_LOCK()
125#endif
126
Ian Rogersc8b306f2012-02-17 21:34:44 -0800127 void TypeInDexCache() {
128 STATS_LOCK();
129 types_in_dex_cache_++;
Ian Rogers996cc582012-02-14 22:23:29 -0800130 }
Ian Rogers996cc582012-02-14 22:23:29 -0800131
Ian Rogersc8b306f2012-02-17 21:34:44 -0800132 void TypeNotInDexCache() {
133 STATS_LOCK();
134 types_not_in_dex_cache_++;
Ian Rogers996cc582012-02-14 22:23:29 -0800135 }
Ian Rogersc8b306f2012-02-17 21:34:44 -0800136
137 void StringInDexCache() {
138 STATS_LOCK();
139 strings_in_dex_cache_++;
140 }
141
142 void StringNotInDexCache() {
143 STATS_LOCK();
144 strings_not_in_dex_cache_++;
145 }
146
147 void TypeDoesntNeedAccessCheck() {
148 STATS_LOCK();
149 resolved_types_++;
150 }
151
152 void TypeNeedsAccessCheck() {
153 STATS_LOCK();
154 unresolved_types_++;
155 }
156
157 void ResolvedInstanceField() {
158 STATS_LOCK();
159 resolved_instance_fields_++;
160 }
161
Elliott Hughesb25c3f62012-03-26 16:35:06 -0700162 void UnresolvedInstanceField() {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800163 STATS_LOCK();
164 unresolved_instance_fields_++;
165 }
166
167 void ResolvedLocalStaticField() {
168 STATS_LOCK();
169 resolved_local_static_fields_++;
170 }
171
172 void ResolvedStaticField() {
173 STATS_LOCK();
174 resolved_static_fields_++;
175 }
176
177 void UnresolvedStaticField() {
178 STATS_LOCK();
179 unresolved_static_fields_++;
180 }
181
182 void ResolvedMethod(InvokeType type) {
183 DCHECK_LE(type, kMaxInvokeType);
184 STATS_LOCK();
185 resolved_methods_[type]++;
186 }
187
188 void UnresolvedMethod(InvokeType type) {
189 DCHECK_LE(type, kMaxInvokeType);
190 STATS_LOCK();
191 unresolved_methods_[type]++;
192 }
193
Ian Rogers2ed3b952012-03-17 11:49:39 -0700194 void VirtualMadeDirect(InvokeType type) {
195 DCHECK_LE(type, kMaxInvokeType);
Ian Rogersfb6adba2012-03-04 21:51:51 -0800196 STATS_LOCK();
Ian Rogers2ed3b952012-03-17 11:49:39 -0700197 virtual_made_direct_[type]++;
Ian Rogersfb6adba2012-03-04 21:51:51 -0800198 }
Ian Rogers2ed3b952012-03-17 11:49:39 -0700199
200 void DirectCallsToBoot(InvokeType type) {
201 DCHECK_LE(type, kMaxInvokeType);
202 STATS_LOCK();
203 direct_calls_to_boot_[type]++;
204 }
205
206 void DirectMethodsToBoot(InvokeType type) {
207 DCHECK_LE(type, kMaxInvokeType);
208 STATS_LOCK();
209 direct_methods_to_boot_[type]++;
210 }
211
Ian Rogersc8b306f2012-02-17 21:34:44 -0800212 private:
213 Mutex stats_lock_;
214
215 size_t types_in_dex_cache_;
216 size_t types_not_in_dex_cache_;
217
218 size_t strings_in_dex_cache_;
219 size_t strings_not_in_dex_cache_;
220
221 size_t resolved_types_;
222 size_t unresolved_types_;
223
224 size_t resolved_instance_fields_;
225 size_t unresolved_instance_fields_;
226
227 size_t resolved_local_static_fields_;
228 size_t resolved_static_fields_;
229 size_t unresolved_static_fields_;
230
231 size_t resolved_methods_[kMaxInvokeType + 1];
232 size_t unresolved_methods_[kMaxInvokeType + 1];
Ian Rogers2ed3b952012-03-17 11:49:39 -0700233 size_t virtual_made_direct_[kMaxInvokeType + 1];
234 size_t direct_calls_to_boot_[kMaxInvokeType + 1];
235 size_t direct_methods_to_boot_[kMaxInvokeType + 1];
Ian Rogersc8b306f2012-02-17 21:34:44 -0800236
Elliott Hughesb25c3f62012-03-26 16:35:06 -0700237 DISALLOW_COPY_AND_ASSIGN(AOTCompilationStats);
Ian Rogersc8b306f2012-02-17 21:34:44 -0800238};
Ian Rogers996cc582012-02-14 22:23:29 -0800239
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800240static std::string MakeCompilerSoName(InstructionSet instruction_set) {
241 // TODO: is the ARM/Thumb2 instruction set distinction really buying us anything,
242 // or just causing hassle like this?
243 if (instruction_set == kThumb2) {
244 instruction_set = kArm;
245 }
246
Elliott Hughes059d5c12012-03-12 17:39:18 -0700247 // Capitalize the instruction set, because that's what we do in the build system.
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800248 std::ostringstream instruction_set_name_os;
249 instruction_set_name_os << instruction_set;
250 std::string instruction_set_name(instruction_set_name_os.str());
251 for (size_t i = 0; i < instruction_set_name.size(); ++i) {
252 instruction_set_name[i] = toupper(instruction_set_name[i]);
253 }
Elliott Hughes059d5c12012-03-12 17:39:18 -0700254
255 // Bad things happen if we pull in the libartd-compiler to a libart dex2oat or vice versa,
256 // because we end up with both libart and libartd in the same address space!
Elliott Hughes67d92002012-03-26 15:08:51 -0700257 const char* suffix = (kIsDebugBuild ? "d" : "");
Elliott Hughes059d5c12012-03-12 17:39:18 -0700258
259 // Work out the filename for the compiler library.
Shih-wei Liaoe94d9b22012-05-22 09:01:24 -0700260#if defined(ART_USE_LLVM_COMPILER)
Shih-wei Liaoc4c98812012-03-10 21:55:51 -0800261 std::string library_name(StringPrintf("art%s-compiler-llvm", suffix));
Shih-wei Liaoe94d9b22012-05-22 09:01:24 -0700262#elif defined(ART_USE_GREENLAND_COMPILER)
263 std::string library_name(StringPrintf("art%s-compiler-greenland", suffix));
264#else
265 std::string library_name(StringPrintf("art%s-compiler-%s", suffix, instruction_set_name.c_str()));
Shih-wei Liaoc4c98812012-03-10 21:55:51 -0800266#endif
Elliott Hughes059d5c12012-03-12 17:39:18 -0700267 std::string filename(StringPrintf(OS_SHARED_LIB_FORMAT_STR, library_name.c_str()));
268
269#if defined(__APPLE__)
270 // On Linux, dex2oat will have been built with an RPATH of $ORIGIN/../lib, so dlopen(3) will find
271 // the .so by itself. On Mac OS, there isn't really an equivalent, so we have to manually do the
272 // same work.
Elliott Hughes059d5c12012-03-12 17:39:18 -0700273 uint32_t executable_path_length = 0;
Elliott Hughes448e93c2012-03-28 22:30:06 -0700274 _NSGetExecutablePath(NULL, &executable_path_length);
275 std::string path(executable_path_length, static_cast<char>(0));
276 CHECK_EQ(_NSGetExecutablePath(&path[0], &executable_path_length), 0);
Elliott Hughes059d5c12012-03-12 17:39:18 -0700277
278 // Strip the "/dex2oat".
279 size_t last_slash = path.find_last_of('/');
280 CHECK_NE(last_slash, std::string::npos) << path;
281 path.resize(last_slash);
282
283 // Strip the "/bin".
284 last_slash = path.find_last_of('/');
285 path.resize(last_slash);
286
287 filename = path + "/lib/" + filename;
288#endif
289 return filename;
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800290}
291
Elliott Hughes46f060a2012-03-09 17:36:50 -0800292template<typename Fn>
293static Fn FindFunction(const std::string& compiler_so_name, void* library, const char* name) {
294 Fn fn = reinterpret_cast<Fn>(dlsym(library, name));
295 if (fn == NULL) {
296 LOG(FATAL) << "Couldn't find \"" << name << "\" in compiler library " << compiler_so_name << ": " << dlerror();
297 }
Elliott Hughes059d5c12012-03-12 17:39:18 -0700298 VLOG(compiler) << "Found \"" << name << "\" at " << reinterpret_cast<void*>(fn);
Elliott Hughes46f060a2012-03-09 17:36:50 -0800299 return fn;
300}
301
Elliott Hughes5523ee02012-02-03 18:18:34 -0800302Compiler::Compiler(InstructionSet instruction_set, bool image, size_t thread_count,
Brian Carlstromba0668e2012-03-26 13:14:07 -0700303 bool support_debugging, const std::set<std::string>* image_classes,
304 bool dump_stats, bool dump_timings)
Brian Carlstromaded5f72011-10-07 17:15:04 -0700305 : instruction_set_(instruction_set),
Elliott Hughesc225caa2012-02-03 15:43:37 -0800306 compiled_classes_lock_("compiled classes lock"),
307 compiled_methods_lock_("compiled method lock"),
308 compiled_invoke_stubs_lock_("compiled invoke stubs lock"),
Logan Chien7a2a23a2012-06-06 11:01:00 +0800309#if defined(ART_USE_LLVM_COMPILER)
310 compiled_proxy_stubs_lock_("compiled proxy stubs lock"),
311#endif
Brian Carlstromaded5f72011-10-07 17:15:04 -0700312 image_(image),
Elliott Hughes5523ee02012-02-03 18:18:34 -0800313 thread_count_(thread_count),
Elliott Hughesde6e4cf2012-02-27 14:46:06 -0800314 support_debugging_(support_debugging),
Ian Rogersc8b306f2012-02-17 21:34:44 -0800315 stats_(new AOTCompilationStats),
Brian Carlstromba0668e2012-03-26 13:14:07 -0700316 dump_stats_(dump_stats),
317 dump_timings_(dump_timings),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800318 image_classes_(image_classes),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800319 compiler_library_(NULL),
Elliott Hughes46f060a2012-03-09 17:36:50 -0800320 compiler_(NULL),
Elliott Hughes6f4976c2012-03-13 21:19:01 -0700321 compiler_context_(NULL),
Elliott Hughes46f060a2012-03-09 17:36:50 -0800322 jni_compiler_(NULL),
Elliott Hughes5ddbe0b2012-06-01 12:58:24 -0700323#if !defined(ART_USE_LLVM_COMPILER)
324 create_invoke_stub_(NULL) {
325#else
326 create_invoke_stub_(NULL),
327 compiler_enable_auto_elf_loading_(NULL),
Logan Chienf7015fd2012-03-18 01:19:37 +0800328 compiler_get_method_code_addr_(NULL),
Elliott Hughes5ddbe0b2012-06-01 12:58:24 -0700329 compiler_get_method_invoke_stub_addr_(NULL) {
Logan Chienf7015fd2012-03-18 01:19:37 +0800330#endif
Shih-wei Liaoc4c98812012-03-10 21:55:51 -0800331 std::string compiler_so_name(MakeCompilerSoName(instruction_set_));
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800332 compiler_library_ = dlopen(compiler_so_name.c_str(), RTLD_LAZY);
333 if (compiler_library_ == NULL) {
334 LOG(FATAL) << "Couldn't find compiler library " << compiler_so_name << ": " << dlerror();
335 }
336 VLOG(compiler) << "dlopen(\"" << compiler_so_name << "\", RTLD_LAZY) returned " << compiler_library_;
337
Shih-wei Liaoe94d9b22012-05-22 09:01:24 -0700338#if defined(ART_USE_LLVM_COMPILER) || defined(ART_USE_GREENLAND_COMPILER)
Logan Chien106b2a02012-03-18 04:41:38 +0800339 // Initialize compiler_context_
340 typedef void (*InitCompilerContextFn)(Compiler&);
341
342 InitCompilerContextFn init_compiler_context =
343 FindFunction<void (*)(Compiler&)>(compiler_so_name,
344 compiler_library_,
345 "ArtInitCompilerContext");
346
347 init_compiler_context(*this);
348#endif
349
Elliott Hughes3fa1b7e2012-03-13 17:06:22 -0700350 compiler_ = FindFunction<CompilerFn>(compiler_so_name, compiler_library_, "ArtCompileMethod");
Elliott Hughes46f060a2012-03-09 17:36:50 -0800351 jni_compiler_ = FindFunction<JniCompilerFn>(compiler_so_name, compiler_library_, "ArtJniCompileMethod");
352 create_invoke_stub_ = FindFunction<CreateInvokeStubFn>(compiler_so_name, compiler_library_, "ArtCreateInvokeStub");
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800353
Logan Chienf7015fd2012-03-18 01:19:37 +0800354#if defined(ART_USE_LLVM_COMPILER)
Logan Chien7a2a23a2012-06-06 11:01:00 +0800355 create_proxy_stub_ = FindFunction<CreateProxyStubFn>(
356 compiler_so_name, compiler_library_, "ArtCreateProxyStub");
Logan Chienf7015fd2012-03-18 01:19:37 +0800357 compiler_enable_auto_elf_loading_ = FindFunction<CompilerEnableAutoElfLoadingFn>(
358 compiler_so_name, compiler_library_, "compilerLLVMEnableAutoElfLoading");
359 compiler_get_method_code_addr_ = FindFunction<CompilerGetMethodCodeAddrFn>(
360 compiler_so_name, compiler_library_, "compilerLLVMGetMethodCodeAddr");
361 compiler_get_method_invoke_stub_addr_ = FindFunction<CompilerGetMethodInvokeStubAddrFn>(
362 compiler_so_name, compiler_library_, "compilerLLVMGetMethodInvokeStubAddr");
363#endif
364
Brian Carlstrom25c33252011-09-18 15:58:35 -0700365 CHECK(!Runtime::Current()->IsStarted());
Brian Carlstromae826982011-11-09 01:33:42 -0800366 if (!image_) {
367 CHECK(image_classes_ == NULL);
368 }
Shih-wei Liaoc486c112011-09-13 16:43:52 -0700369}
370
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700371Compiler::~Compiler() {
Elliott Hughesc225caa2012-02-03 15:43:37 -0800372 {
373 MutexLock mu(compiled_classes_lock_);
374 STLDeleteValues(&compiled_classes_);
375 }
376 {
377 MutexLock mu(compiled_methods_lock_);
378 STLDeleteValues(&compiled_methods_);
379 }
380 {
381 MutexLock mu(compiled_invoke_stubs_lock_);
382 STLDeleteValues(&compiled_invoke_stubs_);
Elliott Hughesbb551fa2012-01-25 16:35:29 -0800383 }
Brian Carlstromd06dfe72012-06-06 22:15:39 -0700384#if defined(ART_USE_LLVM_COMPILER)
Brian Carlstromf5822582012-03-19 22:34:31 -0700385 {
Logan Chien7a2a23a2012-06-06 11:01:00 +0800386 MutexLock mu(compiled_proxy_stubs_lock_);
387 STLDeleteValues(&compiled_proxy_stubs_);
388 }
Brian Carlstromd06dfe72012-06-06 22:15:39 -0700389#endif
Logan Chien7a2a23a2012-06-06 11:01:00 +0800390 {
Brian Carlstromf5822582012-03-19 22:34:31 -0700391 MutexLock mu(compiled_methods_lock_);
392 STLDeleteElements(&code_to_patch_);
393 }
394 {
395 MutexLock mu(compiled_methods_lock_);
396 STLDeleteElements(&methods_to_patch_);
397 }
Shih-wei Liaoc4c98812012-03-10 21:55:51 -0800398#if defined(ART_USE_LLVM_COMPILER)
399 CompilerCallbackFn f = FindFunction<CompilerCallbackFn>(MakeCompilerSoName(instruction_set_),
400 compiler_library_,
401 "compilerLLVMDispose");
402 (*f)(*this);
403#endif
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800404 if (compiler_library_ != NULL) {
405 VLOG(compiler) << "dlclose(" << compiler_library_ << ")";
406 dlclose(compiler_library_);
407 }
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700408}
409
Ian Rogers1cb0a1d2011-10-06 15:24:35 -0700410ByteArray* Compiler::CreateResolutionStub(InstructionSet instruction_set,
411 Runtime::TrampolineType type) {
Ian Rogersad25ac52011-10-04 19:13:33 -0700412 if (instruction_set == kX86) {
Ian Rogers1cb0a1d2011-10-06 15:24:35 -0700413 return x86::X86CreateResolutionTrampoline(type);
Ian Rogersad25ac52011-10-04 19:13:33 -0700414 } else {
415 CHECK(instruction_set == kArm || instruction_set == kThumb2);
416 // Generates resolution stub using ARM instruction set
Ian Rogers1cb0a1d2011-10-06 15:24:35 -0700417 return arm::ArmCreateResolutionTrampoline(type);
Ian Rogersad25ac52011-10-04 19:13:33 -0700418 }
419}
420
Elliott Hughes8add92d2012-01-18 18:18:43 -0800421ByteArray* Compiler::CreateJniDlsymLookupStub(InstructionSet instruction_set) {
Ian Rogers169c9a72011-11-13 20:13:17 -0800422 switch (instruction_set) {
423 case kArm:
424 case kThumb2:
Elliott Hughes8add92d2012-01-18 18:18:43 -0800425 return arm::CreateJniDlsymLookupStub();
Ian Rogers169c9a72011-11-13 20:13:17 -0800426 case kX86:
Elliott Hughes8add92d2012-01-18 18:18:43 -0800427 return x86::CreateJniDlsymLookupStub();
Ian Rogers169c9a72011-11-13 20:13:17 -0800428 default:
Ian Rogers49c48942012-03-11 15:15:37 -0700429 LOG(FATAL) << "Unknown InstructionSet: " << instruction_set;
Ian Rogers169c9a72011-11-13 20:13:17 -0800430 return NULL;
431 }
432}
433
Ian Rogersad25ac52011-10-04 19:13:33 -0700434ByteArray* Compiler::CreateAbstractMethodErrorStub(InstructionSet instruction_set) {
435 if (instruction_set == kX86) {
436 return x86::CreateAbstractMethodErrorStub();
437 } else {
438 CHECK(instruction_set == kArm || instruction_set == kThumb2);
439 // Generates resolution stub using ARM instruction set
440 return arm::CreateAbstractMethodErrorStub();
441 }
442}
443
Jesse Wilson254db0f2011-11-16 16:44:11 -0500444void Compiler::CompileAll(const ClassLoader* class_loader,
Brian Carlstromae826982011-11-09 01:33:42 -0800445 const std::vector<const DexFile*>& dex_files) {
Brian Carlstrom25c33252011-09-18 15:58:35 -0700446 DCHECK(!Runtime::Current()->IsStarted());
Brian Carlstromae826982011-11-09 01:33:42 -0800447
Elliott Hughes601a1232012-02-02 17:47:38 -0800448 TimingLogger timings("compiler");
449
Elliott Hughes4909ba42012-06-14 13:33:49 -0700450 // TODO: make the verifier thread-safe and remove this workaround.
451 size_t thread_count = thread_count_;
452 thread_count_ = 1;
Elliott Hughes601a1232012-02-02 17:47:38 -0800453 PreCompile(class_loader, dex_files, timings);
Elliott Hughes4909ba42012-06-14 13:33:49 -0700454 thread_count_ = thread_count;
Elliott Hughes601a1232012-02-02 17:47:38 -0800455
Brian Carlstromae826982011-11-09 01:33:42 -0800456 Compile(class_loader, dex_files);
Elliott Hughes601a1232012-02-02 17:47:38 -0800457 timings.AddSplit("Compile");
458
Brian Carlstromae826982011-11-09 01:33:42 -0800459 PostCompile(class_loader, dex_files);
Elliott Hughes601a1232012-02-02 17:47:38 -0800460 timings.AddSplit("PostCompile");
461
Brian Carlstromba0668e2012-03-26 13:14:07 -0700462 if (dump_timings_ && timings.GetTotalNs() > MsToNs(1000)) {
Elliott Hughes601a1232012-02-02 17:47:38 -0800463 timings.Dump();
464 }
Ian Rogers996cc582012-02-14 22:23:29 -0800465
Brian Carlstromba0668e2012-03-26 13:14:07 -0700466 if (dump_stats_) {
467 stats_->Dump();
468 }
Brian Carlstrom8a487412011-08-29 20:08:52 -0700469}
470
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700471void Compiler::CompileOne(const Method* method) {
Brian Carlstrom25c33252011-09-18 15:58:35 -0700472 DCHECK(!Runtime::Current()->IsStarted());
Brian Carlstromae826982011-11-09 01:33:42 -0800473
Brian Carlstrom8a487412011-08-29 20:08:52 -0700474 const ClassLoader* class_loader = method->GetDeclaringClass()->GetClassLoader();
Brian Carlstromae826982011-11-09 01:33:42 -0800475
Ian Rogers0571d352011-11-03 19:51:38 -0700476 // Find the dex_file
477 const DexCache* dex_cache = method->GetDeclaringClass()->GetDexCache();
478 const DexFile& dex_file = Runtime::Current()->GetClassLinker()->FindDexFile(dex_cache);
Brian Carlstromae826982011-11-09 01:33:42 -0800479 std::vector<const DexFile*> dex_files;
480 dex_files.push_back(&dex_file);
481
Elliott Hughes601a1232012-02-02 17:47:38 -0800482 TimingLogger timings("CompileOne");
483 PreCompile(class_loader, dex_files, timings);
Brian Carlstromae826982011-11-09 01:33:42 -0800484
Ian Rogers0571d352011-11-03 19:51:38 -0700485 uint32_t method_idx = method->GetDexMethodIndex();
Ian Rogersa3760aa2011-11-14 14:32:37 -0800486 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(method->GetCodeItemOffset());
487 CompileMethod(code_item, method->GetAccessFlags(), method_idx, class_loader, dex_file);
Brian Carlstromae826982011-11-09 01:33:42 -0800488
489 PostCompile(class_loader, dex_files);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700490}
491
Brian Carlstromae826982011-11-09 01:33:42 -0800492void Compiler::Resolve(const ClassLoader* class_loader,
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800493 const std::vector<const DexFile*>& dex_files, TimingLogger& timings) {
Brian Carlstromae826982011-11-09 01:33:42 -0800494 for (size_t i = 0; i != dex_files.size(); ++i) {
495 const DexFile* dex_file = dex_files[i];
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700496 CHECK(dex_file != NULL);
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800497 ResolveDexFile(class_loader, *dex_file, timings);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700498 }
499}
500
Brian Carlstromae826982011-11-09 01:33:42 -0800501void Compiler::PreCompile(const ClassLoader* class_loader,
Elliott Hughes601a1232012-02-02 17:47:38 -0800502 const std::vector<const DexFile*>& dex_files, TimingLogger& timings) {
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800503 Resolve(class_loader, dex_files, timings);
Elliott Hughes601a1232012-02-02 17:47:38 -0800504
Brian Carlstromae826982011-11-09 01:33:42 -0800505 Verify(class_loader, dex_files);
Elliott Hughes601a1232012-02-02 17:47:38 -0800506 timings.AddSplit("PreCompile.Verify");
507
Brian Carlstromae826982011-11-09 01:33:42 -0800508 InitializeClassesWithoutClinit(class_loader, dex_files);
Elliott Hughes601a1232012-02-02 17:47:38 -0800509 timings.AddSplit("PreCompile.InitializeClassesWithoutClinit");
Brian Carlstromae826982011-11-09 01:33:42 -0800510}
511
512void Compiler::PostCompile(const ClassLoader* class_loader,
513 const std::vector<const DexFile*>& dex_files) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -0800514 SetGcMaps(class_loader, dex_files);
Shih-wei Liaod1fec812012-02-13 09:51:10 -0800515#if defined(ART_USE_LLVM_COMPILER)
Shih-wei Liaoc4c98812012-03-10 21:55:51 -0800516 CompilerCallbackFn f = FindFunction<CompilerCallbackFn>(MakeCompilerSoName(instruction_set_),
517 compiler_library_,
518 "compilerLLVMMaterializeRemainder");
519 (*f)(*this);
Shih-wei Liaod1fec812012-02-13 09:51:10 -0800520#endif
Brian Carlstromae826982011-11-09 01:33:42 -0800521}
522
523bool Compiler::IsImageClass(const std::string& descriptor) const {
524 if (image_classes_ == NULL) {
525 return true;
526 }
527 return image_classes_->find(descriptor) != image_classes_->end();
528}
529
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800530bool Compiler::CanAssumeTypeIsPresentInDexCache(const DexCache* dex_cache,
Ian Rogers996cc582012-02-14 22:23:29 -0800531 uint32_t type_idx) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800532 if (!IsImage()) {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800533 stats_->TypeNotInDexCache();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800534 return false;
535 }
Ian Rogers1bddec32012-02-04 12:27:34 -0800536 Class* resolved_class = dex_cache->GetResolvedType(type_idx);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800537 if (resolved_class == NULL) {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800538 stats_->TypeNotInDexCache();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800539 return false;
540 }
Ian Rogers996cc582012-02-14 22:23:29 -0800541 bool result = IsImageClass(ClassHelper(resolved_class).GetDescriptor());
542 if (result) {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800543 stats_->TypeInDexCache();
Ian Rogers996cc582012-02-14 22:23:29 -0800544 } else {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800545 stats_->TypeNotInDexCache();
Ian Rogers996cc582012-02-14 22:23:29 -0800546 }
547 return result;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800548}
549
Ian Rogers1bddec32012-02-04 12:27:34 -0800550bool Compiler::CanAssumeStringIsPresentInDexCache(const DexCache* dex_cache,
Ian Rogers996cc582012-02-14 22:23:29 -0800551 uint32_t string_idx) {
Ian Rogers1bddec32012-02-04 12:27:34 -0800552 // TODO: Add support for loading strings referenced by image_classes_
553 // See also Compiler::ResolveDexFile
554
555 // The following is a test saying that if we're building the image without a restricted set of
556 // image classes then we can assume the string is present in the dex cache if it is there now
Ian Rogers996cc582012-02-14 22:23:29 -0800557 bool result = IsImage() && image_classes_ == NULL && dex_cache->GetResolvedString(string_idx) != NULL;
558 if (result) {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800559 stats_->StringInDexCache();
Ian Rogers996cc582012-02-14 22:23:29 -0800560 } else {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800561 stats_->StringNotInDexCache();
Ian Rogers996cc582012-02-14 22:23:29 -0800562 }
563 return result;
Ian Rogers1bddec32012-02-04 12:27:34 -0800564}
565
566bool Compiler::CanAccessTypeWithoutChecks(uint32_t referrer_idx, const DexCache* dex_cache,
Ian Rogers996cc582012-02-14 22:23:29 -0800567 const DexFile& dex_file, uint32_t type_idx) {
Ian Rogers1bddec32012-02-04 12:27:34 -0800568 // Get type from dex cache assuming it was populated by the verifier
569 Class* resolved_class = dex_cache->GetResolvedType(type_idx);
570 if (resolved_class == NULL) {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800571 stats_->TypeNeedsAccessCheck();
Ian Rogers1bddec32012-02-04 12:27:34 -0800572 return false; // Unknown class needs access checks.
573 }
574 const DexFile::MethodId& method_id = dex_file.GetMethodId(referrer_idx);
575 Class* referrer_class = dex_cache->GetResolvedType(method_id.class_idx_);
576 if (referrer_class == NULL) {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800577 stats_->TypeNeedsAccessCheck();
Ian Rogers1bddec32012-02-04 12:27:34 -0800578 return false; // Incomplete referrer knowledge needs access check.
579 }
580 // Perform access check, will return true if access is ok or false if we're going to have to
581 // check this at runtime (for example for class loaders).
Ian Rogers996cc582012-02-14 22:23:29 -0800582 bool result = referrer_class->CanAccess(resolved_class);
583 if (result) {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800584 stats_->TypeDoesntNeedAccessCheck();
Ian Rogers996cc582012-02-14 22:23:29 -0800585 } else {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800586 stats_->TypeNeedsAccessCheck();
Ian Rogers996cc582012-02-14 22:23:29 -0800587 }
588 return result;
Ian Rogers1bddec32012-02-04 12:27:34 -0800589}
590
591bool Compiler::CanAccessInstantiableTypeWithoutChecks(uint32_t referrer_idx,
592 const DexCache* dex_cache,
593 const DexFile& dex_file,
Ian Rogers996cc582012-02-14 22:23:29 -0800594 uint32_t type_idx) {
Ian Rogers1bddec32012-02-04 12:27:34 -0800595 // Get type from dex cache assuming it was populated by the verifier.
596 Class* resolved_class = dex_cache->GetResolvedType(type_idx);
597 if (resolved_class == NULL) {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800598 stats_->TypeNeedsAccessCheck();
Ian Rogers1bddec32012-02-04 12:27:34 -0800599 return false; // Unknown class needs access checks.
600 }
601 const DexFile::MethodId& method_id = dex_file.GetMethodId(referrer_idx);
602 Class* referrer_class = dex_cache->GetResolvedType(method_id.class_idx_);
603 if (referrer_class == NULL) {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800604 stats_->TypeNeedsAccessCheck();
Ian Rogers1bddec32012-02-04 12:27:34 -0800605 return false; // Incomplete referrer knowledge needs access check.
606 }
607 // Perform access and instantiable checks, will return true if access is ok or false if we're
608 // going to have to check this at runtime (for example for class loaders).
Ian Rogers996cc582012-02-14 22:23:29 -0800609 bool result = referrer_class->CanAccess(resolved_class) && resolved_class->IsInstantiable();
610 if (result) {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800611 stats_->TypeDoesntNeedAccessCheck();
Ian Rogers996cc582012-02-14 22:23:29 -0800612 } else {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800613 stats_->TypeNeedsAccessCheck();
Ian Rogers996cc582012-02-14 22:23:29 -0800614 }
615 return result;
Ian Rogers1bddec32012-02-04 12:27:34 -0800616}
617
Logan Chien4dd96f52012-02-29 01:26:58 +0800618static Class* ComputeReferrerClass(OatCompilationUnit* mUnit) {
619 const DexFile::MethodId& referrer_method_id =
620 mUnit->dex_file_->GetMethodId(mUnit->method_idx_);
621
622 return mUnit->class_linker_->ResolveType(
623 *mUnit->dex_file_, referrer_method_id.class_idx_,
624 mUnit->dex_cache_, mUnit->class_loader_);
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800625}
626
Logan Chien4dd96f52012-02-29 01:26:58 +0800627static Field* ComputeReferrerField(OatCompilationUnit* mUnit, uint32_t field_idx) {
628 return mUnit->class_linker_->ResolveField(
629 *mUnit->dex_file_, field_idx, mUnit->dex_cache_,
630 mUnit->class_loader_, false);
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800631}
632
Logan Chien4dd96f52012-02-29 01:26:58 +0800633static Method* ComputeReferrerMethod(OatCompilationUnit* mUnit, uint32_t method_idx) {
634 return mUnit->class_linker_->ResolveMethod(
635 *mUnit->dex_file_, method_idx, mUnit->dex_cache_,
636 mUnit->class_loader_, true);
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800637}
638
Logan Chien4dd96f52012-02-29 01:26:58 +0800639bool Compiler::ComputeInstanceFieldInfo(uint32_t field_idx, OatCompilationUnit* mUnit,
jeffhao8cd6dda2012-02-22 10:15:34 -0800640 int& field_offset, bool& is_volatile, bool is_put) {
Ian Rogers1bddec32012-02-04 12:27:34 -0800641 // Conservative defaults
642 field_offset = -1;
643 is_volatile = true;
644 // Try to resolve field
Logan Chien4dd96f52012-02-29 01:26:58 +0800645 Field* resolved_field = ComputeReferrerField(mUnit, field_idx);
Ian Rogers1bddec32012-02-04 12:27:34 -0800646 if (resolved_field != NULL) {
Logan Chien4dd96f52012-02-29 01:26:58 +0800647 Class* referrer_class = ComputeReferrerClass(mUnit);
Ian Rogerse2645d32012-04-11 14:42:42 -0700648 if (referrer_class != NULL) {
649 Class* fields_class = resolved_field->GetDeclaringClass();
650 bool access_ok = referrer_class->CanAccess(fields_class) &&
651 referrer_class->CanAccessMember(fields_class,
652 resolved_field->GetAccessFlags());
653 if (!access_ok) {
654 // The referring class can't access the resolved field, this may occur as a result of a
655 // protected field being made public by a sub-class. Resort to the dex file to determine
656 // the correct class for the access check.
657 const DexFile& dex_file = mUnit->class_linker_->FindDexFile(referrer_class->GetDexCache());
658 Class* dex_fields_class = mUnit->class_linker_->ResolveType(dex_file,
659 dex_file.GetFieldId(field_idx).class_idx_,
660 referrer_class);
661 access_ok = referrer_class->CanAccess(dex_fields_class) &&
662 referrer_class->CanAccessMember(dex_fields_class,
663 resolved_field->GetAccessFlags());
664 }
665 bool is_write_to_final_from_wrong_class = is_put && resolved_field->IsFinal() &&
666 fields_class != referrer_class;
667 if (access_ok && !is_write_to_final_from_wrong_class) {
668 field_offset = resolved_field->GetOffset().Int32Value();
669 is_volatile = resolved_field->IsVolatile();
670 stats_->ResolvedInstanceField();
671 return true; // Fast path.
672 }
Ian Rogers1bddec32012-02-04 12:27:34 -0800673 }
674 }
675 // Clean up any exception left by field/type resolution
676 Thread* thread = Thread::Current();
677 if (thread->IsExceptionPending()) {
678 thread->ClearException();
679 }
Ian Rogersc8b306f2012-02-17 21:34:44 -0800680 stats_->UnresolvedInstanceField();
Ian Rogers1bddec32012-02-04 12:27:34 -0800681 return false; // Incomplete knowledge needs slow path.
682}
683
Logan Chien4dd96f52012-02-29 01:26:58 +0800684bool Compiler::ComputeStaticFieldInfo(uint32_t field_idx, OatCompilationUnit* mUnit,
Ian Rogers1bddec32012-02-04 12:27:34 -0800685 int& field_offset, int& ssb_index,
jeffhao8cd6dda2012-02-22 10:15:34 -0800686 bool& is_referrers_class, bool& is_volatile, bool is_put) {
Ian Rogers1bddec32012-02-04 12:27:34 -0800687 // Conservative defaults
688 field_offset = -1;
689 ssb_index = -1;
690 is_referrers_class = false;
691 is_volatile = true;
692 // Try to resolve field
Logan Chien4dd96f52012-02-29 01:26:58 +0800693 Field* resolved_field = ComputeReferrerField(mUnit, field_idx);
Ian Rogers1bddec32012-02-04 12:27:34 -0800694 if (resolved_field != NULL) {
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800695 DCHECK(resolved_field->IsStatic());
Logan Chien4dd96f52012-02-29 01:26:58 +0800696 Class* referrer_class = ComputeReferrerClass(mUnit);
Ian Rogers1bddec32012-02-04 12:27:34 -0800697 if (referrer_class != NULL) {
jeffhao8cd6dda2012-02-22 10:15:34 -0800698 Class* fields_class = resolved_field->GetDeclaringClass();
699 if (fields_class == referrer_class) {
Ian Rogers1bddec32012-02-04 12:27:34 -0800700 is_referrers_class = true; // implies no worrying about class initialization
701 field_offset = resolved_field->GetOffset().Int32Value();
702 is_volatile = resolved_field->IsVolatile();
Ian Rogersc8b306f2012-02-17 21:34:44 -0800703 stats_->ResolvedLocalStaticField();
Ian Rogers1bddec32012-02-04 12:27:34 -0800704 return true; // fast path
705 } else {
Ian Rogerse2645d32012-04-11 14:42:42 -0700706 bool access_ok = referrer_class->CanAccess(fields_class) &&
707 referrer_class->CanAccessMember(fields_class,
708 resolved_field->GetAccessFlags());
709 if (!access_ok) {
710 // The referring class can't access the resolved field, this may occur as a result of a
711 // protected field being made public by a sub-class. Resort to the dex file to determine
712 // the correct class for the access check. Don't change the field's class as that is
713 // used to identify the SSB.
714 const DexFile& dex_file = mUnit->class_linker_->FindDexFile(referrer_class->GetDexCache());
715 Class* dex_fields_class =
716 mUnit->class_linker_->ResolveType(dex_file,
717 dex_file.GetFieldId(field_idx).class_idx_,
718 referrer_class);
719 access_ok = referrer_class->CanAccess(dex_fields_class) &&
720 referrer_class->CanAccessMember(dex_fields_class,
721 resolved_field->GetAccessFlags());
722 }
jeffhao8cd6dda2012-02-22 10:15:34 -0800723 bool is_write_to_final_from_wrong_class = is_put && resolved_field->IsFinal();
Ian Rogerse2645d32012-04-11 14:42:42 -0700724 if (access_ok && !is_write_to_final_from_wrong_class) {
Ian Rogers1bddec32012-02-04 12:27:34 -0800725 // We have the resolved field, we must make it into a ssbIndex for the referrer
726 // in its static storage base (which may fail if it doesn't have a slot for it)
Ian Rogers4103ad22012-02-06 09:18:25 -0800727 // TODO: for images we can elide the static storage base null check
728 // if we know there's a non-null entry in the image
Logan Chien4dd96f52012-02-29 01:26:58 +0800729 if (fields_class->GetDexCache() == mUnit->dex_cache_) {
Ian Rogers4103ad22012-02-06 09:18:25 -0800730 // common case where the dex cache of both the referrer and the field are the same,
731 // no need to search the dex file
732 ssb_index = fields_class->GetDexTypeIndex();
733 field_offset = resolved_field->GetOffset().Int32Value();
734 is_volatile = resolved_field->IsVolatile();
Ian Rogersc8b306f2012-02-17 21:34:44 -0800735 stats_->ResolvedStaticField();
Ian Rogers4103ad22012-02-06 09:18:25 -0800736 return true;
737 }
Ian Rogerse2645d32012-04-11 14:42:42 -0700738 // Search dex file for localized ssb index, may fail if field's class is a parent
739 // of the class mentioned in the dex file and there is no dex cache entry.
Ian Rogers1bddec32012-02-04 12:27:34 -0800740 std::string descriptor(FieldHelper(resolved_field).GetDeclaringClassDescriptor());
741 const DexFile::StringId* string_id =
Logan Chien4dd96f52012-02-29 01:26:58 +0800742 mUnit->dex_file_->FindStringId(descriptor);
Ian Rogers1bddec32012-02-04 12:27:34 -0800743 if (string_id != NULL) {
744 const DexFile::TypeId* type_id =
Logan Chien4dd96f52012-02-29 01:26:58 +0800745 mUnit->dex_file_->FindTypeId(mUnit->dex_file_->GetIndexForStringId(*string_id));
Elliott Hughesb25c3f62012-03-26 16:35:06 -0700746 if (type_id != NULL) {
Ian Rogers1bddec32012-02-04 12:27:34 -0800747 // medium path, needs check of static storage base being initialized
Logan Chien4dd96f52012-02-29 01:26:58 +0800748 ssb_index = mUnit->dex_file_->GetIndexForTypeId(*type_id);
Ian Rogers1bddec32012-02-04 12:27:34 -0800749 field_offset = resolved_field->GetOffset().Int32Value();
750 is_volatile = resolved_field->IsVolatile();
Ian Rogersc8b306f2012-02-17 21:34:44 -0800751 stats_->ResolvedStaticField();
Ian Rogers1bddec32012-02-04 12:27:34 -0800752 return true;
753 }
754 }
755 }
756 }
757 }
758 }
759 // Clean up any exception left by field/type resolution
760 Thread* thread = Thread::Current();
761 if (thread->IsExceptionPending()) {
762 thread->ClearException();
763 }
Ian Rogersc8b306f2012-02-17 21:34:44 -0800764 stats_->UnresolvedStaticField();
Ian Rogers1bddec32012-02-04 12:27:34 -0800765 return false; // Incomplete knowledge needs slow path.
766}
767
Ian Rogers2ed3b952012-03-17 11:49:39 -0700768void Compiler::GetCodeAndMethodForDirectCall(InvokeType type, InvokeType sharp_type, Method* method,
769 uintptr_t& direct_code, uintptr_t& direct_method) {
770 direct_code = 0;
771 direct_method = 0;
772 if (sharp_type != kStatic && sharp_type != kDirect) {
773 return;
774 }
Ian Rogers2ed3b952012-03-17 11:49:39 -0700775 bool method_code_in_boot = method->GetDeclaringClass()->GetClassLoader() == NULL;
776 if (!method_code_in_boot) {
777 return;
778 }
779 bool has_clinit_trampoline = method->IsStatic() && !method->GetDeclaringClass()->IsInitialized();
780 if (has_clinit_trampoline) {
781 return;
782 }
783 stats_->DirectCallsToBoot(type);
784 stats_->DirectMethodsToBoot(type);
Ian Rogers3fa13792012-03-18 15:53:45 -0700785 bool compiling_boot = Runtime::Current()->GetHeap()->GetSpaces().size() == 1;
786 if (compiling_boot) {
Brian Carlstrom0637e272012-03-20 01:07:52 -0700787 const bool kSupportBootImageFixup = true;
Ian Rogers3fa13792012-03-18 15:53:45 -0700788 if (kSupportBootImageFixup) {
789 MethodHelper mh(method);
790 if (IsImageClass(mh.GetDeclaringClassDescriptor())) {
Brian Carlstrom0637e272012-03-20 01:07:52 -0700791 // We can only branch directly to Methods that are resolved in the DexCache.
792 // Otherwise we won't invoke the resolution trampoline.
Ian Rogers3fa13792012-03-18 15:53:45 -0700793 direct_method = -1;
Brian Carlstrom0637e272012-03-20 01:07:52 -0700794 direct_code = -1;
Ian Rogers3fa13792012-03-18 15:53:45 -0700795 }
Ian Rogers3fa13792012-03-18 15:53:45 -0700796 }
797 } else {
798 if (Runtime::Current()->GetHeap()->GetImageSpace()->Contains(method)) {
799 direct_method = reinterpret_cast<uintptr_t>(method);
800 }
801 direct_code = reinterpret_cast<uintptr_t>(method->GetCode());
Ian Rogers2ed3b952012-03-17 11:49:39 -0700802 }
Ian Rogers2ed3b952012-03-17 11:49:39 -0700803}
804
Ian Rogersfb6adba2012-03-04 21:51:51 -0800805bool Compiler::ComputeInvokeInfo(uint32_t method_idx, OatCompilationUnit* mUnit, InvokeType& type,
Ian Rogers2ed3b952012-03-17 11:49:39 -0700806 int& vtable_idx, uintptr_t& direct_code,
807 uintptr_t& direct_method) {
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800808 vtable_idx = -1;
Ian Rogers2ed3b952012-03-17 11:49:39 -0700809 direct_code = 0;
810 direct_method = 0;
Logan Chien4dd96f52012-02-29 01:26:58 +0800811 Method* resolved_method = ComputeReferrerMethod(mUnit, method_idx);
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800812 if (resolved_method != NULL) {
Logan Chien4dd96f52012-02-29 01:26:58 +0800813 Class* referrer_class = ComputeReferrerClass(mUnit);
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800814 if (referrer_class != NULL) {
815 Class* methods_class = resolved_method->GetDeclaringClass();
816 if (!referrer_class->CanAccess(methods_class) ||
817 !referrer_class->CanAccessMember(methods_class,
Ian Rogers996cc582012-02-14 22:23:29 -0800818 resolved_method->GetAccessFlags())) {
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800819 // The referring class can't access the resolved method, this may occur as a result of a
820 // protected method being made public by implementing an interface that re-declares the
821 // method public. Resort to the dex file to determine the correct class for the access check
Logan Chien4dd96f52012-02-29 01:26:58 +0800822 const DexFile& dex_file = mUnit->class_linker_->FindDexFile(referrer_class->GetDexCache());
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800823 methods_class =
Logan Chien4dd96f52012-02-29 01:26:58 +0800824 mUnit->class_linker_->ResolveType(dex_file,
825 dex_file.GetMethodId(method_idx).class_idx_,
826 referrer_class);
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800827 }
828 if (referrer_class->CanAccess(methods_class) &&
829 referrer_class->CanAccessMember(methods_class,
830 resolved_method->GetAccessFlags())) {
831 vtable_idx = resolved_method->GetMethodIndex();
Ian Rogersf320b632012-03-13 18:47:47 -0700832 const bool kEnableSharpening = true;
Ian Rogers2ed3b952012-03-17 11:49:39 -0700833 // Sharpen a virtual call into a direct call when the target is known.
834 bool can_sharpen = type == kVirtual && (resolved_method->IsFinal() ||
835 methods_class->IsFinal());
836 // ensure the vtable index will be correct to dispatch in the vtable of the super class
jeffhao4155fcd2012-03-21 11:42:12 -0700837 can_sharpen = can_sharpen || (type == kSuper && referrer_class != methods_class &&
Ian Rogers2ed3b952012-03-17 11:49:39 -0700838 referrer_class->IsSubClass(methods_class) &&
jeffhao4155fcd2012-03-21 11:42:12 -0700839 vtable_idx < methods_class->GetVTable()->GetLength() &&
840 methods_class->GetVTable()->Get(vtable_idx) == resolved_method);
Ian Rogers2ed3b952012-03-17 11:49:39 -0700841 if (kEnableSharpening && can_sharpen) {
842 stats_->ResolvedMethod(type);
Ian Rogersfb6adba2012-03-04 21:51:51 -0800843 // Sharpen a virtual call into a direct call. The method_idx is into referrer's
844 // dex cache, check that this resolved method is where we expect it.
845 CHECK(referrer_class->GetDexCache()->GetResolvedMethod(method_idx) == resolved_method)
846 << PrettyMethod(resolved_method);
Ian Rogers2ed3b952012-03-17 11:49:39 -0700847 stats_->VirtualMadeDirect(type);
848 GetCodeAndMethodForDirectCall(type, kDirect, resolved_method, direct_code, direct_method);
849 type = kDirect;
850 return true;
851 } else if (type == kSuper) {
852 // Unsharpened super calls are suspicious so go slowpath.
853 } else {
854 stats_->ResolvedMethod(type);
855 GetCodeAndMethodForDirectCall(type, type, resolved_method, direct_code, direct_method);
856 return true;
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800857 }
858 }
859 }
860 }
861 // Clean up any exception left by method/type resolution
862 Thread* thread = Thread::Current();
863 if (thread->IsExceptionPending()) {
864 thread->ClearException();
865 }
Ian Rogersc8b306f2012-02-17 21:34:44 -0800866 stats_->UnresolvedMethod(type);
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800867 return false; // Incomplete knowledge needs slow path.
868}
869
Brian Carlstromf5822582012-03-19 22:34:31 -0700870void Compiler::AddCodePatch(DexCache* dex_cache,
871 const DexFile* dex_file,
872 uint32_t referrer_method_idx,
873 uint32_t referrer_access_flags,
874 uint32_t target_method_idx,
875 bool target_is_direct,
Ian Rogers3fa13792012-03-18 15:53:45 -0700876 size_t literal_offset) {
877 MutexLock mu(compiled_methods_lock_);
Brian Carlstromf5822582012-03-19 22:34:31 -0700878 code_to_patch_.push_back(new PatchInformation(dex_cache,
879 dex_file,
880 referrer_method_idx,
881 referrer_access_flags,
882 target_method_idx,
883 target_is_direct,
884 literal_offset));
Ian Rogers3fa13792012-03-18 15:53:45 -0700885}
Brian Carlstromf5822582012-03-19 22:34:31 -0700886void Compiler::AddMethodPatch(DexCache* dex_cache,
887 const DexFile* dex_file,
888 uint32_t referrer_method_idx,
889 uint32_t referrer_access_flags,
890 uint32_t target_method_idx,
891 bool target_is_direct,
Ian Rogers3fa13792012-03-18 15:53:45 -0700892 size_t literal_offset) {
893 MutexLock mu(compiled_methods_lock_);
Brian Carlstromf5822582012-03-19 22:34:31 -0700894 methods_to_patch_.push_back(new PatchInformation(dex_cache,
895 dex_file,
896 referrer_method_idx,
897 referrer_access_flags,
898 target_method_idx,
899 target_is_direct,
900 literal_offset));
Ian Rogers3fa13792012-03-18 15:53:45 -0700901}
902
Brian Carlstrom5ead0952011-11-28 22:55:52 -0800903// Return true if the class should be skipped during compilation. We
904// never skip classes in the boot class loader. However, if we have a
905// non-boot class loader and we can resolve the class in the boot
906// class loader, we do skip the class. This happens if an app bundles
907// classes found in the boot classpath. Since at runtime we will
908// select the class from the boot classpath, do not attempt to resolve
909// or compile it now.
910static bool SkipClass(const ClassLoader* class_loader,
911 const DexFile& dex_file,
912 const DexFile::ClassDef& class_def) {
913 if (class_loader == NULL) {
914 return false;
915 }
916 const char* descriptor = dex_file.GetClassDescriptor(class_def);
917 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
918 Class* klass = class_linker->FindClass(descriptor, NULL);
919 if (klass == NULL) {
920 Thread* self = Thread::Current();
921 CHECK(self->IsExceptionPending());
922 self->ClearException();
923 return false;
924 }
925 return true;
926}
927
Brian Carlstrom731b2ab2012-03-06 16:53:35 -0800928class Context {
929 public:
930 Context(ClassLinker* class_linker,
931 const ClassLoader* class_loader,
932 Compiler* compiler,
933 DexCache* dex_cache,
934 const DexFile* dex_file)
935 : class_linker_(class_linker),
936 class_loader_(class_loader),
937 compiler_(compiler),
938 dex_cache_(dex_cache),
939 dex_file_(dex_file) {}
940
941 ClassLinker* GetClassLinker() {
942 CHECK(class_linker_ != NULL);
943 return class_linker_;
944 }
945 const ClassLoader* GetClassLoader() {
946 return class_loader_;
947 }
948 Compiler* GetCompiler() {
949 CHECK(compiler_ != NULL);
950 return compiler_;
951 }
952 DexCache* GetDexCache() {
953 CHECK(dex_cache_ != NULL);
954 return dex_cache_;
955 }
956 const DexFile* GetDexFile() {
957 CHECK(dex_file_ != NULL);
958 return dex_file_;
959 }
960
961 private:
962 ClassLinker* class_linker_;
963 const ClassLoader* class_loader_;
964 Compiler* compiler_;
965 DexCache* dex_cache_;
966 const DexFile* dex_file_;
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800967};
968
969typedef void Callback(Context* context, size_t index);
970
971class WorkerThread {
972 public:
Elliott Hughes1e409252012-02-06 11:21:27 -0800973 WorkerThread(Context* context, size_t begin, size_t end, Callback callback, size_t stripe, bool spawn)
974 : spawn_(spawn), context_(context), begin_(begin), end_(end), callback_(callback), stripe_(stripe) {
975 if (spawn_) {
Elliott Hughesbf1b4572012-05-24 19:11:39 -0700976 // Mac OS stacks are only 512KiB. Make sure we have the same stack size on all platforms.
977 pthread_attr_t attr;
978 CHECK_PTHREAD_CALL(pthread_attr_init, (&attr), "new compiler worker thread");
979 CHECK_PTHREAD_CALL(pthread_attr_setstacksize, (&attr, 1*MB), "new compiler worker thread");
980 CHECK_PTHREAD_CALL(pthread_create, (&pthread_, &attr, &Go, this), "new compiler worker thread");
981 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attr), "new compiler worker thread");
Elliott Hughes1e409252012-02-06 11:21:27 -0800982 }
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800983 }
984
985 ~WorkerThread() {
Elliott Hughes1e409252012-02-06 11:21:27 -0800986 if (spawn_) {
987 CHECK_PTHREAD_CALL(pthread_join, (pthread_, NULL), "compiler worker shutdown");
988 }
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800989 }
990
991 private:
Elliott Hughes1e409252012-02-06 11:21:27 -0800992 static void* Go(void* arg) {
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800993 WorkerThread* worker = reinterpret_cast<WorkerThread*>(arg);
994 Runtime* runtime = Runtime::Current();
Elliott Hughes1e409252012-02-06 11:21:27 -0800995 if (worker->spawn_) {
Elliott Hughes462c9442012-03-23 18:47:50 -0700996 runtime->AttachCurrentThread("Compiler Worker", true, NULL);
Elliott Hughes1e409252012-02-06 11:21:27 -0800997 }
Elliott Hughes34e06962012-04-09 13:55:55 -0700998 Thread::Current()->SetState(kRunnable);
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800999 worker->Run();
Elliott Hughes1e409252012-02-06 11:21:27 -08001000 if (worker->spawn_) {
Elliott Hughes34e06962012-04-09 13:55:55 -07001001 Thread::Current()->SetState(kNative);
Elliott Hughes1e409252012-02-06 11:21:27 -08001002 runtime->DetachCurrentThread();
1003 }
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001004 return NULL;
1005 }
1006
Elliott Hughes1e409252012-02-06 11:21:27 -08001007 void Go() {
1008 Go(this);
1009 }
1010
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001011 void Run() {
Brian Carlstrom64277f32012-03-26 23:53:34 -07001012 Thread* self = Thread::Current();
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001013 for (size_t i = begin_; i < end_; i += stripe_) {
1014 callback_(context_, i);
Brian Carlstrom64277f32012-03-26 23:53:34 -07001015 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException()) << " " << i;
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001016 }
1017 }
1018
1019 pthread_t pthread_;
Elliott Hughes1e409252012-02-06 11:21:27 -08001020 bool spawn_;
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001021
1022 Context* context_;
1023 size_t begin_;
1024 size_t end_;
1025 Callback* callback_;
1026 size_t stripe_;
Elliott Hughes1e409252012-02-06 11:21:27 -08001027
1028 friend void ForAll(Context*, size_t, size_t, Callback, size_t);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001029};
1030
Elliott Hughes5523ee02012-02-03 18:18:34 -08001031void ForAll(Context* context, size_t begin, size_t end, Callback callback, size_t thread_count) {
Brian Carlstrom64277f32012-03-26 23:53:34 -07001032 Thread* self = Thread::Current();
1033 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
Elliott Hughes1e409252012-02-06 11:21:27 -08001034 CHECK_GT(thread_count, 0U);
Elliott Hughes81d91512012-02-03 16:38:43 -08001035
Elliott Hughes1e409252012-02-06 11:21:27 -08001036 std::vector<WorkerThread*> threads;
Elliott Hughes81d91512012-02-03 16:38:43 -08001037 for (size_t i = 0; i < thread_count; ++i) {
Elliott Hughes1e409252012-02-06 11:21:27 -08001038 threads.push_back(new WorkerThread(context, begin + i, end, callback, thread_count, (i != 0)));
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001039 }
Elliott Hughes1e409252012-02-06 11:21:27 -08001040 threads[0]->Go();
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001041
Elliott Hughes81d91512012-02-03 16:38:43 -08001042 // Switch to kVmWait while we're blocked waiting for the other threads to finish.
Elliott Hughes34e06962012-04-09 13:55:55 -07001043 ScopedThreadStateChange tsc(self, kVmWait);
Elliott Hughes81d91512012-02-03 16:38:43 -08001044 STLDeleteElements(&threads);
1045}
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001046
1047static void ResolveClassFieldsAndMethods(Context* context, size_t class_def_index) {
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001048 const DexFile& dex_file = *context->GetDexFile();
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001049
1050 // Method and Field are the worst. We can't resolve without either
1051 // context from the code use (to disambiguate virtual vs direct
1052 // method and instance vs static field) or from class
1053 // definitions. While the compiler will resolve what it can as it
1054 // needs it, here we try to resolve fields and methods used in class
1055 // definitions, since many of them many never be referenced by
1056 // generated code.
1057 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001058 if (SkipClass(context->GetClassLoader(), dex_file, class_def)) {
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001059 return;
1060 }
1061
1062 // Note the class_data pointer advances through the headers,
1063 // static fields, instance fields, direct methods, and virtual
1064 // methods.
1065 const byte* class_data = dex_file.GetClassData(class_def);
1066 if (class_data == NULL) {
1067 // empty class such as a marker interface
1068 return;
1069 }
Brian Carlstrom5ead0952011-11-28 22:55:52 -08001070 Thread* self = Thread::Current();
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001071 ClassLinker* class_linker = context->GetClassLinker();
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001072 DexCache* dex_cache = class_linker->FindDexCache(dex_file);
1073 ClassDataItemIterator it(dex_file, class_data);
1074 while (it.HasNextStaticField()) {
1075 Field* field = class_linker->ResolveField(dex_file, it.GetMemberIndex(), dex_cache,
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001076 context->GetClassLoader(), true);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001077 if (field == NULL) {
1078 CHECK(self->IsExceptionPending());
1079 self->ClearException();
1080 }
1081 it.Next();
1082 }
1083 while (it.HasNextInstanceField()) {
1084 Field* field = class_linker->ResolveField(dex_file, it.GetMemberIndex(), dex_cache,
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001085 context->GetClassLoader(), false);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001086 if (field == NULL) {
1087 CHECK(self->IsExceptionPending());
1088 self->ClearException();
1089 }
1090 it.Next();
1091 }
1092 while (it.HasNextDirectMethod()) {
1093 Method* method = class_linker->ResolveMethod(dex_file, it.GetMemberIndex(), dex_cache,
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001094 context->GetClassLoader(), true);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001095 if (method == NULL) {
1096 CHECK(self->IsExceptionPending());
1097 self->ClearException();
1098 }
1099 it.Next();
1100 }
1101 while (it.HasNextVirtualMethod()) {
1102 Method* method = class_linker->ResolveMethod(dex_file, it.GetMemberIndex(), dex_cache,
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001103 context->GetClassLoader(), false);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001104 if (method == NULL) {
1105 CHECK(self->IsExceptionPending());
1106 self->ClearException();
1107 }
1108 it.Next();
1109 }
1110 DCHECK(!it.HasNext());
1111}
1112
1113static void ResolveType(Context* context, size_t type_idx) {
1114 // Class derived values are more complicated, they require the linker and loader.
1115 Thread* self = Thread::Current();
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001116 Class* klass = context->GetClassLinker()->ResolveType(*context->GetDexFile(),
1117 type_idx,
1118 context->GetDexCache(),
1119 context->GetClassLoader());
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001120 if (klass == NULL) {
1121 CHECK(self->IsExceptionPending());
1122 Thread::Current()->ClearException();
1123 }
1124}
1125
1126void Compiler::ResolveDexFile(const ClassLoader* class_loader, const DexFile& dex_file, TimingLogger& timings) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001127 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Brian Carlstromaded5f72011-10-07 17:15:04 -07001128 DexCache* dex_cache = class_linker->FindDexCache(dex_file);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001129
Brian Carlstromae826982011-11-09 01:33:42 -08001130 // Strings are easy in that they always are simply resolved to literals in the same file
1131 if (image_ && image_classes_ == NULL) {
1132 // TODO: Add support for loading strings referenced by image_classes_
1133 // See also Compiler::CanAssumeTypeIsPresentInDexCache.
Brian Carlstromaded5f72011-10-07 17:15:04 -07001134 for (size_t string_idx = 0; string_idx < dex_cache->NumStrings(); string_idx++) {
1135 class_linker->ResolveString(dex_file, string_idx, dex_cache);
1136 }
Elliott Hughesff738062012-02-03 15:00:42 -08001137 timings.AddSplit("Resolve " + dex_file.GetLocation() + " Strings");
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001138 }
1139
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001140 Context context(class_linker, class_loader, this, dex_cache, &dex_file);
Elliott Hughes5523ee02012-02-03 18:18:34 -08001141 ForAll(&context, 0, dex_cache->NumResolvedTypes(), ResolveType, thread_count_);
Elliott Hughesff738062012-02-03 15:00:42 -08001142 timings.AddSplit("Resolve " + dex_file.GetLocation() + " Types");
Brian Carlstrom845490b2011-09-19 15:56:53 -07001143
Elliott Hughes5523ee02012-02-03 18:18:34 -08001144 ForAll(&context, 0, dex_file.NumClassDefs(), ResolveClassFieldsAndMethods, thread_count_);
Elliott Hughesff738062012-02-03 15:00:42 -08001145 timings.AddSplit("Resolve " + dex_file.GetLocation() + " MethodsAndFields");
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001146}
1147
Brian Carlstromae826982011-11-09 01:33:42 -08001148void Compiler::Verify(const ClassLoader* class_loader,
1149 const std::vector<const DexFile*>& dex_files) {
1150 for (size_t i = 0; i != dex_files.size(); ++i) {
1151 const DexFile* dex_file = dex_files[i];
jeffhao98eacac2011-09-14 16:11:53 -07001152 CHECK(dex_file != NULL);
1153 VerifyDexFile(class_loader, *dex_file);
1154 }
1155}
1156
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001157static void VerifyClass(Context* context, size_t class_def_index) {
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001158 const DexFile::ClassDef& class_def = context->GetDexFile()->GetClassDef(class_def_index);
1159 const char* descriptor = context->GetDexFile()->GetClassDescriptor(class_def);
1160 Class* klass = context->GetClassLinker()->FindClass(descriptor, context->GetClassLoader());
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001161 if (klass == NULL) {
1162 Thread* self = Thread::Current();
1163 CHECK(self->IsExceptionPending());
1164 self->ClearException();
jeffhaof56197c2012-03-05 18:01:54 -08001165
1166 /*
1167 * At compile time, we can still structurally verify the class even if FindClass fails.
1168 * This is to ensure the class is structurally sound for compilation. An unsound class
1169 * will be rejected by the verifier and later skipped during compilation in the compiler.
1170 */
1171 std::string error_msg;
jeffhaof1e6b7c2012-06-05 18:33:30 -07001172 if (verifier::MethodVerifier::VerifyClass(context->GetDexFile(), context->GetDexCache(),
1173 context->GetClassLoader(), class_def_index, error_msg) == verifier::MethodVerifier::kHardFailure) {
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001174 const DexFile::ClassDef& class_def = context->GetDexFile()->GetClassDef(class_def_index);
jeffhaof56197c2012-03-05 18:01:54 -08001175 LOG(ERROR) << "Verification failed on class "
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001176 << PrettyDescriptor(context->GetDexFile()->GetClassDescriptor(class_def))
jeffhaof56197c2012-03-05 18:01:54 -08001177 << " because: " << error_msg;
1178 }
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001179 return;
1180 }
1181 CHECK(klass->IsResolved()) << PrettyClass(klass);
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001182 context->GetClassLinker()->VerifyClass(klass);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001183
1184 if (klass->IsErroneous()) {
1185 // ClassLinker::VerifyClass throws, which isn't useful in the compiler.
1186 CHECK(Thread::Current()->IsExceptionPending());
1187 Thread::Current()->ClearException();
jeffhao1ac29442012-03-26 11:37:32 -07001188 art::Compiler::ClassReference ref(context->GetDexFile(), class_def_index);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001189 }
1190
jeffhaof1e6b7c2012-06-05 18:33:30 -07001191 CHECK(klass->IsCompileTimeVerified() || klass->IsErroneous()) << PrettyClass(klass);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001192 CHECK(!Thread::Current()->IsExceptionPending()) << PrettyTypeOf(Thread::Current()->GetException());
1193}
1194
jeffhao98eacac2011-09-14 16:11:53 -07001195void Compiler::VerifyDexFile(const ClassLoader* class_loader, const DexFile& dex_file) {
jeffhaob4df5142011-09-19 20:25:32 -07001196 dex_file.ChangePermissions(PROT_READ | PROT_WRITE);
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07001197
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001198 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1199 Context context(class_linker, class_loader, this, class_linker->FindDexCache(dex_file), &dex_file);
Elliott Hughes5523ee02012-02-03 18:18:34 -08001200 ForAll(&context, 0, dex_file.NumClassDefs(), VerifyClass, thread_count_);
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07001201
jeffhaob4df5142011-09-19 20:25:32 -07001202 dex_file.ChangePermissions(PROT_READ);
Brian Carlstroma5a97a22011-09-15 14:08:49 -07001203}
1204
Brian Carlstromae826982011-11-09 01:33:42 -08001205void Compiler::InitializeClassesWithoutClinit(const ClassLoader* class_loader,
1206 const std::vector<const DexFile*>& dex_files) {
1207 for (size_t i = 0; i != dex_files.size(); ++i) {
1208 const DexFile* dex_file = dex_files[i];
Brian Carlstroma5a97a22011-09-15 14:08:49 -07001209 CHECK(dex_file != NULL);
1210 InitializeClassesWithoutClinit(class_loader, *dex_file);
1211 }
1212}
1213
1214void Compiler::InitializeClassesWithoutClinit(const ClassLoader* class_loader, const DexFile& dex_file) {
1215 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Brian Carlstromffca45d2011-09-16 12:10:49 -07001216 for (size_t class_def_index = 0; class_def_index < dex_file.NumClassDefs(); class_def_index++) {
1217 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
Brian Carlstroma5a97a22011-09-15 14:08:49 -07001218 const char* descriptor = dex_file.GetClassDescriptor(class_def);
1219 Class* klass = class_linker->FindClass(descriptor, class_loader);
Brian Carlstrom27ec9612011-09-19 20:20:38 -07001220 if (klass != NULL) {
jeffhao1ac29442012-03-26 11:37:32 -07001221 if (klass->IsVerified()) {
1222 // Only try to initialize classes that were successfully verified.
Ian Rogers0045a292012-03-31 21:08:41 -07001223 bool compiling_boot = Runtime::Current()->GetHeap()->GetSpaces().size() == 1;
1224 bool can_init_static_fields = compiling_boot &&
1225 IsImageClass(descriptor);
1226 class_linker->EnsureInitialized(klass, false, can_init_static_fields);
jeffhao1ac29442012-03-26 11:37:32 -07001227 }
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001228 // record the final class status if necessary
1229 Class::Status status = klass->GetStatus();
1230 ClassReference ref(&dex_file, class_def_index);
Elliott Hughesc225caa2012-02-03 15:43:37 -08001231 MutexLock mu(compiled_classes_lock_);
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001232 CompiledClass* compiled_class = GetCompiledClass(ref);
1233 if (compiled_class == NULL) {
1234 compiled_class = new CompiledClass(status);
Elliott Hughesa0e18062012-04-13 15:59:59 -07001235 compiled_classes_.Put(ref, compiled_class);
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001236 } else {
1237 DCHECK_EQ(status, compiled_class->GetStatus());
1238 }
Brian Carlstrom27ec9612011-09-19 20:20:38 -07001239 }
1240 // clear any class not found or verification exceptions
1241 Thread::Current()->ClearException();
Brian Carlstromffca45d2011-09-16 12:10:49 -07001242 }
1243
1244 DexCache* dex_cache = class_linker->FindDexCache(dex_file);
1245 for (size_t type_idx = 0; type_idx < dex_cache->NumResolvedTypes(); type_idx++) {
1246 Class* klass = class_linker->ResolveType(dex_file, type_idx, dex_cache, class_loader);
Brian Carlstrom27ec9612011-09-19 20:20:38 -07001247 if (klass == NULL) {
1248 Thread::Current()->ClearException();
1249 } else if (klass->IsInitialized()) {
Brian Carlstromffca45d2011-09-16 12:10:49 -07001250 dex_cache->GetInitializedStaticStorage()->Set(type_idx, klass);
1251 }
jeffhao98eacac2011-09-14 16:11:53 -07001252 }
1253}
1254
Shih-wei Liao90dc30f2012-04-23 02:03:30 -07001255// TODO: This class shares some implementation with WorkerThread. We don't want
1256// to perturb the non-LLVM side at the same time. Staging the refactoring for
1257// the future.
1258class DexFilesWorkerThread {
1259 public:
1260 DexFilesWorkerThread(Context *worker_context, Callback class_callback,
1261 const std::vector<const DexFile*>& dex_files,
1262 volatile int32_t* shared_class_index, bool spawn)
1263 : spawn_(spawn), worker_context_(worker_context),
1264 class_callback_(class_callback), dex_files_(dex_files),
1265 context_(NULL), shared_class_index_(shared_class_index) {
1266 if (spawn_) {
TDYa1278cea5fd2012-05-29 22:22:32 -07001267 pthread_attr_t attr;
1268 CHECK_PTHREAD_CALL(pthread_attr_init, (&attr), "new compiler worker thread");
TDYa12761b409c2012-06-05 23:54:30 -07001269 CHECK_PTHREAD_CALL(pthread_attr_setstacksize, (&attr, 1*MB), "new compiler worker thread");
TDYa1278cea5fd2012-05-29 22:22:32 -07001270 CHECK_PTHREAD_CALL(pthread_create, (&pthread_, &attr, &Go, this), "new compiler worker thread");
1271 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attr), "new compiler worker thread");
Shih-wei Liao90dc30f2012-04-23 02:03:30 -07001272 }
1273 }
1274
1275 ~DexFilesWorkerThread() {
1276 if (spawn_) {
1277 CHECK_PTHREAD_CALL(pthread_join, (pthread_, NULL), "compiler worker shutdown");
1278 }
1279 delete context_;
1280 }
1281
1282 private:
1283 static void* Go(void* arg) {
1284 DexFilesWorkerThread* worker = reinterpret_cast<DexFilesWorkerThread*>(arg);
1285 Runtime* runtime = Runtime::Current();
1286 if (worker->spawn_) {
1287 runtime->AttachCurrentThread("Compiler Worker", true, NULL);
1288 }
1289 Thread::Current()->SetState(kRunnable);
1290 worker->Run();
1291 if (worker->spawn_) {
1292 Thread::Current()->SetState(kNative);
1293 runtime->DetachCurrentThread();
1294 }
1295 return NULL;
1296 }
1297
1298 void Go() {
1299 Go(this);
1300 }
1301
1302 void SwitchToDexFile(size_t dex_file_index) {
1303 CHECK (dex_file_index < dex_files_.size());
1304
1305 const DexFile* dex_file = dex_files_[dex_file_index];
1306 CHECK(dex_file != NULL);
1307
1308 // Destroy the old context
1309 delete context_;
1310
1311 // TODO: Add a callback to let the client specify the class_linker and
1312 // dex_cache in the context for the current working dex file.
1313 context_ = new Context(/* class_linker */NULL,
1314 worker_context_->GetClassLoader(),
1315 worker_context_->GetCompiler(),
1316 /* dex_cache */NULL, dex_file);
1317
1318 CHECK(context_ != NULL);
1319 }
1320
1321 void Run() {
1322 Thread* self = Thread::Current();
1323 size_t cur_dex_file_index = 0;
1324 size_t class_index_base = 0;
1325
1326 SwitchToDexFile(0);
1327
1328 while (true) {
1329 size_t class_index =
1330 static_cast<size_t>(android_atomic_inc(shared_class_index_));
1331
1332 const DexFile* dex_file;
1333 do {
1334 dex_file = dex_files_[cur_dex_file_index];
1335
1336 if (class_index < (class_index_base + dex_file->NumClassDefs())) {
1337 break;
1338 }
1339 class_index_base += dex_file->NumClassDefs();
1340
1341 cur_dex_file_index++;
1342 } while (cur_dex_file_index < dex_files_.size());
1343
1344 if (cur_dex_file_index >= dex_files_.size()) {
1345 return;
1346 }
1347
1348 if (dex_file != context_->GetDexFile()) {
1349 SwitchToDexFile(cur_dex_file_index);
1350 }
1351
1352 class_index -= class_index_base;
1353 class_callback_(context_, class_index);
1354 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
1355 }
1356 }
1357
1358 pthread_t pthread_;
1359 bool spawn_;
1360
1361 Context* worker_context_;
1362 Callback* class_callback_;
1363 const std::vector<const DexFile*>& dex_files_;
1364
1365 Context* context_;
1366 volatile int32_t* shared_class_index_;
1367
1368 friend void ForClassesInAllDexFiles(Context*,
1369 const std::vector<const DexFile*>&,
1370 Callback, size_t);
1371};
1372
1373void ForClassesInAllDexFiles(Context* worker_context,
1374 const std::vector<const DexFile*>& dex_files,
1375 Callback class_callback, size_t thread_count) {
1376 Thread* self = Thread::Current();
1377 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
1378 CHECK_GT(thread_count, 0U);
1379
1380 std::vector<DexFilesWorkerThread*> threads;
1381 volatile int32_t shared_class_index = 0;
1382
1383 for (size_t i = 0; i < thread_count; ++i) {
1384 threads.push_back(new DexFilesWorkerThread(worker_context, class_callback,
1385 dex_files, &shared_class_index,
1386 /* spawn */ (i != 0)));
1387 }
1388 threads[0]->Go();
1389
1390 // Switch to kVmWait while we're blocked waiting for the other threads to finish.
1391 ScopedThreadStateChange tsc(self, kVmWait);
1392 STLDeleteElements(&threads);
1393}
1394
Brian Carlstromae826982011-11-09 01:33:42 -08001395void Compiler::Compile(const ClassLoader* class_loader,
1396 const std::vector<const DexFile*>& dex_files) {
Shih-wei Liao90dc30f2012-04-23 02:03:30 -07001397#if defined(ART_USE_LLVM_COMPILER)
1398 if (dex_files.size() <= 0) {
1399 return; // No dex file
1400 }
1401 Context context(NULL, class_loader, this, NULL, NULL);
1402 ForClassesInAllDexFiles(&context, dex_files, Compiler::CompileClass, thread_count_);
1403#else
Brian Carlstromae826982011-11-09 01:33:42 -08001404 for (size_t i = 0; i != dex_files.size(); ++i) {
1405 const DexFile* dex_file = dex_files[i];
Brian Carlstrom83db7722011-08-26 17:32:56 -07001406 CHECK(dex_file != NULL);
1407 CompileDexFile(class_loader, *dex_file);
1408 }
Shih-wei Liao90dc30f2012-04-23 02:03:30 -07001409#endif
Brian Carlstrom83db7722011-08-26 17:32:56 -07001410}
1411
Elliott Hughesc225caa2012-02-03 15:43:37 -08001412void Compiler::CompileClass(Context* context, size_t class_def_index) {
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001413 const ClassLoader* class_loader = context->GetClassLoader();
1414 const DexFile& dex_file = *context->GetDexFile();
Elliott Hughesc225caa2012-02-03 15:43:37 -08001415 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
Brian Carlstrom5ead0952011-11-28 22:55:52 -08001416 if (SkipClass(class_loader, dex_file, class_def)) {
1417 return;
1418 }
jeffhaod1224c72012-02-29 13:43:08 -08001419 ClassReference ref(&dex_file, class_def_index);
1420 // Skip compiling classes with generic verifier failures since they will still fail at runtime
Ian Rogers776ac1f2012-04-13 23:36:36 -07001421 if (verifier::MethodVerifier::IsClassRejected(ref)) {
jeffhaod1224c72012-02-29 13:43:08 -08001422 return;
1423 }
Ian Rogers0571d352011-11-03 19:51:38 -07001424 const byte* class_data = dex_file.GetClassData(class_def);
1425 if (class_data == NULL) {
1426 // empty class, probably a marker interface
1427 return;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001428 }
Ian Rogers0571d352011-11-03 19:51:38 -07001429 ClassDataItemIterator it(dex_file, class_data);
1430 // Skip fields
1431 while (it.HasNextStaticField()) {
1432 it.Next();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001433 }
Ian Rogers0571d352011-11-03 19:51:38 -07001434 while (it.HasNextInstanceField()) {
1435 it.Next();
1436 }
1437 // Compile direct methods
Brian Carlstrom68adbe42012-05-11 17:18:08 -07001438 int64_t previous_direct_method_idx = -1;
Ian Rogers0571d352011-11-03 19:51:38 -07001439 while (it.HasNextDirectMethod()) {
Brian Carlstrom6f29d0e2012-05-11 15:50:29 -07001440 uint32_t method_idx = it.GetMemberIndex();
1441 if (method_idx == previous_direct_method_idx) {
1442 // smali can create dex files with two encoded_methods sharing the same method_idx
1443 // http://code.google.com/p/smali/issues/detail?id=119
1444 it.Next();
1445 continue;
1446 }
1447 previous_direct_method_idx = method_idx;
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001448 context->GetCompiler()->CompileMethod(it.GetMethodCodeItem(), it.GetMemberAccessFlags(),
Brian Carlstrom6f29d0e2012-05-11 15:50:29 -07001449 method_idx, class_loader, dex_file);
Ian Rogers0571d352011-11-03 19:51:38 -07001450 it.Next();
1451 }
1452 // Compile virtual methods
Brian Carlstrom68adbe42012-05-11 17:18:08 -07001453 int64_t previous_virtual_method_idx = -1;
Ian Rogers0571d352011-11-03 19:51:38 -07001454 while (it.HasNextVirtualMethod()) {
Brian Carlstrom6f29d0e2012-05-11 15:50:29 -07001455 uint32_t method_idx = it.GetMemberIndex();
1456 if (method_idx == previous_virtual_method_idx) {
1457 // smali can create dex files with two encoded_methods sharing the same method_idx
1458 // http://code.google.com/p/smali/issues/detail?id=119
1459 it.Next();
1460 continue;
1461 }
1462 previous_virtual_method_idx = method_idx;
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001463 context->GetCompiler()->CompileMethod(it.GetMethodCodeItem(), it.GetMemberAccessFlags(),
Brian Carlstrom6f29d0e2012-05-11 15:50:29 -07001464 method_idx, class_loader, dex_file);
Ian Rogers0571d352011-11-03 19:51:38 -07001465 it.Next();
1466 }
1467 DCHECK(!it.HasNext());
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001468}
1469
Elliott Hughesc225caa2012-02-03 15:43:37 -08001470void Compiler::CompileDexFile(const ClassLoader* class_loader, const DexFile& dex_file) {
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001471 Context context(NULL, class_loader, this, NULL, &dex_file);
Elliott Hughes5523ee02012-02-03 18:18:34 -08001472 ForAll(&context, 0, dex_file.NumClassDefs(), Compiler::CompileClass, thread_count_);
Elliott Hughesc225caa2012-02-03 15:43:37 -08001473}
1474
Elliott Hughesa0e18062012-04-13 15:59:59 -07001475static std::string MakeInvokeStubKey(bool is_static, const char* shorty) {
1476 std::string key(shorty);
1477 if (is_static) {
1478 key += "$"; // Must not be a shorty type character.
1479 }
1480 return key;
1481}
1482
Ian Rogersa3760aa2011-11-14 14:32:37 -08001483void Compiler::CompileMethod(const DexFile::CodeItem* code_item, uint32_t access_flags,
1484 uint32_t method_idx, const ClassLoader* class_loader,
1485 const DexFile& dex_file) {
Elliott Hughesf09afe82011-10-16 14:24:21 -07001486 CompiledMethod* compiled_method = NULL;
Elliott Hughesbb551fa2012-01-25 16:35:29 -08001487 uint64_t start_ns = NanoTime();
Logan Chien4dd96f52012-02-29 01:26:58 +08001488
Ian Rogers169c9a72011-11-13 20:13:17 -08001489 if ((access_flags & kAccNative) != 0) {
Ian Rogers57b86d42012-03-27 16:05:41 -07001490 compiled_method = (*jni_compiler_)(*this, access_flags, method_idx, dex_file);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07001491 CHECK(compiled_method != NULL);
Ian Rogers169c9a72011-11-13 20:13:17 -08001492 } else if ((access_flags & kAccAbstract) != 0) {
Brian Carlstrom2cc022b2011-08-25 10:05:39 -07001493 } else {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001494 compiled_method = (*compiler_)(*this, code_item, access_flags, method_idx, class_loader,
1495 dex_file);
Elliott Hughesbb551fa2012-01-25 16:35:29 -08001496 CHECK(compiled_method != NULL) << PrettyMethod(method_idx, dex_file);
1497 }
Ian Rogers3bb17a62012-01-27 23:56:44 -08001498 uint64_t duration_ns = NanoTime() - start_ns;
buzbee5abfa3e2012-01-31 17:01:43 -08001499 if (duration_ns > MsToNs(100)) {
Elliott Hughesbb551fa2012-01-25 16:35:29 -08001500 LOG(WARNING) << "Compilation of " << PrettyMethod(method_idx, dex_file)
Ian Rogers3bb17a62012-01-27 23:56:44 -08001501 << " took " << PrettyDuration(duration_ns);
Elliott Hughesf09afe82011-10-16 14:24:21 -07001502 }
1503
1504 if (compiled_method != NULL) {
Ian Rogers0571d352011-11-03 19:51:38 -07001505 MethodReference ref(&dex_file, method_idx);
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001506 CHECK(GetCompiledMethod(ref) == NULL) << PrettyMethod(method_idx, dex_file);
Elliott Hughesc225caa2012-02-03 15:43:37 -08001507 MutexLock mu(compiled_methods_lock_);
Elliott Hughesa0e18062012-04-13 15:59:59 -07001508 compiled_methods_.Put(ref, compiled_method);
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001509 DCHECK(GetCompiledMethod(ref) != NULL) << PrettyMethod(method_idx, dex_file);
Brian Carlstrom2cc022b2011-08-25 10:05:39 -07001510 }
Brian Carlstrom9baa4ae2011-09-01 21:14:14 -07001511
Ian Rogers45619fc2012-02-29 11:15:25 -08001512 uint32_t shorty_len;
1513 const char* shorty = dex_file.GetMethodShorty(dex_file.GetMethodId(method_idx), &shorty_len);
Ian Rogers169c9a72011-11-13 20:13:17 -08001514 bool is_static = (access_flags & kAccStatic) != 0;
Elliott Hughesa0e18062012-04-13 15:59:59 -07001515 std::string key(MakeInvokeStubKey(is_static, shorty));
1516 const CompiledInvokeStub* compiled_invoke_stub = FindInvokeStub(key);
Ian Rogers0571d352011-11-03 19:51:38 -07001517 if (compiled_invoke_stub == NULL) {
Shih-wei Liaoc4c98812012-03-10 21:55:51 -08001518 compiled_invoke_stub = (*create_invoke_stub_)(*this, is_static, shorty, shorty_len);
Ian Rogers0571d352011-11-03 19:51:38 -07001519 CHECK(compiled_invoke_stub != NULL);
Elliott Hughesa0e18062012-04-13 15:59:59 -07001520 InsertInvokeStub(key, compiled_invoke_stub);
Ian Rogers2c8f6532011-09-02 17:16:34 -07001521 }
Logan Chien7a2a23a2012-06-06 11:01:00 +08001522
1523#if defined(ART_USE_LLVM_COMPILER)
1524 if (!is_static) {
1525 const CompiledInvokeStub* compiled_proxy_stub = FindProxyStub(shorty);
1526 if (compiled_proxy_stub == NULL) {
1527 compiled_proxy_stub = (*create_proxy_stub_)(*this, shorty, shorty_len);
1528 CHECK(compiled_proxy_stub != NULL);
1529 InsertProxyStub(shorty, compiled_proxy_stub);
1530 }
1531 }
1532#endif
1533
Ian Rogers0571d352011-11-03 19:51:38 -07001534 CHECK(!Thread::Current()->IsExceptionPending()) << PrettyMethod(method_idx, dex_file);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07001535}
1536
Elliott Hughesa0e18062012-04-13 15:59:59 -07001537const CompiledInvokeStub* Compiler::FindInvokeStub(bool is_static, const char* shorty) const {
1538 const std::string key(MakeInvokeStubKey(is_static, shorty));
1539 return FindInvokeStub(key);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07001540}
1541
Elliott Hughesa0e18062012-04-13 15:59:59 -07001542const CompiledInvokeStub* Compiler::FindInvokeStub(const std::string& key) const {
Elliott Hughesc225caa2012-02-03 15:43:37 -08001543 MutexLock mu(compiled_invoke_stubs_lock_);
Ian Rogers0571d352011-11-03 19:51:38 -07001544 InvokeStubTable::const_iterator it = compiled_invoke_stubs_.find(key);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07001545 if (it == compiled_invoke_stubs_.end()) {
1546 return NULL;
Ian Rogers0571d352011-11-03 19:51:38 -07001547 } else {
1548 DCHECK(it->second != NULL);
1549 return it->second;
1550 }
1551}
1552
Elliott Hughesa0e18062012-04-13 15:59:59 -07001553void Compiler::InsertInvokeStub(const std::string& key,
Ian Rogers0571d352011-11-03 19:51:38 -07001554 const CompiledInvokeStub* compiled_invoke_stub) {
Elliott Hughesc225caa2012-02-03 15:43:37 -08001555 MutexLock mu(compiled_invoke_stubs_lock_);
Elliott Hughesa0e18062012-04-13 15:59:59 -07001556 InvokeStubTable::iterator it = compiled_invoke_stubs_.find(key);
1557 if (it != compiled_invoke_stubs_.end()) {
1558 // Someone else won the race.
1559 delete compiled_invoke_stub;
1560 } else {
1561 compiled_invoke_stubs_.Put(key, compiled_invoke_stub);
1562 }
Ian Rogers0571d352011-11-03 19:51:38 -07001563}
1564
Logan Chien7a2a23a2012-06-06 11:01:00 +08001565#if defined(ART_USE_LLVM_COMPILER)
1566const CompiledInvokeStub* Compiler::FindProxyStub(const char* shorty) const {
1567 MutexLock mu(compiled_proxy_stubs_lock_);
1568 ProxyStubTable::const_iterator it = compiled_proxy_stubs_.find(shorty);
1569 if (it == compiled_proxy_stubs_.end()) {
1570 return NULL;
1571 } else {
1572 DCHECK(it->second != NULL);
1573 return it->second;
1574 }
1575}
1576
1577void Compiler::InsertProxyStub(const char* shorty,
1578 const CompiledInvokeStub* compiled_proxy_stub) {
1579 MutexLock mu(compiled_proxy_stubs_lock_);
1580 InvokeStubTable::iterator it = compiled_proxy_stubs_.find(shorty);
1581 if (it != compiled_proxy_stubs_.end()) {
1582 // Someone else won the race.
1583 delete compiled_proxy_stub;
1584 } else {
1585 compiled_proxy_stubs_.Put(shorty, compiled_proxy_stub);
1586 }
1587}
1588#endif
1589
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001590CompiledClass* Compiler::GetCompiledClass(ClassReference ref) const {
Elliott Hughesc225caa2012-02-03 15:43:37 -08001591 MutexLock mu(compiled_classes_lock_);
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001592 ClassTable::const_iterator it = compiled_classes_.find(ref);
1593 if (it == compiled_classes_.end()) {
1594 return NULL;
1595 }
1596 CHECK(it->second != NULL);
1597 return it->second;
1598}
1599
Ian Rogers0571d352011-11-03 19:51:38 -07001600CompiledMethod* Compiler::GetCompiledMethod(MethodReference ref) const {
Elliott Hughesc225caa2012-02-03 15:43:37 -08001601 MutexLock mu(compiled_methods_lock_);
Ian Rogers0571d352011-11-03 19:51:38 -07001602 MethodTable::const_iterator it = compiled_methods_.find(ref);
1603 if (it == compiled_methods_.end()) {
1604 return NULL;
Brian Carlstrom3320cf42011-10-04 14:58:28 -07001605 }
1606 CHECK(it->second != NULL);
1607 return it->second;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001608}
1609
Brian Carlstrome7d856b2012-01-11 18:10:55 -08001610void Compiler::SetGcMaps(const ClassLoader* class_loader, const std::vector<const DexFile*>& dex_files) {
1611 for (size_t i = 0; i != dex_files.size(); ++i) {
1612 const DexFile* dex_file = dex_files[i];
1613 CHECK(dex_file != NULL);
1614 SetGcMapsDexFile(class_loader, *dex_file);
1615 }
1616}
1617
1618void Compiler::SetGcMapsDexFile(const ClassLoader* class_loader, const DexFile& dex_file) {
1619 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1620 DexCache* dex_cache = class_linker->FindDexCache(dex_file);
1621 for (size_t class_def_index = 0; class_def_index < dex_file.NumClassDefs(); class_def_index++) {
1622 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
1623 const char* descriptor = dex_file.GetClassDescriptor(class_def);
1624 Class* klass = class_linker->FindClass(descriptor, class_loader);
1625 if (klass == NULL || !klass->IsVerified()) {
1626 Thread::Current()->ClearException();
1627 continue;
1628 }
1629 const byte* class_data = dex_file.GetClassData(class_def);
1630 if (class_data == NULL) {
1631 // empty class such as a marker interface
1632 continue;
1633 }
1634 ClassDataItemIterator it(dex_file, class_data);
1635 while (it.HasNextStaticField()) {
1636 it.Next();
1637 }
1638 while (it.HasNextInstanceField()) {
1639 it.Next();
1640 }
1641 while (it.HasNextDirectMethod()) {
1642 Method* method = class_linker->ResolveMethod(dex_file, it.GetMemberIndex(), dex_cache,
1643 class_loader, true);
1644 SetGcMapsMethod(dex_file, method);
1645 it.Next();
1646 }
1647 while (it.HasNextVirtualMethod()) {
1648 Method* method = class_linker->ResolveMethod(dex_file, it.GetMemberIndex(), dex_cache,
1649 class_loader, false);
1650 SetGcMapsMethod(dex_file, method);
1651 it.Next();
1652 }
1653 }
1654}
1655
1656void Compiler::SetGcMapsMethod(const DexFile& dex_file, Method* method) {
1657 if (method == NULL) {
1658 Thread::Current()->ClearException();
1659 return;
1660 }
1661 uint16_t method_idx = method->GetDexMethodIndex();
1662 MethodReference ref(&dex_file, method_idx);
1663 CompiledMethod* compiled_method = GetCompiledMethod(ref);
1664 if (compiled_method == NULL) {
1665 return;
1666 }
Ian Rogers776ac1f2012-04-13 23:36:36 -07001667 const std::vector<uint8_t>* gc_map = verifier::MethodVerifier::GetGcMap(ref);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08001668 if (gc_map == NULL) {
1669 return;
1670 }
1671 compiled_method->SetGcMap(*gc_map);
1672}
1673
buzbee2cfc6392012-05-07 14:51:40 -07001674#if defined(ART_USE_LLVM_COMPILER) || defined(ART_USE_QUICK_COMPILER)
Logan Chien8b977d32012-02-21 19:14:55 +08001675void Compiler::SetBitcodeFileName(std::string const& filename) {
Logan Chien106b2a02012-03-18 04:41:38 +08001676 typedef void (*SetBitcodeFileNameFn)(Compiler&, std::string const&);
1677
1678 SetBitcodeFileNameFn set_bitcode_file_name =
1679 FindFunction<SetBitcodeFileNameFn>(MakeCompilerSoName(instruction_set_),
1680 compiler_library_,
1681 "compilerLLVMSetBitcodeFileName");
1682
1683 set_bitcode_file_name(*this, filename);
Logan Chien8b977d32012-02-21 19:14:55 +08001684}
buzbee2cfc6392012-05-07 14:51:40 -07001685#endif
Logan Chienf7015fd2012-03-18 01:19:37 +08001686
buzbee2cfc6392012-05-07 14:51:40 -07001687#if defined(ART_USE_LLVM_COMPILER)
Logan Chienf7015fd2012-03-18 01:19:37 +08001688void Compiler::EnableAutoElfLoading() {
1689 compiler_enable_auto_elf_loading_(*this);
1690}
1691
1692const void* Compiler::GetMethodCodeAddr(const CompiledMethod* cm,
1693 const Method* method) const {
1694 return compiler_get_method_code_addr_(*this, cm, method);
1695}
1696
1697const Method::InvokeStub* Compiler::GetMethodInvokeStubAddr(const CompiledInvokeStub* cm,
1698 const Method* method) const {
1699 return compiler_get_method_invoke_stub_addr_(*this, cm, method);
1700}
Logan Chiendf576142012-03-20 17:36:32 +08001701
1702std::vector<ElfImage> Compiler::GetElfImages() const {
1703 typedef std::vector<ElfImage> (*GetElfImagesFn)(const Compiler&);
1704
1705 GetElfImagesFn get_elf_images =
1706 FindFunction<GetElfImagesFn>(MakeCompilerSoName(instruction_set_),
1707 compiler_library_,
1708 "compilerLLVMGetElfImages");
1709
1710 return get_elf_images(*this);
1711}
Logan Chien8b977d32012-02-21 19:14:55 +08001712#endif
1713
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001714} // namespace art