blob: 091aad90f7045ef85d853a51246dc24544beb1f9 [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 Rogers00f7d0e2012-07-19 15:28:27 -070030#include "oat/runtime/stub.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"
Ian Rogers00f7d0e2012-07-19 15:28:27 -070034#include "scoped_thread_state_change.h"
35#include "ScopedLocalRef.h"
Brian Carlstrom3320cf42011-10-04 14:58:28 -070036#include "stl_util.h"
Elliott Hughes601a1232012-02-02 17:47:38 -080037#include "timing_logger.h"
Ian Rogers776ac1f2012-04-13 23:36:36 -070038#include "verifier/method_verifier.h"
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -070039
Elliott Hughes059d5c12012-03-12 17:39:18 -070040#if defined(__APPLE__)
41#include <mach-o/dyld.h>
42#endif
43
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -070044namespace art {
45
Ian Rogers996cc582012-02-14 22:23:29 -080046static double Percentage(size_t x, size_t y) {
Elliott Hughes398f64b2012-03-26 18:05:48 -070047 return 100.0 * (static_cast<double>(x)) / (static_cast<double>(x + y));
Ian Rogers996cc582012-02-14 22:23:29 -080048}
49
50static void DumpStat(size_t x, size_t y, const char* str) {
51 if (x == 0 && y == 0) {
52 return;
53 }
54 LOG(INFO) << Percentage(x, y) << "% of " << str << " for " << (x + y) << " cases";
55}
56
Ian Rogersc8b306f2012-02-17 21:34:44 -080057class AOTCompilationStats {
58 public:
Ian Rogersca190662012-06-26 15:45:57 -070059 AOTCompilationStats()
60 : stats_lock_("AOT compilation statistics lock"),
61 types_in_dex_cache_(0), types_not_in_dex_cache_(0),
62 strings_in_dex_cache_(0), strings_not_in_dex_cache_(0),
63 resolved_types_(0), unresolved_types_(0),
64 resolved_instance_fields_(0), unresolved_instance_fields_(0),
65 resolved_local_static_fields_(0), resolved_static_fields_(0), unresolved_static_fields_(0) {
Ian Rogers2ed3b952012-03-17 11:49:39 -070066 for (size_t i = 0; i <= kMaxInvokeType; i++) {
Ian Rogersc8b306f2012-02-17 21:34:44 -080067 resolved_methods_[i] = 0;
68 unresolved_methods_[i] = 0;
Ian Rogers2ed3b952012-03-17 11:49:39 -070069 virtual_made_direct_[i] = 0;
70 direct_calls_to_boot_[i] = 0;
71 direct_methods_to_boot_[i] = 0;
Elliott Hughesb25c3f62012-03-26 16:35:06 -070072 }
Ian Rogersc8b306f2012-02-17 21:34:44 -080073 }
74
75 void Dump() {
76 DumpStat(types_in_dex_cache_, types_not_in_dex_cache_, "types known to be in dex cache");
77 DumpStat(strings_in_dex_cache_, strings_not_in_dex_cache_, "strings known to be in dex cache");
78 DumpStat(resolved_types_, unresolved_types_, "types resolved");
79 DumpStat(resolved_instance_fields_, unresolved_instance_fields_, "instance fields resolved");
80 DumpStat(resolved_local_static_fields_ + resolved_static_fields_, unresolved_static_fields_,
81 "static fields resolved");
82 DumpStat(resolved_local_static_fields_, resolved_static_fields_ + unresolved_static_fields_,
83 "static fields local to a class");
84
Ian Rogers2ed3b952012-03-17 11:49:39 -070085 for (size_t i = 0; i <= kMaxInvokeType; i++) {
Ian Rogersc8b306f2012-02-17 21:34:44 -080086 std::ostringstream oss;
Ian Rogers2ed3b952012-03-17 11:49:39 -070087 oss << static_cast<InvokeType>(i) << " methods were AOT resolved";
Ian Rogersc8b306f2012-02-17 21:34:44 -080088 DumpStat(resolved_methods_[i], unresolved_methods_[i], oss.str().c_str());
Ian Rogers2ed3b952012-03-17 11:49:39 -070089 if (virtual_made_direct_[i] > 0) {
90 std::ostringstream oss2;
91 oss2 << static_cast<InvokeType>(i) << " methods made direct";
92 DumpStat(virtual_made_direct_[i],
93 resolved_methods_[i] + unresolved_methods_[i] - virtual_made_direct_[i],
94 oss2.str().c_str());
95 }
96 if (direct_calls_to_boot_[i] > 0) {
97 std::ostringstream oss2;
98 oss2 << static_cast<InvokeType>(i) << " method calls are direct into boot";
99 DumpStat(direct_calls_to_boot_[i],
100 resolved_methods_[i] + unresolved_methods_[i] - direct_calls_to_boot_[i],
101 oss2.str().c_str());
102 }
103 if (direct_methods_to_boot_[i] > 0) {
104 std::ostringstream oss2;
105 oss2 << static_cast<InvokeType>(i) << " method calls have methods in boot";
106 DumpStat(direct_methods_to_boot_[i],
107 resolved_methods_[i] + unresolved_methods_[i] - direct_methods_to_boot_[i],
108 oss2.str().c_str());
109 }
Ian Rogersc8b306f2012-02-17 21:34:44 -0800110 }
111 }
Ian Rogers996cc582012-02-14 22:23:29 -0800112
113// Allow lossy statistics in non-debug builds
114#ifndef NDEBUG
115#define STATS_LOCK() MutexLock mu(stats_lock_)
116#else
117#define STATS_LOCK()
118#endif
119
Ian Rogersc8b306f2012-02-17 21:34:44 -0800120 void TypeInDexCache() {
121 STATS_LOCK();
122 types_in_dex_cache_++;
Ian Rogers996cc582012-02-14 22:23:29 -0800123 }
Ian Rogers996cc582012-02-14 22:23:29 -0800124
Ian Rogersc8b306f2012-02-17 21:34:44 -0800125 void TypeNotInDexCache() {
126 STATS_LOCK();
127 types_not_in_dex_cache_++;
Ian Rogers996cc582012-02-14 22:23:29 -0800128 }
Ian Rogersc8b306f2012-02-17 21:34:44 -0800129
130 void StringInDexCache() {
131 STATS_LOCK();
132 strings_in_dex_cache_++;
133 }
134
135 void StringNotInDexCache() {
136 STATS_LOCK();
137 strings_not_in_dex_cache_++;
138 }
139
140 void TypeDoesntNeedAccessCheck() {
141 STATS_LOCK();
142 resolved_types_++;
143 }
144
145 void TypeNeedsAccessCheck() {
146 STATS_LOCK();
147 unresolved_types_++;
148 }
149
150 void ResolvedInstanceField() {
151 STATS_LOCK();
152 resolved_instance_fields_++;
153 }
154
Elliott Hughesb25c3f62012-03-26 16:35:06 -0700155 void UnresolvedInstanceField() {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800156 STATS_LOCK();
157 unresolved_instance_fields_++;
158 }
159
160 void ResolvedLocalStaticField() {
161 STATS_LOCK();
162 resolved_local_static_fields_++;
163 }
164
165 void ResolvedStaticField() {
166 STATS_LOCK();
167 resolved_static_fields_++;
168 }
169
170 void UnresolvedStaticField() {
171 STATS_LOCK();
172 unresolved_static_fields_++;
173 }
174
175 void ResolvedMethod(InvokeType type) {
176 DCHECK_LE(type, kMaxInvokeType);
177 STATS_LOCK();
178 resolved_methods_[type]++;
179 }
180
181 void UnresolvedMethod(InvokeType type) {
182 DCHECK_LE(type, kMaxInvokeType);
183 STATS_LOCK();
184 unresolved_methods_[type]++;
185 }
186
Ian Rogers2ed3b952012-03-17 11:49:39 -0700187 void VirtualMadeDirect(InvokeType type) {
188 DCHECK_LE(type, kMaxInvokeType);
Ian Rogersfb6adba2012-03-04 21:51:51 -0800189 STATS_LOCK();
Ian Rogers2ed3b952012-03-17 11:49:39 -0700190 virtual_made_direct_[type]++;
Ian Rogersfb6adba2012-03-04 21:51:51 -0800191 }
Ian Rogers2ed3b952012-03-17 11:49:39 -0700192
193 void DirectCallsToBoot(InvokeType type) {
194 DCHECK_LE(type, kMaxInvokeType);
195 STATS_LOCK();
196 direct_calls_to_boot_[type]++;
197 }
198
199 void DirectMethodsToBoot(InvokeType type) {
200 DCHECK_LE(type, kMaxInvokeType);
201 STATS_LOCK();
202 direct_methods_to_boot_[type]++;
203 }
204
Ian Rogersc8b306f2012-02-17 21:34:44 -0800205 private:
206 Mutex stats_lock_;
207
208 size_t types_in_dex_cache_;
209 size_t types_not_in_dex_cache_;
210
211 size_t strings_in_dex_cache_;
212 size_t strings_not_in_dex_cache_;
213
214 size_t resolved_types_;
215 size_t unresolved_types_;
216
217 size_t resolved_instance_fields_;
218 size_t unresolved_instance_fields_;
219
220 size_t resolved_local_static_fields_;
221 size_t resolved_static_fields_;
222 size_t unresolved_static_fields_;
223
224 size_t resolved_methods_[kMaxInvokeType + 1];
225 size_t unresolved_methods_[kMaxInvokeType + 1];
Ian Rogers2ed3b952012-03-17 11:49:39 -0700226 size_t virtual_made_direct_[kMaxInvokeType + 1];
227 size_t direct_calls_to_boot_[kMaxInvokeType + 1];
228 size_t direct_methods_to_boot_[kMaxInvokeType + 1];
Ian Rogersc8b306f2012-02-17 21:34:44 -0800229
Elliott Hughesb25c3f62012-03-26 16:35:06 -0700230 DISALLOW_COPY_AND_ASSIGN(AOTCompilationStats);
Ian Rogersc8b306f2012-02-17 21:34:44 -0800231};
Ian Rogers996cc582012-02-14 22:23:29 -0800232
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800233static std::string MakeCompilerSoName(InstructionSet instruction_set) {
234 // TODO: is the ARM/Thumb2 instruction set distinction really buying us anything,
235 // or just causing hassle like this?
236 if (instruction_set == kThumb2) {
237 instruction_set = kArm;
238 }
239
Brian Carlstrom5644f002012-06-27 23:05:17 -0700240 // Lower case the instruction set, because that's what we do in the build system.
Elliott Hughes6fcce302012-06-19 16:54:19 -0700241 std::string instruction_set_name(ToStr<InstructionSet>(instruction_set).str());
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800242 for (size_t i = 0; i < instruction_set_name.size(); ++i) {
Brian Carlstrom5644f002012-06-27 23:05:17 -0700243 instruction_set_name[i] = tolower(instruction_set_name[i]);
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800244 }
Elliott Hughes059d5c12012-03-12 17:39:18 -0700245
246 // Bad things happen if we pull in the libartd-compiler to a libart dex2oat or vice versa,
247 // because we end up with both libart and libartd in the same address space!
Elliott Hughes67d92002012-03-26 15:08:51 -0700248 const char* suffix = (kIsDebugBuild ? "d" : "");
Elliott Hughes059d5c12012-03-12 17:39:18 -0700249
250 // Work out the filename for the compiler library.
Shih-wei Liaoe94d9b22012-05-22 09:01:24 -0700251#if defined(ART_USE_LLVM_COMPILER)
Shih-wei Liaoc4c98812012-03-10 21:55:51 -0800252 std::string library_name(StringPrintf("art%s-compiler-llvm", suffix));
Shih-wei Liaoe94d9b22012-05-22 09:01:24 -0700253#elif defined(ART_USE_GREENLAND_COMPILER)
254 std::string library_name(StringPrintf("art%s-compiler-greenland", suffix));
255#else
256 std::string library_name(StringPrintf("art%s-compiler-%s", suffix, instruction_set_name.c_str()));
Shih-wei Liaoc4c98812012-03-10 21:55:51 -0800257#endif
Elliott Hughes059d5c12012-03-12 17:39:18 -0700258 std::string filename(StringPrintf(OS_SHARED_LIB_FORMAT_STR, library_name.c_str()));
259
260#if defined(__APPLE__)
261 // On Linux, dex2oat will have been built with an RPATH of $ORIGIN/../lib, so dlopen(3) will find
262 // the .so by itself. On Mac OS, there isn't really an equivalent, so we have to manually do the
263 // same work.
Elliott Hughes059d5c12012-03-12 17:39:18 -0700264 uint32_t executable_path_length = 0;
Elliott Hughes448e93c2012-03-28 22:30:06 -0700265 _NSGetExecutablePath(NULL, &executable_path_length);
266 std::string path(executable_path_length, static_cast<char>(0));
267 CHECK_EQ(_NSGetExecutablePath(&path[0], &executable_path_length), 0);
Elliott Hughes059d5c12012-03-12 17:39:18 -0700268
269 // Strip the "/dex2oat".
270 size_t last_slash = path.find_last_of('/');
271 CHECK_NE(last_slash, std::string::npos) << path;
272 path.resize(last_slash);
273
274 // Strip the "/bin".
275 last_slash = path.find_last_of('/');
276 path.resize(last_slash);
277
278 filename = path + "/lib/" + filename;
279#endif
280 return filename;
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800281}
282
Elliott Hughes46f060a2012-03-09 17:36:50 -0800283template<typename Fn>
284static Fn FindFunction(const std::string& compiler_so_name, void* library, const char* name) {
285 Fn fn = reinterpret_cast<Fn>(dlsym(library, name));
286 if (fn == NULL) {
287 LOG(FATAL) << "Couldn't find \"" << name << "\" in compiler library " << compiler_so_name << ": " << dlerror();
288 }
Elliott Hughes059d5c12012-03-12 17:39:18 -0700289 VLOG(compiler) << "Found \"" << name << "\" at " << reinterpret_cast<void*>(fn);
Elliott Hughes46f060a2012-03-09 17:36:50 -0800290 return fn;
291}
292
Elliott Hughes5523ee02012-02-03 18:18:34 -0800293Compiler::Compiler(InstructionSet instruction_set, bool image, size_t thread_count,
Brian Carlstromba0668e2012-03-26 13:14:07 -0700294 bool support_debugging, const std::set<std::string>* image_classes,
295 bool dump_stats, bool dump_timings)
Brian Carlstromaded5f72011-10-07 17:15:04 -0700296 : instruction_set_(instruction_set),
Elliott Hughesc225caa2012-02-03 15:43:37 -0800297 compiled_classes_lock_("compiled classes lock"),
298 compiled_methods_lock_("compiled method lock"),
299 compiled_invoke_stubs_lock_("compiled invoke stubs lock"),
Logan Chien7a2a23a2012-06-06 11:01:00 +0800300#if defined(ART_USE_LLVM_COMPILER)
301 compiled_proxy_stubs_lock_("compiled proxy stubs lock"),
302#endif
Brian Carlstromaded5f72011-10-07 17:15:04 -0700303 image_(image),
Elliott Hughes5523ee02012-02-03 18:18:34 -0800304 thread_count_(thread_count),
Elliott Hughesde6e4cf2012-02-27 14:46:06 -0800305 support_debugging_(support_debugging),
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700306 start_ns_(0),
Ian Rogersc8b306f2012-02-17 21:34:44 -0800307 stats_(new AOTCompilationStats),
Brian Carlstromba0668e2012-03-26 13:14:07 -0700308 dump_stats_(dump_stats),
309 dump_timings_(dump_timings),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800310 image_classes_(image_classes),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800311 compiler_library_(NULL),
Elliott Hughes46f060a2012-03-09 17:36:50 -0800312 compiler_(NULL),
Elliott Hughes6f4976c2012-03-13 21:19:01 -0700313 compiler_context_(NULL),
Elliott Hughes46f060a2012-03-09 17:36:50 -0800314 jni_compiler_(NULL),
Logan Chien971bf3f2012-05-01 15:47:55 +0800315 create_invoke_stub_(NULL)
316{
Shih-wei Liaoc4c98812012-03-10 21:55:51 -0800317 std::string compiler_so_name(MakeCompilerSoName(instruction_set_));
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800318 compiler_library_ = dlopen(compiler_so_name.c_str(), RTLD_LAZY);
319 if (compiler_library_ == NULL) {
320 LOG(FATAL) << "Couldn't find compiler library " << compiler_so_name << ": " << dlerror();
321 }
322 VLOG(compiler) << "dlopen(\"" << compiler_so_name << "\", RTLD_LAZY) returned " << compiler_library_;
323
Shih-wei Liaoe94d9b22012-05-22 09:01:24 -0700324#if defined(ART_USE_LLVM_COMPILER) || defined(ART_USE_GREENLAND_COMPILER)
Logan Chien106b2a02012-03-18 04:41:38 +0800325 // Initialize compiler_context_
326 typedef void (*InitCompilerContextFn)(Compiler&);
327
328 InitCompilerContextFn init_compiler_context =
329 FindFunction<void (*)(Compiler&)>(compiler_so_name,
330 compiler_library_,
331 "ArtInitCompilerContext");
332
333 init_compiler_context(*this);
334#endif
335
Elliott Hughes3fa1b7e2012-03-13 17:06:22 -0700336 compiler_ = FindFunction<CompilerFn>(compiler_so_name, compiler_library_, "ArtCompileMethod");
Elliott Hughes46f060a2012-03-09 17:36:50 -0800337 jni_compiler_ = FindFunction<JniCompilerFn>(compiler_so_name, compiler_library_, "ArtJniCompileMethod");
338 create_invoke_stub_ = FindFunction<CreateInvokeStubFn>(compiler_so_name, compiler_library_, "ArtCreateInvokeStub");
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800339
Logan Chienf7015fd2012-03-18 01:19:37 +0800340#if defined(ART_USE_LLVM_COMPILER)
Logan Chien7a2a23a2012-06-06 11:01:00 +0800341 create_proxy_stub_ = FindFunction<CreateProxyStubFn>(
342 compiler_so_name, compiler_library_, "ArtCreateProxyStub");
Logan Chienf7015fd2012-03-18 01:19:37 +0800343#endif
344
Brian Carlstrom25c33252011-09-18 15:58:35 -0700345 CHECK(!Runtime::Current()->IsStarted());
Brian Carlstromae826982011-11-09 01:33:42 -0800346 if (!image_) {
347 CHECK(image_classes_ == NULL);
348 }
Shih-wei Liaoc486c112011-09-13 16:43:52 -0700349}
350
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700351Compiler::~Compiler() {
Elliott Hughesc225caa2012-02-03 15:43:37 -0800352 {
353 MutexLock mu(compiled_classes_lock_);
354 STLDeleteValues(&compiled_classes_);
355 }
356 {
357 MutexLock mu(compiled_methods_lock_);
358 STLDeleteValues(&compiled_methods_);
359 }
360 {
361 MutexLock mu(compiled_invoke_stubs_lock_);
362 STLDeleteValues(&compiled_invoke_stubs_);
Elliott Hughesbb551fa2012-01-25 16:35:29 -0800363 }
Brian Carlstromd06dfe72012-06-06 22:15:39 -0700364#if defined(ART_USE_LLVM_COMPILER)
Brian Carlstromf5822582012-03-19 22:34:31 -0700365 {
Logan Chien7a2a23a2012-06-06 11:01:00 +0800366 MutexLock mu(compiled_proxy_stubs_lock_);
367 STLDeleteValues(&compiled_proxy_stubs_);
368 }
Brian Carlstromd06dfe72012-06-06 22:15:39 -0700369#endif
Logan Chien7a2a23a2012-06-06 11:01:00 +0800370 {
Brian Carlstromf5822582012-03-19 22:34:31 -0700371 MutexLock mu(compiled_methods_lock_);
372 STLDeleteElements(&code_to_patch_);
373 }
374 {
375 MutexLock mu(compiled_methods_lock_);
376 STLDeleteElements(&methods_to_patch_);
377 }
Shih-wei Liaoc4c98812012-03-10 21:55:51 -0800378#if defined(ART_USE_LLVM_COMPILER)
Logan Chien971bf3f2012-05-01 15:47:55 +0800379 // Uninitialize compiler_context_
380 typedef void (*UninitCompilerContextFn)(Compiler&);
381
382 std::string compiler_so_name(MakeCompilerSoName(instruction_set_));
383
384 UninitCompilerContextFn uninit_compiler_context =
385 FindFunction<void (*)(Compiler&)>(compiler_so_name,
386 compiler_library_,
387 "ArtUnInitCompilerContext");
388
389 uninit_compiler_context(*this);
Shih-wei Liaoc4c98812012-03-10 21:55:51 -0800390#endif
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800391 if (compiler_library_ != NULL) {
392 VLOG(compiler) << "dlclose(" << compiler_library_ << ")";
buzbeeca7a5e42012-08-20 11:12:18 -0700393#if !defined(ART_USE_QUICK_COMPILER)
394 /*
395 * FIXME: Temporary workaround
396 * Apparently, llvm is adding dctors to atexit, but if we unload
397 * the library here the code will no longer be around at exit time
398 * and we die a flaming death in __cxa_finalize(). Apparently, some
399 * dlclose() implementations will scan the atexit list on unload and
400 * handle any associated with the soon-to-be-unloaded library.
401 * However, this is not required by POSIX and we don't do it.
402 * See: http://b/issue?id=4998315
403 * What's the right thing to do here?
404 */
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800405 dlclose(compiler_library_);
buzbeeca7a5e42012-08-20 11:12:18 -0700406#endif
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800407 }
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) {
jeffhao7fbee072012-08-24 17:56:54 -0700412 switch (instruction_set) {
413 case kArm:
414 case kThumb2:
415 return arm::ArmCreateResolutionTrampoline(type);
416 case kMips:
417 return mips::MipsCreateResolutionTrampoline(type);
418 case kX86:
419 return x86::X86CreateResolutionTrampoline(type);
420 default:
421 LOG(FATAL) << "Unknown InstructionSet: " << instruction_set;
422 return NULL;
Ian Rogersad25ac52011-10-04 19:13:33 -0700423 }
424}
425
Elliott Hughes8add92d2012-01-18 18:18:43 -0800426ByteArray* Compiler::CreateJniDlsymLookupStub(InstructionSet instruction_set) {
Ian Rogers169c9a72011-11-13 20:13:17 -0800427 switch (instruction_set) {
428 case kArm:
429 case kThumb2:
Elliott Hughes8add92d2012-01-18 18:18:43 -0800430 return arm::CreateJniDlsymLookupStub();
jeffhao7fbee072012-08-24 17:56:54 -0700431 case kMips:
432 return mips::CreateJniDlsymLookupStub();
Ian Rogers169c9a72011-11-13 20:13:17 -0800433 case kX86:
Elliott Hughes8add92d2012-01-18 18:18:43 -0800434 return x86::CreateJniDlsymLookupStub();
Ian Rogers169c9a72011-11-13 20:13:17 -0800435 default:
Ian Rogers49c48942012-03-11 15:15:37 -0700436 LOG(FATAL) << "Unknown InstructionSet: " << instruction_set;
Ian Rogers169c9a72011-11-13 20:13:17 -0800437 return NULL;
438 }
439}
440
Ian Rogersad25ac52011-10-04 19:13:33 -0700441ByteArray* Compiler::CreateAbstractMethodErrorStub(InstructionSet instruction_set) {
jeffhao7fbee072012-08-24 17:56:54 -0700442 switch (instruction_set) {
443 case kArm:
444 case kThumb2:
445 return arm::CreateAbstractMethodErrorStub();
446 case kMips:
447 return mips::CreateAbstractMethodErrorStub();
448 case kX86:
449 return x86::CreateAbstractMethodErrorStub();
450 default:
451 LOG(FATAL) << "Unknown InstructionSet: " << instruction_set;
452 return NULL;
Ian Rogersad25ac52011-10-04 19:13:33 -0700453 }
454}
455
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700456void Compiler::CompileAll(jobject class_loader,
Brian Carlstromae826982011-11-09 01:33:42 -0800457 const std::vector<const DexFile*>& dex_files) {
Brian Carlstrom25c33252011-09-18 15:58:35 -0700458 DCHECK(!Runtime::Current()->IsStarted());
Brian Carlstromae826982011-11-09 01:33:42 -0800459
Elliott Hughes601a1232012-02-02 17:47:38 -0800460 TimingLogger timings("compiler");
461
Elliott Hughes4909ba42012-06-14 13:33:49 -0700462 // TODO: make the verifier thread-safe and remove this workaround.
463 size_t thread_count = thread_count_;
464 thread_count_ = 1;
Elliott Hughes601a1232012-02-02 17:47:38 -0800465 PreCompile(class_loader, dex_files, timings);
Elliott Hughes4909ba42012-06-14 13:33:49 -0700466 thread_count_ = thread_count;
Elliott Hughes601a1232012-02-02 17:47:38 -0800467
Brian Carlstromae826982011-11-09 01:33:42 -0800468 Compile(class_loader, dex_files);
Elliott Hughes601a1232012-02-02 17:47:38 -0800469 timings.AddSplit("Compile");
470
Brian Carlstromae826982011-11-09 01:33:42 -0800471 PostCompile(class_loader, dex_files);
Elliott Hughes601a1232012-02-02 17:47:38 -0800472 timings.AddSplit("PostCompile");
473
Brian Carlstromba0668e2012-03-26 13:14:07 -0700474 if (dump_timings_ && timings.GetTotalNs() > MsToNs(1000)) {
Elliott Hughes601a1232012-02-02 17:47:38 -0800475 timings.Dump();
476 }
Ian Rogers996cc582012-02-14 22:23:29 -0800477
Brian Carlstromba0668e2012-03-26 13:14:07 -0700478 if (dump_stats_) {
479 stats_->Dump();
480 }
Brian Carlstrom8a487412011-08-29 20:08:52 -0700481}
482
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700483void Compiler::CompileOne(const Method* method) {
Brian Carlstrom25c33252011-09-18 15:58:35 -0700484 DCHECK(!Runtime::Current()->IsStarted());
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700485 Thread* self = Thread::Current();
486 jobject class_loader;
487 const DexCache* dex_cache;
488 const DexFile* dex_file;
489 {
490 ScopedObjectAccessUnchecked soa(self);
491 ScopedLocalRef<jobject>
492 local_class_loader(soa.Env(),
493 soa.AddLocalReference<jobject>(method->GetDeclaringClass()->GetClassLoader()));
494 class_loader = soa.Env()->NewGlobalRef(local_class_loader.get());
495 // Find the dex_file
496 dex_cache = method->GetDeclaringClass()->GetDexCache();
497 dex_file = &Runtime::Current()->GetClassLinker()->FindDexFile(dex_cache);
498 }
499 self->TransitionFromRunnableToSuspended(kNative);
Brian Carlstromae826982011-11-09 01:33:42 -0800500
Brian Carlstromae826982011-11-09 01:33:42 -0800501 std::vector<const DexFile*> dex_files;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700502 dex_files.push_back(dex_file);
Brian Carlstromae826982011-11-09 01:33:42 -0800503
Elliott Hughes601a1232012-02-02 17:47:38 -0800504 TimingLogger timings("CompileOne");
505 PreCompile(class_loader, dex_files, timings);
Brian Carlstromae826982011-11-09 01:33:42 -0800506
Ian Rogers0571d352011-11-03 19:51:38 -0700507 uint32_t method_idx = method->GetDexMethodIndex();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700508 const DexFile::CodeItem* code_item = dex_file->GetCodeItem(method->GetCodeItemOffset());
Ian Rogers08f753d2012-08-24 14:35:25 -0700509 CompileMethod(code_item, method->GetAccessFlags(), method->GetInvokeType(),
510 method_idx, class_loader, *dex_file);
Brian Carlstromae826982011-11-09 01:33:42 -0800511
512 PostCompile(class_loader, dex_files);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700513
514 self->GetJniEnv()->DeleteGlobalRef(class_loader);
515
516 self->TransitionFromSuspendedToRunnable();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700517}
518
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700519void Compiler::Resolve(jobject class_loader, const std::vector<const DexFile*>& dex_files,
520 TimingLogger& timings) {
Brian Carlstromae826982011-11-09 01:33:42 -0800521 for (size_t i = 0; i != dex_files.size(); ++i) {
522 const DexFile* dex_file = dex_files[i];
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700523 CHECK(dex_file != NULL);
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800524 ResolveDexFile(class_loader, *dex_file, timings);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700525 }
526}
527
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700528void Compiler::PreCompile(jobject class_loader, const std::vector<const DexFile*>& dex_files,
529 TimingLogger& timings) {
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800530 Resolve(class_loader, dex_files, timings);
Elliott Hughes601a1232012-02-02 17:47:38 -0800531
Brian Carlstromae826982011-11-09 01:33:42 -0800532 Verify(class_loader, dex_files);
Elliott Hughes601a1232012-02-02 17:47:38 -0800533 timings.AddSplit("PreCompile.Verify");
534
Brian Carlstromae826982011-11-09 01:33:42 -0800535 InitializeClassesWithoutClinit(class_loader, dex_files);
Elliott Hughes601a1232012-02-02 17:47:38 -0800536 timings.AddSplit("PreCompile.InitializeClassesWithoutClinit");
Brian Carlstromae826982011-11-09 01:33:42 -0800537}
538
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700539void Compiler::PostCompile(jobject class_loader, const std::vector<const DexFile*>& dex_files) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -0800540 SetGcMaps(class_loader, dex_files);
Brian Carlstromae826982011-11-09 01:33:42 -0800541}
542
543bool Compiler::IsImageClass(const std::string& descriptor) const {
544 if (image_classes_ == NULL) {
545 return true;
546 }
547 return image_classes_->find(descriptor) != image_classes_->end();
548}
549
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700550bool Compiler::CanAssumeTypeIsPresentInDexCache(const DexFile& dex_file,
Ian Rogers996cc582012-02-14 22:23:29 -0800551 uint32_t type_idx) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700552 ScopedObjectAccess soa(Thread::Current());
553 DexCache* dex_cache = Runtime::Current()->GetClassLinker()->FindDexCache(dex_file);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800554 if (!IsImage()) {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800555 stats_->TypeNotInDexCache();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800556 return false;
557 }
Ian Rogers1bddec32012-02-04 12:27:34 -0800558 Class* resolved_class = dex_cache->GetResolvedType(type_idx);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800559 if (resolved_class == NULL) {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800560 stats_->TypeNotInDexCache();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800561 return false;
562 }
Ian Rogers996cc582012-02-14 22:23:29 -0800563 bool result = IsImageClass(ClassHelper(resolved_class).GetDescriptor());
564 if (result) {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800565 stats_->TypeInDexCache();
Ian Rogers996cc582012-02-14 22:23:29 -0800566 } else {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800567 stats_->TypeNotInDexCache();
Ian Rogers996cc582012-02-14 22:23:29 -0800568 }
569 return result;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800570}
571
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700572bool Compiler::CanAssumeStringIsPresentInDexCache(const DexFile& dex_file,
Ian Rogers996cc582012-02-14 22:23:29 -0800573 uint32_t string_idx) {
Ian Rogers1bddec32012-02-04 12:27:34 -0800574 // TODO: Add support for loading strings referenced by image_classes_
575 // See also Compiler::ResolveDexFile
576
577 // The following is a test saying that if we're building the image without a restricted set of
578 // image classes then we can assume the string is present in the dex cache if it is there now
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700579 bool result = IsImage() && image_classes_ == NULL;
580 if (result) {
581 ScopedObjectAccess soa(Thread::Current());
582 DexCache* dex_cache = Runtime::Current()->GetClassLinker()->FindDexCache(dex_file);
583 result = dex_cache->GetResolvedString(string_idx) != NULL;
584 }
Ian Rogers996cc582012-02-14 22:23:29 -0800585 if (result) {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800586 stats_->StringInDexCache();
Ian Rogers996cc582012-02-14 22:23:29 -0800587 } else {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800588 stats_->StringNotInDexCache();
Ian Rogers996cc582012-02-14 22:23:29 -0800589 }
590 return result;
Ian Rogers1bddec32012-02-04 12:27:34 -0800591}
592
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700593bool Compiler::CanAccessTypeWithoutChecks(uint32_t referrer_idx, const DexFile& dex_file,
594 uint32_t type_idx) {
595 ScopedObjectAccess soa(Thread::Current());
596 DexCache* dex_cache = Runtime::Current()->GetClassLinker()->FindDexCache(dex_file);
Ian Rogers1bddec32012-02-04 12:27:34 -0800597 // Get type from dex cache assuming it was populated by the verifier
598 Class* resolved_class = dex_cache->GetResolvedType(type_idx);
599 if (resolved_class == NULL) {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800600 stats_->TypeNeedsAccessCheck();
Ian Rogers1bddec32012-02-04 12:27:34 -0800601 return false; // Unknown class needs access checks.
602 }
603 const DexFile::MethodId& method_id = dex_file.GetMethodId(referrer_idx);
604 Class* referrer_class = dex_cache->GetResolvedType(method_id.class_idx_);
605 if (referrer_class == NULL) {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800606 stats_->TypeNeedsAccessCheck();
Ian Rogers1bddec32012-02-04 12:27:34 -0800607 return false; // Incomplete referrer knowledge needs access check.
608 }
609 // Perform access check, will return true if access is ok or false if we're going to have to
610 // check this at runtime (for example for class loaders).
Ian Rogers996cc582012-02-14 22:23:29 -0800611 bool result = referrer_class->CanAccess(resolved_class);
612 if (result) {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800613 stats_->TypeDoesntNeedAccessCheck();
Ian Rogers996cc582012-02-14 22:23:29 -0800614 } else {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800615 stats_->TypeNeedsAccessCheck();
Ian Rogers996cc582012-02-14 22:23:29 -0800616 }
617 return result;
Ian Rogers1bddec32012-02-04 12:27:34 -0800618}
619
620bool Compiler::CanAccessInstantiableTypeWithoutChecks(uint32_t referrer_idx,
Ian Rogers1bddec32012-02-04 12:27:34 -0800621 const DexFile& dex_file,
Ian Rogers996cc582012-02-14 22:23:29 -0800622 uint32_t type_idx) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700623 ScopedObjectAccess soa(Thread::Current());
624 DexCache* dex_cache = Runtime::Current()->GetClassLinker()->FindDexCache(dex_file);
Ian Rogers1bddec32012-02-04 12:27:34 -0800625 // Get type from dex cache assuming it was populated by the verifier.
626 Class* resolved_class = dex_cache->GetResolvedType(type_idx);
627 if (resolved_class == NULL) {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800628 stats_->TypeNeedsAccessCheck();
Ian Rogers1bddec32012-02-04 12:27:34 -0800629 return false; // Unknown class needs access checks.
630 }
631 const DexFile::MethodId& method_id = dex_file.GetMethodId(referrer_idx);
632 Class* referrer_class = dex_cache->GetResolvedType(method_id.class_idx_);
633 if (referrer_class == NULL) {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800634 stats_->TypeNeedsAccessCheck();
Ian Rogers1bddec32012-02-04 12:27:34 -0800635 return false; // Incomplete referrer knowledge needs access check.
636 }
637 // Perform access and instantiable checks, will return true if access is ok or false if we're
638 // going to have to check this at runtime (for example for class loaders).
Ian Rogers996cc582012-02-14 22:23:29 -0800639 bool result = referrer_class->CanAccess(resolved_class) && resolved_class->IsInstantiable();
640 if (result) {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800641 stats_->TypeDoesntNeedAccessCheck();
Ian Rogers996cc582012-02-14 22:23:29 -0800642 } else {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800643 stats_->TypeNeedsAccessCheck();
Ian Rogers996cc582012-02-14 22:23:29 -0800644 }
645 return result;
Ian Rogers1bddec32012-02-04 12:27:34 -0800646}
647
Ian Rogers08f753d2012-08-24 14:35:25 -0700648static Class* ComputeCompilingMethodsClass(ScopedObjectAccess& soa,
649 OatCompilationUnit* mUnit)
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700650 SHARED_LOCKS_REQUIRED(GlobalSynchronization::mutator_lock_) {
651 DexCache* dex_cache = mUnit->class_linker_->FindDexCache(*mUnit->dex_file_);
652 ClassLoader* class_loader = soa.Decode<ClassLoader*>(mUnit->class_loader_);
653 const DexFile::MethodId& referrer_method_id = mUnit->dex_file_->GetMethodId(mUnit->method_idx_);
654 return mUnit->class_linker_->ResolveType(*mUnit->dex_file_, referrer_method_id.class_idx_,
655 dex_cache, class_loader);
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800656}
657
Ian Rogers08f753d2012-08-24 14:35:25 -0700658static Field* ComputeFieldReferencedFromCompilingMethod(ScopedObjectAccess& soa,
659 OatCompilationUnit* mUnit,
660 uint32_t field_idx)
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700661 SHARED_LOCKS_REQUIRED(GlobalSynchronization::mutator_lock_) {
662 DexCache* dex_cache = mUnit->class_linker_->FindDexCache(*mUnit->dex_file_);
663 ClassLoader* class_loader = soa.Decode<ClassLoader*>(mUnit->class_loader_);
664 return mUnit->class_linker_->ResolveField(*mUnit->dex_file_, field_idx, dex_cache,
665 class_loader, false);
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800666}
667
Ian Rogers08f753d2012-08-24 14:35:25 -0700668static Method* ComputeMethodReferencedFromCompilingMethod(ScopedObjectAccess& soa,
669 OatCompilationUnit* mUnit,
670 uint32_t method_idx,
671 InvokeType type)
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700672 SHARED_LOCKS_REQUIRED(GlobalSynchronization::mutator_lock_) {
673 DexCache* dex_cache = mUnit->class_linker_->FindDexCache(*mUnit->dex_file_);
674 ClassLoader* class_loader = soa.Decode<ClassLoader*>(mUnit->class_loader_);
675 return mUnit->class_linker_->ResolveMethod(*mUnit->dex_file_, method_idx, dex_cache,
jeffhaoc0228b82012-08-29 18:15:05 -0700676 class_loader, NULL, type);
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800677}
678
Logan Chien4dd96f52012-02-29 01:26:58 +0800679bool Compiler::ComputeInstanceFieldInfo(uint32_t field_idx, OatCompilationUnit* mUnit,
jeffhao8cd6dda2012-02-22 10:15:34 -0800680 int& field_offset, bool& is_volatile, bool is_put) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700681 ScopedObjectAccess soa(Thread::Current());
Ian Rogers08f753d2012-08-24 14:35:25 -0700682 // Conservative defaults.
Ian Rogers1bddec32012-02-04 12:27:34 -0800683 field_offset = -1;
684 is_volatile = true;
Ian Rogers08f753d2012-08-24 14:35:25 -0700685 // Try to resolve field and ignore if an Incompatible Class Change Error (ie is static).
686 Field* resolved_field = ComputeFieldReferencedFromCompilingMethod(soa, mUnit, field_idx);
687 if (resolved_field != NULL && !resolved_field->IsStatic()) {
688 Class* referrer_class = ComputeCompilingMethodsClass(soa, mUnit);
Ian Rogerse2645d32012-04-11 14:42:42 -0700689 if (referrer_class != NULL) {
690 Class* fields_class = resolved_field->GetDeclaringClass();
691 bool access_ok = referrer_class->CanAccess(fields_class) &&
692 referrer_class->CanAccessMember(fields_class,
693 resolved_field->GetAccessFlags());
694 if (!access_ok) {
695 // The referring class can't access the resolved field, this may occur as a result of a
696 // protected field being made public by a sub-class. Resort to the dex file to determine
697 // the correct class for the access check.
698 const DexFile& dex_file = mUnit->class_linker_->FindDexFile(referrer_class->GetDexCache());
699 Class* dex_fields_class = mUnit->class_linker_->ResolveType(dex_file,
700 dex_file.GetFieldId(field_idx).class_idx_,
701 referrer_class);
702 access_ok = referrer_class->CanAccess(dex_fields_class) &&
703 referrer_class->CanAccessMember(dex_fields_class,
704 resolved_field->GetAccessFlags());
705 }
706 bool is_write_to_final_from_wrong_class = is_put && resolved_field->IsFinal() &&
707 fields_class != referrer_class;
708 if (access_ok && !is_write_to_final_from_wrong_class) {
709 field_offset = resolved_field->GetOffset().Int32Value();
710 is_volatile = resolved_field->IsVolatile();
711 stats_->ResolvedInstanceField();
712 return true; // Fast path.
713 }
Ian Rogers1bddec32012-02-04 12:27:34 -0800714 }
715 }
716 // Clean up any exception left by field/type resolution
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700717 if (soa.Self()->IsExceptionPending()) {
718 soa.Self()->ClearException();
Ian Rogers1bddec32012-02-04 12:27:34 -0800719 }
Ian Rogersc8b306f2012-02-17 21:34:44 -0800720 stats_->UnresolvedInstanceField();
Ian Rogers1bddec32012-02-04 12:27:34 -0800721 return false; // Incomplete knowledge needs slow path.
722}
723
Logan Chien4dd96f52012-02-29 01:26:58 +0800724bool Compiler::ComputeStaticFieldInfo(uint32_t field_idx, OatCompilationUnit* mUnit,
Ian Rogers1bddec32012-02-04 12:27:34 -0800725 int& field_offset, int& ssb_index,
jeffhao8cd6dda2012-02-22 10:15:34 -0800726 bool& is_referrers_class, bool& is_volatile, bool is_put) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700727 ScopedObjectAccess soa(Thread::Current());
Ian Rogers08f753d2012-08-24 14:35:25 -0700728 // Conservative defaults.
Ian Rogers1bddec32012-02-04 12:27:34 -0800729 field_offset = -1;
730 ssb_index = -1;
731 is_referrers_class = false;
732 is_volatile = true;
Ian Rogers08f753d2012-08-24 14:35:25 -0700733 // Try to resolve field and ignore if an Incompatible Class Change Error (ie isn't static).
734 Field* resolved_field = ComputeFieldReferencedFromCompilingMethod(soa, mUnit, field_idx);
735 if (resolved_field != NULL && resolved_field->IsStatic()) {
736 Class* referrer_class = ComputeCompilingMethodsClass(soa, mUnit);
Ian Rogers1bddec32012-02-04 12:27:34 -0800737 if (referrer_class != NULL) {
jeffhao8cd6dda2012-02-22 10:15:34 -0800738 Class* fields_class = resolved_field->GetDeclaringClass();
739 if (fields_class == referrer_class) {
Ian Rogers1bddec32012-02-04 12:27:34 -0800740 is_referrers_class = true; // implies no worrying about class initialization
741 field_offset = resolved_field->GetOffset().Int32Value();
742 is_volatile = resolved_field->IsVolatile();
Ian Rogersc8b306f2012-02-17 21:34:44 -0800743 stats_->ResolvedLocalStaticField();
Ian Rogers1bddec32012-02-04 12:27:34 -0800744 return true; // fast path
745 } else {
Ian Rogerse2645d32012-04-11 14:42:42 -0700746 bool access_ok = referrer_class->CanAccess(fields_class) &&
747 referrer_class->CanAccessMember(fields_class,
748 resolved_field->GetAccessFlags());
749 if (!access_ok) {
750 // The referring class can't access the resolved field, this may occur as a result of a
751 // protected field being made public by a sub-class. Resort to the dex file to determine
752 // the correct class for the access check. Don't change the field's class as that is
753 // used to identify the SSB.
754 const DexFile& dex_file = mUnit->class_linker_->FindDexFile(referrer_class->GetDexCache());
755 Class* dex_fields_class =
756 mUnit->class_linker_->ResolveType(dex_file,
757 dex_file.GetFieldId(field_idx).class_idx_,
758 referrer_class);
759 access_ok = referrer_class->CanAccess(dex_fields_class) &&
760 referrer_class->CanAccessMember(dex_fields_class,
761 resolved_field->GetAccessFlags());
762 }
jeffhao8cd6dda2012-02-22 10:15:34 -0800763 bool is_write_to_final_from_wrong_class = is_put && resolved_field->IsFinal();
Ian Rogerse2645d32012-04-11 14:42:42 -0700764 if (access_ok && !is_write_to_final_from_wrong_class) {
Ian Rogers1bddec32012-02-04 12:27:34 -0800765 // We have the resolved field, we must make it into a ssbIndex for the referrer
766 // in its static storage base (which may fail if it doesn't have a slot for it)
Ian Rogers4103ad22012-02-06 09:18:25 -0800767 // TODO: for images we can elide the static storage base null check
768 // if we know there's a non-null entry in the image
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700769 DexCache* dex_cache = mUnit->class_linker_->FindDexCache(*mUnit->dex_file_);
770 if (fields_class->GetDexCache() == dex_cache) {
Ian Rogers4103ad22012-02-06 09:18:25 -0800771 // common case where the dex cache of both the referrer and the field are the same,
772 // no need to search the dex file
773 ssb_index = fields_class->GetDexTypeIndex();
774 field_offset = resolved_field->GetOffset().Int32Value();
775 is_volatile = resolved_field->IsVolatile();
Ian Rogersc8b306f2012-02-17 21:34:44 -0800776 stats_->ResolvedStaticField();
Ian Rogers4103ad22012-02-06 09:18:25 -0800777 return true;
778 }
Ian Rogerse2645d32012-04-11 14:42:42 -0700779 // Search dex file for localized ssb index, may fail if field's class is a parent
780 // of the class mentioned in the dex file and there is no dex cache entry.
Ian Rogers1bddec32012-02-04 12:27:34 -0800781 std::string descriptor(FieldHelper(resolved_field).GetDeclaringClassDescriptor());
782 const DexFile::StringId* string_id =
Logan Chien4dd96f52012-02-29 01:26:58 +0800783 mUnit->dex_file_->FindStringId(descriptor);
Ian Rogers1bddec32012-02-04 12:27:34 -0800784 if (string_id != NULL) {
785 const DexFile::TypeId* type_id =
Logan Chien4dd96f52012-02-29 01:26:58 +0800786 mUnit->dex_file_->FindTypeId(mUnit->dex_file_->GetIndexForStringId(*string_id));
Elliott Hughesb25c3f62012-03-26 16:35:06 -0700787 if (type_id != NULL) {
Ian Rogers1bddec32012-02-04 12:27:34 -0800788 // medium path, needs check of static storage base being initialized
Logan Chien4dd96f52012-02-29 01:26:58 +0800789 ssb_index = mUnit->dex_file_->GetIndexForTypeId(*type_id);
Ian Rogers1bddec32012-02-04 12:27:34 -0800790 field_offset = resolved_field->GetOffset().Int32Value();
791 is_volatile = resolved_field->IsVolatile();
Ian Rogersc8b306f2012-02-17 21:34:44 -0800792 stats_->ResolvedStaticField();
Ian Rogers1bddec32012-02-04 12:27:34 -0800793 return true;
794 }
795 }
796 }
797 }
798 }
799 }
800 // Clean up any exception left by field/type resolution
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700801 if (soa.Self()->IsExceptionPending()) {
802 soa.Self()->ClearException();
Ian Rogers1bddec32012-02-04 12:27:34 -0800803 }
Ian Rogersc8b306f2012-02-17 21:34:44 -0800804 stats_->UnresolvedStaticField();
Ian Rogers1bddec32012-02-04 12:27:34 -0800805 return false; // Incomplete knowledge needs slow path.
806}
807
Ian Rogers2ed3b952012-03-17 11:49:39 -0700808void Compiler::GetCodeAndMethodForDirectCall(InvokeType type, InvokeType sharp_type, Method* method,
809 uintptr_t& direct_code, uintptr_t& direct_method) {
810 direct_code = 0;
811 direct_method = 0;
812 if (sharp_type != kStatic && sharp_type != kDirect) {
813 return;
814 }
Ian Rogers2ed3b952012-03-17 11:49:39 -0700815 bool method_code_in_boot = method->GetDeclaringClass()->GetClassLoader() == NULL;
816 if (!method_code_in_boot) {
817 return;
818 }
819 bool has_clinit_trampoline = method->IsStatic() && !method->GetDeclaringClass()->IsInitialized();
820 if (has_clinit_trampoline) {
821 return;
822 }
823 stats_->DirectCallsToBoot(type);
824 stats_->DirectMethodsToBoot(type);
Ian Rogers3fa13792012-03-18 15:53:45 -0700825 bool compiling_boot = Runtime::Current()->GetHeap()->GetSpaces().size() == 1;
826 if (compiling_boot) {
Brian Carlstrom0637e272012-03-20 01:07:52 -0700827 const bool kSupportBootImageFixup = true;
Ian Rogers3fa13792012-03-18 15:53:45 -0700828 if (kSupportBootImageFixup) {
829 MethodHelper mh(method);
830 if (IsImageClass(mh.GetDeclaringClassDescriptor())) {
Brian Carlstrom0637e272012-03-20 01:07:52 -0700831 // We can only branch directly to Methods that are resolved in the DexCache.
832 // Otherwise we won't invoke the resolution trampoline.
Ian Rogers3fa13792012-03-18 15:53:45 -0700833 direct_method = -1;
Brian Carlstrom0637e272012-03-20 01:07:52 -0700834 direct_code = -1;
Ian Rogers3fa13792012-03-18 15:53:45 -0700835 }
Ian Rogers3fa13792012-03-18 15:53:45 -0700836 }
837 } else {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700838 if (Runtime::Current()->GetHeap()->FindSpaceFromObject(method)->IsImageSpace()) {
Ian Rogers3fa13792012-03-18 15:53:45 -0700839 direct_method = reinterpret_cast<uintptr_t>(method);
840 }
841 direct_code = reinterpret_cast<uintptr_t>(method->GetCode());
Ian Rogers2ed3b952012-03-17 11:49:39 -0700842 }
Ian Rogers2ed3b952012-03-17 11:49:39 -0700843}
844
Ian Rogersfb6adba2012-03-04 21:51:51 -0800845bool Compiler::ComputeInvokeInfo(uint32_t method_idx, OatCompilationUnit* mUnit, InvokeType& type,
Ian Rogers2ed3b952012-03-17 11:49:39 -0700846 int& vtable_idx, uintptr_t& direct_code,
847 uintptr_t& direct_method) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700848 ScopedObjectAccess soa(Thread::Current());
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800849 vtable_idx = -1;
Ian Rogers2ed3b952012-03-17 11:49:39 -0700850 direct_code = 0;
851 direct_method = 0;
Ian Rogers08f753d2012-08-24 14:35:25 -0700852 Method* resolved_method =
853 ComputeMethodReferencedFromCompilingMethod(soa, mUnit, method_idx, type);
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800854 if (resolved_method != NULL) {
Ian Rogers08f753d2012-08-24 14:35:25 -0700855 // Don't try to fast-path if we don't understand the caller's class or this appears to be an
856 // Incompatible Class Change Error.
857 Class* referrer_class = ComputeCompilingMethodsClass(soa, mUnit);
858 bool icce = resolved_method->CheckIncompatibleClassChange(type);
859 if (referrer_class != NULL && !icce) {
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800860 Class* methods_class = resolved_method->GetDeclaringClass();
861 if (!referrer_class->CanAccess(methods_class) ||
862 !referrer_class->CanAccessMember(methods_class,
Ian Rogers996cc582012-02-14 22:23:29 -0800863 resolved_method->GetAccessFlags())) {
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800864 // The referring class can't access the resolved method, this may occur as a result of a
865 // protected method being made public by implementing an interface that re-declares the
Ian Rogers08f753d2012-08-24 14:35:25 -0700866 // method public. Resort to the dex file to determine the correct class for the access
867 // check.
Logan Chien4dd96f52012-02-29 01:26:58 +0800868 const DexFile& dex_file = mUnit->class_linker_->FindDexFile(referrer_class->GetDexCache());
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800869 methods_class =
Logan Chien4dd96f52012-02-29 01:26:58 +0800870 mUnit->class_linker_->ResolveType(dex_file,
871 dex_file.GetMethodId(method_idx).class_idx_,
872 referrer_class);
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800873 }
874 if (referrer_class->CanAccess(methods_class) &&
875 referrer_class->CanAccessMember(methods_class,
876 resolved_method->GetAccessFlags())) {
877 vtable_idx = resolved_method->GetMethodIndex();
Ian Rogersf320b632012-03-13 18:47:47 -0700878 const bool kEnableSharpening = true;
Ian Rogers2ed3b952012-03-17 11:49:39 -0700879 // Sharpen a virtual call into a direct call when the target is known.
880 bool can_sharpen = type == kVirtual && (resolved_method->IsFinal() ||
Ian Rogers08f753d2012-08-24 14:35:25 -0700881 methods_class->IsFinal());
882 // Ensure the vtable index will be correct to dispatch in the vtable of the super class.
jeffhao4155fcd2012-03-21 11:42:12 -0700883 can_sharpen = can_sharpen || (type == kSuper && referrer_class != methods_class &&
Ian Rogers08f753d2012-08-24 14:35:25 -0700884 referrer_class->IsSubClass(methods_class) &&
885 vtable_idx < methods_class->GetVTable()->GetLength() &&
886 methods_class->GetVTable()->Get(vtable_idx) == resolved_method);
Ian Rogers2ed3b952012-03-17 11:49:39 -0700887 if (kEnableSharpening && can_sharpen) {
888 stats_->ResolvedMethod(type);
Ian Rogersfb6adba2012-03-04 21:51:51 -0800889 // Sharpen a virtual call into a direct call. The method_idx is into referrer's
890 // dex cache, check that this resolved method is where we expect it.
891 CHECK(referrer_class->GetDexCache()->GetResolvedMethod(method_idx) == resolved_method)
Ian Rogers08f753d2012-08-24 14:35:25 -0700892 << PrettyMethod(resolved_method);
Ian Rogers2ed3b952012-03-17 11:49:39 -0700893 stats_->VirtualMadeDirect(type);
894 GetCodeAndMethodForDirectCall(type, kDirect, resolved_method, direct_code, direct_method);
895 type = kDirect;
896 return true;
897 } else if (type == kSuper) {
Ian Rogers08f753d2012-08-24 14:35:25 -0700898 // Unsharpened super calls are suspicious so go slow-path.
Ian Rogers2ed3b952012-03-17 11:49:39 -0700899 } else {
900 stats_->ResolvedMethod(type);
901 GetCodeAndMethodForDirectCall(type, type, resolved_method, direct_code, direct_method);
902 return true;
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800903 }
904 }
905 }
906 }
907 // Clean up any exception left by method/type resolution
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700908 if (soa.Self()->IsExceptionPending()) {
909 soa.Self()->ClearException();
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800910 }
Ian Rogersc8b306f2012-02-17 21:34:44 -0800911 stats_->UnresolvedMethod(type);
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800912 return false; // Incomplete knowledge needs slow path.
913}
914
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700915void Compiler::AddCodePatch(const DexFile* dex_file,
Brian Carlstromf5822582012-03-19 22:34:31 -0700916 uint32_t referrer_method_idx,
Ian Rogers08f753d2012-08-24 14:35:25 -0700917 InvokeType referrer_invoke_type,
Brian Carlstromf5822582012-03-19 22:34:31 -0700918 uint32_t target_method_idx,
Ian Rogers08f753d2012-08-24 14:35:25 -0700919 InvokeType target_invoke_type,
Ian Rogers3fa13792012-03-18 15:53:45 -0700920 size_t literal_offset) {
921 MutexLock mu(compiled_methods_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700922 code_to_patch_.push_back(new PatchInformation(dex_file,
Brian Carlstromf5822582012-03-19 22:34:31 -0700923 referrer_method_idx,
Ian Rogers08f753d2012-08-24 14:35:25 -0700924 referrer_invoke_type,
Brian Carlstromf5822582012-03-19 22:34:31 -0700925 target_method_idx,
Ian Rogers08f753d2012-08-24 14:35:25 -0700926 target_invoke_type,
Brian Carlstromf5822582012-03-19 22:34:31 -0700927 literal_offset));
Ian Rogers3fa13792012-03-18 15:53:45 -0700928}
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700929void Compiler::AddMethodPatch(const DexFile* dex_file,
Brian Carlstromf5822582012-03-19 22:34:31 -0700930 uint32_t referrer_method_idx,
Ian Rogers08f753d2012-08-24 14:35:25 -0700931 InvokeType referrer_invoke_type,
Brian Carlstromf5822582012-03-19 22:34:31 -0700932 uint32_t target_method_idx,
Ian Rogers08f753d2012-08-24 14:35:25 -0700933 InvokeType target_invoke_type,
Ian Rogers3fa13792012-03-18 15:53:45 -0700934 size_t literal_offset) {
935 MutexLock mu(compiled_methods_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700936 methods_to_patch_.push_back(new PatchInformation(dex_file,
Brian Carlstromf5822582012-03-19 22:34:31 -0700937 referrer_method_idx,
Ian Rogers08f753d2012-08-24 14:35:25 -0700938 referrer_invoke_type,
Brian Carlstromf5822582012-03-19 22:34:31 -0700939 target_method_idx,
Ian Rogers08f753d2012-08-24 14:35:25 -0700940 target_invoke_type,
Brian Carlstromf5822582012-03-19 22:34:31 -0700941 literal_offset));
Ian Rogers3fa13792012-03-18 15:53:45 -0700942}
943
Ian Rogers0399dde2012-06-06 17:09:28 -0700944class CompilationContext {
Brian Carlstrom731b2ab2012-03-06 16:53:35 -0800945 public:
Ian Rogers0399dde2012-06-06 17:09:28 -0700946 CompilationContext(ClassLinker* class_linker,
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700947 jobject class_loader,
Brian Carlstrom731b2ab2012-03-06 16:53:35 -0800948 Compiler* compiler,
Brian Carlstrom731b2ab2012-03-06 16:53:35 -0800949 const DexFile* dex_file)
950 : class_linker_(class_linker),
951 class_loader_(class_loader),
952 compiler_(compiler),
Brian Carlstrom731b2ab2012-03-06 16:53:35 -0800953 dex_file_(dex_file) {}
954
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700955 ClassLinker* GetClassLinker() const {
Brian Carlstrom731b2ab2012-03-06 16:53:35 -0800956 CHECK(class_linker_ != NULL);
957 return class_linker_;
958 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700959
960 jobject GetClassLoader() const {
Brian Carlstrom731b2ab2012-03-06 16:53:35 -0800961 return class_loader_;
962 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700963
964 Compiler* GetCompiler() const {
Brian Carlstrom731b2ab2012-03-06 16:53:35 -0800965 CHECK(compiler_ != NULL);
966 return compiler_;
967 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700968
969 const DexFile* GetDexFile() const {
Brian Carlstrom731b2ab2012-03-06 16:53:35 -0800970 CHECK(dex_file_ != NULL);
971 return dex_file_;
972 }
973
974 private:
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700975 ClassLinker* const class_linker_;
976 const jobject class_loader_;
977 Compiler* const compiler_;
978 const DexFile* const dex_file_;
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800979};
980
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700981typedef void Callback(const CompilationContext* context, size_t index);
982
983static void ForAll(CompilationContext* context, size_t begin, size_t end, Callback callback,
984 size_t thread_count);
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800985
986class WorkerThread {
987 public:
Ian Rogers0399dde2012-06-06 17:09:28 -0700988 WorkerThread(CompilationContext* context, size_t begin, size_t end, Callback callback, size_t stripe, bool spawn)
Elliott Hughes1e409252012-02-06 11:21:27 -0800989 : spawn_(spawn), context_(context), begin_(begin), end_(end), callback_(callback), stripe_(stripe) {
990 if (spawn_) {
Elliott Hughesbf1b4572012-05-24 19:11:39 -0700991 // Mac OS stacks are only 512KiB. Make sure we have the same stack size on all platforms.
992 pthread_attr_t attr;
993 CHECK_PTHREAD_CALL(pthread_attr_init, (&attr), "new compiler worker thread");
994 CHECK_PTHREAD_CALL(pthread_attr_setstacksize, (&attr, 1*MB), "new compiler worker thread");
995 CHECK_PTHREAD_CALL(pthread_create, (&pthread_, &attr, &Go, this), "new compiler worker thread");
996 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attr), "new compiler worker thread");
Elliott Hughes1e409252012-02-06 11:21:27 -0800997 }
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800998 }
999
1000 ~WorkerThread() {
Elliott Hughes1e409252012-02-06 11:21:27 -08001001 if (spawn_) {
1002 CHECK_PTHREAD_CALL(pthread_join, (pthread_, NULL), "compiler worker shutdown");
1003 }
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001004 }
1005
1006 private:
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001007 static void* Go(void* arg) LOCKS_EXCLUDED(GlobalSynchronization::mutator_lock_) {
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001008 WorkerThread* worker = reinterpret_cast<WorkerThread*>(arg);
1009 Runtime* runtime = Runtime::Current();
Elliott Hughes1e409252012-02-06 11:21:27 -08001010 if (worker->spawn_) {
Elliott Hughes462c9442012-03-23 18:47:50 -07001011 runtime->AttachCurrentThread("Compiler Worker", true, NULL);
Elliott Hughes1e409252012-02-06 11:21:27 -08001012 }
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001013 worker->Run();
Elliott Hughes1e409252012-02-06 11:21:27 -08001014 if (worker->spawn_) {
Elliott Hughes1e409252012-02-06 11:21:27 -08001015 runtime->DetachCurrentThread();
1016 }
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001017 return NULL;
1018 }
1019
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001020 void Go() LOCKS_EXCLUDED(GlobalSynchronization::mutator_lock_) {
Elliott Hughes1e409252012-02-06 11:21:27 -08001021 Go(this);
1022 }
1023
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001024 void Run() LOCKS_EXCLUDED(GlobalSynchronization::mutator_lock_) {
Brian Carlstrom64277f32012-03-26 23:53:34 -07001025 Thread* self = Thread::Current();
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001026 for (size_t i = begin_; i < end_; i += stripe_) {
1027 callback_(context_, i);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001028 self->AssertNoPendingException();
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001029 }
1030 }
1031
1032 pthread_t pthread_;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001033 // Was this thread spawned or is it the main thread?
1034 const bool spawn_;
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001035
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001036 const CompilationContext* const context_;
1037 const size_t begin_;
1038 const size_t end_;
Ian Rogers1b09b092012-08-20 15:35:52 -07001039 Callback* callback_;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001040 const size_t stripe_;
Elliott Hughes1e409252012-02-06 11:21:27 -08001041
Ian Rogers0399dde2012-06-06 17:09:28 -07001042 friend void ForAll(CompilationContext*, size_t, size_t, Callback, size_t);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001043};
1044
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001045static void ForAll(CompilationContext* context, size_t begin, size_t end, Callback callback,
1046 size_t thread_count)
1047 LOCKS_EXCLUDED(GlobalSynchronization::mutator_lock_) {
Brian Carlstrom64277f32012-03-26 23:53:34 -07001048 Thread* self = Thread::Current();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001049 self->AssertNoPendingException();
Elliott Hughes1e409252012-02-06 11:21:27 -08001050 CHECK_GT(thread_count, 0U);
Elliott Hughes81d91512012-02-03 16:38:43 -08001051
Elliott Hughes1e409252012-02-06 11:21:27 -08001052 std::vector<WorkerThread*> threads;
Elliott Hughes81d91512012-02-03 16:38:43 -08001053 for (size_t i = 0; i < thread_count; ++i) {
Elliott Hughes1e409252012-02-06 11:21:27 -08001054 threads.push_back(new WorkerThread(context, begin + i, end, callback, thread_count, (i != 0)));
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001055 }
Elliott Hughes1e409252012-02-06 11:21:27 -08001056 threads[0]->Go();
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001057
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001058 // Ensure we're suspended while we're blocked waiting for the other threads to finish (worker
1059 // thread destructor's called below perform join).
1060 {
1061 MutexLock mu(*GlobalSynchronization::thread_suspend_count_lock_);
1062 CHECK_NE(self->GetState(), kRunnable);
1063 }
Elliott Hughes81d91512012-02-03 16:38:43 -08001064 STLDeleteElements(&threads);
1065}
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001066
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001067// Return true if the class should be skipped during compilation. We
1068// never skip classes in the boot class loader. However, if we have a
1069// non-boot class loader and we can resolve the class in the boot
1070// class loader, we do skip the class. This happens if an app bundles
1071// classes found in the boot classpath. Since at runtime we will
1072// select the class from the boot classpath, do not attempt to resolve
1073// or compile it now.
1074static bool SkipClass(ClassLoader* class_loader,
1075 const DexFile& dex_file,
1076 const DexFile::ClassDef& class_def)
1077 SHARED_LOCKS_REQUIRED(GlobalSynchronization::mutator_lock_) {
1078 if (class_loader == NULL) {
1079 return false;
1080 }
1081 const char* descriptor = dex_file.GetClassDescriptor(class_def);
1082 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1083 Class* klass = class_linker->FindClass(descriptor, NULL);
1084 if (klass == NULL) {
1085 Thread* self = Thread::Current();
1086 CHECK(self->IsExceptionPending());
1087 self->ClearException();
1088 return false;
1089 }
1090 return true;
1091}
1092
1093static void ResolveClassFieldsAndMethods(const CompilationContext* context, size_t class_def_index)
1094 LOCKS_EXCLUDED(GlobalSynchronization::mutator_lock_) {
1095 ScopedObjectAccess soa(Thread::Current());
1096 ClassLoader* class_loader = soa.Decode<ClassLoader*>(context->GetClassLoader());
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001097 const DexFile& dex_file = *context->GetDexFile();
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001098
1099 // Method and Field are the worst. We can't resolve without either
1100 // context from the code use (to disambiguate virtual vs direct
1101 // method and instance vs static field) or from class
1102 // definitions. While the compiler will resolve what it can as it
1103 // needs it, here we try to resolve fields and methods used in class
1104 // definitions, since many of them many never be referenced by
1105 // generated code.
1106 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001107 if (SkipClass(class_loader, dex_file, class_def)) {
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001108 return;
1109 }
1110
1111 // Note the class_data pointer advances through the headers,
1112 // static fields, instance fields, direct methods, and virtual
1113 // methods.
1114 const byte* class_data = dex_file.GetClassData(class_def);
1115 if (class_data == NULL) {
1116 // empty class such as a marker interface
1117 return;
1118 }
Brian Carlstrom5ead0952011-11-28 22:55:52 -08001119 Thread* self = Thread::Current();
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001120 ClassLinker* class_linker = context->GetClassLinker();
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001121 DexCache* dex_cache = class_linker->FindDexCache(dex_file);
1122 ClassDataItemIterator it(dex_file, class_data);
1123 while (it.HasNextStaticField()) {
1124 Field* field = class_linker->ResolveField(dex_file, it.GetMemberIndex(), dex_cache,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001125 class_loader, true);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001126 if (field == NULL) {
1127 CHECK(self->IsExceptionPending());
1128 self->ClearException();
1129 }
1130 it.Next();
1131 }
1132 while (it.HasNextInstanceField()) {
1133 Field* field = class_linker->ResolveField(dex_file, it.GetMemberIndex(), dex_cache,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001134 class_loader, false);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001135 if (field == NULL) {
1136 CHECK(self->IsExceptionPending());
1137 self->ClearException();
1138 }
1139 it.Next();
1140 }
1141 while (it.HasNextDirectMethod()) {
1142 Method* method = class_linker->ResolveMethod(dex_file, it.GetMemberIndex(), dex_cache,
jeffhaoc0228b82012-08-29 18:15:05 -07001143 class_loader, NULL, it.GetMethodInvokeType(class_def));
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001144 if (method == NULL) {
1145 CHECK(self->IsExceptionPending());
1146 self->ClearException();
1147 }
1148 it.Next();
1149 }
1150 while (it.HasNextVirtualMethod()) {
1151 Method* method = class_linker->ResolveMethod(dex_file, it.GetMemberIndex(), dex_cache,
jeffhaoc0228b82012-08-29 18:15:05 -07001152 class_loader, NULL, it.GetMethodInvokeType(class_def));
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001153 if (method == NULL) {
1154 CHECK(self->IsExceptionPending());
1155 self->ClearException();
1156 }
1157 it.Next();
1158 }
1159 DCHECK(!it.HasNext());
1160}
1161
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001162static void ResolveType(const CompilationContext* context, size_t type_idx)
1163 LOCKS_EXCLUDED(GlobalSynchronization::mutator_lock_) {
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001164 // Class derived values are more complicated, they require the linker and loader.
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001165 ScopedObjectAccess soa(Thread::Current());
1166 ClassLinker* class_linker = context->GetClassLinker();
1167 const DexFile& dex_file = *context->GetDexFile();
1168 DexCache* dex_cache = class_linker->FindDexCache(dex_file);
1169 ClassLoader* class_loader = soa.Decode<ClassLoader*>(context->GetClassLoader());
1170 Class* klass = class_linker->ResolveType(dex_file, type_idx, dex_cache, class_loader);
1171
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001172 if (klass == NULL) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001173 CHECK(soa.Self()->IsExceptionPending());
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001174 Thread::Current()->ClearException();
1175 }
1176}
1177
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001178void Compiler::ResolveDexFile(jobject class_loader, const DexFile& dex_file,
1179 TimingLogger& timings) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001180 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1181
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001182 // TODO: we could resolve strings here, although the string table is largely filled with class
1183 // and method names.
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001184
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001185 CompilationContext context(class_linker, class_loader, this, &dex_file);
1186 ForAll(&context, 0, dex_file.NumTypeIds(), ResolveType, thread_count_);
Elliott Hughesff738062012-02-03 15:00:42 -08001187 timings.AddSplit("Resolve " + dex_file.GetLocation() + " Types");
Brian Carlstrom845490b2011-09-19 15:56:53 -07001188
Elliott Hughes5523ee02012-02-03 18:18:34 -08001189 ForAll(&context, 0, dex_file.NumClassDefs(), ResolveClassFieldsAndMethods, thread_count_);
Elliott Hughesff738062012-02-03 15:00:42 -08001190 timings.AddSplit("Resolve " + dex_file.GetLocation() + " MethodsAndFields");
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001191}
1192
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001193void Compiler::Verify(jobject class_loader, const std::vector<const DexFile*>& dex_files) {
Brian Carlstromae826982011-11-09 01:33:42 -08001194 for (size_t i = 0; i != dex_files.size(); ++i) {
1195 const DexFile* dex_file = dex_files[i];
jeffhao98eacac2011-09-14 16:11:53 -07001196 CHECK(dex_file != NULL);
1197 VerifyDexFile(class_loader, *dex_file);
1198 }
1199}
1200
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001201static void VerifyClass(const CompilationContext* context, size_t class_def_index)
1202 LOCKS_EXCLUDED(GlobalSynchronization::mutator_lock_) {
1203 ScopedObjectAccess soa(Thread::Current());
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001204 const DexFile::ClassDef& class_def = context->GetDexFile()->GetClassDef(class_def_index);
1205 const char* descriptor = context->GetDexFile()->GetClassDescriptor(class_def);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001206 Class* klass =
1207 context->GetClassLinker()->FindClass(descriptor,
1208 soa.Decode<ClassLoader*>(context->GetClassLoader()));
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001209 if (klass == NULL) {
1210 Thread* self = Thread::Current();
1211 CHECK(self->IsExceptionPending());
1212 self->ClearException();
jeffhaof56197c2012-03-05 18:01:54 -08001213
1214 /*
1215 * At compile time, we can still structurally verify the class even if FindClass fails.
1216 * This is to ensure the class is structurally sound for compilation. An unsound class
1217 * will be rejected by the verifier and later skipped during compilation in the compiler.
1218 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001219 DexCache* dex_cache = context->GetClassLinker()->FindDexCache(*context->GetDexFile());
jeffhaof56197c2012-03-05 18:01:54 -08001220 std::string error_msg;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001221 if (verifier::MethodVerifier::VerifyClass(context->GetDexFile(),
1222 dex_cache,
1223 soa.Decode<ClassLoader*>(context->GetClassLoader()),
1224 class_def_index, error_msg) ==
1225 verifier::MethodVerifier::kHardFailure) {
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001226 const DexFile::ClassDef& class_def = context->GetDexFile()->GetClassDef(class_def_index);
jeffhaof56197c2012-03-05 18:01:54 -08001227 LOG(ERROR) << "Verification failed on class "
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001228 << PrettyDescriptor(context->GetDexFile()->GetClassDescriptor(class_def))
jeffhaof56197c2012-03-05 18:01:54 -08001229 << " because: " << error_msg;
1230 }
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001231 return;
1232 }
1233 CHECK(klass->IsResolved()) << PrettyClass(klass);
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001234 context->GetClassLinker()->VerifyClass(klass);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001235
1236 if (klass->IsErroneous()) {
1237 // ClassLinker::VerifyClass throws, which isn't useful in the compiler.
1238 CHECK(Thread::Current()->IsExceptionPending());
1239 Thread::Current()->ClearException();
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001240 }
1241
jeffhaof1e6b7c2012-06-05 18:33:30 -07001242 CHECK(klass->IsCompileTimeVerified() || klass->IsErroneous()) << PrettyClass(klass);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001243 CHECK(!Thread::Current()->IsExceptionPending()) << PrettyTypeOf(Thread::Current()->GetException());
1244}
1245
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001246void Compiler::VerifyDexFile(jobject class_loader, const DexFile& dex_file) {
jeffhaob4df5142011-09-19 20:25:32 -07001247 dex_file.ChangePermissions(PROT_READ | PROT_WRITE);
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07001248
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001249 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001250 jobject dex_cache;
1251 {
1252 ScopedObjectAccess soa(Thread::Current());
1253 ScopedLocalRef<jobject>
1254 dex_cache_local(soa.Env(),
1255 soa.AddLocalReference<jobject>(class_linker->FindDexCache(dex_file)));
1256 dex_cache = soa.Env()->NewGlobalRef(dex_cache_local.get());
1257 }
1258 CompilationContext context(class_linker, class_loader, this, &dex_file);
Elliott Hughes5523ee02012-02-03 18:18:34 -08001259 ForAll(&context, 0, dex_file.NumClassDefs(), VerifyClass, thread_count_);
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07001260
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001261 Thread::Current()->GetJniEnv()->DeleteGlobalRef(dex_cache);
jeffhaob4df5142011-09-19 20:25:32 -07001262 dex_file.ChangePermissions(PROT_READ);
Brian Carlstroma5a97a22011-09-15 14:08:49 -07001263}
1264
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001265void Compiler::InitializeClassesWithoutClinit(jobject class_loader,
Brian Carlstromae826982011-11-09 01:33:42 -08001266 const std::vector<const DexFile*>& dex_files) {
1267 for (size_t i = 0; i != dex_files.size(); ++i) {
1268 const DexFile* dex_file = dex_files[i];
Brian Carlstroma5a97a22011-09-15 14:08:49 -07001269 CHECK(dex_file != NULL);
1270 InitializeClassesWithoutClinit(class_loader, *dex_file);
1271 }
1272}
1273
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001274void Compiler::InitializeClassesWithoutClinit(jobject jni_class_loader, const DexFile& dex_file) {
1275 ScopedObjectAccess soa(Thread::Current());
1276 ClassLoader* class_loader = soa.Decode<ClassLoader*>(jni_class_loader);
Brian Carlstroma5a97a22011-09-15 14:08:49 -07001277 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Brian Carlstromffca45d2011-09-16 12:10:49 -07001278 for (size_t class_def_index = 0; class_def_index < dex_file.NumClassDefs(); class_def_index++) {
1279 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
Brian Carlstroma5a97a22011-09-15 14:08:49 -07001280 const char* descriptor = dex_file.GetClassDescriptor(class_def);
1281 Class* klass = class_linker->FindClass(descriptor, class_loader);
Brian Carlstrom27ec9612011-09-19 20:20:38 -07001282 if (klass != NULL) {
jeffhao1ac29442012-03-26 11:37:32 -07001283 if (klass->IsVerified()) {
1284 // Only try to initialize classes that were successfully verified.
Ian Rogers0045a292012-03-31 21:08:41 -07001285 bool compiling_boot = Runtime::Current()->GetHeap()->GetSpaces().size() == 1;
1286 bool can_init_static_fields = compiling_boot &&
1287 IsImageClass(descriptor);
1288 class_linker->EnsureInitialized(klass, false, can_init_static_fields);
jeffhao1ac29442012-03-26 11:37:32 -07001289 }
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001290 // record the final class status if necessary
1291 Class::Status status = klass->GetStatus();
1292 ClassReference ref(&dex_file, class_def_index);
1293 CompiledClass* compiled_class = GetCompiledClass(ref);
1294 if (compiled_class == NULL) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001295 MutexLock mu(compiled_classes_lock_);
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001296 compiled_class = new CompiledClass(status);
Elliott Hughesa0e18062012-04-13 15:59:59 -07001297 compiled_classes_.Put(ref, compiled_class);
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001298 } else {
1299 DCHECK_EQ(status, compiled_class->GetStatus());
1300 }
Brian Carlstrom27ec9612011-09-19 20:20:38 -07001301 }
1302 // clear any class not found or verification exceptions
1303 Thread::Current()->ClearException();
Brian Carlstromffca45d2011-09-16 12:10:49 -07001304 }
1305
1306 DexCache* dex_cache = class_linker->FindDexCache(dex_file);
1307 for (size_t type_idx = 0; type_idx < dex_cache->NumResolvedTypes(); type_idx++) {
1308 Class* klass = class_linker->ResolveType(dex_file, type_idx, dex_cache, class_loader);
Brian Carlstrom27ec9612011-09-19 20:20:38 -07001309 if (klass == NULL) {
1310 Thread::Current()->ClearException();
1311 } else if (klass->IsInitialized()) {
Brian Carlstromffca45d2011-09-16 12:10:49 -07001312 dex_cache->GetInitializedStaticStorage()->Set(type_idx, klass);
1313 }
jeffhao98eacac2011-09-14 16:11:53 -07001314 }
1315}
1316
Shih-wei Liao90dc30f2012-04-23 02:03:30 -07001317// TODO: This class shares some implementation with WorkerThread. We don't want
1318// to perturb the non-LLVM side at the same time. Staging the refactoring for
1319// the future.
1320class DexFilesWorkerThread {
1321 public:
Ian Rogers0399dde2012-06-06 17:09:28 -07001322 DexFilesWorkerThread(CompilationContext *worker_context, Callback class_callback,
Shih-wei Liao90dc30f2012-04-23 02:03:30 -07001323 const std::vector<const DexFile*>& dex_files,
1324 volatile int32_t* shared_class_index, bool spawn)
1325 : spawn_(spawn), worker_context_(worker_context),
1326 class_callback_(class_callback), dex_files_(dex_files),
1327 context_(NULL), shared_class_index_(shared_class_index) {
1328 if (spawn_) {
TDYa1278cea5fd2012-05-29 22:22:32 -07001329 pthread_attr_t attr;
1330 CHECK_PTHREAD_CALL(pthread_attr_init, (&attr), "new compiler worker thread");
TDYa12761b409c2012-06-05 23:54:30 -07001331 CHECK_PTHREAD_CALL(pthread_attr_setstacksize, (&attr, 1*MB), "new compiler worker thread");
TDYa1278cea5fd2012-05-29 22:22:32 -07001332 CHECK_PTHREAD_CALL(pthread_create, (&pthread_, &attr, &Go, this), "new compiler worker thread");
1333 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attr), "new compiler worker thread");
Shih-wei Liao90dc30f2012-04-23 02:03:30 -07001334 }
1335 }
1336
1337 ~DexFilesWorkerThread() {
1338 if (spawn_) {
1339 CHECK_PTHREAD_CALL(pthread_join, (pthread_, NULL), "compiler worker shutdown");
1340 }
1341 delete context_;
1342 }
1343
1344 private:
1345 static void* Go(void* arg) {
1346 DexFilesWorkerThread* worker = reinterpret_cast<DexFilesWorkerThread*>(arg);
1347 Runtime* runtime = Runtime::Current();
1348 if (worker->spawn_) {
1349 runtime->AttachCurrentThread("Compiler Worker", true, NULL);
1350 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001351 {
1352 ScopedObjectAccess soa(Thread::Current());
1353 worker->Run();
1354 }
Shih-wei Liao90dc30f2012-04-23 02:03:30 -07001355 if (worker->spawn_) {
Shih-wei Liao90dc30f2012-04-23 02:03:30 -07001356 runtime->DetachCurrentThread();
1357 }
1358 return NULL;
1359 }
1360
1361 void Go() {
1362 Go(this);
1363 }
1364
1365 void SwitchToDexFile(size_t dex_file_index) {
Elliott Hughesa21039c2012-06-21 12:09:25 -07001366 CHECK_LT(dex_file_index, dex_files_.size());
Shih-wei Liao90dc30f2012-04-23 02:03:30 -07001367
1368 const DexFile* dex_file = dex_files_[dex_file_index];
1369 CHECK(dex_file != NULL);
1370
1371 // Destroy the old context
1372 delete context_;
1373
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001374 // TODO: Add a callback to let the client specify the class_linker in the context for the
1375 // current working dex file.
Ian Rogers0399dde2012-06-06 17:09:28 -07001376 context_ = new CompilationContext(/* class_linker */NULL,
1377 worker_context_->GetClassLoader(),
1378 worker_context_->GetCompiler(),
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001379 dex_file);
Shih-wei Liao90dc30f2012-04-23 02:03:30 -07001380
1381 CHECK(context_ != NULL);
1382 }
1383
1384 void Run() {
1385 Thread* self = Thread::Current();
1386 size_t cur_dex_file_index = 0;
1387 size_t class_index_base = 0;
1388
1389 SwitchToDexFile(0);
1390
1391 while (true) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001392 size_t class_index = static_cast<size_t>(android_atomic_inc(shared_class_index_));
Shih-wei Liao90dc30f2012-04-23 02:03:30 -07001393
1394 const DexFile* dex_file;
1395 do {
1396 dex_file = dex_files_[cur_dex_file_index];
1397
1398 if (class_index < (class_index_base + dex_file->NumClassDefs())) {
1399 break;
1400 }
1401 class_index_base += dex_file->NumClassDefs();
1402
1403 cur_dex_file_index++;
1404 } while (cur_dex_file_index < dex_files_.size());
1405
1406 if (cur_dex_file_index >= dex_files_.size()) {
1407 return;
1408 }
1409
1410 if (dex_file != context_->GetDexFile()) {
1411 SwitchToDexFile(cur_dex_file_index);
1412 }
1413
1414 class_index -= class_index_base;
1415 class_callback_(context_, class_index);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001416 self->AssertNoPendingException();
Shih-wei Liao90dc30f2012-04-23 02:03:30 -07001417 }
1418 }
1419
1420 pthread_t pthread_;
1421 bool spawn_;
1422
Ian Rogers0399dde2012-06-06 17:09:28 -07001423 CompilationContext* worker_context_;
Shih-wei Liao90dc30f2012-04-23 02:03:30 -07001424 Callback* class_callback_;
1425 const std::vector<const DexFile*>& dex_files_;
1426
Ian Rogers0399dde2012-06-06 17:09:28 -07001427 CompilationContext* context_;
Shih-wei Liao90dc30f2012-04-23 02:03:30 -07001428 volatile int32_t* shared_class_index_;
1429
Ian Rogers0399dde2012-06-06 17:09:28 -07001430 friend void ForClassesInAllDexFiles(CompilationContext*,
Shih-wei Liao90dc30f2012-04-23 02:03:30 -07001431 const std::vector<const DexFile*>&,
1432 Callback, size_t);
1433};
1434
Ian Rogers0399dde2012-06-06 17:09:28 -07001435void ForClassesInAllDexFiles(CompilationContext* worker_context,
Shih-wei Liao90dc30f2012-04-23 02:03:30 -07001436 const std::vector<const DexFile*>& dex_files,
1437 Callback class_callback, size_t thread_count) {
1438 Thread* self = Thread::Current();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001439 self->AssertNoPendingException();
Shih-wei Liao90dc30f2012-04-23 02:03:30 -07001440 CHECK_GT(thread_count, 0U);
1441
1442 std::vector<DexFilesWorkerThread*> threads;
1443 volatile int32_t shared_class_index = 0;
1444
1445 for (size_t i = 0; i < thread_count; ++i) {
1446 threads.push_back(new DexFilesWorkerThread(worker_context, class_callback,
1447 dex_files, &shared_class_index,
1448 /* spawn */ (i != 0)));
1449 }
1450 threads[0]->Go();
1451
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001452 // Ensure we're suspended while we're blocked waiting for the other threads to finish (worker
1453 // thread destructor's called below perform join).
1454 {
1455 MutexLock mu(*GlobalSynchronization::thread_suspend_count_lock_);
1456 CHECK_NE(self->GetState(), kRunnable);
1457 }
Shih-wei Liao90dc30f2012-04-23 02:03:30 -07001458 STLDeleteElements(&threads);
1459}
1460
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001461void Compiler::Compile(jobject class_loader, const std::vector<const DexFile*>& dex_files) {
Shih-wei Liao90dc30f2012-04-23 02:03:30 -07001462#if defined(ART_USE_LLVM_COMPILER)
1463 if (dex_files.size() <= 0) {
1464 return; // No dex file
1465 }
Ian Rogersc05f85a2012-08-14 15:39:34 -07001466 CompilationContext context(NULL, class_loader, this, NULL);
Shih-wei Liao90dc30f2012-04-23 02:03:30 -07001467 ForClassesInAllDexFiles(&context, dex_files, Compiler::CompileClass, thread_count_);
1468#else
Brian Carlstromae826982011-11-09 01:33:42 -08001469 for (size_t i = 0; i != dex_files.size(); ++i) {
1470 const DexFile* dex_file = dex_files[i];
Brian Carlstrom83db7722011-08-26 17:32:56 -07001471 CHECK(dex_file != NULL);
1472 CompileDexFile(class_loader, *dex_file);
1473 }
Shih-wei Liao90dc30f2012-04-23 02:03:30 -07001474#endif
Brian Carlstrom83db7722011-08-26 17:32:56 -07001475}
1476
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001477void Compiler::CompileClass(const CompilationContext* context, size_t class_def_index) {
1478 jobject class_loader = context->GetClassLoader();
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001479 const DexFile& dex_file = *context->GetDexFile();
Elliott Hughesc225caa2012-02-03 15:43:37 -08001480 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001481 {
1482 ScopedObjectAccess soa(Thread::Current());
1483 ClassLoader* class_loader = soa.Decode<ClassLoader*>(context->GetClassLoader());
1484 if (SkipClass(class_loader, dex_file, class_def)) {
1485 return;
1486 }
Brian Carlstrom5ead0952011-11-28 22:55:52 -08001487 }
jeffhaod1224c72012-02-29 13:43:08 -08001488 ClassReference ref(&dex_file, class_def_index);
1489 // Skip compiling classes with generic verifier failures since they will still fail at runtime
Ian Rogers776ac1f2012-04-13 23:36:36 -07001490 if (verifier::MethodVerifier::IsClassRejected(ref)) {
jeffhaod1224c72012-02-29 13:43:08 -08001491 return;
1492 }
Ian Rogers0571d352011-11-03 19:51:38 -07001493 const byte* class_data = dex_file.GetClassData(class_def);
1494 if (class_data == NULL) {
1495 // empty class, probably a marker interface
1496 return;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001497 }
Ian Rogers0571d352011-11-03 19:51:38 -07001498 ClassDataItemIterator it(dex_file, class_data);
1499 // Skip fields
1500 while (it.HasNextStaticField()) {
1501 it.Next();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001502 }
Ian Rogers0571d352011-11-03 19:51:38 -07001503 while (it.HasNextInstanceField()) {
1504 it.Next();
1505 }
1506 // Compile direct methods
Brian Carlstrom68adbe42012-05-11 17:18:08 -07001507 int64_t previous_direct_method_idx = -1;
Ian Rogers0571d352011-11-03 19:51:38 -07001508 while (it.HasNextDirectMethod()) {
Brian Carlstrom6f29d0e2012-05-11 15:50:29 -07001509 uint32_t method_idx = it.GetMemberIndex();
1510 if (method_idx == previous_direct_method_idx) {
1511 // smali can create dex files with two encoded_methods sharing the same method_idx
1512 // http://code.google.com/p/smali/issues/detail?id=119
1513 it.Next();
1514 continue;
1515 }
1516 previous_direct_method_idx = method_idx;
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001517 context->GetCompiler()->CompileMethod(it.GetMethodCodeItem(), it.GetMemberAccessFlags(),
Ian Rogers08f753d2012-08-24 14:35:25 -07001518 it.GetMethodInvokeType(class_def), method_idx,
1519 class_loader, dex_file);
Ian Rogers0571d352011-11-03 19:51:38 -07001520 it.Next();
1521 }
1522 // Compile virtual methods
Brian Carlstrom68adbe42012-05-11 17:18:08 -07001523 int64_t previous_virtual_method_idx = -1;
Ian Rogers0571d352011-11-03 19:51:38 -07001524 while (it.HasNextVirtualMethod()) {
Brian Carlstrom6f29d0e2012-05-11 15:50:29 -07001525 uint32_t method_idx = it.GetMemberIndex();
1526 if (method_idx == previous_virtual_method_idx) {
1527 // smali can create dex files with two encoded_methods sharing the same method_idx
1528 // http://code.google.com/p/smali/issues/detail?id=119
1529 it.Next();
1530 continue;
1531 }
1532 previous_virtual_method_idx = method_idx;
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001533 context->GetCompiler()->CompileMethod(it.GetMethodCodeItem(), it.GetMemberAccessFlags(),
Ian Rogers08f753d2012-08-24 14:35:25 -07001534 it.GetMethodInvokeType(class_def), method_idx,
1535 class_loader, dex_file);
Ian Rogers0571d352011-11-03 19:51:38 -07001536 it.Next();
1537 }
1538 DCHECK(!it.HasNext());
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001539}
1540
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001541void Compiler::CompileDexFile(jobject class_loader, const DexFile& dex_file) {
1542 CompilationContext context(NULL, class_loader, this, &dex_file);
Elliott Hughes5523ee02012-02-03 18:18:34 -08001543 ForAll(&context, 0, dex_file.NumClassDefs(), Compiler::CompileClass, thread_count_);
Elliott Hughesc225caa2012-02-03 15:43:37 -08001544}
1545
Elliott Hughesa0e18062012-04-13 15:59:59 -07001546static std::string MakeInvokeStubKey(bool is_static, const char* shorty) {
1547 std::string key(shorty);
1548 if (is_static) {
1549 key += "$"; // Must not be a shorty type character.
1550 }
1551 return key;
1552}
1553
Ian Rogersa3760aa2011-11-14 14:32:37 -08001554void Compiler::CompileMethod(const DexFile::CodeItem* code_item, uint32_t access_flags,
Ian Rogers08f753d2012-08-24 14:35:25 -07001555 InvokeType invoke_type, uint32_t method_idx, jobject class_loader,
Ian Rogersa3760aa2011-11-14 14:32:37 -08001556 const DexFile& dex_file) {
Elliott Hughesf09afe82011-10-16 14:24:21 -07001557 CompiledMethod* compiled_method = NULL;
Elliott Hughesbb551fa2012-01-25 16:35:29 -08001558 uint64_t start_ns = NanoTime();
Logan Chien4dd96f52012-02-29 01:26:58 +08001559
Ian Rogers169c9a72011-11-13 20:13:17 -08001560 if ((access_flags & kAccNative) != 0) {
Ian Rogers57b86d42012-03-27 16:05:41 -07001561 compiled_method = (*jni_compiler_)(*this, access_flags, method_idx, dex_file);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07001562 CHECK(compiled_method != NULL);
Ian Rogers169c9a72011-11-13 20:13:17 -08001563 } else if ((access_flags & kAccAbstract) != 0) {
Brian Carlstrom2cc022b2011-08-25 10:05:39 -07001564 } else {
Ian Rogers08f753d2012-08-24 14:35:25 -07001565 compiled_method = (*compiler_)(*this, code_item, access_flags, invoke_type, method_idx,
1566 class_loader, dex_file);
Elliott Hughesbb551fa2012-01-25 16:35:29 -08001567 CHECK(compiled_method != NULL) << PrettyMethod(method_idx, dex_file);
1568 }
Ian Rogers3bb17a62012-01-27 23:56:44 -08001569 uint64_t duration_ns = NanoTime() - start_ns;
buzbee5abfa3e2012-01-31 17:01:43 -08001570 if (duration_ns > MsToNs(100)) {
Elliott Hughesbb551fa2012-01-25 16:35:29 -08001571 LOG(WARNING) << "Compilation of " << PrettyMethod(method_idx, dex_file)
Ian Rogers3bb17a62012-01-27 23:56:44 -08001572 << " took " << PrettyDuration(duration_ns);
Elliott Hughesf09afe82011-10-16 14:24:21 -07001573 }
1574
1575 if (compiled_method != NULL) {
Ian Rogers0571d352011-11-03 19:51:38 -07001576 MethodReference ref(&dex_file, method_idx);
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001577 CHECK(GetCompiledMethod(ref) == NULL) << PrettyMethod(method_idx, dex_file);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001578 {
1579 MutexLock mu(compiled_methods_lock_);
1580 compiled_methods_.Put(ref, compiled_method);
1581 }
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001582 DCHECK(GetCompiledMethod(ref) != NULL) << PrettyMethod(method_idx, dex_file);
Brian Carlstrom2cc022b2011-08-25 10:05:39 -07001583 }
Brian Carlstrom9baa4ae2011-09-01 21:14:14 -07001584
Ian Rogers45619fc2012-02-29 11:15:25 -08001585 uint32_t shorty_len;
1586 const char* shorty = dex_file.GetMethodShorty(dex_file.GetMethodId(method_idx), &shorty_len);
Ian Rogers169c9a72011-11-13 20:13:17 -08001587 bool is_static = (access_flags & kAccStatic) != 0;
Elliott Hughesa0e18062012-04-13 15:59:59 -07001588 std::string key(MakeInvokeStubKey(is_static, shorty));
1589 const CompiledInvokeStub* compiled_invoke_stub = FindInvokeStub(key);
Ian Rogers0571d352011-11-03 19:51:38 -07001590 if (compiled_invoke_stub == NULL) {
Shih-wei Liaoc4c98812012-03-10 21:55:51 -08001591 compiled_invoke_stub = (*create_invoke_stub_)(*this, is_static, shorty, shorty_len);
Ian Rogers0571d352011-11-03 19:51:38 -07001592 CHECK(compiled_invoke_stub != NULL);
Elliott Hughesa0e18062012-04-13 15:59:59 -07001593 InsertInvokeStub(key, compiled_invoke_stub);
Ian Rogers2c8f6532011-09-02 17:16:34 -07001594 }
Logan Chien7a2a23a2012-06-06 11:01:00 +08001595
1596#if defined(ART_USE_LLVM_COMPILER)
1597 if (!is_static) {
1598 const CompiledInvokeStub* compiled_proxy_stub = FindProxyStub(shorty);
1599 if (compiled_proxy_stub == NULL) {
1600 compiled_proxy_stub = (*create_proxy_stub_)(*this, shorty, shorty_len);
1601 CHECK(compiled_proxy_stub != NULL);
1602 InsertProxyStub(shorty, compiled_proxy_stub);
1603 }
1604 }
1605#endif
1606
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001607 if (Thread::Current()->IsExceptionPending()) {
1608 ScopedObjectAccess soa(Thread::Current());
1609 LOG(FATAL) << "Unexpected exception compiling: " << PrettyMethod(method_idx, dex_file) << "\n"
1610 << Thread::Current()->GetException()->Dump();
1611 }
Brian Carlstrom3320cf42011-10-04 14:58:28 -07001612}
1613
Elliott Hughesa0e18062012-04-13 15:59:59 -07001614const CompiledInvokeStub* Compiler::FindInvokeStub(bool is_static, const char* shorty) const {
1615 const std::string key(MakeInvokeStubKey(is_static, shorty));
1616 return FindInvokeStub(key);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07001617}
1618
Elliott Hughesa0e18062012-04-13 15:59:59 -07001619const CompiledInvokeStub* Compiler::FindInvokeStub(const std::string& key) const {
Elliott Hughesc225caa2012-02-03 15:43:37 -08001620 MutexLock mu(compiled_invoke_stubs_lock_);
Ian Rogers0571d352011-11-03 19:51:38 -07001621 InvokeStubTable::const_iterator it = compiled_invoke_stubs_.find(key);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07001622 if (it == compiled_invoke_stubs_.end()) {
1623 return NULL;
Ian Rogers0571d352011-11-03 19:51:38 -07001624 } else {
1625 DCHECK(it->second != NULL);
1626 return it->second;
1627 }
1628}
1629
Elliott Hughesa0e18062012-04-13 15:59:59 -07001630void Compiler::InsertInvokeStub(const std::string& key,
Ian Rogers0571d352011-11-03 19:51:38 -07001631 const CompiledInvokeStub* compiled_invoke_stub) {
Elliott Hughesc225caa2012-02-03 15:43:37 -08001632 MutexLock mu(compiled_invoke_stubs_lock_);
Elliott Hughesa0e18062012-04-13 15:59:59 -07001633 InvokeStubTable::iterator it = compiled_invoke_stubs_.find(key);
1634 if (it != compiled_invoke_stubs_.end()) {
1635 // Someone else won the race.
1636 delete compiled_invoke_stub;
1637 } else {
1638 compiled_invoke_stubs_.Put(key, compiled_invoke_stub);
1639 }
Ian Rogers0571d352011-11-03 19:51:38 -07001640}
1641
Logan Chien7a2a23a2012-06-06 11:01:00 +08001642#if defined(ART_USE_LLVM_COMPILER)
1643const CompiledInvokeStub* Compiler::FindProxyStub(const char* shorty) const {
1644 MutexLock mu(compiled_proxy_stubs_lock_);
1645 ProxyStubTable::const_iterator it = compiled_proxy_stubs_.find(shorty);
1646 if (it == compiled_proxy_stubs_.end()) {
1647 return NULL;
1648 } else {
1649 DCHECK(it->second != NULL);
1650 return it->second;
1651 }
1652}
1653
1654void Compiler::InsertProxyStub(const char* shorty,
1655 const CompiledInvokeStub* compiled_proxy_stub) {
1656 MutexLock mu(compiled_proxy_stubs_lock_);
1657 InvokeStubTable::iterator it = compiled_proxy_stubs_.find(shorty);
1658 if (it != compiled_proxy_stubs_.end()) {
1659 // Someone else won the race.
1660 delete compiled_proxy_stub;
1661 } else {
1662 compiled_proxy_stubs_.Put(shorty, compiled_proxy_stub);
1663 }
1664}
1665#endif
1666
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001667CompiledClass* Compiler::GetCompiledClass(ClassReference ref) const {
Elliott Hughesc225caa2012-02-03 15:43:37 -08001668 MutexLock mu(compiled_classes_lock_);
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001669 ClassTable::const_iterator it = compiled_classes_.find(ref);
1670 if (it == compiled_classes_.end()) {
1671 return NULL;
1672 }
1673 CHECK(it->second != NULL);
1674 return it->second;
1675}
1676
Ian Rogers0571d352011-11-03 19:51:38 -07001677CompiledMethod* Compiler::GetCompiledMethod(MethodReference ref) const {
Elliott Hughesc225caa2012-02-03 15:43:37 -08001678 MutexLock mu(compiled_methods_lock_);
Ian Rogers0571d352011-11-03 19:51:38 -07001679 MethodTable::const_iterator it = compiled_methods_.find(ref);
1680 if (it == compiled_methods_.end()) {
1681 return NULL;
Brian Carlstrom3320cf42011-10-04 14:58:28 -07001682 }
1683 CHECK(it->second != NULL);
1684 return it->second;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001685}
1686
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001687void Compiler::SetGcMaps(jobject class_loader, const std::vector<const DexFile*>& dex_files) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08001688 for (size_t i = 0; i != dex_files.size(); ++i) {
1689 const DexFile* dex_file = dex_files[i];
1690 CHECK(dex_file != NULL);
1691 SetGcMapsDexFile(class_loader, *dex_file);
1692 }
1693}
1694
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001695void Compiler::SetGcMapsDexFile(jobject jni_class_loader, const DexFile& dex_file) {
1696 ScopedObjectAccess soa(Thread::Current());
1697 ClassLoader* class_loader = soa.Decode<ClassLoader*>(jni_class_loader);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08001698 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1699 DexCache* dex_cache = class_linker->FindDexCache(dex_file);
1700 for (size_t class_def_index = 0; class_def_index < dex_file.NumClassDefs(); class_def_index++) {
1701 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
1702 const char* descriptor = dex_file.GetClassDescriptor(class_def);
1703 Class* klass = class_linker->FindClass(descriptor, class_loader);
1704 if (klass == NULL || !klass->IsVerified()) {
1705 Thread::Current()->ClearException();
1706 continue;
1707 }
1708 const byte* class_data = dex_file.GetClassData(class_def);
1709 if (class_data == NULL) {
1710 // empty class such as a marker interface
1711 continue;
1712 }
1713 ClassDataItemIterator it(dex_file, class_data);
1714 while (it.HasNextStaticField()) {
1715 it.Next();
1716 }
1717 while (it.HasNextInstanceField()) {
1718 it.Next();
1719 }
1720 while (it.HasNextDirectMethod()) {
1721 Method* method = class_linker->ResolveMethod(dex_file, it.GetMemberIndex(), dex_cache,
jeffhaoc0228b82012-08-29 18:15:05 -07001722 class_loader, NULL, it.GetMethodInvokeType(class_def));
Brian Carlstrome7d856b2012-01-11 18:10:55 -08001723 SetGcMapsMethod(dex_file, method);
1724 it.Next();
1725 }
1726 while (it.HasNextVirtualMethod()) {
1727 Method* method = class_linker->ResolveMethod(dex_file, it.GetMemberIndex(), dex_cache,
jeffhaoc0228b82012-08-29 18:15:05 -07001728 class_loader, NULL, it.GetMethodInvokeType(class_def));
Brian Carlstrome7d856b2012-01-11 18:10:55 -08001729 SetGcMapsMethod(dex_file, method);
1730 it.Next();
1731 }
1732 }
1733}
1734
1735void Compiler::SetGcMapsMethod(const DexFile& dex_file, Method* method) {
1736 if (method == NULL) {
1737 Thread::Current()->ClearException();
1738 return;
1739 }
1740 uint16_t method_idx = method->GetDexMethodIndex();
1741 MethodReference ref(&dex_file, method_idx);
1742 CompiledMethod* compiled_method = GetCompiledMethod(ref);
1743 if (compiled_method == NULL) {
1744 return;
1745 }
Ian Rogers776ac1f2012-04-13 23:36:36 -07001746 const std::vector<uint8_t>* gc_map = verifier::MethodVerifier::GetGcMap(ref);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08001747 if (gc_map == NULL) {
1748 return;
1749 }
1750 compiled_method->SetGcMap(*gc_map);
1751}
1752
buzbee2cfc6392012-05-07 14:51:40 -07001753#if defined(ART_USE_LLVM_COMPILER) || defined(ART_USE_QUICK_COMPILER)
Logan Chien8b977d32012-02-21 19:14:55 +08001754void Compiler::SetBitcodeFileName(std::string const& filename) {
Logan Chien106b2a02012-03-18 04:41:38 +08001755 typedef void (*SetBitcodeFileNameFn)(Compiler&, std::string const&);
1756
1757 SetBitcodeFileNameFn set_bitcode_file_name =
1758 FindFunction<SetBitcodeFileNameFn>(MakeCompilerSoName(instruction_set_),
1759 compiler_library_,
1760 "compilerLLVMSetBitcodeFileName");
1761
1762 set_bitcode_file_name(*this, filename);
Logan Chien8b977d32012-02-21 19:14:55 +08001763}
buzbee2cfc6392012-05-07 14:51:40 -07001764#endif
Logan Chienf7015fd2012-03-18 01:19:37 +08001765
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001766} // namespace art