blob: 7369535e2b9d2d6df769b335565898087feb63e3 [file] [log] [blame]
Elliott Hughes2faa5f12012-01-30 14:42:07 -08001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -070016
17#include "compiler.h"
18
Elliott Hughesd9c67be2012-02-02 19:54:06 -080019#include <vector>
20
Elliott Hughesb3bd5f02012-03-08 21:05:27 -080021#include <dlfcn.h>
Brian Carlstrom27ec9612011-09-19 20:20:38 -070022#include <sys/mman.h>
Elliott Hughesd9c67be2012-02-02 19:54:06 -080023#include <unistd.h>
Brian Carlstrom27ec9612011-09-19 20:20:38 -070024
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -070025#include "class_linker.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -070026#include "class_loader.h"
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -070027#include "dex_cache.h"
jeffhaof56197c2012-03-05 18:01:54 -080028#include "dex_verifier.h"
Brian Carlstrom9baa4ae2011-09-01 21:14:14 -070029#include "jni_internal.h"
Logan Chien4dd96f52012-02-29 01:26:58 +080030#include "oat_compilation_unit.h"
Brian Carlstrom3320cf42011-10-04 14:58:28 -070031#include "oat_file.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080032#include "object_utils.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -070033#include "runtime.h"
Elliott Hughesb3bd5f02012-03-08 21:05:27 -080034#include "space.h"
Brian Carlstrom3320cf42011-10-04 14:58:28 -070035#include "stl_util.h"
Elliott Hughes601a1232012-02-02 17:47:38 -080036#include "timing_logger.h"
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -070037
Elliott Hughes059d5c12012-03-12 17:39:18 -070038#if defined(__APPLE__)
39#include <mach-o/dyld.h>
40#endif
41
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -070042namespace art {
43
Shih-wei Liaoc486c112011-09-13 16:43:52 -070044namespace arm {
Ian Rogersbdb03912011-09-14 00:55:44 -070045 ByteArray* CreateAbstractMethodErrorStub();
Ian Rogers1cb0a1d2011-10-06 15:24:35 -070046 ByteArray* ArmCreateResolutionTrampoline(Runtime::TrampolineType type);
Elliott Hughes8add92d2012-01-18 18:18:43 -080047 ByteArray* CreateJniDlsymLookupStub();
Shih-wei Liaoc486c112011-09-13 16:43:52 -070048}
Shih-wei Liaoc486c112011-09-13 16:43:52 -070049namespace x86 {
Ian Rogersbdb03912011-09-14 00:55:44 -070050 ByteArray* CreateAbstractMethodErrorStub();
Ian Rogers1cb0a1d2011-10-06 15:24:35 -070051 ByteArray* X86CreateResolutionTrampoline(Runtime::TrampolineType type);
Elliott Hughes8add92d2012-01-18 18:18:43 -080052 ByteArray* CreateJniDlsymLookupStub();
Brian Carlstrome24fa612011-09-29 00:53:55 -070053}
54
Ian Rogers996cc582012-02-14 22:23:29 -080055static double Percentage(size_t x, size_t y) {
Elliott Hughes398f64b2012-03-26 18:05:48 -070056 return 100.0 * (static_cast<double>(x)) / (static_cast<double>(x + y));
Ian Rogers996cc582012-02-14 22:23:29 -080057}
58
59static void DumpStat(size_t x, size_t y, const char* str) {
60 if (x == 0 && y == 0) {
61 return;
62 }
63 LOG(INFO) << Percentage(x, y) << "% of " << str << " for " << (x + y) << " cases";
64}
65
Ian Rogersc8b306f2012-02-17 21:34:44 -080066class AOTCompilationStats {
67 public:
68 AOTCompilationStats() : stats_lock_("AOT compilation statistics lock"),
69 types_in_dex_cache_(0), types_not_in_dex_cache_(0),
70 strings_in_dex_cache_(0), strings_not_in_dex_cache_(0),
71 resolved_types_(0), unresolved_types_(0),
72 resolved_instance_fields_(0), unresolved_instance_fields_(0),
Ian Rogers2ed3b952012-03-17 11:49:39 -070073 resolved_local_static_fields_(0), resolved_static_fields_(0), unresolved_static_fields_(0) {
74 for (size_t i = 0; i <= kMaxInvokeType; i++) {
Ian Rogersc8b306f2012-02-17 21:34:44 -080075 resolved_methods_[i] = 0;
76 unresolved_methods_[i] = 0;
Ian Rogers2ed3b952012-03-17 11:49:39 -070077 virtual_made_direct_[i] = 0;
78 direct_calls_to_boot_[i] = 0;
79 direct_methods_to_boot_[i] = 0;
Elliott Hughesb25c3f62012-03-26 16:35:06 -070080 }
Ian Rogersc8b306f2012-02-17 21:34:44 -080081 }
82
83 void Dump() {
84 DumpStat(types_in_dex_cache_, types_not_in_dex_cache_, "types known to be in dex cache");
85 DumpStat(strings_in_dex_cache_, strings_not_in_dex_cache_, "strings known to be in dex cache");
86 DumpStat(resolved_types_, unresolved_types_, "types resolved");
87 DumpStat(resolved_instance_fields_, unresolved_instance_fields_, "instance fields resolved");
88 DumpStat(resolved_local_static_fields_ + resolved_static_fields_, unresolved_static_fields_,
89 "static fields resolved");
90 DumpStat(resolved_local_static_fields_, resolved_static_fields_ + unresolved_static_fields_,
91 "static fields local to a class");
92
Ian Rogers2ed3b952012-03-17 11:49:39 -070093 for (size_t i = 0; i <= kMaxInvokeType; i++) {
Ian Rogersc8b306f2012-02-17 21:34:44 -080094 std::ostringstream oss;
Ian Rogers2ed3b952012-03-17 11:49:39 -070095 oss << static_cast<InvokeType>(i) << " methods were AOT resolved";
Ian Rogersc8b306f2012-02-17 21:34:44 -080096 DumpStat(resolved_methods_[i], unresolved_methods_[i], oss.str().c_str());
Ian Rogers2ed3b952012-03-17 11:49:39 -070097 if (virtual_made_direct_[i] > 0) {
98 std::ostringstream oss2;
99 oss2 << static_cast<InvokeType>(i) << " methods made direct";
100 DumpStat(virtual_made_direct_[i],
101 resolved_methods_[i] + unresolved_methods_[i] - virtual_made_direct_[i],
102 oss2.str().c_str());
103 }
104 if (direct_calls_to_boot_[i] > 0) {
105 std::ostringstream oss2;
106 oss2 << static_cast<InvokeType>(i) << " method calls are direct into boot";
107 DumpStat(direct_calls_to_boot_[i],
108 resolved_methods_[i] + unresolved_methods_[i] - direct_calls_to_boot_[i],
109 oss2.str().c_str());
110 }
111 if (direct_methods_to_boot_[i] > 0) {
112 std::ostringstream oss2;
113 oss2 << static_cast<InvokeType>(i) << " method calls have methods in boot";
114 DumpStat(direct_methods_to_boot_[i],
115 resolved_methods_[i] + unresolved_methods_[i] - direct_methods_to_boot_[i],
116 oss2.str().c_str());
117 }
Ian Rogersc8b306f2012-02-17 21:34:44 -0800118 }
119 }
Ian Rogers996cc582012-02-14 22:23:29 -0800120
121// Allow lossy statistics in non-debug builds
122#ifndef NDEBUG
123#define STATS_LOCK() MutexLock mu(stats_lock_)
124#else
125#define STATS_LOCK()
126#endif
127
Ian Rogersc8b306f2012-02-17 21:34:44 -0800128 void TypeInDexCache() {
129 STATS_LOCK();
130 types_in_dex_cache_++;
Ian Rogers996cc582012-02-14 22:23:29 -0800131 }
Ian Rogers996cc582012-02-14 22:23:29 -0800132
Ian Rogersc8b306f2012-02-17 21:34:44 -0800133 void TypeNotInDexCache() {
134 STATS_LOCK();
135 types_not_in_dex_cache_++;
Ian Rogers996cc582012-02-14 22:23:29 -0800136 }
Ian Rogersc8b306f2012-02-17 21:34:44 -0800137
138 void StringInDexCache() {
139 STATS_LOCK();
140 strings_in_dex_cache_++;
141 }
142
143 void StringNotInDexCache() {
144 STATS_LOCK();
145 strings_not_in_dex_cache_++;
146 }
147
148 void TypeDoesntNeedAccessCheck() {
149 STATS_LOCK();
150 resolved_types_++;
151 }
152
153 void TypeNeedsAccessCheck() {
154 STATS_LOCK();
155 unresolved_types_++;
156 }
157
158 void ResolvedInstanceField() {
159 STATS_LOCK();
160 resolved_instance_fields_++;
161 }
162
Elliott Hughesb25c3f62012-03-26 16:35:06 -0700163 void UnresolvedInstanceField() {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800164 STATS_LOCK();
165 unresolved_instance_fields_++;
166 }
167
168 void ResolvedLocalStaticField() {
169 STATS_LOCK();
170 resolved_local_static_fields_++;
171 }
172
173 void ResolvedStaticField() {
174 STATS_LOCK();
175 resolved_static_fields_++;
176 }
177
178 void UnresolvedStaticField() {
179 STATS_LOCK();
180 unresolved_static_fields_++;
181 }
182
183 void ResolvedMethod(InvokeType type) {
184 DCHECK_LE(type, kMaxInvokeType);
185 STATS_LOCK();
186 resolved_methods_[type]++;
187 }
188
189 void UnresolvedMethod(InvokeType type) {
190 DCHECK_LE(type, kMaxInvokeType);
191 STATS_LOCK();
192 unresolved_methods_[type]++;
193 }
194
Ian Rogers2ed3b952012-03-17 11:49:39 -0700195 void VirtualMadeDirect(InvokeType type) {
196 DCHECK_LE(type, kMaxInvokeType);
Ian Rogersfb6adba2012-03-04 21:51:51 -0800197 STATS_LOCK();
Ian Rogers2ed3b952012-03-17 11:49:39 -0700198 virtual_made_direct_[type]++;
Ian Rogersfb6adba2012-03-04 21:51:51 -0800199 }
Ian Rogers2ed3b952012-03-17 11:49:39 -0700200
201 void DirectCallsToBoot(InvokeType type) {
202 DCHECK_LE(type, kMaxInvokeType);
203 STATS_LOCK();
204 direct_calls_to_boot_[type]++;
205 }
206
207 void DirectMethodsToBoot(InvokeType type) {
208 DCHECK_LE(type, kMaxInvokeType);
209 STATS_LOCK();
210 direct_methods_to_boot_[type]++;
211 }
212
Ian Rogersc8b306f2012-02-17 21:34:44 -0800213 private:
214 Mutex stats_lock_;
215
216 size_t types_in_dex_cache_;
217 size_t types_not_in_dex_cache_;
218
219 size_t strings_in_dex_cache_;
220 size_t strings_not_in_dex_cache_;
221
222 size_t resolved_types_;
223 size_t unresolved_types_;
224
225 size_t resolved_instance_fields_;
226 size_t unresolved_instance_fields_;
227
228 size_t resolved_local_static_fields_;
229 size_t resolved_static_fields_;
230 size_t unresolved_static_fields_;
231
232 size_t resolved_methods_[kMaxInvokeType + 1];
233 size_t unresolved_methods_[kMaxInvokeType + 1];
Ian Rogers2ed3b952012-03-17 11:49:39 -0700234 size_t virtual_made_direct_[kMaxInvokeType + 1];
235 size_t direct_calls_to_boot_[kMaxInvokeType + 1];
236 size_t direct_methods_to_boot_[kMaxInvokeType + 1];
Ian Rogersc8b306f2012-02-17 21:34:44 -0800237
Elliott Hughesb25c3f62012-03-26 16:35:06 -0700238 DISALLOW_COPY_AND_ASSIGN(AOTCompilationStats);
Ian Rogersc8b306f2012-02-17 21:34:44 -0800239};
Ian Rogers996cc582012-02-14 22:23:29 -0800240
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800241static std::string MakeCompilerSoName(InstructionSet instruction_set) {
242 // TODO: is the ARM/Thumb2 instruction set distinction really buying us anything,
243 // or just causing hassle like this?
244 if (instruction_set == kThumb2) {
245 instruction_set = kArm;
246 }
247
Elliott Hughes059d5c12012-03-12 17:39:18 -0700248 // Capitalize the instruction set, because that's what we do in the build system.
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800249 std::ostringstream instruction_set_name_os;
250 instruction_set_name_os << instruction_set;
251 std::string instruction_set_name(instruction_set_name_os.str());
252 for (size_t i = 0; i < instruction_set_name.size(); ++i) {
253 instruction_set_name[i] = toupper(instruction_set_name[i]);
254 }
Elliott Hughes059d5c12012-03-12 17:39:18 -0700255
256 // Bad things happen if we pull in the libartd-compiler to a libart dex2oat or vice versa,
257 // because we end up with both libart and libartd in the same address space!
Elliott Hughes67d92002012-03-26 15:08:51 -0700258 const char* suffix = (kIsDebugBuild ? "d" : "");
Elliott Hughes059d5c12012-03-12 17:39:18 -0700259
260 // Work out the filename for the compiler library.
Shih-wei Liaoc4c98812012-03-10 21:55:51 -0800261#if !defined(ART_USE_LLVM_COMPILER)
Elliott Hughes059d5c12012-03-12 17:39:18 -0700262 std::string library_name(StringPrintf("art%s-compiler-%s", suffix, instruction_set_name.c_str()));
Shih-wei Liaoc4c98812012-03-10 21:55:51 -0800263#else
264 std::string library_name(StringPrintf("art%s-compiler-llvm", suffix));
265#endif
Elliott Hughes059d5c12012-03-12 17:39:18 -0700266 std::string filename(StringPrintf(OS_SHARED_LIB_FORMAT_STR, library_name.c_str()));
267
268#if defined(__APPLE__)
269 // On Linux, dex2oat will have been built with an RPATH of $ORIGIN/../lib, so dlopen(3) will find
270 // the .so by itself. On Mac OS, there isn't really an equivalent, so we have to manually do the
271 // same work.
Elliott Hughes059d5c12012-03-12 17:39:18 -0700272 uint32_t executable_path_length = 0;
Elliott Hughes448e93c2012-03-28 22:30:06 -0700273 _NSGetExecutablePath(NULL, &executable_path_length);
274 std::string path(executable_path_length, static_cast<char>(0));
275 CHECK_EQ(_NSGetExecutablePath(&path[0], &executable_path_length), 0);
Elliott Hughes059d5c12012-03-12 17:39:18 -0700276
277 // Strip the "/dex2oat".
278 size_t last_slash = path.find_last_of('/');
279 CHECK_NE(last_slash, std::string::npos) << path;
280 path.resize(last_slash);
281
282 // Strip the "/bin".
283 last_slash = path.find_last_of('/');
284 path.resize(last_slash);
285
286 filename = path + "/lib/" + filename;
287#endif
288 return filename;
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800289}
290
Elliott Hughes46f060a2012-03-09 17:36:50 -0800291template<typename Fn>
292static Fn FindFunction(const std::string& compiler_so_name, void* library, const char* name) {
293 Fn fn = reinterpret_cast<Fn>(dlsym(library, name));
294 if (fn == NULL) {
295 LOG(FATAL) << "Couldn't find \"" << name << "\" in compiler library " << compiler_so_name << ": " << dlerror();
296 }
Elliott Hughes059d5c12012-03-12 17:39:18 -0700297 VLOG(compiler) << "Found \"" << name << "\" at " << reinterpret_cast<void*>(fn);
Elliott Hughes46f060a2012-03-09 17:36:50 -0800298 return fn;
299}
300
Elliott Hughes5523ee02012-02-03 18:18:34 -0800301Compiler::Compiler(InstructionSet instruction_set, bool image, size_t thread_count,
Brian Carlstromba0668e2012-03-26 13:14:07 -0700302 bool support_debugging, const std::set<std::string>* image_classes,
303 bool dump_stats, bool dump_timings)
Brian Carlstromaded5f72011-10-07 17:15:04 -0700304 : instruction_set_(instruction_set),
Elliott Hughesc225caa2012-02-03 15:43:37 -0800305 compiled_classes_lock_("compiled classes lock"),
306 compiled_methods_lock_("compiled method lock"),
307 compiled_invoke_stubs_lock_("compiled invoke stubs lock"),
Brian Carlstromaded5f72011-10-07 17:15:04 -0700308 image_(image),
Elliott Hughes5523ee02012-02-03 18:18:34 -0800309 thread_count_(thread_count),
Elliott Hughesde6e4cf2012-02-27 14:46:06 -0800310 support_debugging_(support_debugging),
Ian Rogersc8b306f2012-02-17 21:34:44 -0800311 stats_(new AOTCompilationStats),
Brian Carlstromba0668e2012-03-26 13:14:07 -0700312 dump_stats_(dump_stats),
313 dump_timings_(dump_timings),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800314 image_classes_(image_classes),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800315 compiler_library_(NULL),
Elliott Hughes46f060a2012-03-09 17:36:50 -0800316 compiler_(NULL),
Elliott Hughes6f4976c2012-03-13 21:19:01 -0700317 compiler_context_(NULL),
Elliott Hughes46f060a2012-03-09 17:36:50 -0800318 jni_compiler_(NULL),
Logan Chienf7015fd2012-03-18 01:19:37 +0800319 create_invoke_stub_(NULL)
320#if defined(ART_USE_LLVM_COMPILER)
321 , compiler_enable_auto_elf_loading_(NULL),
322 compiler_get_method_code_addr_(NULL),
323 compiler_get_method_invoke_stub_addr_(NULL)
324#endif
325{
Shih-wei Liaoc4c98812012-03-10 21:55:51 -0800326 std::string compiler_so_name(MakeCompilerSoName(instruction_set_));
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800327 compiler_library_ = dlopen(compiler_so_name.c_str(), RTLD_LAZY);
328 if (compiler_library_ == NULL) {
329 LOG(FATAL) << "Couldn't find compiler library " << compiler_so_name << ": " << dlerror();
330 }
331 VLOG(compiler) << "dlopen(\"" << compiler_so_name << "\", RTLD_LAZY) returned " << compiler_library_;
332
Logan Chien106b2a02012-03-18 04:41:38 +0800333#if defined(ART_USE_LLVM_COMPILER)
334 // Initialize compiler_context_
335 typedef void (*InitCompilerContextFn)(Compiler&);
336
337 InitCompilerContextFn init_compiler_context =
338 FindFunction<void (*)(Compiler&)>(compiler_so_name,
339 compiler_library_,
340 "ArtInitCompilerContext");
341
342 init_compiler_context(*this);
343#endif
344
Elliott Hughes3fa1b7e2012-03-13 17:06:22 -0700345 compiler_ = FindFunction<CompilerFn>(compiler_so_name, compiler_library_, "ArtCompileMethod");
Elliott Hughes46f060a2012-03-09 17:36:50 -0800346 jni_compiler_ = FindFunction<JniCompilerFn>(compiler_so_name, compiler_library_, "ArtJniCompileMethod");
347 create_invoke_stub_ = FindFunction<CreateInvokeStubFn>(compiler_so_name, compiler_library_, "ArtCreateInvokeStub");
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800348
Logan Chienf7015fd2012-03-18 01:19:37 +0800349#if defined(ART_USE_LLVM_COMPILER)
350 compiler_enable_auto_elf_loading_ = FindFunction<CompilerEnableAutoElfLoadingFn>(
351 compiler_so_name, compiler_library_, "compilerLLVMEnableAutoElfLoading");
352 compiler_get_method_code_addr_ = FindFunction<CompilerGetMethodCodeAddrFn>(
353 compiler_so_name, compiler_library_, "compilerLLVMGetMethodCodeAddr");
354 compiler_get_method_invoke_stub_addr_ = FindFunction<CompilerGetMethodInvokeStubAddrFn>(
355 compiler_so_name, compiler_library_, "compilerLLVMGetMethodInvokeStubAddr");
356#endif
357
Brian Carlstrom25c33252011-09-18 15:58:35 -0700358 CHECK(!Runtime::Current()->IsStarted());
Brian Carlstromae826982011-11-09 01:33:42 -0800359 if (!image_) {
360 CHECK(image_classes_ == NULL);
361 }
Shih-wei Liaoc486c112011-09-13 16:43:52 -0700362}
363
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700364Compiler::~Compiler() {
Elliott Hughesc225caa2012-02-03 15:43:37 -0800365 {
366 MutexLock mu(compiled_classes_lock_);
367 STLDeleteValues(&compiled_classes_);
368 }
369 {
370 MutexLock mu(compiled_methods_lock_);
371 STLDeleteValues(&compiled_methods_);
372 }
373 {
374 MutexLock mu(compiled_invoke_stubs_lock_);
375 STLDeleteValues(&compiled_invoke_stubs_);
Elliott Hughesbb551fa2012-01-25 16:35:29 -0800376 }
Brian Carlstromf5822582012-03-19 22:34:31 -0700377 {
378 MutexLock mu(compiled_methods_lock_);
379 STLDeleteElements(&code_to_patch_);
380 }
381 {
382 MutexLock mu(compiled_methods_lock_);
383 STLDeleteElements(&methods_to_patch_);
384 }
Shih-wei Liaoc4c98812012-03-10 21:55:51 -0800385#if defined(ART_USE_LLVM_COMPILER)
386 CompilerCallbackFn f = FindFunction<CompilerCallbackFn>(MakeCompilerSoName(instruction_set_),
387 compiler_library_,
388 "compilerLLVMDispose");
389 (*f)(*this);
390#endif
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800391 if (compiler_library_ != NULL) {
392 VLOG(compiler) << "dlclose(" << compiler_library_ << ")";
393 dlclose(compiler_library_);
394 }
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700395}
396
Ian Rogers1cb0a1d2011-10-06 15:24:35 -0700397ByteArray* Compiler::CreateResolutionStub(InstructionSet instruction_set,
398 Runtime::TrampolineType type) {
Ian Rogersad25ac52011-10-04 19:13:33 -0700399 if (instruction_set == kX86) {
Ian Rogers1cb0a1d2011-10-06 15:24:35 -0700400 return x86::X86CreateResolutionTrampoline(type);
Ian Rogersad25ac52011-10-04 19:13:33 -0700401 } else {
402 CHECK(instruction_set == kArm || instruction_set == kThumb2);
403 // Generates resolution stub using ARM instruction set
Ian Rogers1cb0a1d2011-10-06 15:24:35 -0700404 return arm::ArmCreateResolutionTrampoline(type);
Ian Rogersad25ac52011-10-04 19:13:33 -0700405 }
406}
407
Elliott Hughes8add92d2012-01-18 18:18:43 -0800408ByteArray* Compiler::CreateJniDlsymLookupStub(InstructionSet instruction_set) {
Ian Rogers169c9a72011-11-13 20:13:17 -0800409 switch (instruction_set) {
410 case kArm:
411 case kThumb2:
Elliott Hughes8add92d2012-01-18 18:18:43 -0800412 return arm::CreateJniDlsymLookupStub();
Ian Rogers169c9a72011-11-13 20:13:17 -0800413 case kX86:
Elliott Hughes8add92d2012-01-18 18:18:43 -0800414 return x86::CreateJniDlsymLookupStub();
Ian Rogers169c9a72011-11-13 20:13:17 -0800415 default:
Ian Rogers49c48942012-03-11 15:15:37 -0700416 LOG(FATAL) << "Unknown InstructionSet: " << instruction_set;
Ian Rogers169c9a72011-11-13 20:13:17 -0800417 return NULL;
418 }
419}
420
Ian Rogersad25ac52011-10-04 19:13:33 -0700421ByteArray* Compiler::CreateAbstractMethodErrorStub(InstructionSet instruction_set) {
422 if (instruction_set == kX86) {
423 return x86::CreateAbstractMethodErrorStub();
424 } else {
425 CHECK(instruction_set == kArm || instruction_set == kThumb2);
426 // Generates resolution stub using ARM instruction set
427 return arm::CreateAbstractMethodErrorStub();
428 }
429}
430
Jesse Wilson254db0f2011-11-16 16:44:11 -0500431void Compiler::CompileAll(const ClassLoader* class_loader,
Brian Carlstromae826982011-11-09 01:33:42 -0800432 const std::vector<const DexFile*>& dex_files) {
Brian Carlstrom25c33252011-09-18 15:58:35 -0700433 DCHECK(!Runtime::Current()->IsStarted());
Brian Carlstromae826982011-11-09 01:33:42 -0800434
Elliott Hughes601a1232012-02-02 17:47:38 -0800435 TimingLogger timings("compiler");
436
437 PreCompile(class_loader, dex_files, timings);
438
Brian Carlstromae826982011-11-09 01:33:42 -0800439 Compile(class_loader, dex_files);
Elliott Hughes601a1232012-02-02 17:47:38 -0800440 timings.AddSplit("Compile");
441
Brian Carlstromae826982011-11-09 01:33:42 -0800442 PostCompile(class_loader, dex_files);
Elliott Hughes601a1232012-02-02 17:47:38 -0800443 timings.AddSplit("PostCompile");
444
Brian Carlstromba0668e2012-03-26 13:14:07 -0700445 if (dump_timings_ && timings.GetTotalNs() > MsToNs(1000)) {
Elliott Hughes601a1232012-02-02 17:47:38 -0800446 timings.Dump();
447 }
Ian Rogers996cc582012-02-14 22:23:29 -0800448
Brian Carlstromba0668e2012-03-26 13:14:07 -0700449 if (dump_stats_) {
450 stats_->Dump();
451 }
Brian Carlstrom8a487412011-08-29 20:08:52 -0700452}
453
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700454void Compiler::CompileOne(const Method* method) {
Brian Carlstrom25c33252011-09-18 15:58:35 -0700455 DCHECK(!Runtime::Current()->IsStarted());
Brian Carlstromae826982011-11-09 01:33:42 -0800456
Brian Carlstrom8a487412011-08-29 20:08:52 -0700457 const ClassLoader* class_loader = method->GetDeclaringClass()->GetClassLoader();
Brian Carlstromae826982011-11-09 01:33:42 -0800458
Ian Rogers0571d352011-11-03 19:51:38 -0700459 // Find the dex_file
460 const DexCache* dex_cache = method->GetDeclaringClass()->GetDexCache();
461 const DexFile& dex_file = Runtime::Current()->GetClassLinker()->FindDexFile(dex_cache);
Brian Carlstromae826982011-11-09 01:33:42 -0800462 std::vector<const DexFile*> dex_files;
463 dex_files.push_back(&dex_file);
464
Elliott Hughes601a1232012-02-02 17:47:38 -0800465 TimingLogger timings("CompileOne");
466 PreCompile(class_loader, dex_files, timings);
Brian Carlstromae826982011-11-09 01:33:42 -0800467
Ian Rogers0571d352011-11-03 19:51:38 -0700468 uint32_t method_idx = method->GetDexMethodIndex();
Ian Rogersa3760aa2011-11-14 14:32:37 -0800469 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(method->GetCodeItemOffset());
470 CompileMethod(code_item, method->GetAccessFlags(), method_idx, class_loader, dex_file);
Brian Carlstromae826982011-11-09 01:33:42 -0800471
472 PostCompile(class_loader, dex_files);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700473}
474
Brian Carlstromae826982011-11-09 01:33:42 -0800475void Compiler::Resolve(const ClassLoader* class_loader,
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800476 const std::vector<const DexFile*>& dex_files, TimingLogger& timings) {
Brian Carlstromae826982011-11-09 01:33:42 -0800477 for (size_t i = 0; i != dex_files.size(); ++i) {
478 const DexFile* dex_file = dex_files[i];
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700479 CHECK(dex_file != NULL);
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800480 ResolveDexFile(class_loader, *dex_file, timings);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700481 }
482}
483
Brian Carlstromae826982011-11-09 01:33:42 -0800484void Compiler::PreCompile(const ClassLoader* class_loader,
Elliott Hughes601a1232012-02-02 17:47:38 -0800485 const std::vector<const DexFile*>& dex_files, TimingLogger& timings) {
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800486 Resolve(class_loader, dex_files, timings);
Elliott Hughes601a1232012-02-02 17:47:38 -0800487
Brian Carlstromae826982011-11-09 01:33:42 -0800488 Verify(class_loader, dex_files);
Elliott Hughes601a1232012-02-02 17:47:38 -0800489 timings.AddSplit("PreCompile.Verify");
490
Brian Carlstromae826982011-11-09 01:33:42 -0800491 InitializeClassesWithoutClinit(class_loader, dex_files);
Elliott Hughes601a1232012-02-02 17:47:38 -0800492 timings.AddSplit("PreCompile.InitializeClassesWithoutClinit");
Brian Carlstromae826982011-11-09 01:33:42 -0800493}
494
495void Compiler::PostCompile(const ClassLoader* class_loader,
496 const std::vector<const DexFile*>& dex_files) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -0800497 SetGcMaps(class_loader, dex_files);
Shih-wei Liaod1fec812012-02-13 09:51:10 -0800498#if defined(ART_USE_LLVM_COMPILER)
Shih-wei Liaoc4c98812012-03-10 21:55:51 -0800499 CompilerCallbackFn f = FindFunction<CompilerCallbackFn>(MakeCompilerSoName(instruction_set_),
500 compiler_library_,
501 "compilerLLVMMaterializeRemainder");
502 (*f)(*this);
Shih-wei Liaod1fec812012-02-13 09:51:10 -0800503#endif
Brian Carlstromae826982011-11-09 01:33:42 -0800504}
505
506bool Compiler::IsImageClass(const std::string& descriptor) const {
507 if (image_classes_ == NULL) {
508 return true;
509 }
510 return image_classes_->find(descriptor) != image_classes_->end();
511}
512
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800513bool Compiler::CanAssumeTypeIsPresentInDexCache(const DexCache* dex_cache,
Ian Rogers996cc582012-02-14 22:23:29 -0800514 uint32_t type_idx) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800515 if (!IsImage()) {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800516 stats_->TypeNotInDexCache();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800517 return false;
518 }
Ian Rogers1bddec32012-02-04 12:27:34 -0800519 Class* resolved_class = dex_cache->GetResolvedType(type_idx);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800520 if (resolved_class == NULL) {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800521 stats_->TypeNotInDexCache();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800522 return false;
523 }
Ian Rogers996cc582012-02-14 22:23:29 -0800524 bool result = IsImageClass(ClassHelper(resolved_class).GetDescriptor());
525 if (result) {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800526 stats_->TypeInDexCache();
Ian Rogers996cc582012-02-14 22:23:29 -0800527 } else {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800528 stats_->TypeNotInDexCache();
Ian Rogers996cc582012-02-14 22:23:29 -0800529 }
530 return result;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800531}
532
Ian Rogers1bddec32012-02-04 12:27:34 -0800533bool Compiler::CanAssumeStringIsPresentInDexCache(const DexCache* dex_cache,
Ian Rogers996cc582012-02-14 22:23:29 -0800534 uint32_t string_idx) {
Ian Rogers1bddec32012-02-04 12:27:34 -0800535 // TODO: Add support for loading strings referenced by image_classes_
536 // See also Compiler::ResolveDexFile
537
538 // The following is a test saying that if we're building the image without a restricted set of
539 // image classes then we can assume the string is present in the dex cache if it is there now
Ian Rogers996cc582012-02-14 22:23:29 -0800540 bool result = IsImage() && image_classes_ == NULL && dex_cache->GetResolvedString(string_idx) != NULL;
541 if (result) {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800542 stats_->StringInDexCache();
Ian Rogers996cc582012-02-14 22:23:29 -0800543 } else {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800544 stats_->StringNotInDexCache();
Ian Rogers996cc582012-02-14 22:23:29 -0800545 }
546 return result;
Ian Rogers1bddec32012-02-04 12:27:34 -0800547}
548
549bool Compiler::CanAccessTypeWithoutChecks(uint32_t referrer_idx, const DexCache* dex_cache,
Ian Rogers996cc582012-02-14 22:23:29 -0800550 const DexFile& dex_file, uint32_t type_idx) {
Ian Rogers1bddec32012-02-04 12:27:34 -0800551 // Get type from dex cache assuming it was populated by the verifier
552 Class* resolved_class = dex_cache->GetResolvedType(type_idx);
553 if (resolved_class == NULL) {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800554 stats_->TypeNeedsAccessCheck();
Ian Rogers1bddec32012-02-04 12:27:34 -0800555 return false; // Unknown class needs access checks.
556 }
557 const DexFile::MethodId& method_id = dex_file.GetMethodId(referrer_idx);
558 Class* referrer_class = dex_cache->GetResolvedType(method_id.class_idx_);
559 if (referrer_class == NULL) {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800560 stats_->TypeNeedsAccessCheck();
Ian Rogers1bddec32012-02-04 12:27:34 -0800561 return false; // Incomplete referrer knowledge needs access check.
562 }
563 // Perform access check, will return true if access is ok or false if we're going to have to
564 // check this at runtime (for example for class loaders).
Ian Rogers996cc582012-02-14 22:23:29 -0800565 bool result = referrer_class->CanAccess(resolved_class);
566 if (result) {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800567 stats_->TypeDoesntNeedAccessCheck();
Ian Rogers996cc582012-02-14 22:23:29 -0800568 } else {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800569 stats_->TypeNeedsAccessCheck();
Ian Rogers996cc582012-02-14 22:23:29 -0800570 }
571 return result;
Ian Rogers1bddec32012-02-04 12:27:34 -0800572}
573
574bool Compiler::CanAccessInstantiableTypeWithoutChecks(uint32_t referrer_idx,
575 const DexCache* dex_cache,
576 const DexFile& dex_file,
Ian Rogers996cc582012-02-14 22:23:29 -0800577 uint32_t type_idx) {
Ian Rogers1bddec32012-02-04 12:27:34 -0800578 // Get type from dex cache assuming it was populated by the verifier.
579 Class* resolved_class = dex_cache->GetResolvedType(type_idx);
580 if (resolved_class == NULL) {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800581 stats_->TypeNeedsAccessCheck();
Ian Rogers1bddec32012-02-04 12:27:34 -0800582 return false; // Unknown class needs access checks.
583 }
584 const DexFile::MethodId& method_id = dex_file.GetMethodId(referrer_idx);
585 Class* referrer_class = dex_cache->GetResolvedType(method_id.class_idx_);
586 if (referrer_class == NULL) {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800587 stats_->TypeNeedsAccessCheck();
Ian Rogers1bddec32012-02-04 12:27:34 -0800588 return false; // Incomplete referrer knowledge needs access check.
589 }
590 // Perform access and instantiable checks, will return true if access is ok or false if we're
591 // going to have to check this at runtime (for example for class loaders).
Ian Rogers996cc582012-02-14 22:23:29 -0800592 bool result = referrer_class->CanAccess(resolved_class) && resolved_class->IsInstantiable();
593 if (result) {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800594 stats_->TypeDoesntNeedAccessCheck();
Ian Rogers996cc582012-02-14 22:23:29 -0800595 } else {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800596 stats_->TypeNeedsAccessCheck();
Ian Rogers996cc582012-02-14 22:23:29 -0800597 }
598 return result;
Ian Rogers1bddec32012-02-04 12:27:34 -0800599}
600
Logan Chien4dd96f52012-02-29 01:26:58 +0800601static Class* ComputeReferrerClass(OatCompilationUnit* mUnit) {
602 const DexFile::MethodId& referrer_method_id =
603 mUnit->dex_file_->GetMethodId(mUnit->method_idx_);
604
605 return mUnit->class_linker_->ResolveType(
606 *mUnit->dex_file_, referrer_method_id.class_idx_,
607 mUnit->dex_cache_, mUnit->class_loader_);
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800608}
609
Logan Chien4dd96f52012-02-29 01:26:58 +0800610static Field* ComputeReferrerField(OatCompilationUnit* mUnit, uint32_t field_idx) {
611 return mUnit->class_linker_->ResolveField(
612 *mUnit->dex_file_, field_idx, mUnit->dex_cache_,
613 mUnit->class_loader_, false);
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800614}
615
Logan Chien4dd96f52012-02-29 01:26:58 +0800616static Method* ComputeReferrerMethod(OatCompilationUnit* mUnit, uint32_t method_idx) {
617 return mUnit->class_linker_->ResolveMethod(
618 *mUnit->dex_file_, method_idx, mUnit->dex_cache_,
619 mUnit->class_loader_, true);
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800620}
621
Logan Chien4dd96f52012-02-29 01:26:58 +0800622bool Compiler::ComputeInstanceFieldInfo(uint32_t field_idx, OatCompilationUnit* mUnit,
jeffhao8cd6dda2012-02-22 10:15:34 -0800623 int& field_offset, bool& is_volatile, bool is_put) {
Ian Rogers1bddec32012-02-04 12:27:34 -0800624 // Conservative defaults
625 field_offset = -1;
626 is_volatile = true;
627 // Try to resolve field
Logan Chien4dd96f52012-02-29 01:26:58 +0800628 Field* resolved_field = ComputeReferrerField(mUnit, field_idx);
Ian Rogers1bddec32012-02-04 12:27:34 -0800629 if (resolved_field != NULL) {
Logan Chien4dd96f52012-02-29 01:26:58 +0800630 Class* referrer_class = ComputeReferrerClass(mUnit);
Ian Rogerse2645d32012-04-11 14:42:42 -0700631 if (referrer_class != NULL) {
632 Class* fields_class = resolved_field->GetDeclaringClass();
633 bool access_ok = referrer_class->CanAccess(fields_class) &&
634 referrer_class->CanAccessMember(fields_class,
635 resolved_field->GetAccessFlags());
636 if (!access_ok) {
637 // The referring class can't access the resolved field, this may occur as a result of a
638 // protected field being made public by a sub-class. Resort to the dex file to determine
639 // the correct class for the access check.
640 const DexFile& dex_file = mUnit->class_linker_->FindDexFile(referrer_class->GetDexCache());
641 Class* dex_fields_class = mUnit->class_linker_->ResolveType(dex_file,
642 dex_file.GetFieldId(field_idx).class_idx_,
643 referrer_class);
644 access_ok = referrer_class->CanAccess(dex_fields_class) &&
645 referrer_class->CanAccessMember(dex_fields_class,
646 resolved_field->GetAccessFlags());
647 }
648 bool is_write_to_final_from_wrong_class = is_put && resolved_field->IsFinal() &&
649 fields_class != referrer_class;
650 if (access_ok && !is_write_to_final_from_wrong_class) {
651 field_offset = resolved_field->GetOffset().Int32Value();
652 is_volatile = resolved_field->IsVolatile();
653 stats_->ResolvedInstanceField();
654 return true; // Fast path.
655 }
Ian Rogers1bddec32012-02-04 12:27:34 -0800656 }
657 }
658 // Clean up any exception left by field/type resolution
659 Thread* thread = Thread::Current();
660 if (thread->IsExceptionPending()) {
661 thread->ClearException();
662 }
Ian Rogersc8b306f2012-02-17 21:34:44 -0800663 stats_->UnresolvedInstanceField();
Ian Rogers1bddec32012-02-04 12:27:34 -0800664 return false; // Incomplete knowledge needs slow path.
665}
666
Logan Chien4dd96f52012-02-29 01:26:58 +0800667bool Compiler::ComputeStaticFieldInfo(uint32_t field_idx, OatCompilationUnit* mUnit,
Ian Rogers1bddec32012-02-04 12:27:34 -0800668 int& field_offset, int& ssb_index,
jeffhao8cd6dda2012-02-22 10:15:34 -0800669 bool& is_referrers_class, bool& is_volatile, bool is_put) {
Ian Rogers1bddec32012-02-04 12:27:34 -0800670 // Conservative defaults
671 field_offset = -1;
672 ssb_index = -1;
673 is_referrers_class = false;
674 is_volatile = true;
675 // Try to resolve field
Logan Chien4dd96f52012-02-29 01:26:58 +0800676 Field* resolved_field = ComputeReferrerField(mUnit, field_idx);
Ian Rogers1bddec32012-02-04 12:27:34 -0800677 if (resolved_field != NULL) {
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800678 DCHECK(resolved_field->IsStatic());
Logan Chien4dd96f52012-02-29 01:26:58 +0800679 Class* referrer_class = ComputeReferrerClass(mUnit);
Ian Rogers1bddec32012-02-04 12:27:34 -0800680 if (referrer_class != NULL) {
jeffhao8cd6dda2012-02-22 10:15:34 -0800681 Class* fields_class = resolved_field->GetDeclaringClass();
682 if (fields_class == referrer_class) {
Ian Rogers1bddec32012-02-04 12:27:34 -0800683 is_referrers_class = true; // implies no worrying about class initialization
684 field_offset = resolved_field->GetOffset().Int32Value();
685 is_volatile = resolved_field->IsVolatile();
Ian Rogersc8b306f2012-02-17 21:34:44 -0800686 stats_->ResolvedLocalStaticField();
Ian Rogers1bddec32012-02-04 12:27:34 -0800687 return true; // fast path
688 } else {
Ian Rogerse2645d32012-04-11 14:42:42 -0700689 bool access_ok = referrer_class->CanAccess(fields_class) &&
690 referrer_class->CanAccessMember(fields_class,
691 resolved_field->GetAccessFlags());
692 if (!access_ok) {
693 // The referring class can't access the resolved field, this may occur as a result of a
694 // protected field being made public by a sub-class. Resort to the dex file to determine
695 // the correct class for the access check. Don't change the field's class as that is
696 // used to identify the SSB.
697 const DexFile& dex_file = mUnit->class_linker_->FindDexFile(referrer_class->GetDexCache());
698 Class* dex_fields_class =
699 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 }
jeffhao8cd6dda2012-02-22 10:15:34 -0800706 bool is_write_to_final_from_wrong_class = is_put && resolved_field->IsFinal();
Ian Rogerse2645d32012-04-11 14:42:42 -0700707 if (access_ok && !is_write_to_final_from_wrong_class) {
Ian Rogers1bddec32012-02-04 12:27:34 -0800708 // We have the resolved field, we must make it into a ssbIndex for the referrer
709 // in its static storage base (which may fail if it doesn't have a slot for it)
Ian Rogers4103ad22012-02-06 09:18:25 -0800710 // TODO: for images we can elide the static storage base null check
711 // if we know there's a non-null entry in the image
Logan Chien4dd96f52012-02-29 01:26:58 +0800712 if (fields_class->GetDexCache() == mUnit->dex_cache_) {
Ian Rogers4103ad22012-02-06 09:18:25 -0800713 // common case where the dex cache of both the referrer and the field are the same,
714 // no need to search the dex file
715 ssb_index = fields_class->GetDexTypeIndex();
716 field_offset = resolved_field->GetOffset().Int32Value();
717 is_volatile = resolved_field->IsVolatile();
Ian Rogersc8b306f2012-02-17 21:34:44 -0800718 stats_->ResolvedStaticField();
Ian Rogers4103ad22012-02-06 09:18:25 -0800719 return true;
720 }
Ian Rogerse2645d32012-04-11 14:42:42 -0700721 // Search dex file for localized ssb index, may fail if field's class is a parent
722 // of the class mentioned in the dex file and there is no dex cache entry.
Ian Rogers1bddec32012-02-04 12:27:34 -0800723 std::string descriptor(FieldHelper(resolved_field).GetDeclaringClassDescriptor());
724 const DexFile::StringId* string_id =
Logan Chien4dd96f52012-02-29 01:26:58 +0800725 mUnit->dex_file_->FindStringId(descriptor);
Ian Rogers1bddec32012-02-04 12:27:34 -0800726 if (string_id != NULL) {
727 const DexFile::TypeId* type_id =
Logan Chien4dd96f52012-02-29 01:26:58 +0800728 mUnit->dex_file_->FindTypeId(mUnit->dex_file_->GetIndexForStringId(*string_id));
Elliott Hughesb25c3f62012-03-26 16:35:06 -0700729 if (type_id != NULL) {
Ian Rogers1bddec32012-02-04 12:27:34 -0800730 // medium path, needs check of static storage base being initialized
Logan Chien4dd96f52012-02-29 01:26:58 +0800731 ssb_index = mUnit->dex_file_->GetIndexForTypeId(*type_id);
Ian Rogers1bddec32012-02-04 12:27:34 -0800732 field_offset = resolved_field->GetOffset().Int32Value();
733 is_volatile = resolved_field->IsVolatile();
Ian Rogersc8b306f2012-02-17 21:34:44 -0800734 stats_->ResolvedStaticField();
Ian Rogers1bddec32012-02-04 12:27:34 -0800735 return true;
736 }
737 }
738 }
739 }
740 }
741 }
742 // Clean up any exception left by field/type resolution
743 Thread* thread = Thread::Current();
744 if (thread->IsExceptionPending()) {
745 thread->ClearException();
746 }
Ian Rogersc8b306f2012-02-17 21:34:44 -0800747 stats_->UnresolvedStaticField();
Ian Rogers1bddec32012-02-04 12:27:34 -0800748 return false; // Incomplete knowledge needs slow path.
749}
750
Ian Rogers2ed3b952012-03-17 11:49:39 -0700751void Compiler::GetCodeAndMethodForDirectCall(InvokeType type, InvokeType sharp_type, Method* method,
752 uintptr_t& direct_code, uintptr_t& direct_method) {
753 direct_code = 0;
754 direct_method = 0;
755 if (sharp_type != kStatic && sharp_type != kDirect) {
756 return;
757 }
Ian Rogers2ed3b952012-03-17 11:49:39 -0700758 bool method_code_in_boot = method->GetDeclaringClass()->GetClassLoader() == NULL;
759 if (!method_code_in_boot) {
760 return;
761 }
762 bool has_clinit_trampoline = method->IsStatic() && !method->GetDeclaringClass()->IsInitialized();
763 if (has_clinit_trampoline) {
764 return;
765 }
766 stats_->DirectCallsToBoot(type);
767 stats_->DirectMethodsToBoot(type);
Ian Rogers3fa13792012-03-18 15:53:45 -0700768 bool compiling_boot = Runtime::Current()->GetHeap()->GetSpaces().size() == 1;
769 if (compiling_boot) {
Brian Carlstrom0637e272012-03-20 01:07:52 -0700770 const bool kSupportBootImageFixup = true;
Ian Rogers3fa13792012-03-18 15:53:45 -0700771 if (kSupportBootImageFixup) {
772 MethodHelper mh(method);
773 if (IsImageClass(mh.GetDeclaringClassDescriptor())) {
Brian Carlstrom0637e272012-03-20 01:07:52 -0700774 // We can only branch directly to Methods that are resolved in the DexCache.
775 // Otherwise we won't invoke the resolution trampoline.
Ian Rogers3fa13792012-03-18 15:53:45 -0700776 direct_method = -1;
Brian Carlstrom0637e272012-03-20 01:07:52 -0700777 direct_code = -1;
Ian Rogers3fa13792012-03-18 15:53:45 -0700778 }
Ian Rogers3fa13792012-03-18 15:53:45 -0700779 }
780 } else {
781 if (Runtime::Current()->GetHeap()->GetImageSpace()->Contains(method)) {
782 direct_method = reinterpret_cast<uintptr_t>(method);
783 }
784 direct_code = reinterpret_cast<uintptr_t>(method->GetCode());
Ian Rogers2ed3b952012-03-17 11:49:39 -0700785 }
Ian Rogers2ed3b952012-03-17 11:49:39 -0700786}
787
Ian Rogersfb6adba2012-03-04 21:51:51 -0800788bool Compiler::ComputeInvokeInfo(uint32_t method_idx, OatCompilationUnit* mUnit, InvokeType& type,
Ian Rogers2ed3b952012-03-17 11:49:39 -0700789 int& vtable_idx, uintptr_t& direct_code,
790 uintptr_t& direct_method) {
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800791 vtable_idx = -1;
Ian Rogers2ed3b952012-03-17 11:49:39 -0700792 direct_code = 0;
793 direct_method = 0;
Logan Chien4dd96f52012-02-29 01:26:58 +0800794 Method* resolved_method = ComputeReferrerMethod(mUnit, method_idx);
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800795 if (resolved_method != NULL) {
Logan Chien4dd96f52012-02-29 01:26:58 +0800796 Class* referrer_class = ComputeReferrerClass(mUnit);
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800797 if (referrer_class != NULL) {
798 Class* methods_class = resolved_method->GetDeclaringClass();
799 if (!referrer_class->CanAccess(methods_class) ||
800 !referrer_class->CanAccessMember(methods_class,
Ian Rogers996cc582012-02-14 22:23:29 -0800801 resolved_method->GetAccessFlags())) {
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800802 // The referring class can't access the resolved method, this may occur as a result of a
803 // protected method being made public by implementing an interface that re-declares the
804 // method public. Resort to the dex file to determine the correct class for the access check
Logan Chien4dd96f52012-02-29 01:26:58 +0800805 const DexFile& dex_file = mUnit->class_linker_->FindDexFile(referrer_class->GetDexCache());
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800806 methods_class =
Logan Chien4dd96f52012-02-29 01:26:58 +0800807 mUnit->class_linker_->ResolveType(dex_file,
808 dex_file.GetMethodId(method_idx).class_idx_,
809 referrer_class);
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800810 }
811 if (referrer_class->CanAccess(methods_class) &&
812 referrer_class->CanAccessMember(methods_class,
813 resolved_method->GetAccessFlags())) {
814 vtable_idx = resolved_method->GetMethodIndex();
Ian Rogersf320b632012-03-13 18:47:47 -0700815 const bool kEnableSharpening = true;
Ian Rogers2ed3b952012-03-17 11:49:39 -0700816 // Sharpen a virtual call into a direct call when the target is known.
817 bool can_sharpen = type == kVirtual && (resolved_method->IsFinal() ||
818 methods_class->IsFinal());
819 // ensure the vtable index will be correct to dispatch in the vtable of the super class
jeffhao4155fcd2012-03-21 11:42:12 -0700820 can_sharpen = can_sharpen || (type == kSuper && referrer_class != methods_class &&
Ian Rogers2ed3b952012-03-17 11:49:39 -0700821 referrer_class->IsSubClass(methods_class) &&
jeffhao4155fcd2012-03-21 11:42:12 -0700822 vtable_idx < methods_class->GetVTable()->GetLength() &&
823 methods_class->GetVTable()->Get(vtable_idx) == resolved_method);
Ian Rogers2ed3b952012-03-17 11:49:39 -0700824 if (kEnableSharpening && can_sharpen) {
825 stats_->ResolvedMethod(type);
Ian Rogersfb6adba2012-03-04 21:51:51 -0800826 // Sharpen a virtual call into a direct call. The method_idx is into referrer's
827 // dex cache, check that this resolved method is where we expect it.
828 CHECK(referrer_class->GetDexCache()->GetResolvedMethod(method_idx) == resolved_method)
829 << PrettyMethod(resolved_method);
Ian Rogers2ed3b952012-03-17 11:49:39 -0700830 stats_->VirtualMadeDirect(type);
831 GetCodeAndMethodForDirectCall(type, kDirect, resolved_method, direct_code, direct_method);
832 type = kDirect;
833 return true;
834 } else if (type == kSuper) {
835 // Unsharpened super calls are suspicious so go slowpath.
836 } else {
837 stats_->ResolvedMethod(type);
838 GetCodeAndMethodForDirectCall(type, type, resolved_method, direct_code, direct_method);
839 return true;
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800840 }
841 }
842 }
843 }
844 // Clean up any exception left by method/type resolution
845 Thread* thread = Thread::Current();
846 if (thread->IsExceptionPending()) {
847 thread->ClearException();
848 }
Ian Rogersc8b306f2012-02-17 21:34:44 -0800849 stats_->UnresolvedMethod(type);
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800850 return false; // Incomplete knowledge needs slow path.
851}
852
Brian Carlstromf5822582012-03-19 22:34:31 -0700853void Compiler::AddCodePatch(DexCache* dex_cache,
854 const DexFile* dex_file,
855 uint32_t referrer_method_idx,
856 uint32_t referrer_access_flags,
857 uint32_t target_method_idx,
858 bool target_is_direct,
Ian Rogers3fa13792012-03-18 15:53:45 -0700859 size_t literal_offset) {
860 MutexLock mu(compiled_methods_lock_);
Brian Carlstromf5822582012-03-19 22:34:31 -0700861 code_to_patch_.push_back(new PatchInformation(dex_cache,
862 dex_file,
863 referrer_method_idx,
864 referrer_access_flags,
865 target_method_idx,
866 target_is_direct,
867 literal_offset));
Ian Rogers3fa13792012-03-18 15:53:45 -0700868}
Brian Carlstromf5822582012-03-19 22:34:31 -0700869void Compiler::AddMethodPatch(DexCache* dex_cache,
870 const DexFile* dex_file,
871 uint32_t referrer_method_idx,
872 uint32_t referrer_access_flags,
873 uint32_t target_method_idx,
874 bool target_is_direct,
Ian Rogers3fa13792012-03-18 15:53:45 -0700875 size_t literal_offset) {
876 MutexLock mu(compiled_methods_lock_);
Brian Carlstromf5822582012-03-19 22:34:31 -0700877 methods_to_patch_.push_back(new PatchInformation(dex_cache,
878 dex_file,
879 referrer_method_idx,
880 referrer_access_flags,
881 target_method_idx,
882 target_is_direct,
883 literal_offset));
Ian Rogers3fa13792012-03-18 15:53:45 -0700884}
885
Brian Carlstrom5ead0952011-11-28 22:55:52 -0800886// Return true if the class should be skipped during compilation. We
887// never skip classes in the boot class loader. However, if we have a
888// non-boot class loader and we can resolve the class in the boot
889// class loader, we do skip the class. This happens if an app bundles
890// classes found in the boot classpath. Since at runtime we will
891// select the class from the boot classpath, do not attempt to resolve
892// or compile it now.
893static bool SkipClass(const ClassLoader* class_loader,
894 const DexFile& dex_file,
895 const DexFile::ClassDef& class_def) {
896 if (class_loader == NULL) {
897 return false;
898 }
899 const char* descriptor = dex_file.GetClassDescriptor(class_def);
900 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
901 Class* klass = class_linker->FindClass(descriptor, NULL);
902 if (klass == NULL) {
903 Thread* self = Thread::Current();
904 CHECK(self->IsExceptionPending());
905 self->ClearException();
906 return false;
907 }
908 return true;
909}
910
Brian Carlstrom731b2ab2012-03-06 16:53:35 -0800911class Context {
912 public:
913 Context(ClassLinker* class_linker,
914 const ClassLoader* class_loader,
915 Compiler* compiler,
916 DexCache* dex_cache,
917 const DexFile* dex_file)
918 : class_linker_(class_linker),
919 class_loader_(class_loader),
920 compiler_(compiler),
921 dex_cache_(dex_cache),
922 dex_file_(dex_file) {}
923
924 ClassLinker* GetClassLinker() {
925 CHECK(class_linker_ != NULL);
926 return class_linker_;
927 }
928 const ClassLoader* GetClassLoader() {
929 return class_loader_;
930 }
931 Compiler* GetCompiler() {
932 CHECK(compiler_ != NULL);
933 return compiler_;
934 }
935 DexCache* GetDexCache() {
936 CHECK(dex_cache_ != NULL);
937 return dex_cache_;
938 }
939 const DexFile* GetDexFile() {
940 CHECK(dex_file_ != NULL);
941 return dex_file_;
942 }
943
944 private:
945 ClassLinker* class_linker_;
946 const ClassLoader* class_loader_;
947 Compiler* compiler_;
948 DexCache* dex_cache_;
949 const DexFile* dex_file_;
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800950};
951
952typedef void Callback(Context* context, size_t index);
953
954class WorkerThread {
955 public:
Elliott Hughes1e409252012-02-06 11:21:27 -0800956 WorkerThread(Context* context, size_t begin, size_t end, Callback callback, size_t stripe, bool spawn)
957 : spawn_(spawn), context_(context), begin_(begin), end_(end), callback_(callback), stripe_(stripe) {
958 if (spawn_) {
959 CHECK_PTHREAD_CALL(pthread_create, (&pthread_, NULL, &Go, this), "compiler worker thread");
960 }
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800961 }
962
963 ~WorkerThread() {
Elliott Hughes1e409252012-02-06 11:21:27 -0800964 if (spawn_) {
965 CHECK_PTHREAD_CALL(pthread_join, (pthread_, NULL), "compiler worker shutdown");
966 }
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800967 }
968
969 private:
Elliott Hughes1e409252012-02-06 11:21:27 -0800970 static void* Go(void* arg) {
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800971 WorkerThread* worker = reinterpret_cast<WorkerThread*>(arg);
972 Runtime* runtime = Runtime::Current();
Elliott Hughes1e409252012-02-06 11:21:27 -0800973 if (worker->spawn_) {
Elliott Hughes462c9442012-03-23 18:47:50 -0700974 runtime->AttachCurrentThread("Compiler Worker", true, NULL);
Elliott Hughes1e409252012-02-06 11:21:27 -0800975 }
Elliott Hughes34e06962012-04-09 13:55:55 -0700976 Thread::Current()->SetState(kRunnable);
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800977 worker->Run();
Elliott Hughes1e409252012-02-06 11:21:27 -0800978 if (worker->spawn_) {
Elliott Hughes34e06962012-04-09 13:55:55 -0700979 Thread::Current()->SetState(kNative);
Elliott Hughes1e409252012-02-06 11:21:27 -0800980 runtime->DetachCurrentThread();
981 }
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800982 return NULL;
983 }
984
Elliott Hughes1e409252012-02-06 11:21:27 -0800985 void Go() {
986 Go(this);
987 }
988
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800989 void Run() {
Brian Carlstrom64277f32012-03-26 23:53:34 -0700990 Thread* self = Thread::Current();
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800991 for (size_t i = begin_; i < end_; i += stripe_) {
992 callback_(context_, i);
Brian Carlstrom64277f32012-03-26 23:53:34 -0700993 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException()) << " " << i;
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800994 }
995 }
996
997 pthread_t pthread_;
Elliott Hughes1e409252012-02-06 11:21:27 -0800998 bool spawn_;
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800999
1000 Context* context_;
1001 size_t begin_;
1002 size_t end_;
1003 Callback* callback_;
1004 size_t stripe_;
Elliott Hughes1e409252012-02-06 11:21:27 -08001005
1006 friend void ForAll(Context*, size_t, size_t, Callback, size_t);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001007};
1008
Elliott Hughes5523ee02012-02-03 18:18:34 -08001009void ForAll(Context* context, size_t begin, size_t end, Callback callback, size_t thread_count) {
Brian Carlstrom64277f32012-03-26 23:53:34 -07001010 Thread* self = Thread::Current();
1011 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
Elliott Hughes1e409252012-02-06 11:21:27 -08001012 CHECK_GT(thread_count, 0U);
Elliott Hughes81d91512012-02-03 16:38:43 -08001013
Elliott Hughes1e409252012-02-06 11:21:27 -08001014 std::vector<WorkerThread*> threads;
Elliott Hughes81d91512012-02-03 16:38:43 -08001015 for (size_t i = 0; i < thread_count; ++i) {
Elliott Hughes1e409252012-02-06 11:21:27 -08001016 threads.push_back(new WorkerThread(context, begin + i, end, callback, thread_count, (i != 0)));
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001017 }
Elliott Hughes1e409252012-02-06 11:21:27 -08001018 threads[0]->Go();
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001019
Elliott Hughes81d91512012-02-03 16:38:43 -08001020 // Switch to kVmWait while we're blocked waiting for the other threads to finish.
Elliott Hughes34e06962012-04-09 13:55:55 -07001021 ScopedThreadStateChange tsc(self, kVmWait);
Elliott Hughes81d91512012-02-03 16:38:43 -08001022 STLDeleteElements(&threads);
1023}
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001024
1025static void ResolveClassFieldsAndMethods(Context* context, size_t class_def_index) {
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001026 const DexFile& dex_file = *context->GetDexFile();
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001027
1028 // Method and Field are the worst. We can't resolve without either
1029 // context from the code use (to disambiguate virtual vs direct
1030 // method and instance vs static field) or from class
1031 // definitions. While the compiler will resolve what it can as it
1032 // needs it, here we try to resolve fields and methods used in class
1033 // definitions, since many of them many never be referenced by
1034 // generated code.
1035 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001036 if (SkipClass(context->GetClassLoader(), dex_file, class_def)) {
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001037 return;
1038 }
1039
1040 // Note the class_data pointer advances through the headers,
1041 // static fields, instance fields, direct methods, and virtual
1042 // methods.
1043 const byte* class_data = dex_file.GetClassData(class_def);
1044 if (class_data == NULL) {
1045 // empty class such as a marker interface
1046 return;
1047 }
Brian Carlstrom5ead0952011-11-28 22:55:52 -08001048 Thread* self = Thread::Current();
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001049 ClassLinker* class_linker = context->GetClassLinker();
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001050 DexCache* dex_cache = class_linker->FindDexCache(dex_file);
1051 ClassDataItemIterator it(dex_file, class_data);
1052 while (it.HasNextStaticField()) {
1053 Field* field = class_linker->ResolveField(dex_file, it.GetMemberIndex(), dex_cache,
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001054 context->GetClassLoader(), true);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001055 if (field == NULL) {
1056 CHECK(self->IsExceptionPending());
1057 self->ClearException();
1058 }
1059 it.Next();
1060 }
1061 while (it.HasNextInstanceField()) {
1062 Field* field = class_linker->ResolveField(dex_file, it.GetMemberIndex(), dex_cache,
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001063 context->GetClassLoader(), false);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001064 if (field == NULL) {
1065 CHECK(self->IsExceptionPending());
1066 self->ClearException();
1067 }
1068 it.Next();
1069 }
1070 while (it.HasNextDirectMethod()) {
1071 Method* method = class_linker->ResolveMethod(dex_file, it.GetMemberIndex(), dex_cache,
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001072 context->GetClassLoader(), true);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001073 if (method == NULL) {
1074 CHECK(self->IsExceptionPending());
1075 self->ClearException();
1076 }
1077 it.Next();
1078 }
1079 while (it.HasNextVirtualMethod()) {
1080 Method* method = class_linker->ResolveMethod(dex_file, it.GetMemberIndex(), dex_cache,
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001081 context->GetClassLoader(), false);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001082 if (method == NULL) {
1083 CHECK(self->IsExceptionPending());
1084 self->ClearException();
1085 }
1086 it.Next();
1087 }
1088 DCHECK(!it.HasNext());
1089}
1090
1091static void ResolveType(Context* context, size_t type_idx) {
1092 // Class derived values are more complicated, they require the linker and loader.
1093 Thread* self = Thread::Current();
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001094 Class* klass = context->GetClassLinker()->ResolveType(*context->GetDexFile(),
1095 type_idx,
1096 context->GetDexCache(),
1097 context->GetClassLoader());
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001098 if (klass == NULL) {
1099 CHECK(self->IsExceptionPending());
1100 Thread::Current()->ClearException();
1101 }
1102}
1103
1104void Compiler::ResolveDexFile(const ClassLoader* class_loader, const DexFile& dex_file, TimingLogger& timings) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001105 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Brian Carlstromaded5f72011-10-07 17:15:04 -07001106 DexCache* dex_cache = class_linker->FindDexCache(dex_file);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001107
Brian Carlstromae826982011-11-09 01:33:42 -08001108 // Strings are easy in that they always are simply resolved to literals in the same file
1109 if (image_ && image_classes_ == NULL) {
1110 // TODO: Add support for loading strings referenced by image_classes_
1111 // See also Compiler::CanAssumeTypeIsPresentInDexCache.
Brian Carlstromaded5f72011-10-07 17:15:04 -07001112 for (size_t string_idx = 0; string_idx < dex_cache->NumStrings(); string_idx++) {
1113 class_linker->ResolveString(dex_file, string_idx, dex_cache);
1114 }
Elliott Hughesff738062012-02-03 15:00:42 -08001115 timings.AddSplit("Resolve " + dex_file.GetLocation() + " Strings");
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001116 }
1117
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001118 Context context(class_linker, class_loader, this, dex_cache, &dex_file);
Elliott Hughes5523ee02012-02-03 18:18:34 -08001119 ForAll(&context, 0, dex_cache->NumResolvedTypes(), ResolveType, thread_count_);
Elliott Hughesff738062012-02-03 15:00:42 -08001120 timings.AddSplit("Resolve " + dex_file.GetLocation() + " Types");
Brian Carlstrom845490b2011-09-19 15:56:53 -07001121
Elliott Hughes5523ee02012-02-03 18:18:34 -08001122 ForAll(&context, 0, dex_file.NumClassDefs(), ResolveClassFieldsAndMethods, thread_count_);
Elliott Hughesff738062012-02-03 15:00:42 -08001123 timings.AddSplit("Resolve " + dex_file.GetLocation() + " MethodsAndFields");
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001124}
1125
Brian Carlstromae826982011-11-09 01:33:42 -08001126void Compiler::Verify(const ClassLoader* class_loader,
1127 const std::vector<const DexFile*>& dex_files) {
1128 for (size_t i = 0; i != dex_files.size(); ++i) {
1129 const DexFile* dex_file = dex_files[i];
jeffhao98eacac2011-09-14 16:11:53 -07001130 CHECK(dex_file != NULL);
1131 VerifyDexFile(class_loader, *dex_file);
1132 }
1133}
1134
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001135static void VerifyClass(Context* context, size_t class_def_index) {
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001136 const DexFile::ClassDef& class_def = context->GetDexFile()->GetClassDef(class_def_index);
1137 const char* descriptor = context->GetDexFile()->GetClassDescriptor(class_def);
1138 Class* klass = context->GetClassLinker()->FindClass(descriptor, context->GetClassLoader());
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001139 if (klass == NULL) {
1140 Thread* self = Thread::Current();
1141 CHECK(self->IsExceptionPending());
1142 self->ClearException();
jeffhaof56197c2012-03-05 18:01:54 -08001143
1144 /*
1145 * At compile time, we can still structurally verify the class even if FindClass fails.
1146 * This is to ensure the class is structurally sound for compilation. An unsound class
1147 * will be rejected by the verifier and later skipped during compilation in the compiler.
1148 */
1149 std::string error_msg;
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001150 if (!verifier::DexVerifier::VerifyClass(context->GetDexFile(), context->GetDexCache(),
1151 context->GetClassLoader(), class_def_index, error_msg)) {
1152 const DexFile::ClassDef& class_def = context->GetDexFile()->GetClassDef(class_def_index);
jeffhaof56197c2012-03-05 18:01:54 -08001153 LOG(ERROR) << "Verification failed on class "
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001154 << PrettyDescriptor(context->GetDexFile()->GetClassDescriptor(class_def))
jeffhaof56197c2012-03-05 18:01:54 -08001155 << " because: " << error_msg;
1156 }
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001157 return;
1158 }
1159 CHECK(klass->IsResolved()) << PrettyClass(klass);
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001160 context->GetClassLinker()->VerifyClass(klass);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001161
1162 if (klass->IsErroneous()) {
1163 // ClassLinker::VerifyClass throws, which isn't useful in the compiler.
1164 CHECK(Thread::Current()->IsExceptionPending());
1165 Thread::Current()->ClearException();
jeffhao1ac29442012-03-26 11:37:32 -07001166 art::Compiler::ClassReference ref(context->GetDexFile(), class_def_index);
1167 if (!verifier::DexVerifier::IsClassRejected(ref)) {
1168 // If the erroneous class wasn't rejected by the verifier, it was a soft error. We want
1169 // to try verification again at run-time, so move back into the resolved state.
1170 klass->SetStatus(Class::kStatusResolved);
1171 }
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001172 }
1173
jeffhao1ac29442012-03-26 11:37:32 -07001174 CHECK(klass->IsVerified() || klass->IsResolved() || klass->IsErroneous()) << PrettyClass(klass);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001175 CHECK(!Thread::Current()->IsExceptionPending()) << PrettyTypeOf(Thread::Current()->GetException());
1176}
1177
jeffhao98eacac2011-09-14 16:11:53 -07001178void Compiler::VerifyDexFile(const ClassLoader* class_loader, const DexFile& dex_file) {
jeffhaob4df5142011-09-19 20:25:32 -07001179 dex_file.ChangePermissions(PROT_READ | PROT_WRITE);
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07001180
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001181 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1182 Context context(class_linker, class_loader, this, class_linker->FindDexCache(dex_file), &dex_file);
Elliott Hughes5523ee02012-02-03 18:18:34 -08001183 ForAll(&context, 0, dex_file.NumClassDefs(), VerifyClass, thread_count_);
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07001184
jeffhaob4df5142011-09-19 20:25:32 -07001185 dex_file.ChangePermissions(PROT_READ);
Brian Carlstroma5a97a22011-09-15 14:08:49 -07001186}
1187
Brian Carlstromae826982011-11-09 01:33:42 -08001188void Compiler::InitializeClassesWithoutClinit(const ClassLoader* class_loader,
1189 const std::vector<const DexFile*>& dex_files) {
1190 for (size_t i = 0; i != dex_files.size(); ++i) {
1191 const DexFile* dex_file = dex_files[i];
Brian Carlstroma5a97a22011-09-15 14:08:49 -07001192 CHECK(dex_file != NULL);
1193 InitializeClassesWithoutClinit(class_loader, *dex_file);
1194 }
1195}
1196
1197void Compiler::InitializeClassesWithoutClinit(const ClassLoader* class_loader, const DexFile& dex_file) {
1198 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Brian Carlstromffca45d2011-09-16 12:10:49 -07001199 for (size_t class_def_index = 0; class_def_index < dex_file.NumClassDefs(); class_def_index++) {
1200 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
Brian Carlstroma5a97a22011-09-15 14:08:49 -07001201 const char* descriptor = dex_file.GetClassDescriptor(class_def);
1202 Class* klass = class_linker->FindClass(descriptor, class_loader);
Brian Carlstrom27ec9612011-09-19 20:20:38 -07001203 if (klass != NULL) {
jeffhao1ac29442012-03-26 11:37:32 -07001204 if (klass->IsVerified()) {
1205 // Only try to initialize classes that were successfully verified.
Ian Rogers0045a292012-03-31 21:08:41 -07001206 bool compiling_boot = Runtime::Current()->GetHeap()->GetSpaces().size() == 1;
1207 bool can_init_static_fields = compiling_boot &&
1208 IsImageClass(descriptor);
1209 class_linker->EnsureInitialized(klass, false, can_init_static_fields);
jeffhao1ac29442012-03-26 11:37:32 -07001210 }
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001211 // record the final class status if necessary
1212 Class::Status status = klass->GetStatus();
1213 ClassReference ref(&dex_file, class_def_index);
Elliott Hughesc225caa2012-02-03 15:43:37 -08001214 MutexLock mu(compiled_classes_lock_);
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001215 CompiledClass* compiled_class = GetCompiledClass(ref);
1216 if (compiled_class == NULL) {
1217 compiled_class = new CompiledClass(status);
1218 compiled_classes_[ref] = compiled_class;
1219 } else {
1220 DCHECK_EQ(status, compiled_class->GetStatus());
1221 }
Brian Carlstrom27ec9612011-09-19 20:20:38 -07001222 }
1223 // clear any class not found or verification exceptions
1224 Thread::Current()->ClearException();
Brian Carlstromffca45d2011-09-16 12:10:49 -07001225 }
1226
1227 DexCache* dex_cache = class_linker->FindDexCache(dex_file);
1228 for (size_t type_idx = 0; type_idx < dex_cache->NumResolvedTypes(); type_idx++) {
1229 Class* klass = class_linker->ResolveType(dex_file, type_idx, dex_cache, class_loader);
Brian Carlstrom27ec9612011-09-19 20:20:38 -07001230 if (klass == NULL) {
1231 Thread::Current()->ClearException();
1232 } else if (klass->IsInitialized()) {
Brian Carlstromffca45d2011-09-16 12:10:49 -07001233 dex_cache->GetInitializedStaticStorage()->Set(type_idx, klass);
1234 }
jeffhao98eacac2011-09-14 16:11:53 -07001235 }
1236}
1237
Brian Carlstromae826982011-11-09 01:33:42 -08001238void Compiler::Compile(const ClassLoader* class_loader,
1239 const std::vector<const DexFile*>& dex_files) {
1240 for (size_t i = 0; i != dex_files.size(); ++i) {
1241 const DexFile* dex_file = dex_files[i];
Brian Carlstrom83db7722011-08-26 17:32:56 -07001242 CHECK(dex_file != NULL);
1243 CompileDexFile(class_loader, *dex_file);
1244 }
1245}
1246
Elliott Hughesc225caa2012-02-03 15:43:37 -08001247void Compiler::CompileClass(Context* context, size_t class_def_index) {
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001248 const ClassLoader* class_loader = context->GetClassLoader();
1249 const DexFile& dex_file = *context->GetDexFile();
Elliott Hughesc225caa2012-02-03 15:43:37 -08001250 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
Logan Chien7f767612012-03-01 18:54:49 +08001251#if defined(ART_USE_LLVM_COMPILER)
Logan Chien7f767612012-03-01 18:54:49 +08001252 // TODO: Remove this. We should not lock the compiler_lock_ in CompileClass()
Shih-wei Liaoc4c98812012-03-10 21:55:51 -08001253 // However, without this mutex lock, we will get segmentation fault before
1254 // LLVM becomes multithreaded.
1255 Compiler* cmplr = context->GetCompiler();
1256 CompilerMutexLockFn f =
1257 FindFunction<CompilerMutexLockFn>(MakeCompilerSoName(cmplr->GetInstructionSet()),
1258 cmplr->compiler_library_,
1259 "compilerLLVMMutexLock");
1260 UniquePtr<MutexLock> GUARD((*f)(*cmplr));
Logan Chien7f767612012-03-01 18:54:49 +08001261#endif
1262
Brian Carlstrom5ead0952011-11-28 22:55:52 -08001263 if (SkipClass(class_loader, dex_file, class_def)) {
1264 return;
1265 }
jeffhaod1224c72012-02-29 13:43:08 -08001266 ClassReference ref(&dex_file, class_def_index);
1267 // Skip compiling classes with generic verifier failures since they will still fail at runtime
1268 if (verifier::DexVerifier::IsClassRejected(ref)) {
1269 return;
1270 }
Ian Rogers0571d352011-11-03 19:51:38 -07001271 const byte* class_data = dex_file.GetClassData(class_def);
1272 if (class_data == NULL) {
1273 // empty class, probably a marker interface
1274 return;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001275 }
Ian Rogers0571d352011-11-03 19:51:38 -07001276 ClassDataItemIterator it(dex_file, class_data);
1277 // Skip fields
1278 while (it.HasNextStaticField()) {
1279 it.Next();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001280 }
Ian Rogers0571d352011-11-03 19:51:38 -07001281 while (it.HasNextInstanceField()) {
1282 it.Next();
1283 }
1284 // Compile direct methods
1285 while (it.HasNextDirectMethod()) {
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001286 context->GetCompiler()->CompileMethod(it.GetMethodCodeItem(), it.GetMemberAccessFlags(),
1287 it.GetMemberIndex(), class_loader, dex_file);
Ian Rogers0571d352011-11-03 19:51:38 -07001288 it.Next();
1289 }
1290 // Compile virtual methods
1291 while (it.HasNextVirtualMethod()) {
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001292 context->GetCompiler()->CompileMethod(it.GetMethodCodeItem(), it.GetMemberAccessFlags(),
1293 it.GetMemberIndex(), class_loader, dex_file);
Ian Rogers0571d352011-11-03 19:51:38 -07001294 it.Next();
1295 }
1296 DCHECK(!it.HasNext());
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001297}
1298
Elliott Hughesc225caa2012-02-03 15:43:37 -08001299void Compiler::CompileDexFile(const ClassLoader* class_loader, const DexFile& dex_file) {
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001300 Context context(NULL, class_loader, this, NULL, &dex_file);
Elliott Hughes5523ee02012-02-03 18:18:34 -08001301 ForAll(&context, 0, dex_file.NumClassDefs(), Compiler::CompileClass, thread_count_);
Elliott Hughesc225caa2012-02-03 15:43:37 -08001302}
1303
Ian Rogersa3760aa2011-11-14 14:32:37 -08001304void Compiler::CompileMethod(const DexFile::CodeItem* code_item, uint32_t access_flags,
1305 uint32_t method_idx, const ClassLoader* class_loader,
1306 const DexFile& dex_file) {
Elliott Hughesf09afe82011-10-16 14:24:21 -07001307 CompiledMethod* compiled_method = NULL;
Elliott Hughesbb551fa2012-01-25 16:35:29 -08001308 uint64_t start_ns = NanoTime();
Logan Chien4dd96f52012-02-29 01:26:58 +08001309
Ian Rogers169c9a72011-11-13 20:13:17 -08001310 if ((access_flags & kAccNative) != 0) {
Ian Rogers57b86d42012-03-27 16:05:41 -07001311 compiled_method = (*jni_compiler_)(*this, access_flags, method_idx, dex_file);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07001312 CHECK(compiled_method != NULL);
Ian Rogers169c9a72011-11-13 20:13:17 -08001313 } else if ((access_flags & kAccAbstract) != 0) {
Brian Carlstrom2cc022b2011-08-25 10:05:39 -07001314 } else {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001315 compiled_method = (*compiler_)(*this, code_item, access_flags, method_idx, class_loader,
1316 dex_file);
Elliott Hughesbb551fa2012-01-25 16:35:29 -08001317 CHECK(compiled_method != NULL) << PrettyMethod(method_idx, dex_file);
1318 }
Ian Rogers3bb17a62012-01-27 23:56:44 -08001319 uint64_t duration_ns = NanoTime() - start_ns;
buzbee5abfa3e2012-01-31 17:01:43 -08001320 if (duration_ns > MsToNs(100)) {
Elliott Hughesbb551fa2012-01-25 16:35:29 -08001321 LOG(WARNING) << "Compilation of " << PrettyMethod(method_idx, dex_file)
Ian Rogers3bb17a62012-01-27 23:56:44 -08001322 << " took " << PrettyDuration(duration_ns);
Elliott Hughesf09afe82011-10-16 14:24:21 -07001323 }
1324
1325 if (compiled_method != NULL) {
Ian Rogers0571d352011-11-03 19:51:38 -07001326 MethodReference ref(&dex_file, method_idx);
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001327 CHECK(GetCompiledMethod(ref) == NULL) << PrettyMethod(method_idx, dex_file);
Elliott Hughesc225caa2012-02-03 15:43:37 -08001328 MutexLock mu(compiled_methods_lock_);
Ian Rogers0571d352011-11-03 19:51:38 -07001329 compiled_methods_[ref] = compiled_method;
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001330 DCHECK(GetCompiledMethod(ref) != NULL) << PrettyMethod(method_idx, dex_file);
Brian Carlstrom2cc022b2011-08-25 10:05:39 -07001331 }
Brian Carlstrom9baa4ae2011-09-01 21:14:14 -07001332
Ian Rogers45619fc2012-02-29 11:15:25 -08001333 uint32_t shorty_len;
1334 const char* shorty = dex_file.GetMethodShorty(dex_file.GetMethodId(method_idx), &shorty_len);
Ian Rogers169c9a72011-11-13 20:13:17 -08001335 bool is_static = (access_flags & kAccStatic) != 0;
Ian Rogers0571d352011-11-03 19:51:38 -07001336 const CompiledInvokeStub* compiled_invoke_stub = FindInvokeStub(is_static, shorty);
1337 if (compiled_invoke_stub == NULL) {
Shih-wei Liaoc4c98812012-03-10 21:55:51 -08001338 compiled_invoke_stub = (*create_invoke_stub_)(*this, is_static, shorty, shorty_len);
Ian Rogers0571d352011-11-03 19:51:38 -07001339 CHECK(compiled_invoke_stub != NULL);
1340 InsertInvokeStub(is_static, shorty, compiled_invoke_stub);
Ian Rogers2c8f6532011-09-02 17:16:34 -07001341 }
Ian Rogers0571d352011-11-03 19:51:38 -07001342 CHECK(!Thread::Current()->IsExceptionPending()) << PrettyMethod(method_idx, dex_file);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07001343}
1344
Ian Rogers0571d352011-11-03 19:51:38 -07001345static std::string MakeInvokeStubKey(bool is_static, const char* shorty) {
1346 std::string key(shorty);
1347 if (is_static) {
Elliott Hughesbb551fa2012-01-25 16:35:29 -08001348 key += "$"; // Must not be a shorty type character.
Brian Carlstrom3320cf42011-10-04 14:58:28 -07001349 }
Ian Rogers0571d352011-11-03 19:51:38 -07001350 return key;
Brian Carlstrom3320cf42011-10-04 14:58:28 -07001351}
1352
Ian Rogers0571d352011-11-03 19:51:38 -07001353const CompiledInvokeStub* Compiler::FindInvokeStub(bool is_static, const char* shorty) const {
Elliott Hughesc225caa2012-02-03 15:43:37 -08001354 MutexLock mu(compiled_invoke_stubs_lock_);
Elliott Hughes95572412011-12-13 18:14:20 -08001355 const std::string key(MakeInvokeStubKey(is_static, shorty));
Ian Rogers0571d352011-11-03 19:51:38 -07001356 InvokeStubTable::const_iterator it = compiled_invoke_stubs_.find(key);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07001357 if (it == compiled_invoke_stubs_.end()) {
1358 return NULL;
Ian Rogers0571d352011-11-03 19:51:38 -07001359 } else {
1360 DCHECK(it->second != NULL);
1361 return it->second;
1362 }
1363}
1364
1365void Compiler::InsertInvokeStub(bool is_static, const char* shorty,
1366 const CompiledInvokeStub* compiled_invoke_stub) {
Elliott Hughesc225caa2012-02-03 15:43:37 -08001367 MutexLock mu(compiled_invoke_stubs_lock_);
Elliott Hughes95572412011-12-13 18:14:20 -08001368 std::string key(MakeInvokeStubKey(is_static, shorty));
Ian Rogers0571d352011-11-03 19:51:38 -07001369 compiled_invoke_stubs_[key] = compiled_invoke_stub;
1370}
1371
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001372CompiledClass* Compiler::GetCompiledClass(ClassReference ref) const {
Elliott Hughesc225caa2012-02-03 15:43:37 -08001373 MutexLock mu(compiled_classes_lock_);
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001374 ClassTable::const_iterator it = compiled_classes_.find(ref);
1375 if (it == compiled_classes_.end()) {
1376 return NULL;
1377 }
1378 CHECK(it->second != NULL);
1379 return it->second;
1380}
1381
Ian Rogers0571d352011-11-03 19:51:38 -07001382CompiledMethod* Compiler::GetCompiledMethod(MethodReference ref) const {
Elliott Hughesc225caa2012-02-03 15:43:37 -08001383 MutexLock mu(compiled_methods_lock_);
Ian Rogers0571d352011-11-03 19:51:38 -07001384 MethodTable::const_iterator it = compiled_methods_.find(ref);
1385 if (it == compiled_methods_.end()) {
1386 return NULL;
Brian Carlstrom3320cf42011-10-04 14:58:28 -07001387 }
1388 CHECK(it->second != NULL);
1389 return it->second;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001390}
1391
Brian Carlstrome7d856b2012-01-11 18:10:55 -08001392void Compiler::SetGcMaps(const ClassLoader* class_loader, const std::vector<const DexFile*>& dex_files) {
1393 for (size_t i = 0; i != dex_files.size(); ++i) {
1394 const DexFile* dex_file = dex_files[i];
1395 CHECK(dex_file != NULL);
1396 SetGcMapsDexFile(class_loader, *dex_file);
1397 }
1398}
1399
1400void Compiler::SetGcMapsDexFile(const ClassLoader* class_loader, const DexFile& dex_file) {
1401 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1402 DexCache* dex_cache = class_linker->FindDexCache(dex_file);
1403 for (size_t class_def_index = 0; class_def_index < dex_file.NumClassDefs(); class_def_index++) {
1404 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
1405 const char* descriptor = dex_file.GetClassDescriptor(class_def);
1406 Class* klass = class_linker->FindClass(descriptor, class_loader);
1407 if (klass == NULL || !klass->IsVerified()) {
1408 Thread::Current()->ClearException();
1409 continue;
1410 }
1411 const byte* class_data = dex_file.GetClassData(class_def);
1412 if (class_data == NULL) {
1413 // empty class such as a marker interface
1414 continue;
1415 }
1416 ClassDataItemIterator it(dex_file, class_data);
1417 while (it.HasNextStaticField()) {
1418 it.Next();
1419 }
1420 while (it.HasNextInstanceField()) {
1421 it.Next();
1422 }
1423 while (it.HasNextDirectMethod()) {
1424 Method* method = class_linker->ResolveMethod(dex_file, it.GetMemberIndex(), dex_cache,
1425 class_loader, true);
1426 SetGcMapsMethod(dex_file, method);
1427 it.Next();
1428 }
1429 while (it.HasNextVirtualMethod()) {
1430 Method* method = class_linker->ResolveMethod(dex_file, it.GetMemberIndex(), dex_cache,
1431 class_loader, false);
1432 SetGcMapsMethod(dex_file, method);
1433 it.Next();
1434 }
1435 }
1436}
1437
1438void Compiler::SetGcMapsMethod(const DexFile& dex_file, Method* method) {
1439 if (method == NULL) {
1440 Thread::Current()->ClearException();
1441 return;
1442 }
1443 uint16_t method_idx = method->GetDexMethodIndex();
1444 MethodReference ref(&dex_file, method_idx);
1445 CompiledMethod* compiled_method = GetCompiledMethod(ref);
1446 if (compiled_method == NULL) {
1447 return;
1448 }
1449 const std::vector<uint8_t>* gc_map = verifier::DexVerifier::GetGcMap(ref);
1450 if (gc_map == NULL) {
1451 return;
1452 }
1453 compiled_method->SetGcMap(*gc_map);
1454}
1455
Logan Chien8b977d32012-02-21 19:14:55 +08001456#if defined(ART_USE_LLVM_COMPILER)
Logan Chien8b977d32012-02-21 19:14:55 +08001457void Compiler::SetBitcodeFileName(std::string const& filename) {
Logan Chien106b2a02012-03-18 04:41:38 +08001458 typedef void (*SetBitcodeFileNameFn)(Compiler&, std::string const&);
1459
1460 SetBitcodeFileNameFn set_bitcode_file_name =
1461 FindFunction<SetBitcodeFileNameFn>(MakeCompilerSoName(instruction_set_),
1462 compiler_library_,
1463 "compilerLLVMSetBitcodeFileName");
1464
1465 set_bitcode_file_name(*this, filename);
Logan Chien8b977d32012-02-21 19:14:55 +08001466}
Logan Chienf7015fd2012-03-18 01:19:37 +08001467
1468void Compiler::EnableAutoElfLoading() {
1469 compiler_enable_auto_elf_loading_(*this);
1470}
1471
1472const void* Compiler::GetMethodCodeAddr(const CompiledMethod* cm,
1473 const Method* method) const {
1474 return compiler_get_method_code_addr_(*this, cm, method);
1475}
1476
1477const Method::InvokeStub* Compiler::GetMethodInvokeStubAddr(const CompiledInvokeStub* cm,
1478 const Method* method) const {
1479 return compiler_get_method_invoke_stub_addr_(*this, cm, method);
1480}
Logan Chiendf576142012-03-20 17:36:32 +08001481
1482std::vector<ElfImage> Compiler::GetElfImages() const {
1483 typedef std::vector<ElfImage> (*GetElfImagesFn)(const Compiler&);
1484
1485 GetElfImagesFn get_elf_images =
1486 FindFunction<GetElfImagesFn>(MakeCompilerSoName(instruction_set_),
1487 compiler_library_,
1488 "compilerLLVMGetElfImages");
1489
1490 return get_elf_images(*this);
1491}
Logan Chien8b977d32012-02-21 19:14:55 +08001492#endif
1493
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001494} // namespace art