blob: 477b6cc4d8cecd71df2fb577637018961e79e772 [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>
Brian Carlstrom27ec9612011-09-19 20:20:38 -070022#include <sys/mman.h>
Elliott Hughesd9c67be2012-02-02 19:54:06 -080023#include <unistd.h>
Brian Carlstrom27ec9612011-09-19 20:20:38 -070024
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -070025#include "class_linker.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -070026#include "class_loader.h"
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -070027#include "dex_cache.h"
Brian Carlstrom9baa4ae2011-09-01 21:14:14 -070028#include "jni_internal.h"
Logan Chien4dd96f52012-02-29 01:26:58 +080029#include "oat_compilation_unit.h"
Brian Carlstrom3320cf42011-10-04 14:58:28 -070030#include "oat_file.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080031#include "object_utils.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -070032#include "runtime.h"
Elliott Hughesb3bd5f02012-03-08 21:05:27 -080033#include "space.h"
Brian Carlstrom3320cf42011-10-04 14:58:28 -070034#include "stl_util.h"
Elliott Hughes601a1232012-02-02 17:47:38 -080035#include "timing_logger.h"
Ian Rogers776ac1f2012-04-13 23:36:36 -070036#include "verifier/method_verifier.h"
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -070037
Elliott Hughes059d5c12012-03-12 17:39:18 -070038#if defined(__APPLE__)
39#include <mach-o/dyld.h>
40#endif
41
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -070042namespace art {
43
Shih-wei Liaoc486c112011-09-13 16:43:52 -070044namespace arm {
Ian Rogersbdb03912011-09-14 00:55:44 -070045 ByteArray* CreateAbstractMethodErrorStub();
Ian Rogers1cb0a1d2011-10-06 15:24:35 -070046 ByteArray* ArmCreateResolutionTrampoline(Runtime::TrampolineType type);
Elliott Hughes8add92d2012-01-18 18:18:43 -080047 ByteArray* CreateJniDlsymLookupStub();
Shih-wei Liaoc486c112011-09-13 16:43:52 -070048}
Shih-wei Liaoc486c112011-09-13 16:43:52 -070049namespace x86 {
Ian Rogersbdb03912011-09-14 00:55:44 -070050 ByteArray* CreateAbstractMethodErrorStub();
Ian Rogers1cb0a1d2011-10-06 15:24:35 -070051 ByteArray* X86CreateResolutionTrampoline(Runtime::TrampolineType type);
Elliott Hughes8add92d2012-01-18 18:18:43 -080052 ByteArray* CreateJniDlsymLookupStub();
Brian Carlstrome24fa612011-09-29 00:53:55 -070053}
54
Ian Rogers996cc582012-02-14 22:23:29 -080055static double Percentage(size_t x, size_t y) {
Elliott Hughes398f64b2012-03-26 18:05:48 -070056 return 100.0 * (static_cast<double>(x)) / (static_cast<double>(x + y));
Ian Rogers996cc582012-02-14 22:23:29 -080057}
58
59static void DumpStat(size_t x, size_t y, const char* str) {
60 if (x == 0 && y == 0) {
61 return;
62 }
63 LOG(INFO) << Percentage(x, y) << "% of " << str << " for " << (x + y) << " cases";
64}
65
Ian Rogersc8b306f2012-02-17 21:34:44 -080066class AOTCompilationStats {
67 public:
68 AOTCompilationStats() : stats_lock_("AOT compilation statistics lock"),
69 types_in_dex_cache_(0), types_not_in_dex_cache_(0),
70 strings_in_dex_cache_(0), strings_not_in_dex_cache_(0),
71 resolved_types_(0), unresolved_types_(0),
72 resolved_instance_fields_(0), unresolved_instance_fields_(0),
Ian Rogers2ed3b952012-03-17 11:49:39 -070073 resolved_local_static_fields_(0), resolved_static_fields_(0), unresolved_static_fields_(0) {
74 for (size_t i = 0; i <= kMaxInvokeType; i++) {
Ian Rogersc8b306f2012-02-17 21:34:44 -080075 resolved_methods_[i] = 0;
76 unresolved_methods_[i] = 0;
Ian Rogers2ed3b952012-03-17 11:49:39 -070077 virtual_made_direct_[i] = 0;
78 direct_calls_to_boot_[i] = 0;
79 direct_methods_to_boot_[i] = 0;
Elliott Hughesb25c3f62012-03-26 16:35:06 -070080 }
Ian Rogersc8b306f2012-02-17 21:34:44 -080081 }
82
83 void Dump() {
84 DumpStat(types_in_dex_cache_, types_not_in_dex_cache_, "types known to be in dex cache");
85 DumpStat(strings_in_dex_cache_, strings_not_in_dex_cache_, "strings known to be in dex cache");
86 DumpStat(resolved_types_, unresolved_types_, "types resolved");
87 DumpStat(resolved_instance_fields_, unresolved_instance_fields_, "instance fields resolved");
88 DumpStat(resolved_local_static_fields_ + resolved_static_fields_, unresolved_static_fields_,
89 "static fields resolved");
90 DumpStat(resolved_local_static_fields_, resolved_static_fields_ + unresolved_static_fields_,
91 "static fields local to a class");
92
Ian Rogers2ed3b952012-03-17 11:49:39 -070093 for (size_t i = 0; i <= kMaxInvokeType; i++) {
Ian Rogersc8b306f2012-02-17 21:34:44 -080094 std::ostringstream oss;
Ian Rogers2ed3b952012-03-17 11:49:39 -070095 oss << static_cast<InvokeType>(i) << " methods were AOT resolved";
Ian Rogersc8b306f2012-02-17 21:34:44 -080096 DumpStat(resolved_methods_[i], unresolved_methods_[i], oss.str().c_str());
Ian Rogers2ed3b952012-03-17 11:49:39 -070097 if (virtual_made_direct_[i] > 0) {
98 std::ostringstream oss2;
99 oss2 << static_cast<InvokeType>(i) << " methods made direct";
100 DumpStat(virtual_made_direct_[i],
101 resolved_methods_[i] + unresolved_methods_[i] - virtual_made_direct_[i],
102 oss2.str().c_str());
103 }
104 if (direct_calls_to_boot_[i] > 0) {
105 std::ostringstream oss2;
106 oss2 << static_cast<InvokeType>(i) << " method calls are direct into boot";
107 DumpStat(direct_calls_to_boot_[i],
108 resolved_methods_[i] + unresolved_methods_[i] - direct_calls_to_boot_[i],
109 oss2.str().c_str());
110 }
111 if (direct_methods_to_boot_[i] > 0) {
112 std::ostringstream oss2;
113 oss2 << static_cast<InvokeType>(i) << " method calls have methods in boot";
114 DumpStat(direct_methods_to_boot_[i],
115 resolved_methods_[i] + unresolved_methods_[i] - direct_methods_to_boot_[i],
116 oss2.str().c_str());
117 }
Ian Rogersc8b306f2012-02-17 21:34:44 -0800118 }
119 }
Ian Rogers996cc582012-02-14 22:23:29 -0800120
121// Allow lossy statistics in non-debug builds
122#ifndef NDEBUG
123#define STATS_LOCK() MutexLock mu(stats_lock_)
124#else
125#define STATS_LOCK()
126#endif
127
Ian Rogersc8b306f2012-02-17 21:34:44 -0800128 void TypeInDexCache() {
129 STATS_LOCK();
130 types_in_dex_cache_++;
Ian Rogers996cc582012-02-14 22:23:29 -0800131 }
Ian Rogers996cc582012-02-14 22:23:29 -0800132
Ian Rogersc8b306f2012-02-17 21:34:44 -0800133 void TypeNotInDexCache() {
134 STATS_LOCK();
135 types_not_in_dex_cache_++;
Ian Rogers996cc582012-02-14 22:23:29 -0800136 }
Ian Rogersc8b306f2012-02-17 21:34:44 -0800137
138 void StringInDexCache() {
139 STATS_LOCK();
140 strings_in_dex_cache_++;
141 }
142
143 void StringNotInDexCache() {
144 STATS_LOCK();
145 strings_not_in_dex_cache_++;
146 }
147
148 void TypeDoesntNeedAccessCheck() {
149 STATS_LOCK();
150 resolved_types_++;
151 }
152
153 void TypeNeedsAccessCheck() {
154 STATS_LOCK();
155 unresolved_types_++;
156 }
157
158 void ResolvedInstanceField() {
159 STATS_LOCK();
160 resolved_instance_fields_++;
161 }
162
Elliott Hughesb25c3f62012-03-26 16:35:06 -0700163 void UnresolvedInstanceField() {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800164 STATS_LOCK();
165 unresolved_instance_fields_++;
166 }
167
168 void ResolvedLocalStaticField() {
169 STATS_LOCK();
170 resolved_local_static_fields_++;
171 }
172
173 void ResolvedStaticField() {
174 STATS_LOCK();
175 resolved_static_fields_++;
176 }
177
178 void UnresolvedStaticField() {
179 STATS_LOCK();
180 unresolved_static_fields_++;
181 }
182
183 void ResolvedMethod(InvokeType type) {
184 DCHECK_LE(type, kMaxInvokeType);
185 STATS_LOCK();
186 resolved_methods_[type]++;
187 }
188
189 void UnresolvedMethod(InvokeType type) {
190 DCHECK_LE(type, kMaxInvokeType);
191 STATS_LOCK();
192 unresolved_methods_[type]++;
193 }
194
Ian Rogers2ed3b952012-03-17 11:49:39 -0700195 void VirtualMadeDirect(InvokeType type) {
196 DCHECK_LE(type, kMaxInvokeType);
Ian Rogersfb6adba2012-03-04 21:51:51 -0800197 STATS_LOCK();
Ian Rogers2ed3b952012-03-17 11:49:39 -0700198 virtual_made_direct_[type]++;
Ian Rogersfb6adba2012-03-04 21:51:51 -0800199 }
Ian Rogers2ed3b952012-03-17 11:49:39 -0700200
201 void DirectCallsToBoot(InvokeType type) {
202 DCHECK_LE(type, kMaxInvokeType);
203 STATS_LOCK();
204 direct_calls_to_boot_[type]++;
205 }
206
207 void DirectMethodsToBoot(InvokeType type) {
208 DCHECK_LE(type, kMaxInvokeType);
209 STATS_LOCK();
210 direct_methods_to_boot_[type]++;
211 }
212
Ian Rogersc8b306f2012-02-17 21:34:44 -0800213 private:
214 Mutex stats_lock_;
215
216 size_t types_in_dex_cache_;
217 size_t types_not_in_dex_cache_;
218
219 size_t strings_in_dex_cache_;
220 size_t strings_not_in_dex_cache_;
221
222 size_t resolved_types_;
223 size_t unresolved_types_;
224
225 size_t resolved_instance_fields_;
226 size_t unresolved_instance_fields_;
227
228 size_t resolved_local_static_fields_;
229 size_t resolved_static_fields_;
230 size_t unresolved_static_fields_;
231
232 size_t resolved_methods_[kMaxInvokeType + 1];
233 size_t unresolved_methods_[kMaxInvokeType + 1];
Ian Rogers2ed3b952012-03-17 11:49:39 -0700234 size_t virtual_made_direct_[kMaxInvokeType + 1];
235 size_t direct_calls_to_boot_[kMaxInvokeType + 1];
236 size_t direct_methods_to_boot_[kMaxInvokeType + 1];
Ian Rogersc8b306f2012-02-17 21:34:44 -0800237
Elliott Hughesb25c3f62012-03-26 16:35:06 -0700238 DISALLOW_COPY_AND_ASSIGN(AOTCompilationStats);
Ian Rogersc8b306f2012-02-17 21:34:44 -0800239};
Ian Rogers996cc582012-02-14 22:23:29 -0800240
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800241static std::string MakeCompilerSoName(InstructionSet instruction_set) {
242 // TODO: is the ARM/Thumb2 instruction set distinction really buying us anything,
243 // or just causing hassle like this?
244 if (instruction_set == kThumb2) {
245 instruction_set = kArm;
246 }
247
Elliott Hughes059d5c12012-03-12 17:39:18 -0700248 // Capitalize the instruction set, because that's what we do in the build system.
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800249 std::ostringstream instruction_set_name_os;
250 instruction_set_name_os << instruction_set;
251 std::string instruction_set_name(instruction_set_name_os.str());
252 for (size_t i = 0; i < instruction_set_name.size(); ++i) {
253 instruction_set_name[i] = toupper(instruction_set_name[i]);
254 }
Elliott Hughes059d5c12012-03-12 17:39:18 -0700255
256 // Bad things happen if we pull in the libartd-compiler to a libart dex2oat or vice versa,
257 // because we end up with both libart and libartd in the same address space!
Elliott Hughes67d92002012-03-26 15:08:51 -0700258 const char* suffix = (kIsDebugBuild ? "d" : "");
Elliott Hughes059d5c12012-03-12 17:39:18 -0700259
260 // Work out the filename for the compiler library.
Shih-wei Liaoe94d9b22012-05-22 09:01:24 -0700261#if defined(ART_USE_LLVM_COMPILER)
Shih-wei Liaoc4c98812012-03-10 21:55:51 -0800262 std::string library_name(StringPrintf("art%s-compiler-llvm", suffix));
Shih-wei Liaoe94d9b22012-05-22 09:01:24 -0700263#elif defined(ART_USE_GREENLAND_COMPILER)
264 std::string library_name(StringPrintf("art%s-compiler-greenland", suffix));
265#else
266 std::string library_name(StringPrintf("art%s-compiler-%s", suffix, instruction_set_name.c_str()));
Shih-wei Liaoc4c98812012-03-10 21:55:51 -0800267#endif
Elliott Hughes059d5c12012-03-12 17:39:18 -0700268 std::string filename(StringPrintf(OS_SHARED_LIB_FORMAT_STR, library_name.c_str()));
269
270#if defined(__APPLE__)
271 // On Linux, dex2oat will have been built with an RPATH of $ORIGIN/../lib, so dlopen(3) will find
272 // the .so by itself. On Mac OS, there isn't really an equivalent, so we have to manually do the
273 // same work.
Elliott Hughes059d5c12012-03-12 17:39:18 -0700274 uint32_t executable_path_length = 0;
Elliott Hughes448e93c2012-03-28 22:30:06 -0700275 _NSGetExecutablePath(NULL, &executable_path_length);
276 std::string path(executable_path_length, static_cast<char>(0));
277 CHECK_EQ(_NSGetExecutablePath(&path[0], &executable_path_length), 0);
Elliott Hughes059d5c12012-03-12 17:39:18 -0700278
279 // Strip the "/dex2oat".
280 size_t last_slash = path.find_last_of('/');
281 CHECK_NE(last_slash, std::string::npos) << path;
282 path.resize(last_slash);
283
284 // Strip the "/bin".
285 last_slash = path.find_last_of('/');
286 path.resize(last_slash);
287
288 filename = path + "/lib/" + filename;
289#endif
290 return filename;
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800291}
292
Elliott Hughes46f060a2012-03-09 17:36:50 -0800293template<typename Fn>
294static Fn FindFunction(const std::string& compiler_so_name, void* library, const char* name) {
295 Fn fn = reinterpret_cast<Fn>(dlsym(library, name));
296 if (fn == NULL) {
297 LOG(FATAL) << "Couldn't find \"" << name << "\" in compiler library " << compiler_so_name << ": " << dlerror();
298 }
Elliott Hughes059d5c12012-03-12 17:39:18 -0700299 VLOG(compiler) << "Found \"" << name << "\" at " << reinterpret_cast<void*>(fn);
Elliott Hughes46f060a2012-03-09 17:36:50 -0800300 return fn;
301}
302
Elliott Hughes5523ee02012-02-03 18:18:34 -0800303Compiler::Compiler(InstructionSet instruction_set, bool image, size_t thread_count,
Brian Carlstromba0668e2012-03-26 13:14:07 -0700304 bool support_debugging, const std::set<std::string>* image_classes,
305 bool dump_stats, bool dump_timings)
Brian Carlstromaded5f72011-10-07 17:15:04 -0700306 : instruction_set_(instruction_set),
Elliott Hughesc225caa2012-02-03 15:43:37 -0800307 compiled_classes_lock_("compiled classes lock"),
308 compiled_methods_lock_("compiled method lock"),
309 compiled_invoke_stubs_lock_("compiled invoke stubs lock"),
Logan Chien7a2a23a2012-06-06 11:01:00 +0800310#if defined(ART_USE_LLVM_COMPILER)
311 compiled_proxy_stubs_lock_("compiled proxy stubs lock"),
312#endif
Brian Carlstromaded5f72011-10-07 17:15:04 -0700313 image_(image),
Elliott Hughes5523ee02012-02-03 18:18:34 -0800314 thread_count_(thread_count),
Elliott Hughesde6e4cf2012-02-27 14:46:06 -0800315 support_debugging_(support_debugging),
Ian Rogersc8b306f2012-02-17 21:34:44 -0800316 stats_(new AOTCompilationStats),
Brian Carlstromba0668e2012-03-26 13:14:07 -0700317 dump_stats_(dump_stats),
318 dump_timings_(dump_timings),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800319 image_classes_(image_classes),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800320 compiler_library_(NULL),
Elliott Hughes46f060a2012-03-09 17:36:50 -0800321 compiler_(NULL),
Elliott Hughes6f4976c2012-03-13 21:19:01 -0700322 compiler_context_(NULL),
Elliott Hughes46f060a2012-03-09 17:36:50 -0800323 jni_compiler_(NULL),
Elliott Hughes5ddbe0b2012-06-01 12:58:24 -0700324#if !defined(ART_USE_LLVM_COMPILER)
325 create_invoke_stub_(NULL) {
326#else
327 create_invoke_stub_(NULL),
328 compiler_enable_auto_elf_loading_(NULL),
Logan Chienf7015fd2012-03-18 01:19:37 +0800329 compiler_get_method_code_addr_(NULL),
Elliott Hughes5ddbe0b2012-06-01 12:58:24 -0700330 compiler_get_method_invoke_stub_addr_(NULL) {
Logan Chienf7015fd2012-03-18 01:19:37 +0800331#endif
Shih-wei Liaoc4c98812012-03-10 21:55:51 -0800332 std::string compiler_so_name(MakeCompilerSoName(instruction_set_));
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800333 compiler_library_ = dlopen(compiler_so_name.c_str(), RTLD_LAZY);
334 if (compiler_library_ == NULL) {
335 LOG(FATAL) << "Couldn't find compiler library " << compiler_so_name << ": " << dlerror();
336 }
337 VLOG(compiler) << "dlopen(\"" << compiler_so_name << "\", RTLD_LAZY) returned " << compiler_library_;
338
Shih-wei Liaoe94d9b22012-05-22 09:01:24 -0700339#if defined(ART_USE_LLVM_COMPILER) || defined(ART_USE_GREENLAND_COMPILER)
Logan Chien106b2a02012-03-18 04:41:38 +0800340 // Initialize compiler_context_
341 typedef void (*InitCompilerContextFn)(Compiler&);
342
343 InitCompilerContextFn init_compiler_context =
344 FindFunction<void (*)(Compiler&)>(compiler_so_name,
345 compiler_library_,
346 "ArtInitCompilerContext");
347
348 init_compiler_context(*this);
349#endif
350
Elliott Hughes3fa1b7e2012-03-13 17:06:22 -0700351 compiler_ = FindFunction<CompilerFn>(compiler_so_name, compiler_library_, "ArtCompileMethod");
Elliott Hughes46f060a2012-03-09 17:36:50 -0800352 jni_compiler_ = FindFunction<JniCompilerFn>(compiler_so_name, compiler_library_, "ArtJniCompileMethod");
353 create_invoke_stub_ = FindFunction<CreateInvokeStubFn>(compiler_so_name, compiler_library_, "ArtCreateInvokeStub");
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800354
Logan Chienf7015fd2012-03-18 01:19:37 +0800355#if defined(ART_USE_LLVM_COMPILER)
Logan Chien7a2a23a2012-06-06 11:01:00 +0800356 create_proxy_stub_ = FindFunction<CreateProxyStubFn>(
357 compiler_so_name, compiler_library_, "ArtCreateProxyStub");
Logan Chienf7015fd2012-03-18 01:19:37 +0800358 compiler_enable_auto_elf_loading_ = FindFunction<CompilerEnableAutoElfLoadingFn>(
359 compiler_so_name, compiler_library_, "compilerLLVMEnableAutoElfLoading");
360 compiler_get_method_code_addr_ = FindFunction<CompilerGetMethodCodeAddrFn>(
361 compiler_so_name, compiler_library_, "compilerLLVMGetMethodCodeAddr");
362 compiler_get_method_invoke_stub_addr_ = FindFunction<CompilerGetMethodInvokeStubAddrFn>(
363 compiler_so_name, compiler_library_, "compilerLLVMGetMethodInvokeStubAddr");
364#endif
365
Brian Carlstrom25c33252011-09-18 15:58:35 -0700366 CHECK(!Runtime::Current()->IsStarted());
Brian Carlstromae826982011-11-09 01:33:42 -0800367 if (!image_) {
368 CHECK(image_classes_ == NULL);
369 }
Shih-wei Liaoc486c112011-09-13 16:43:52 -0700370}
371
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700372Compiler::~Compiler() {
Elliott Hughesc225caa2012-02-03 15:43:37 -0800373 {
374 MutexLock mu(compiled_classes_lock_);
375 STLDeleteValues(&compiled_classes_);
376 }
377 {
378 MutexLock mu(compiled_methods_lock_);
379 STLDeleteValues(&compiled_methods_);
380 }
381 {
382 MutexLock mu(compiled_invoke_stubs_lock_);
383 STLDeleteValues(&compiled_invoke_stubs_);
Elliott Hughesbb551fa2012-01-25 16:35:29 -0800384 }
Brian Carlstromd06dfe72012-06-06 22:15:39 -0700385#if defined(ART_USE_LLVM_COMPILER)
Brian Carlstromf5822582012-03-19 22:34:31 -0700386 {
Logan Chien7a2a23a2012-06-06 11:01:00 +0800387 MutexLock mu(compiled_proxy_stubs_lock_);
388 STLDeleteValues(&compiled_proxy_stubs_);
389 }
Brian Carlstromd06dfe72012-06-06 22:15:39 -0700390#endif
Logan Chien7a2a23a2012-06-06 11:01:00 +0800391 {
Brian Carlstromf5822582012-03-19 22:34:31 -0700392 MutexLock mu(compiled_methods_lock_);
393 STLDeleteElements(&code_to_patch_);
394 }
395 {
396 MutexLock mu(compiled_methods_lock_);
397 STLDeleteElements(&methods_to_patch_);
398 }
Shih-wei Liaoc4c98812012-03-10 21:55:51 -0800399#if defined(ART_USE_LLVM_COMPILER)
400 CompilerCallbackFn f = FindFunction<CompilerCallbackFn>(MakeCompilerSoName(instruction_set_),
401 compiler_library_,
402 "compilerLLVMDispose");
403 (*f)(*this);
404#endif
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800405 if (compiler_library_ != NULL) {
406 VLOG(compiler) << "dlclose(" << compiler_library_ << ")";
407 dlclose(compiler_library_);
408 }
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700409}
410
Ian Rogers1cb0a1d2011-10-06 15:24:35 -0700411ByteArray* Compiler::CreateResolutionStub(InstructionSet instruction_set,
412 Runtime::TrampolineType type) {
Ian Rogersad25ac52011-10-04 19:13:33 -0700413 if (instruction_set == kX86) {
Ian Rogers1cb0a1d2011-10-06 15:24:35 -0700414 return x86::X86CreateResolutionTrampoline(type);
Ian Rogersad25ac52011-10-04 19:13:33 -0700415 } else {
416 CHECK(instruction_set == kArm || instruction_set == kThumb2);
417 // Generates resolution stub using ARM instruction set
Ian Rogers1cb0a1d2011-10-06 15:24:35 -0700418 return arm::ArmCreateResolutionTrampoline(type);
Ian Rogersad25ac52011-10-04 19:13:33 -0700419 }
420}
421
Elliott Hughes8add92d2012-01-18 18:18:43 -0800422ByteArray* Compiler::CreateJniDlsymLookupStub(InstructionSet instruction_set) {
Ian Rogers169c9a72011-11-13 20:13:17 -0800423 switch (instruction_set) {
424 case kArm:
425 case kThumb2:
Elliott Hughes8add92d2012-01-18 18:18:43 -0800426 return arm::CreateJniDlsymLookupStub();
Ian Rogers169c9a72011-11-13 20:13:17 -0800427 case kX86:
Elliott Hughes8add92d2012-01-18 18:18:43 -0800428 return x86::CreateJniDlsymLookupStub();
Ian Rogers169c9a72011-11-13 20:13:17 -0800429 default:
Ian Rogers49c48942012-03-11 15:15:37 -0700430 LOG(FATAL) << "Unknown InstructionSet: " << instruction_set;
Ian Rogers169c9a72011-11-13 20:13:17 -0800431 return NULL;
432 }
433}
434
Ian Rogersad25ac52011-10-04 19:13:33 -0700435ByteArray* Compiler::CreateAbstractMethodErrorStub(InstructionSet instruction_set) {
436 if (instruction_set == kX86) {
437 return x86::CreateAbstractMethodErrorStub();
438 } else {
439 CHECK(instruction_set == kArm || instruction_set == kThumb2);
440 // Generates resolution stub using ARM instruction set
441 return arm::CreateAbstractMethodErrorStub();
442 }
443}
444
Jesse Wilson254db0f2011-11-16 16:44:11 -0500445void Compiler::CompileAll(const ClassLoader* class_loader,
Brian Carlstromae826982011-11-09 01:33:42 -0800446 const std::vector<const DexFile*>& dex_files) {
Brian Carlstrom25c33252011-09-18 15:58:35 -0700447 DCHECK(!Runtime::Current()->IsStarted());
Brian Carlstromae826982011-11-09 01:33:42 -0800448
Elliott Hughes601a1232012-02-02 17:47:38 -0800449 TimingLogger timings("compiler");
450
451 PreCompile(class_loader, dex_files, timings);
452
Brian Carlstromae826982011-11-09 01:33:42 -0800453 Compile(class_loader, dex_files);
Elliott Hughes601a1232012-02-02 17:47:38 -0800454 timings.AddSplit("Compile");
455
Brian Carlstromae826982011-11-09 01:33:42 -0800456 PostCompile(class_loader, dex_files);
Elliott Hughes601a1232012-02-02 17:47:38 -0800457 timings.AddSplit("PostCompile");
458
Brian Carlstromba0668e2012-03-26 13:14:07 -0700459 if (dump_timings_ && timings.GetTotalNs() > MsToNs(1000)) {
Elliott Hughes601a1232012-02-02 17:47:38 -0800460 timings.Dump();
461 }
Ian Rogers996cc582012-02-14 22:23:29 -0800462
Brian Carlstromba0668e2012-03-26 13:14:07 -0700463 if (dump_stats_) {
464 stats_->Dump();
465 }
Brian Carlstrom8a487412011-08-29 20:08:52 -0700466}
467
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700468void Compiler::CompileOne(const Method* method) {
Brian Carlstrom25c33252011-09-18 15:58:35 -0700469 DCHECK(!Runtime::Current()->IsStarted());
Brian Carlstromae826982011-11-09 01:33:42 -0800470
Brian Carlstrom8a487412011-08-29 20:08:52 -0700471 const ClassLoader* class_loader = method->GetDeclaringClass()->GetClassLoader();
Brian Carlstromae826982011-11-09 01:33:42 -0800472
Ian Rogers0571d352011-11-03 19:51:38 -0700473 // Find the dex_file
474 const DexCache* dex_cache = method->GetDeclaringClass()->GetDexCache();
475 const DexFile& dex_file = Runtime::Current()->GetClassLinker()->FindDexFile(dex_cache);
Brian Carlstromae826982011-11-09 01:33:42 -0800476 std::vector<const DexFile*> dex_files;
477 dex_files.push_back(&dex_file);
478
Elliott Hughes601a1232012-02-02 17:47:38 -0800479 TimingLogger timings("CompileOne");
480 PreCompile(class_loader, dex_files, timings);
Brian Carlstromae826982011-11-09 01:33:42 -0800481
Ian Rogers0571d352011-11-03 19:51:38 -0700482 uint32_t method_idx = method->GetDexMethodIndex();
Ian Rogersa3760aa2011-11-14 14:32:37 -0800483 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(method->GetCodeItemOffset());
484 CompileMethod(code_item, method->GetAccessFlags(), method_idx, class_loader, dex_file);
Brian Carlstromae826982011-11-09 01:33:42 -0800485
486 PostCompile(class_loader, dex_files);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700487}
488
Brian Carlstromae826982011-11-09 01:33:42 -0800489void Compiler::Resolve(const ClassLoader* class_loader,
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800490 const std::vector<const DexFile*>& dex_files, TimingLogger& timings) {
Brian Carlstromae826982011-11-09 01:33:42 -0800491 for (size_t i = 0; i != dex_files.size(); ++i) {
492 const DexFile* dex_file = dex_files[i];
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700493 CHECK(dex_file != NULL);
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800494 ResolveDexFile(class_loader, *dex_file, timings);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700495 }
496}
497
Brian Carlstromae826982011-11-09 01:33:42 -0800498void Compiler::PreCompile(const ClassLoader* class_loader,
Elliott Hughes601a1232012-02-02 17:47:38 -0800499 const std::vector<const DexFile*>& dex_files, TimingLogger& timings) {
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800500 Resolve(class_loader, dex_files, timings);
Elliott Hughes601a1232012-02-02 17:47:38 -0800501
Brian Carlstromae826982011-11-09 01:33:42 -0800502 Verify(class_loader, dex_files);
Elliott Hughes601a1232012-02-02 17:47:38 -0800503 timings.AddSplit("PreCompile.Verify");
504
Brian Carlstromae826982011-11-09 01:33:42 -0800505 InitializeClassesWithoutClinit(class_loader, dex_files);
Elliott Hughes601a1232012-02-02 17:47:38 -0800506 timings.AddSplit("PreCompile.InitializeClassesWithoutClinit");
Brian Carlstromae826982011-11-09 01:33:42 -0800507}
508
509void Compiler::PostCompile(const ClassLoader* class_loader,
510 const std::vector<const DexFile*>& dex_files) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -0800511 SetGcMaps(class_loader, dex_files);
Shih-wei Liaod1fec812012-02-13 09:51:10 -0800512#if defined(ART_USE_LLVM_COMPILER)
Shih-wei Liaoc4c98812012-03-10 21:55:51 -0800513 CompilerCallbackFn f = FindFunction<CompilerCallbackFn>(MakeCompilerSoName(instruction_set_),
514 compiler_library_,
515 "compilerLLVMMaterializeRemainder");
516 (*f)(*this);
Shih-wei Liaod1fec812012-02-13 09:51:10 -0800517#endif
Brian Carlstromae826982011-11-09 01:33:42 -0800518}
519
520bool Compiler::IsImageClass(const std::string& descriptor) const {
521 if (image_classes_ == NULL) {
522 return true;
523 }
524 return image_classes_->find(descriptor) != image_classes_->end();
525}
526
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800527bool Compiler::CanAssumeTypeIsPresentInDexCache(const DexCache* dex_cache,
Ian Rogers996cc582012-02-14 22:23:29 -0800528 uint32_t type_idx) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800529 if (!IsImage()) {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800530 stats_->TypeNotInDexCache();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800531 return false;
532 }
Ian Rogers1bddec32012-02-04 12:27:34 -0800533 Class* resolved_class = dex_cache->GetResolvedType(type_idx);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800534 if (resolved_class == NULL) {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800535 stats_->TypeNotInDexCache();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800536 return false;
537 }
Ian Rogers996cc582012-02-14 22:23:29 -0800538 bool result = IsImageClass(ClassHelper(resolved_class).GetDescriptor());
539 if (result) {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800540 stats_->TypeInDexCache();
Ian Rogers996cc582012-02-14 22:23:29 -0800541 } else {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800542 stats_->TypeNotInDexCache();
Ian Rogers996cc582012-02-14 22:23:29 -0800543 }
544 return result;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800545}
546
Ian Rogers1bddec32012-02-04 12:27:34 -0800547bool Compiler::CanAssumeStringIsPresentInDexCache(const DexCache* dex_cache,
Ian Rogers996cc582012-02-14 22:23:29 -0800548 uint32_t string_idx) {
Ian Rogers1bddec32012-02-04 12:27:34 -0800549 // TODO: Add support for loading strings referenced by image_classes_
550 // See also Compiler::ResolveDexFile
551
552 // The following is a test saying that if we're building the image without a restricted set of
553 // 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 -0800554 bool result = IsImage() && image_classes_ == NULL && dex_cache->GetResolvedString(string_idx) != NULL;
555 if (result) {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800556 stats_->StringInDexCache();
Ian Rogers996cc582012-02-14 22:23:29 -0800557 } else {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800558 stats_->StringNotInDexCache();
Ian Rogers996cc582012-02-14 22:23:29 -0800559 }
560 return result;
Ian Rogers1bddec32012-02-04 12:27:34 -0800561}
562
563bool Compiler::CanAccessTypeWithoutChecks(uint32_t referrer_idx, const DexCache* dex_cache,
Ian Rogers996cc582012-02-14 22:23:29 -0800564 const DexFile& dex_file, uint32_t type_idx) {
Ian Rogers1bddec32012-02-04 12:27:34 -0800565 // Get type from dex cache assuming it was populated by the verifier
566 Class* resolved_class = dex_cache->GetResolvedType(type_idx);
567 if (resolved_class == NULL) {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800568 stats_->TypeNeedsAccessCheck();
Ian Rogers1bddec32012-02-04 12:27:34 -0800569 return false; // Unknown class needs access checks.
570 }
571 const DexFile::MethodId& method_id = dex_file.GetMethodId(referrer_idx);
572 Class* referrer_class = dex_cache->GetResolvedType(method_id.class_idx_);
573 if (referrer_class == NULL) {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800574 stats_->TypeNeedsAccessCheck();
Ian Rogers1bddec32012-02-04 12:27:34 -0800575 return false; // Incomplete referrer knowledge needs access check.
576 }
577 // Perform access check, will return true if access is ok or false if we're going to have to
578 // check this at runtime (for example for class loaders).
Ian Rogers996cc582012-02-14 22:23:29 -0800579 bool result = referrer_class->CanAccess(resolved_class);
580 if (result) {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800581 stats_->TypeDoesntNeedAccessCheck();
Ian Rogers996cc582012-02-14 22:23:29 -0800582 } else {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800583 stats_->TypeNeedsAccessCheck();
Ian Rogers996cc582012-02-14 22:23:29 -0800584 }
585 return result;
Ian Rogers1bddec32012-02-04 12:27:34 -0800586}
587
588bool Compiler::CanAccessInstantiableTypeWithoutChecks(uint32_t referrer_idx,
589 const DexCache* dex_cache,
590 const DexFile& dex_file,
Ian Rogers996cc582012-02-14 22:23:29 -0800591 uint32_t type_idx) {
Ian Rogers1bddec32012-02-04 12:27:34 -0800592 // Get type from dex cache assuming it was populated by the verifier.
593 Class* resolved_class = dex_cache->GetResolvedType(type_idx);
594 if (resolved_class == NULL) {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800595 stats_->TypeNeedsAccessCheck();
Ian Rogers1bddec32012-02-04 12:27:34 -0800596 return false; // Unknown class needs access checks.
597 }
598 const DexFile::MethodId& method_id = dex_file.GetMethodId(referrer_idx);
599 Class* referrer_class = dex_cache->GetResolvedType(method_id.class_idx_);
600 if (referrer_class == NULL) {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800601 stats_->TypeNeedsAccessCheck();
Ian Rogers1bddec32012-02-04 12:27:34 -0800602 return false; // Incomplete referrer knowledge needs access check.
603 }
604 // Perform access and instantiable checks, will return true if access is ok or false if we're
605 // going to have to check this at runtime (for example for class loaders).
Ian Rogers996cc582012-02-14 22:23:29 -0800606 bool result = referrer_class->CanAccess(resolved_class) && resolved_class->IsInstantiable();
607 if (result) {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800608 stats_->TypeDoesntNeedAccessCheck();
Ian Rogers996cc582012-02-14 22:23:29 -0800609 } else {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800610 stats_->TypeNeedsAccessCheck();
Ian Rogers996cc582012-02-14 22:23:29 -0800611 }
612 return result;
Ian Rogers1bddec32012-02-04 12:27:34 -0800613}
614
Logan Chien4dd96f52012-02-29 01:26:58 +0800615static Class* ComputeReferrerClass(OatCompilationUnit* mUnit) {
616 const DexFile::MethodId& referrer_method_id =
617 mUnit->dex_file_->GetMethodId(mUnit->method_idx_);
618
619 return mUnit->class_linker_->ResolveType(
620 *mUnit->dex_file_, referrer_method_id.class_idx_,
621 mUnit->dex_cache_, mUnit->class_loader_);
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800622}
623
Logan Chien4dd96f52012-02-29 01:26:58 +0800624static Field* ComputeReferrerField(OatCompilationUnit* mUnit, uint32_t field_idx) {
625 return mUnit->class_linker_->ResolveField(
626 *mUnit->dex_file_, field_idx, mUnit->dex_cache_,
627 mUnit->class_loader_, false);
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800628}
629
Logan Chien4dd96f52012-02-29 01:26:58 +0800630static Method* ComputeReferrerMethod(OatCompilationUnit* mUnit, uint32_t method_idx) {
631 return mUnit->class_linker_->ResolveMethod(
632 *mUnit->dex_file_, method_idx, mUnit->dex_cache_,
633 mUnit->class_loader_, true);
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800634}
635
Logan Chien4dd96f52012-02-29 01:26:58 +0800636bool Compiler::ComputeInstanceFieldInfo(uint32_t field_idx, OatCompilationUnit* mUnit,
jeffhao8cd6dda2012-02-22 10:15:34 -0800637 int& field_offset, bool& is_volatile, bool is_put) {
Ian Rogers1bddec32012-02-04 12:27:34 -0800638 // Conservative defaults
639 field_offset = -1;
640 is_volatile = true;
641 // Try to resolve field
Logan Chien4dd96f52012-02-29 01:26:58 +0800642 Field* resolved_field = ComputeReferrerField(mUnit, field_idx);
Ian Rogers1bddec32012-02-04 12:27:34 -0800643 if (resolved_field != NULL) {
Logan Chien4dd96f52012-02-29 01:26:58 +0800644 Class* referrer_class = ComputeReferrerClass(mUnit);
Ian Rogerse2645d32012-04-11 14:42:42 -0700645 if (referrer_class != NULL) {
646 Class* fields_class = resolved_field->GetDeclaringClass();
647 bool access_ok = referrer_class->CanAccess(fields_class) &&
648 referrer_class->CanAccessMember(fields_class,
649 resolved_field->GetAccessFlags());
650 if (!access_ok) {
651 // The referring class can't access the resolved field, this may occur as a result of a
652 // protected field being made public by a sub-class. Resort to the dex file to determine
653 // the correct class for the access check.
654 const DexFile& dex_file = mUnit->class_linker_->FindDexFile(referrer_class->GetDexCache());
655 Class* dex_fields_class = mUnit->class_linker_->ResolveType(dex_file,
656 dex_file.GetFieldId(field_idx).class_idx_,
657 referrer_class);
658 access_ok = referrer_class->CanAccess(dex_fields_class) &&
659 referrer_class->CanAccessMember(dex_fields_class,
660 resolved_field->GetAccessFlags());
661 }
662 bool is_write_to_final_from_wrong_class = is_put && resolved_field->IsFinal() &&
663 fields_class != referrer_class;
664 if (access_ok && !is_write_to_final_from_wrong_class) {
665 field_offset = resolved_field->GetOffset().Int32Value();
666 is_volatile = resolved_field->IsVolatile();
667 stats_->ResolvedInstanceField();
668 return true; // Fast path.
669 }
Ian Rogers1bddec32012-02-04 12:27:34 -0800670 }
671 }
672 // Clean up any exception left by field/type resolution
673 Thread* thread = Thread::Current();
674 if (thread->IsExceptionPending()) {
675 thread->ClearException();
676 }
Ian Rogersc8b306f2012-02-17 21:34:44 -0800677 stats_->UnresolvedInstanceField();
Ian Rogers1bddec32012-02-04 12:27:34 -0800678 return false; // Incomplete knowledge needs slow path.
679}
680
Logan Chien4dd96f52012-02-29 01:26:58 +0800681bool Compiler::ComputeStaticFieldInfo(uint32_t field_idx, OatCompilationUnit* mUnit,
Ian Rogers1bddec32012-02-04 12:27:34 -0800682 int& field_offset, int& ssb_index,
jeffhao8cd6dda2012-02-22 10:15:34 -0800683 bool& is_referrers_class, bool& is_volatile, bool is_put) {
Ian Rogers1bddec32012-02-04 12:27:34 -0800684 // Conservative defaults
685 field_offset = -1;
686 ssb_index = -1;
687 is_referrers_class = false;
688 is_volatile = true;
689 // Try to resolve field
Logan Chien4dd96f52012-02-29 01:26:58 +0800690 Field* resolved_field = ComputeReferrerField(mUnit, field_idx);
Ian Rogers1bddec32012-02-04 12:27:34 -0800691 if (resolved_field != NULL) {
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800692 DCHECK(resolved_field->IsStatic());
Logan Chien4dd96f52012-02-29 01:26:58 +0800693 Class* referrer_class = ComputeReferrerClass(mUnit);
Ian Rogers1bddec32012-02-04 12:27:34 -0800694 if (referrer_class != NULL) {
jeffhao8cd6dda2012-02-22 10:15:34 -0800695 Class* fields_class = resolved_field->GetDeclaringClass();
696 if (fields_class == referrer_class) {
Ian Rogers1bddec32012-02-04 12:27:34 -0800697 is_referrers_class = true; // implies no worrying about class initialization
698 field_offset = resolved_field->GetOffset().Int32Value();
699 is_volatile = resolved_field->IsVolatile();
Ian Rogersc8b306f2012-02-17 21:34:44 -0800700 stats_->ResolvedLocalStaticField();
Ian Rogers1bddec32012-02-04 12:27:34 -0800701 return true; // fast path
702 } else {
Ian Rogerse2645d32012-04-11 14:42:42 -0700703 bool access_ok = referrer_class->CanAccess(fields_class) &&
704 referrer_class->CanAccessMember(fields_class,
705 resolved_field->GetAccessFlags());
706 if (!access_ok) {
707 // The referring class can't access the resolved field, this may occur as a result of a
708 // protected field being made public by a sub-class. Resort to the dex file to determine
709 // the correct class for the access check. Don't change the field's class as that is
710 // used to identify the SSB.
711 const DexFile& dex_file = mUnit->class_linker_->FindDexFile(referrer_class->GetDexCache());
712 Class* dex_fields_class =
713 mUnit->class_linker_->ResolveType(dex_file,
714 dex_file.GetFieldId(field_idx).class_idx_,
715 referrer_class);
716 access_ok = referrer_class->CanAccess(dex_fields_class) &&
717 referrer_class->CanAccessMember(dex_fields_class,
718 resolved_field->GetAccessFlags());
719 }
jeffhao8cd6dda2012-02-22 10:15:34 -0800720 bool is_write_to_final_from_wrong_class = is_put && resolved_field->IsFinal();
Ian Rogerse2645d32012-04-11 14:42:42 -0700721 if (access_ok && !is_write_to_final_from_wrong_class) {
Ian Rogers1bddec32012-02-04 12:27:34 -0800722 // We have the resolved field, we must make it into a ssbIndex for the referrer
723 // in its static storage base (which may fail if it doesn't have a slot for it)
Ian Rogers4103ad22012-02-06 09:18:25 -0800724 // TODO: for images we can elide the static storage base null check
725 // if we know there's a non-null entry in the image
Logan Chien4dd96f52012-02-29 01:26:58 +0800726 if (fields_class->GetDexCache() == mUnit->dex_cache_) {
Ian Rogers4103ad22012-02-06 09:18:25 -0800727 // common case where the dex cache of both the referrer and the field are the same,
728 // no need to search the dex file
729 ssb_index = fields_class->GetDexTypeIndex();
730 field_offset = resolved_field->GetOffset().Int32Value();
731 is_volatile = resolved_field->IsVolatile();
Ian Rogersc8b306f2012-02-17 21:34:44 -0800732 stats_->ResolvedStaticField();
Ian Rogers4103ad22012-02-06 09:18:25 -0800733 return true;
734 }
Ian Rogerse2645d32012-04-11 14:42:42 -0700735 // Search dex file for localized ssb index, may fail if field's class is a parent
736 // of the class mentioned in the dex file and there is no dex cache entry.
Ian Rogers1bddec32012-02-04 12:27:34 -0800737 std::string descriptor(FieldHelper(resolved_field).GetDeclaringClassDescriptor());
738 const DexFile::StringId* string_id =
Logan Chien4dd96f52012-02-29 01:26:58 +0800739 mUnit->dex_file_->FindStringId(descriptor);
Ian Rogers1bddec32012-02-04 12:27:34 -0800740 if (string_id != NULL) {
741 const DexFile::TypeId* type_id =
Logan Chien4dd96f52012-02-29 01:26:58 +0800742 mUnit->dex_file_->FindTypeId(mUnit->dex_file_->GetIndexForStringId(*string_id));
Elliott Hughesb25c3f62012-03-26 16:35:06 -0700743 if (type_id != NULL) {
Ian Rogers1bddec32012-02-04 12:27:34 -0800744 // medium path, needs check of static storage base being initialized
Logan Chien4dd96f52012-02-29 01:26:58 +0800745 ssb_index = mUnit->dex_file_->GetIndexForTypeId(*type_id);
Ian Rogers1bddec32012-02-04 12:27:34 -0800746 field_offset = resolved_field->GetOffset().Int32Value();
747 is_volatile = resolved_field->IsVolatile();
Ian Rogersc8b306f2012-02-17 21:34:44 -0800748 stats_->ResolvedStaticField();
Ian Rogers1bddec32012-02-04 12:27:34 -0800749 return true;
750 }
751 }
752 }
753 }
754 }
755 }
756 // Clean up any exception left by field/type resolution
757 Thread* thread = Thread::Current();
758 if (thread->IsExceptionPending()) {
759 thread->ClearException();
760 }
Ian Rogersc8b306f2012-02-17 21:34:44 -0800761 stats_->UnresolvedStaticField();
Ian Rogers1bddec32012-02-04 12:27:34 -0800762 return false; // Incomplete knowledge needs slow path.
763}
764
Ian Rogers2ed3b952012-03-17 11:49:39 -0700765void Compiler::GetCodeAndMethodForDirectCall(InvokeType type, InvokeType sharp_type, Method* method,
766 uintptr_t& direct_code, uintptr_t& direct_method) {
767 direct_code = 0;
768 direct_method = 0;
769 if (sharp_type != kStatic && sharp_type != kDirect) {
770 return;
771 }
Ian Rogers2ed3b952012-03-17 11:49:39 -0700772 bool method_code_in_boot = method->GetDeclaringClass()->GetClassLoader() == NULL;
773 if (!method_code_in_boot) {
774 return;
775 }
776 bool has_clinit_trampoline = method->IsStatic() && !method->GetDeclaringClass()->IsInitialized();
777 if (has_clinit_trampoline) {
778 return;
779 }
780 stats_->DirectCallsToBoot(type);
781 stats_->DirectMethodsToBoot(type);
Ian Rogers3fa13792012-03-18 15:53:45 -0700782 bool compiling_boot = Runtime::Current()->GetHeap()->GetSpaces().size() == 1;
783 if (compiling_boot) {
Brian Carlstrom0637e272012-03-20 01:07:52 -0700784 const bool kSupportBootImageFixup = true;
Ian Rogers3fa13792012-03-18 15:53:45 -0700785 if (kSupportBootImageFixup) {
786 MethodHelper mh(method);
787 if (IsImageClass(mh.GetDeclaringClassDescriptor())) {
Brian Carlstrom0637e272012-03-20 01:07:52 -0700788 // We can only branch directly to Methods that are resolved in the DexCache.
789 // Otherwise we won't invoke the resolution trampoline.
Ian Rogers3fa13792012-03-18 15:53:45 -0700790 direct_method = -1;
Brian Carlstrom0637e272012-03-20 01:07:52 -0700791 direct_code = -1;
Ian Rogers3fa13792012-03-18 15:53:45 -0700792 }
Ian Rogers3fa13792012-03-18 15:53:45 -0700793 }
794 } else {
795 if (Runtime::Current()->GetHeap()->GetImageSpace()->Contains(method)) {
796 direct_method = reinterpret_cast<uintptr_t>(method);
797 }
798 direct_code = reinterpret_cast<uintptr_t>(method->GetCode());
Ian Rogers2ed3b952012-03-17 11:49:39 -0700799 }
Ian Rogers2ed3b952012-03-17 11:49:39 -0700800}
801
Ian Rogersfb6adba2012-03-04 21:51:51 -0800802bool Compiler::ComputeInvokeInfo(uint32_t method_idx, OatCompilationUnit* mUnit, InvokeType& type,
Ian Rogers2ed3b952012-03-17 11:49:39 -0700803 int& vtable_idx, uintptr_t& direct_code,
804 uintptr_t& direct_method) {
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800805 vtable_idx = -1;
Ian Rogers2ed3b952012-03-17 11:49:39 -0700806 direct_code = 0;
807 direct_method = 0;
Logan Chien4dd96f52012-02-29 01:26:58 +0800808 Method* resolved_method = ComputeReferrerMethod(mUnit, method_idx);
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800809 if (resolved_method != NULL) {
Logan Chien4dd96f52012-02-29 01:26:58 +0800810 Class* referrer_class = ComputeReferrerClass(mUnit);
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800811 if (referrer_class != NULL) {
812 Class* methods_class = resolved_method->GetDeclaringClass();
813 if (!referrer_class->CanAccess(methods_class) ||
814 !referrer_class->CanAccessMember(methods_class,
Ian Rogers996cc582012-02-14 22:23:29 -0800815 resolved_method->GetAccessFlags())) {
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800816 // The referring class can't access the resolved method, this may occur as a result of a
817 // protected method being made public by implementing an interface that re-declares the
818 // method public. Resort to the dex file to determine the correct class for the access check
Logan Chien4dd96f52012-02-29 01:26:58 +0800819 const DexFile& dex_file = mUnit->class_linker_->FindDexFile(referrer_class->GetDexCache());
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800820 methods_class =
Logan Chien4dd96f52012-02-29 01:26:58 +0800821 mUnit->class_linker_->ResolveType(dex_file,
822 dex_file.GetMethodId(method_idx).class_idx_,
823 referrer_class);
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800824 }
825 if (referrer_class->CanAccess(methods_class) &&
826 referrer_class->CanAccessMember(methods_class,
827 resolved_method->GetAccessFlags())) {
828 vtable_idx = resolved_method->GetMethodIndex();
Ian Rogersf320b632012-03-13 18:47:47 -0700829 const bool kEnableSharpening = true;
Ian Rogers2ed3b952012-03-17 11:49:39 -0700830 // Sharpen a virtual call into a direct call when the target is known.
831 bool can_sharpen = type == kVirtual && (resolved_method->IsFinal() ||
832 methods_class->IsFinal());
833 // ensure the vtable index will be correct to dispatch in the vtable of the super class
jeffhao4155fcd2012-03-21 11:42:12 -0700834 can_sharpen = can_sharpen || (type == kSuper && referrer_class != methods_class &&
Ian Rogers2ed3b952012-03-17 11:49:39 -0700835 referrer_class->IsSubClass(methods_class) &&
jeffhao4155fcd2012-03-21 11:42:12 -0700836 vtable_idx < methods_class->GetVTable()->GetLength() &&
837 methods_class->GetVTable()->Get(vtable_idx) == resolved_method);
Ian Rogers2ed3b952012-03-17 11:49:39 -0700838 if (kEnableSharpening && can_sharpen) {
839 stats_->ResolvedMethod(type);
Ian Rogersfb6adba2012-03-04 21:51:51 -0800840 // Sharpen a virtual call into a direct call. The method_idx is into referrer's
841 // dex cache, check that this resolved method is where we expect it.
842 CHECK(referrer_class->GetDexCache()->GetResolvedMethod(method_idx) == resolved_method)
843 << PrettyMethod(resolved_method);
Ian Rogers2ed3b952012-03-17 11:49:39 -0700844 stats_->VirtualMadeDirect(type);
845 GetCodeAndMethodForDirectCall(type, kDirect, resolved_method, direct_code, direct_method);
846 type = kDirect;
847 return true;
848 } else if (type == kSuper) {
849 // Unsharpened super calls are suspicious so go slowpath.
850 } else {
851 stats_->ResolvedMethod(type);
852 GetCodeAndMethodForDirectCall(type, type, resolved_method, direct_code, direct_method);
853 return true;
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800854 }
855 }
856 }
857 }
858 // Clean up any exception left by method/type resolution
859 Thread* thread = Thread::Current();
860 if (thread->IsExceptionPending()) {
861 thread->ClearException();
862 }
Ian Rogersc8b306f2012-02-17 21:34:44 -0800863 stats_->UnresolvedMethod(type);
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800864 return false; // Incomplete knowledge needs slow path.
865}
866
Brian Carlstromf5822582012-03-19 22:34:31 -0700867void Compiler::AddCodePatch(DexCache* dex_cache,
868 const DexFile* dex_file,
869 uint32_t referrer_method_idx,
870 uint32_t referrer_access_flags,
871 uint32_t target_method_idx,
872 bool target_is_direct,
Ian Rogers3fa13792012-03-18 15:53:45 -0700873 size_t literal_offset) {
874 MutexLock mu(compiled_methods_lock_);
Brian Carlstromf5822582012-03-19 22:34:31 -0700875 code_to_patch_.push_back(new PatchInformation(dex_cache,
876 dex_file,
877 referrer_method_idx,
878 referrer_access_flags,
879 target_method_idx,
880 target_is_direct,
881 literal_offset));
Ian Rogers3fa13792012-03-18 15:53:45 -0700882}
Brian Carlstromf5822582012-03-19 22:34:31 -0700883void Compiler::AddMethodPatch(DexCache* dex_cache,
884 const DexFile* dex_file,
885 uint32_t referrer_method_idx,
886 uint32_t referrer_access_flags,
887 uint32_t target_method_idx,
888 bool target_is_direct,
Ian Rogers3fa13792012-03-18 15:53:45 -0700889 size_t literal_offset) {
890 MutexLock mu(compiled_methods_lock_);
Brian Carlstromf5822582012-03-19 22:34:31 -0700891 methods_to_patch_.push_back(new PatchInformation(dex_cache,
892 dex_file,
893 referrer_method_idx,
894 referrer_access_flags,
895 target_method_idx,
896 target_is_direct,
897 literal_offset));
Ian Rogers3fa13792012-03-18 15:53:45 -0700898}
899
Brian Carlstrom5ead0952011-11-28 22:55:52 -0800900// Return true if the class should be skipped during compilation. We
901// never skip classes in the boot class loader. However, if we have a
902// non-boot class loader and we can resolve the class in the boot
903// class loader, we do skip the class. This happens if an app bundles
904// classes found in the boot classpath. Since at runtime we will
905// select the class from the boot classpath, do not attempt to resolve
906// or compile it now.
907static bool SkipClass(const ClassLoader* class_loader,
908 const DexFile& dex_file,
909 const DexFile::ClassDef& class_def) {
910 if (class_loader == NULL) {
911 return false;
912 }
913 const char* descriptor = dex_file.GetClassDescriptor(class_def);
914 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
915 Class* klass = class_linker->FindClass(descriptor, NULL);
916 if (klass == NULL) {
917 Thread* self = Thread::Current();
918 CHECK(self->IsExceptionPending());
919 self->ClearException();
920 return false;
921 }
922 return true;
923}
924
Brian Carlstrom731b2ab2012-03-06 16:53:35 -0800925class Context {
926 public:
927 Context(ClassLinker* class_linker,
928 const ClassLoader* class_loader,
929 Compiler* compiler,
930 DexCache* dex_cache,
931 const DexFile* dex_file)
932 : class_linker_(class_linker),
933 class_loader_(class_loader),
934 compiler_(compiler),
935 dex_cache_(dex_cache),
936 dex_file_(dex_file) {}
937
938 ClassLinker* GetClassLinker() {
939 CHECK(class_linker_ != NULL);
940 return class_linker_;
941 }
942 const ClassLoader* GetClassLoader() {
943 return class_loader_;
944 }
945 Compiler* GetCompiler() {
946 CHECK(compiler_ != NULL);
947 return compiler_;
948 }
949 DexCache* GetDexCache() {
950 CHECK(dex_cache_ != NULL);
951 return dex_cache_;
952 }
953 const DexFile* GetDexFile() {
954 CHECK(dex_file_ != NULL);
955 return dex_file_;
956 }
957
958 private:
959 ClassLinker* class_linker_;
960 const ClassLoader* class_loader_;
961 Compiler* compiler_;
962 DexCache* dex_cache_;
963 const DexFile* dex_file_;
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800964};
965
966typedef void Callback(Context* context, size_t index);
967
968class WorkerThread {
969 public:
Elliott Hughes1e409252012-02-06 11:21:27 -0800970 WorkerThread(Context* context, size_t begin, size_t end, Callback callback, size_t stripe, bool spawn)
971 : spawn_(spawn), context_(context), begin_(begin), end_(end), callback_(callback), stripe_(stripe) {
972 if (spawn_) {
Elliott Hughesbf1b4572012-05-24 19:11:39 -0700973 // Mac OS stacks are only 512KiB. Make sure we have the same stack size on all platforms.
974 pthread_attr_t attr;
975 CHECK_PTHREAD_CALL(pthread_attr_init, (&attr), "new compiler worker thread");
976 CHECK_PTHREAD_CALL(pthread_attr_setstacksize, (&attr, 1*MB), "new compiler worker thread");
977 CHECK_PTHREAD_CALL(pthread_create, (&pthread_, &attr, &Go, this), "new compiler worker thread");
978 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attr), "new compiler worker thread");
Elliott Hughes1e409252012-02-06 11:21:27 -0800979 }
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800980 }
981
982 ~WorkerThread() {
Elliott Hughes1e409252012-02-06 11:21:27 -0800983 if (spawn_) {
984 CHECK_PTHREAD_CALL(pthread_join, (pthread_, NULL), "compiler worker shutdown");
985 }
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800986 }
987
988 private:
Elliott Hughes1e409252012-02-06 11:21:27 -0800989 static void* Go(void* arg) {
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800990 WorkerThread* worker = reinterpret_cast<WorkerThread*>(arg);
991 Runtime* runtime = Runtime::Current();
Elliott Hughes1e409252012-02-06 11:21:27 -0800992 if (worker->spawn_) {
Elliott Hughes462c9442012-03-23 18:47:50 -0700993 runtime->AttachCurrentThread("Compiler Worker", true, NULL);
Elliott Hughes1e409252012-02-06 11:21:27 -0800994 }
Elliott Hughes34e06962012-04-09 13:55:55 -0700995 Thread::Current()->SetState(kRunnable);
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800996 worker->Run();
Elliott Hughes1e409252012-02-06 11:21:27 -0800997 if (worker->spawn_) {
Elliott Hughes34e06962012-04-09 13:55:55 -0700998 Thread::Current()->SetState(kNative);
Elliott Hughes1e409252012-02-06 11:21:27 -0800999 runtime->DetachCurrentThread();
1000 }
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001001 return NULL;
1002 }
1003
Elliott Hughes1e409252012-02-06 11:21:27 -08001004 void Go() {
1005 Go(this);
1006 }
1007
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001008 void Run() {
Brian Carlstrom64277f32012-03-26 23:53:34 -07001009 Thread* self = Thread::Current();
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001010 for (size_t i = begin_; i < end_; i += stripe_) {
1011 callback_(context_, i);
Brian Carlstrom64277f32012-03-26 23:53:34 -07001012 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException()) << " " << i;
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001013 }
1014 }
1015
1016 pthread_t pthread_;
Elliott Hughes1e409252012-02-06 11:21:27 -08001017 bool spawn_;
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001018
1019 Context* context_;
1020 size_t begin_;
1021 size_t end_;
1022 Callback* callback_;
1023 size_t stripe_;
Elliott Hughes1e409252012-02-06 11:21:27 -08001024
1025 friend void ForAll(Context*, size_t, size_t, Callback, size_t);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001026};
1027
Elliott Hughes5523ee02012-02-03 18:18:34 -08001028void ForAll(Context* context, size_t begin, size_t end, Callback callback, size_t thread_count) {
Brian Carlstrom64277f32012-03-26 23:53:34 -07001029 Thread* self = Thread::Current();
1030 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
Elliott Hughes1e409252012-02-06 11:21:27 -08001031 CHECK_GT(thread_count, 0U);
Elliott Hughes81d91512012-02-03 16:38:43 -08001032
Elliott Hughes1e409252012-02-06 11:21:27 -08001033 std::vector<WorkerThread*> threads;
Elliott Hughes81d91512012-02-03 16:38:43 -08001034 for (size_t i = 0; i < thread_count; ++i) {
Elliott Hughes1e409252012-02-06 11:21:27 -08001035 threads.push_back(new WorkerThread(context, begin + i, end, callback, thread_count, (i != 0)));
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001036 }
Elliott Hughes1e409252012-02-06 11:21:27 -08001037 threads[0]->Go();
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001038
Elliott Hughes81d91512012-02-03 16:38:43 -08001039 // Switch to kVmWait while we're blocked waiting for the other threads to finish.
Elliott Hughes34e06962012-04-09 13:55:55 -07001040 ScopedThreadStateChange tsc(self, kVmWait);
Elliott Hughes81d91512012-02-03 16:38:43 -08001041 STLDeleteElements(&threads);
1042}
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001043
1044static void ResolveClassFieldsAndMethods(Context* context, size_t class_def_index) {
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001045 const DexFile& dex_file = *context->GetDexFile();
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001046
1047 // Method and Field are the worst. We can't resolve without either
1048 // context from the code use (to disambiguate virtual vs direct
1049 // method and instance vs static field) or from class
1050 // definitions. While the compiler will resolve what it can as it
1051 // needs it, here we try to resolve fields and methods used in class
1052 // definitions, since many of them many never be referenced by
1053 // generated code.
1054 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001055 if (SkipClass(context->GetClassLoader(), dex_file, class_def)) {
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001056 return;
1057 }
1058
1059 // Note the class_data pointer advances through the headers,
1060 // static fields, instance fields, direct methods, and virtual
1061 // methods.
1062 const byte* class_data = dex_file.GetClassData(class_def);
1063 if (class_data == NULL) {
1064 // empty class such as a marker interface
1065 return;
1066 }
Brian Carlstrom5ead0952011-11-28 22:55:52 -08001067 Thread* self = Thread::Current();
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001068 ClassLinker* class_linker = context->GetClassLinker();
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001069 DexCache* dex_cache = class_linker->FindDexCache(dex_file);
1070 ClassDataItemIterator it(dex_file, class_data);
1071 while (it.HasNextStaticField()) {
1072 Field* field = class_linker->ResolveField(dex_file, it.GetMemberIndex(), dex_cache,
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001073 context->GetClassLoader(), true);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001074 if (field == NULL) {
1075 CHECK(self->IsExceptionPending());
1076 self->ClearException();
1077 }
1078 it.Next();
1079 }
1080 while (it.HasNextInstanceField()) {
1081 Field* field = class_linker->ResolveField(dex_file, it.GetMemberIndex(), dex_cache,
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001082 context->GetClassLoader(), false);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001083 if (field == NULL) {
1084 CHECK(self->IsExceptionPending());
1085 self->ClearException();
1086 }
1087 it.Next();
1088 }
1089 while (it.HasNextDirectMethod()) {
1090 Method* method = class_linker->ResolveMethod(dex_file, it.GetMemberIndex(), dex_cache,
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001091 context->GetClassLoader(), true);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001092 if (method == NULL) {
1093 CHECK(self->IsExceptionPending());
1094 self->ClearException();
1095 }
1096 it.Next();
1097 }
1098 while (it.HasNextVirtualMethod()) {
1099 Method* method = class_linker->ResolveMethod(dex_file, it.GetMemberIndex(), dex_cache,
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001100 context->GetClassLoader(), false);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001101 if (method == NULL) {
1102 CHECK(self->IsExceptionPending());
1103 self->ClearException();
1104 }
1105 it.Next();
1106 }
1107 DCHECK(!it.HasNext());
1108}
1109
1110static void ResolveType(Context* context, size_t type_idx) {
1111 // Class derived values are more complicated, they require the linker and loader.
1112 Thread* self = Thread::Current();
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001113 Class* klass = context->GetClassLinker()->ResolveType(*context->GetDexFile(),
1114 type_idx,
1115 context->GetDexCache(),
1116 context->GetClassLoader());
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001117 if (klass == NULL) {
1118 CHECK(self->IsExceptionPending());
1119 Thread::Current()->ClearException();
1120 }
1121}
1122
1123void Compiler::ResolveDexFile(const ClassLoader* class_loader, const DexFile& dex_file, TimingLogger& timings) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001124 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Brian Carlstromaded5f72011-10-07 17:15:04 -07001125 DexCache* dex_cache = class_linker->FindDexCache(dex_file);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001126
Brian Carlstromae826982011-11-09 01:33:42 -08001127 // Strings are easy in that they always are simply resolved to literals in the same file
1128 if (image_ && image_classes_ == NULL) {
1129 // TODO: Add support for loading strings referenced by image_classes_
1130 // See also Compiler::CanAssumeTypeIsPresentInDexCache.
Brian Carlstromaded5f72011-10-07 17:15:04 -07001131 for (size_t string_idx = 0; string_idx < dex_cache->NumStrings(); string_idx++) {
1132 class_linker->ResolveString(dex_file, string_idx, dex_cache);
1133 }
Elliott Hughesff738062012-02-03 15:00:42 -08001134 timings.AddSplit("Resolve " + dex_file.GetLocation() + " Strings");
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001135 }
1136
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001137 Context context(class_linker, class_loader, this, dex_cache, &dex_file);
Elliott Hughes5523ee02012-02-03 18:18:34 -08001138 ForAll(&context, 0, dex_cache->NumResolvedTypes(), ResolveType, thread_count_);
Elliott Hughesff738062012-02-03 15:00:42 -08001139 timings.AddSplit("Resolve " + dex_file.GetLocation() + " Types");
Brian Carlstrom845490b2011-09-19 15:56:53 -07001140
Elliott Hughes5523ee02012-02-03 18:18:34 -08001141 ForAll(&context, 0, dex_file.NumClassDefs(), ResolveClassFieldsAndMethods, thread_count_);
Elliott Hughesff738062012-02-03 15:00:42 -08001142 timings.AddSplit("Resolve " + dex_file.GetLocation() + " MethodsAndFields");
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001143}
1144
Brian Carlstromae826982011-11-09 01:33:42 -08001145void Compiler::Verify(const ClassLoader* class_loader,
1146 const std::vector<const DexFile*>& dex_files) {
1147 for (size_t i = 0; i != dex_files.size(); ++i) {
1148 const DexFile* dex_file = dex_files[i];
jeffhao98eacac2011-09-14 16:11:53 -07001149 CHECK(dex_file != NULL);
1150 VerifyDexFile(class_loader, *dex_file);
1151 }
1152}
1153
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001154static void VerifyClass(Context* context, size_t class_def_index) {
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001155 const DexFile::ClassDef& class_def = context->GetDexFile()->GetClassDef(class_def_index);
1156 const char* descriptor = context->GetDexFile()->GetClassDescriptor(class_def);
1157 Class* klass = context->GetClassLinker()->FindClass(descriptor, context->GetClassLoader());
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001158 if (klass == NULL) {
1159 Thread* self = Thread::Current();
1160 CHECK(self->IsExceptionPending());
1161 self->ClearException();
jeffhaof56197c2012-03-05 18:01:54 -08001162
1163 /*
1164 * At compile time, we can still structurally verify the class even if FindClass fails.
1165 * This is to ensure the class is structurally sound for compilation. An unsound class
1166 * will be rejected by the verifier and later skipped during compilation in the compiler.
1167 */
1168 std::string error_msg;
jeffhaof1e6b7c2012-06-05 18:33:30 -07001169 if (verifier::MethodVerifier::VerifyClass(context->GetDexFile(), context->GetDexCache(),
1170 context->GetClassLoader(), class_def_index, error_msg) == verifier::MethodVerifier::kHardFailure) {
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001171 const DexFile::ClassDef& class_def = context->GetDexFile()->GetClassDef(class_def_index);
jeffhaof56197c2012-03-05 18:01:54 -08001172 LOG(ERROR) << "Verification failed on class "
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001173 << PrettyDescriptor(context->GetDexFile()->GetClassDescriptor(class_def))
jeffhaof56197c2012-03-05 18:01:54 -08001174 << " because: " << error_msg;
1175 }
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001176 return;
1177 }
1178 CHECK(klass->IsResolved()) << PrettyClass(klass);
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001179 context->GetClassLinker()->VerifyClass(klass);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001180
1181 if (klass->IsErroneous()) {
1182 // ClassLinker::VerifyClass throws, which isn't useful in the compiler.
1183 CHECK(Thread::Current()->IsExceptionPending());
1184 Thread::Current()->ClearException();
jeffhao1ac29442012-03-26 11:37:32 -07001185 art::Compiler::ClassReference ref(context->GetDexFile(), class_def_index);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001186 }
1187
jeffhaof1e6b7c2012-06-05 18:33:30 -07001188 CHECK(klass->IsCompileTimeVerified() || klass->IsErroneous()) << PrettyClass(klass);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001189 CHECK(!Thread::Current()->IsExceptionPending()) << PrettyTypeOf(Thread::Current()->GetException());
1190}
1191
jeffhao98eacac2011-09-14 16:11:53 -07001192void Compiler::VerifyDexFile(const ClassLoader* class_loader, const DexFile& dex_file) {
jeffhaob4df5142011-09-19 20:25:32 -07001193 dex_file.ChangePermissions(PROT_READ | PROT_WRITE);
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07001194
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001195 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1196 Context context(class_linker, class_loader, this, class_linker->FindDexCache(dex_file), &dex_file);
Elliott Hughes5523ee02012-02-03 18:18:34 -08001197 ForAll(&context, 0, dex_file.NumClassDefs(), VerifyClass, thread_count_);
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07001198
jeffhaob4df5142011-09-19 20:25:32 -07001199 dex_file.ChangePermissions(PROT_READ);
Brian Carlstroma5a97a22011-09-15 14:08:49 -07001200}
1201
Brian Carlstromae826982011-11-09 01:33:42 -08001202void Compiler::InitializeClassesWithoutClinit(const ClassLoader* class_loader,
1203 const std::vector<const DexFile*>& dex_files) {
1204 for (size_t i = 0; i != dex_files.size(); ++i) {
1205 const DexFile* dex_file = dex_files[i];
Brian Carlstroma5a97a22011-09-15 14:08:49 -07001206 CHECK(dex_file != NULL);
1207 InitializeClassesWithoutClinit(class_loader, *dex_file);
1208 }
1209}
1210
1211void Compiler::InitializeClassesWithoutClinit(const ClassLoader* class_loader, const DexFile& dex_file) {
1212 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Brian Carlstromffca45d2011-09-16 12:10:49 -07001213 for (size_t class_def_index = 0; class_def_index < dex_file.NumClassDefs(); class_def_index++) {
1214 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
Brian Carlstroma5a97a22011-09-15 14:08:49 -07001215 const char* descriptor = dex_file.GetClassDescriptor(class_def);
1216 Class* klass = class_linker->FindClass(descriptor, class_loader);
Brian Carlstrom27ec9612011-09-19 20:20:38 -07001217 if (klass != NULL) {
jeffhao1ac29442012-03-26 11:37:32 -07001218 if (klass->IsVerified()) {
1219 // Only try to initialize classes that were successfully verified.
Ian Rogers0045a292012-03-31 21:08:41 -07001220 bool compiling_boot = Runtime::Current()->GetHeap()->GetSpaces().size() == 1;
1221 bool can_init_static_fields = compiling_boot &&
1222 IsImageClass(descriptor);
1223 class_linker->EnsureInitialized(klass, false, can_init_static_fields);
jeffhao1ac29442012-03-26 11:37:32 -07001224 }
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001225 // record the final class status if necessary
1226 Class::Status status = klass->GetStatus();
1227 ClassReference ref(&dex_file, class_def_index);
Elliott Hughesc225caa2012-02-03 15:43:37 -08001228 MutexLock mu(compiled_classes_lock_);
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001229 CompiledClass* compiled_class = GetCompiledClass(ref);
1230 if (compiled_class == NULL) {
1231 compiled_class = new CompiledClass(status);
Elliott Hughesa0e18062012-04-13 15:59:59 -07001232 compiled_classes_.Put(ref, compiled_class);
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001233 } else {
1234 DCHECK_EQ(status, compiled_class->GetStatus());
1235 }
Brian Carlstrom27ec9612011-09-19 20:20:38 -07001236 }
1237 // clear any class not found or verification exceptions
1238 Thread::Current()->ClearException();
Brian Carlstromffca45d2011-09-16 12:10:49 -07001239 }
1240
1241 DexCache* dex_cache = class_linker->FindDexCache(dex_file);
1242 for (size_t type_idx = 0; type_idx < dex_cache->NumResolvedTypes(); type_idx++) {
1243 Class* klass = class_linker->ResolveType(dex_file, type_idx, dex_cache, class_loader);
Brian Carlstrom27ec9612011-09-19 20:20:38 -07001244 if (klass == NULL) {
1245 Thread::Current()->ClearException();
1246 } else if (klass->IsInitialized()) {
Brian Carlstromffca45d2011-09-16 12:10:49 -07001247 dex_cache->GetInitializedStaticStorage()->Set(type_idx, klass);
1248 }
jeffhao98eacac2011-09-14 16:11:53 -07001249 }
1250}
1251
Shih-wei Liao90dc30f2012-04-23 02:03:30 -07001252// TODO: This class shares some implementation with WorkerThread. We don't want
1253// to perturb the non-LLVM side at the same time. Staging the refactoring for
1254// the future.
1255class DexFilesWorkerThread {
1256 public:
1257 DexFilesWorkerThread(Context *worker_context, Callback class_callback,
1258 const std::vector<const DexFile*>& dex_files,
1259 volatile int32_t* shared_class_index, bool spawn)
1260 : spawn_(spawn), worker_context_(worker_context),
1261 class_callback_(class_callback), dex_files_(dex_files),
1262 context_(NULL), shared_class_index_(shared_class_index) {
1263 if (spawn_) {
TDYa1278cea5fd2012-05-29 22:22:32 -07001264 pthread_attr_t attr;
1265 CHECK_PTHREAD_CALL(pthread_attr_init, (&attr), "new compiler worker thread");
TDYa12761b409c2012-06-05 23:54:30 -07001266 CHECK_PTHREAD_CALL(pthread_attr_setstacksize, (&attr, 1*MB), "new compiler worker thread");
TDYa1278cea5fd2012-05-29 22:22:32 -07001267 CHECK_PTHREAD_CALL(pthread_create, (&pthread_, &attr, &Go, this), "new compiler worker thread");
1268 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attr), "new compiler worker thread");
Shih-wei Liao90dc30f2012-04-23 02:03:30 -07001269 }
1270 }
1271
1272 ~DexFilesWorkerThread() {
1273 if (spawn_) {
1274 CHECK_PTHREAD_CALL(pthread_join, (pthread_, NULL), "compiler worker shutdown");
1275 }
1276 delete context_;
1277 }
1278
1279 private:
1280 static void* Go(void* arg) {
1281 DexFilesWorkerThread* worker = reinterpret_cast<DexFilesWorkerThread*>(arg);
1282 Runtime* runtime = Runtime::Current();
1283 if (worker->spawn_) {
1284 runtime->AttachCurrentThread("Compiler Worker", true, NULL);
1285 }
1286 Thread::Current()->SetState(kRunnable);
1287 worker->Run();
1288 if (worker->spawn_) {
1289 Thread::Current()->SetState(kNative);
1290 runtime->DetachCurrentThread();
1291 }
1292 return NULL;
1293 }
1294
1295 void Go() {
1296 Go(this);
1297 }
1298
1299 void SwitchToDexFile(size_t dex_file_index) {
1300 CHECK (dex_file_index < dex_files_.size());
1301
1302 const DexFile* dex_file = dex_files_[dex_file_index];
1303 CHECK(dex_file != NULL);
1304
1305 // Destroy the old context
1306 delete context_;
1307
1308 // TODO: Add a callback to let the client specify the class_linker and
1309 // dex_cache in the context for the current working dex file.
1310 context_ = new Context(/* class_linker */NULL,
1311 worker_context_->GetClassLoader(),
1312 worker_context_->GetCompiler(),
1313 /* dex_cache */NULL, dex_file);
1314
1315 CHECK(context_ != NULL);
1316 }
1317
1318 void Run() {
1319 Thread* self = Thread::Current();
1320 size_t cur_dex_file_index = 0;
1321 size_t class_index_base = 0;
1322
1323 SwitchToDexFile(0);
1324
1325 while (true) {
1326 size_t class_index =
1327 static_cast<size_t>(android_atomic_inc(shared_class_index_));
1328
1329 const DexFile* dex_file;
1330 do {
1331 dex_file = dex_files_[cur_dex_file_index];
1332
1333 if (class_index < (class_index_base + dex_file->NumClassDefs())) {
1334 break;
1335 }
1336 class_index_base += dex_file->NumClassDefs();
1337
1338 cur_dex_file_index++;
1339 } while (cur_dex_file_index < dex_files_.size());
1340
1341 if (cur_dex_file_index >= dex_files_.size()) {
1342 return;
1343 }
1344
1345 if (dex_file != context_->GetDexFile()) {
1346 SwitchToDexFile(cur_dex_file_index);
1347 }
1348
1349 class_index -= class_index_base;
1350 class_callback_(context_, class_index);
1351 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
1352 }
1353 }
1354
1355 pthread_t pthread_;
1356 bool spawn_;
1357
1358 Context* worker_context_;
1359 Callback* class_callback_;
1360 const std::vector<const DexFile*>& dex_files_;
1361
1362 Context* context_;
1363 volatile int32_t* shared_class_index_;
1364
1365 friend void ForClassesInAllDexFiles(Context*,
1366 const std::vector<const DexFile*>&,
1367 Callback, size_t);
1368};
1369
1370void ForClassesInAllDexFiles(Context* worker_context,
1371 const std::vector<const DexFile*>& dex_files,
1372 Callback class_callback, size_t thread_count) {
1373 Thread* self = Thread::Current();
1374 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
1375 CHECK_GT(thread_count, 0U);
1376
1377 std::vector<DexFilesWorkerThread*> threads;
1378 volatile int32_t shared_class_index = 0;
1379
1380 for (size_t i = 0; i < thread_count; ++i) {
1381 threads.push_back(new DexFilesWorkerThread(worker_context, class_callback,
1382 dex_files, &shared_class_index,
1383 /* spawn */ (i != 0)));
1384 }
1385 threads[0]->Go();
1386
1387 // Switch to kVmWait while we're blocked waiting for the other threads to finish.
1388 ScopedThreadStateChange tsc(self, kVmWait);
1389 STLDeleteElements(&threads);
1390}
1391
Brian Carlstromae826982011-11-09 01:33:42 -08001392void Compiler::Compile(const ClassLoader* class_loader,
1393 const std::vector<const DexFile*>& dex_files) {
Shih-wei Liao90dc30f2012-04-23 02:03:30 -07001394#if defined(ART_USE_LLVM_COMPILER)
1395 if (dex_files.size() <= 0) {
1396 return; // No dex file
1397 }
1398 Context context(NULL, class_loader, this, NULL, NULL);
1399 ForClassesInAllDexFiles(&context, dex_files, Compiler::CompileClass, thread_count_);
1400#else
Brian Carlstromae826982011-11-09 01:33:42 -08001401 for (size_t i = 0; i != dex_files.size(); ++i) {
1402 const DexFile* dex_file = dex_files[i];
Brian Carlstrom83db7722011-08-26 17:32:56 -07001403 CHECK(dex_file != NULL);
1404 CompileDexFile(class_loader, *dex_file);
1405 }
Shih-wei Liao90dc30f2012-04-23 02:03:30 -07001406#endif
Brian Carlstrom83db7722011-08-26 17:32:56 -07001407}
1408
Elliott Hughesc225caa2012-02-03 15:43:37 -08001409void Compiler::CompileClass(Context* context, size_t class_def_index) {
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001410 const ClassLoader* class_loader = context->GetClassLoader();
1411 const DexFile& dex_file = *context->GetDexFile();
Elliott Hughesc225caa2012-02-03 15:43:37 -08001412 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
Brian Carlstrom5ead0952011-11-28 22:55:52 -08001413 if (SkipClass(class_loader, dex_file, class_def)) {
1414 return;
1415 }
jeffhaod1224c72012-02-29 13:43:08 -08001416 ClassReference ref(&dex_file, class_def_index);
1417 // Skip compiling classes with generic verifier failures since they will still fail at runtime
Ian Rogers776ac1f2012-04-13 23:36:36 -07001418 if (verifier::MethodVerifier::IsClassRejected(ref)) {
jeffhaod1224c72012-02-29 13:43:08 -08001419 return;
1420 }
Ian Rogers0571d352011-11-03 19:51:38 -07001421 const byte* class_data = dex_file.GetClassData(class_def);
1422 if (class_data == NULL) {
1423 // empty class, probably a marker interface
1424 return;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001425 }
Ian Rogers0571d352011-11-03 19:51:38 -07001426 ClassDataItemIterator it(dex_file, class_data);
1427 // Skip fields
1428 while (it.HasNextStaticField()) {
1429 it.Next();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001430 }
Ian Rogers0571d352011-11-03 19:51:38 -07001431 while (it.HasNextInstanceField()) {
1432 it.Next();
1433 }
1434 // Compile direct methods
Brian Carlstrom68adbe42012-05-11 17:18:08 -07001435 int64_t previous_direct_method_idx = -1;
Ian Rogers0571d352011-11-03 19:51:38 -07001436 while (it.HasNextDirectMethod()) {
Brian Carlstrom6f29d0e2012-05-11 15:50:29 -07001437 uint32_t method_idx = it.GetMemberIndex();
1438 if (method_idx == previous_direct_method_idx) {
1439 // smali can create dex files with two encoded_methods sharing the same method_idx
1440 // http://code.google.com/p/smali/issues/detail?id=119
1441 it.Next();
1442 continue;
1443 }
1444 previous_direct_method_idx = method_idx;
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001445 context->GetCompiler()->CompileMethod(it.GetMethodCodeItem(), it.GetMemberAccessFlags(),
Brian Carlstrom6f29d0e2012-05-11 15:50:29 -07001446 method_idx, class_loader, dex_file);
Ian Rogers0571d352011-11-03 19:51:38 -07001447 it.Next();
1448 }
1449 // Compile virtual methods
Brian Carlstrom68adbe42012-05-11 17:18:08 -07001450 int64_t previous_virtual_method_idx = -1;
Ian Rogers0571d352011-11-03 19:51:38 -07001451 while (it.HasNextVirtualMethod()) {
Brian Carlstrom6f29d0e2012-05-11 15:50:29 -07001452 uint32_t method_idx = it.GetMemberIndex();
1453 if (method_idx == previous_virtual_method_idx) {
1454 // smali can create dex files with two encoded_methods sharing the same method_idx
1455 // http://code.google.com/p/smali/issues/detail?id=119
1456 it.Next();
1457 continue;
1458 }
1459 previous_virtual_method_idx = method_idx;
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001460 context->GetCompiler()->CompileMethod(it.GetMethodCodeItem(), it.GetMemberAccessFlags(),
Brian Carlstrom6f29d0e2012-05-11 15:50:29 -07001461 method_idx, class_loader, dex_file);
Ian Rogers0571d352011-11-03 19:51:38 -07001462 it.Next();
1463 }
1464 DCHECK(!it.HasNext());
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001465}
1466
Elliott Hughesc225caa2012-02-03 15:43:37 -08001467void Compiler::CompileDexFile(const ClassLoader* class_loader, const DexFile& dex_file) {
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001468 Context context(NULL, class_loader, this, NULL, &dex_file);
Elliott Hughes5523ee02012-02-03 18:18:34 -08001469 ForAll(&context, 0, dex_file.NumClassDefs(), Compiler::CompileClass, thread_count_);
Elliott Hughesc225caa2012-02-03 15:43:37 -08001470}
1471
Elliott Hughesa0e18062012-04-13 15:59:59 -07001472static std::string MakeInvokeStubKey(bool is_static, const char* shorty) {
1473 std::string key(shorty);
1474 if (is_static) {
1475 key += "$"; // Must not be a shorty type character.
1476 }
1477 return key;
1478}
1479
Ian Rogersa3760aa2011-11-14 14:32:37 -08001480void Compiler::CompileMethod(const DexFile::CodeItem* code_item, uint32_t access_flags,
1481 uint32_t method_idx, const ClassLoader* class_loader,
1482 const DexFile& dex_file) {
Elliott Hughesf09afe82011-10-16 14:24:21 -07001483 CompiledMethod* compiled_method = NULL;
Elliott Hughesbb551fa2012-01-25 16:35:29 -08001484 uint64_t start_ns = NanoTime();
Logan Chien4dd96f52012-02-29 01:26:58 +08001485
Ian Rogers169c9a72011-11-13 20:13:17 -08001486 if ((access_flags & kAccNative) != 0) {
Ian Rogers57b86d42012-03-27 16:05:41 -07001487 compiled_method = (*jni_compiler_)(*this, access_flags, method_idx, dex_file);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07001488 CHECK(compiled_method != NULL);
Ian Rogers169c9a72011-11-13 20:13:17 -08001489 } else if ((access_flags & kAccAbstract) != 0) {
Brian Carlstrom2cc022b2011-08-25 10:05:39 -07001490 } else {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001491 compiled_method = (*compiler_)(*this, code_item, access_flags, method_idx, class_loader,
1492 dex_file);
Elliott Hughesbb551fa2012-01-25 16:35:29 -08001493 CHECK(compiled_method != NULL) << PrettyMethod(method_idx, dex_file);
1494 }
Ian Rogers3bb17a62012-01-27 23:56:44 -08001495 uint64_t duration_ns = NanoTime() - start_ns;
buzbee5abfa3e2012-01-31 17:01:43 -08001496 if (duration_ns > MsToNs(100)) {
Elliott Hughesbb551fa2012-01-25 16:35:29 -08001497 LOG(WARNING) << "Compilation of " << PrettyMethod(method_idx, dex_file)
Ian Rogers3bb17a62012-01-27 23:56:44 -08001498 << " took " << PrettyDuration(duration_ns);
Elliott Hughesf09afe82011-10-16 14:24:21 -07001499 }
1500
1501 if (compiled_method != NULL) {
Ian Rogers0571d352011-11-03 19:51:38 -07001502 MethodReference ref(&dex_file, method_idx);
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001503 CHECK(GetCompiledMethod(ref) == NULL) << PrettyMethod(method_idx, dex_file);
Elliott Hughesc225caa2012-02-03 15:43:37 -08001504 MutexLock mu(compiled_methods_lock_);
Elliott Hughesa0e18062012-04-13 15:59:59 -07001505 compiled_methods_.Put(ref, compiled_method);
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001506 DCHECK(GetCompiledMethod(ref) != NULL) << PrettyMethod(method_idx, dex_file);
Brian Carlstrom2cc022b2011-08-25 10:05:39 -07001507 }
Brian Carlstrom9baa4ae2011-09-01 21:14:14 -07001508
Ian Rogers45619fc2012-02-29 11:15:25 -08001509 uint32_t shorty_len;
1510 const char* shorty = dex_file.GetMethodShorty(dex_file.GetMethodId(method_idx), &shorty_len);
Ian Rogers169c9a72011-11-13 20:13:17 -08001511 bool is_static = (access_flags & kAccStatic) != 0;
Elliott Hughesa0e18062012-04-13 15:59:59 -07001512 std::string key(MakeInvokeStubKey(is_static, shorty));
1513 const CompiledInvokeStub* compiled_invoke_stub = FindInvokeStub(key);
Ian Rogers0571d352011-11-03 19:51:38 -07001514 if (compiled_invoke_stub == NULL) {
Shih-wei Liaoc4c98812012-03-10 21:55:51 -08001515 compiled_invoke_stub = (*create_invoke_stub_)(*this, is_static, shorty, shorty_len);
Ian Rogers0571d352011-11-03 19:51:38 -07001516 CHECK(compiled_invoke_stub != NULL);
Elliott Hughesa0e18062012-04-13 15:59:59 -07001517 InsertInvokeStub(key, compiled_invoke_stub);
Ian Rogers2c8f6532011-09-02 17:16:34 -07001518 }
Logan Chien7a2a23a2012-06-06 11:01:00 +08001519
1520#if defined(ART_USE_LLVM_COMPILER)
1521 if (!is_static) {
1522 const CompiledInvokeStub* compiled_proxy_stub = FindProxyStub(shorty);
1523 if (compiled_proxy_stub == NULL) {
1524 compiled_proxy_stub = (*create_proxy_stub_)(*this, shorty, shorty_len);
1525 CHECK(compiled_proxy_stub != NULL);
1526 InsertProxyStub(shorty, compiled_proxy_stub);
1527 }
1528 }
1529#endif
1530
Ian Rogers0571d352011-11-03 19:51:38 -07001531 CHECK(!Thread::Current()->IsExceptionPending()) << PrettyMethod(method_idx, dex_file);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07001532}
1533
Elliott Hughesa0e18062012-04-13 15:59:59 -07001534const CompiledInvokeStub* Compiler::FindInvokeStub(bool is_static, const char* shorty) const {
1535 const std::string key(MakeInvokeStubKey(is_static, shorty));
1536 return FindInvokeStub(key);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07001537}
1538
Elliott Hughesa0e18062012-04-13 15:59:59 -07001539const CompiledInvokeStub* Compiler::FindInvokeStub(const std::string& key) const {
Elliott Hughesc225caa2012-02-03 15:43:37 -08001540 MutexLock mu(compiled_invoke_stubs_lock_);
Ian Rogers0571d352011-11-03 19:51:38 -07001541 InvokeStubTable::const_iterator it = compiled_invoke_stubs_.find(key);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07001542 if (it == compiled_invoke_stubs_.end()) {
1543 return NULL;
Ian Rogers0571d352011-11-03 19:51:38 -07001544 } else {
1545 DCHECK(it->second != NULL);
1546 return it->second;
1547 }
1548}
1549
Elliott Hughesa0e18062012-04-13 15:59:59 -07001550void Compiler::InsertInvokeStub(const std::string& key,
Ian Rogers0571d352011-11-03 19:51:38 -07001551 const CompiledInvokeStub* compiled_invoke_stub) {
Elliott Hughesc225caa2012-02-03 15:43:37 -08001552 MutexLock mu(compiled_invoke_stubs_lock_);
Elliott Hughesa0e18062012-04-13 15:59:59 -07001553 InvokeStubTable::iterator it = compiled_invoke_stubs_.find(key);
1554 if (it != compiled_invoke_stubs_.end()) {
1555 // Someone else won the race.
1556 delete compiled_invoke_stub;
1557 } else {
1558 compiled_invoke_stubs_.Put(key, compiled_invoke_stub);
1559 }
Ian Rogers0571d352011-11-03 19:51:38 -07001560}
1561
Logan Chien7a2a23a2012-06-06 11:01:00 +08001562#if defined(ART_USE_LLVM_COMPILER)
1563const CompiledInvokeStub* Compiler::FindProxyStub(const char* shorty) const {
1564 MutexLock mu(compiled_proxy_stubs_lock_);
1565 ProxyStubTable::const_iterator it = compiled_proxy_stubs_.find(shorty);
1566 if (it == compiled_proxy_stubs_.end()) {
1567 return NULL;
1568 } else {
1569 DCHECK(it->second != NULL);
1570 return it->second;
1571 }
1572}
1573
1574void Compiler::InsertProxyStub(const char* shorty,
1575 const CompiledInvokeStub* compiled_proxy_stub) {
1576 MutexLock mu(compiled_proxy_stubs_lock_);
1577 InvokeStubTable::iterator it = compiled_proxy_stubs_.find(shorty);
1578 if (it != compiled_proxy_stubs_.end()) {
1579 // Someone else won the race.
1580 delete compiled_proxy_stub;
1581 } else {
1582 compiled_proxy_stubs_.Put(shorty, compiled_proxy_stub);
1583 }
1584}
1585#endif
1586
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001587CompiledClass* Compiler::GetCompiledClass(ClassReference ref) const {
Elliott Hughesc225caa2012-02-03 15:43:37 -08001588 MutexLock mu(compiled_classes_lock_);
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001589 ClassTable::const_iterator it = compiled_classes_.find(ref);
1590 if (it == compiled_classes_.end()) {
1591 return NULL;
1592 }
1593 CHECK(it->second != NULL);
1594 return it->second;
1595}
1596
Ian Rogers0571d352011-11-03 19:51:38 -07001597CompiledMethod* Compiler::GetCompiledMethod(MethodReference ref) const {
Elliott Hughesc225caa2012-02-03 15:43:37 -08001598 MutexLock mu(compiled_methods_lock_);
Ian Rogers0571d352011-11-03 19:51:38 -07001599 MethodTable::const_iterator it = compiled_methods_.find(ref);
1600 if (it == compiled_methods_.end()) {
1601 return NULL;
Brian Carlstrom3320cf42011-10-04 14:58:28 -07001602 }
1603 CHECK(it->second != NULL);
1604 return it->second;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001605}
1606
Brian Carlstrome7d856b2012-01-11 18:10:55 -08001607void Compiler::SetGcMaps(const ClassLoader* class_loader, const std::vector<const DexFile*>& dex_files) {
1608 for (size_t i = 0; i != dex_files.size(); ++i) {
1609 const DexFile* dex_file = dex_files[i];
1610 CHECK(dex_file != NULL);
1611 SetGcMapsDexFile(class_loader, *dex_file);
1612 }
1613}
1614
1615void Compiler::SetGcMapsDexFile(const ClassLoader* class_loader, const DexFile& dex_file) {
1616 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1617 DexCache* dex_cache = class_linker->FindDexCache(dex_file);
1618 for (size_t class_def_index = 0; class_def_index < dex_file.NumClassDefs(); class_def_index++) {
1619 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
1620 const char* descriptor = dex_file.GetClassDescriptor(class_def);
1621 Class* klass = class_linker->FindClass(descriptor, class_loader);
1622 if (klass == NULL || !klass->IsVerified()) {
1623 Thread::Current()->ClearException();
1624 continue;
1625 }
1626 const byte* class_data = dex_file.GetClassData(class_def);
1627 if (class_data == NULL) {
1628 // empty class such as a marker interface
1629 continue;
1630 }
1631 ClassDataItemIterator it(dex_file, class_data);
1632 while (it.HasNextStaticField()) {
1633 it.Next();
1634 }
1635 while (it.HasNextInstanceField()) {
1636 it.Next();
1637 }
1638 while (it.HasNextDirectMethod()) {
1639 Method* method = class_linker->ResolveMethod(dex_file, it.GetMemberIndex(), dex_cache,
1640 class_loader, true);
1641 SetGcMapsMethod(dex_file, method);
1642 it.Next();
1643 }
1644 while (it.HasNextVirtualMethod()) {
1645 Method* method = class_linker->ResolveMethod(dex_file, it.GetMemberIndex(), dex_cache,
1646 class_loader, false);
1647 SetGcMapsMethod(dex_file, method);
1648 it.Next();
1649 }
1650 }
1651}
1652
1653void Compiler::SetGcMapsMethod(const DexFile& dex_file, Method* method) {
1654 if (method == NULL) {
1655 Thread::Current()->ClearException();
1656 return;
1657 }
1658 uint16_t method_idx = method->GetDexMethodIndex();
1659 MethodReference ref(&dex_file, method_idx);
1660 CompiledMethod* compiled_method = GetCompiledMethod(ref);
1661 if (compiled_method == NULL) {
1662 return;
1663 }
Ian Rogers776ac1f2012-04-13 23:36:36 -07001664 const std::vector<uint8_t>* gc_map = verifier::MethodVerifier::GetGcMap(ref);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08001665 if (gc_map == NULL) {
1666 return;
1667 }
1668 compiled_method->SetGcMap(*gc_map);
1669}
1670
Logan Chien8b977d32012-02-21 19:14:55 +08001671#if defined(ART_USE_LLVM_COMPILER)
Logan Chien8b977d32012-02-21 19:14:55 +08001672void Compiler::SetBitcodeFileName(std::string const& filename) {
Logan Chien106b2a02012-03-18 04:41:38 +08001673 typedef void (*SetBitcodeFileNameFn)(Compiler&, std::string const&);
1674
1675 SetBitcodeFileNameFn set_bitcode_file_name =
1676 FindFunction<SetBitcodeFileNameFn>(MakeCompilerSoName(instruction_set_),
1677 compiler_library_,
1678 "compilerLLVMSetBitcodeFileName");
1679
1680 set_bitcode_file_name(*this, filename);
Logan Chien8b977d32012-02-21 19:14:55 +08001681}
Logan Chienf7015fd2012-03-18 01:19:37 +08001682
1683void Compiler::EnableAutoElfLoading() {
1684 compiler_enable_auto_elf_loading_(*this);
1685}
1686
1687const void* Compiler::GetMethodCodeAddr(const CompiledMethod* cm,
1688 const Method* method) const {
1689 return compiler_get_method_code_addr_(*this, cm, method);
1690}
1691
1692const Method::InvokeStub* Compiler::GetMethodInvokeStubAddr(const CompiledInvokeStub* cm,
1693 const Method* method) const {
1694 return compiler_get_method_invoke_stub_addr_(*this, cm, method);
1695}
Logan Chiendf576142012-03-20 17:36:32 +08001696
1697std::vector<ElfImage> Compiler::GetElfImages() const {
1698 typedef std::vector<ElfImage> (*GetElfImagesFn)(const Compiler&);
1699
1700 GetElfImagesFn get_elf_images =
1701 FindFunction<GetElfImagesFn>(MakeCompilerSoName(instruction_set_),
1702 compiler_library_,
1703 "compilerLLVMGetElfImages");
1704
1705 return get_elf_images(*this);
1706}
Logan Chien8b977d32012-02-21 19:14:55 +08001707#endif
1708
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001709} // namespace art