blob: 0bf46731e7b621a4019e22521f01f48318dc1555 [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 Carlstrom2cc022b2011-08-25 10:05:39 -070025#include "assembler.h"
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -070026#include "class_linker.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -070027#include "class_loader.h"
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -070028#include "dex_cache.h"
jeffhaof56197c2012-03-05 18:01:54 -080029#include "dex_verifier.h"
Brian Carlstrom9baa4ae2011-09-01 21:14:14 -070030#include "jni_internal.h"
Logan Chien4dd96f52012-02-29 01:26:58 +080031#include "oat_compilation_unit.h"
Brian Carlstrom3320cf42011-10-04 14:58:28 -070032#include "oat_file.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080033#include "object_utils.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -070034#include "runtime.h"
Elliott Hughesb3bd5f02012-03-08 21:05:27 -080035#include "space.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"
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -070038
Elliott Hughes059d5c12012-03-12 17:39:18 -070039#if defined(__APPLE__)
40#include <mach-o/dyld.h>
41#endif
42
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -070043namespace art {
44
Shih-wei Liaoc486c112011-09-13 16:43:52 -070045namespace arm {
Ian Rogersbdb03912011-09-14 00:55:44 -070046 ByteArray* CreateAbstractMethodErrorStub();
Ian Rogers1cb0a1d2011-10-06 15:24:35 -070047 ByteArray* ArmCreateResolutionTrampoline(Runtime::TrampolineType type);
Elliott Hughes8add92d2012-01-18 18:18:43 -080048 ByteArray* CreateJniDlsymLookupStub();
Shih-wei Liaoc486c112011-09-13 16:43:52 -070049}
Shih-wei Liaoc486c112011-09-13 16:43:52 -070050namespace x86 {
Ian Rogersbdb03912011-09-14 00:55:44 -070051 ByteArray* CreateAbstractMethodErrorStub();
Ian Rogers1cb0a1d2011-10-06 15:24:35 -070052 ByteArray* X86CreateResolutionTrampoline(Runtime::TrampolineType type);
Elliott Hughes8add92d2012-01-18 18:18:43 -080053 ByteArray* CreateJniDlsymLookupStub();
Brian Carlstrome24fa612011-09-29 00:53:55 -070054}
55
Ian Rogers996cc582012-02-14 22:23:29 -080056static double Percentage(size_t x, size_t y) {
Elliott Hughes398f64b2012-03-26 18:05:48 -070057 return 100.0 * (static_cast<double>(x)) / (static_cast<double>(x + y));
Ian Rogers996cc582012-02-14 22:23:29 -080058}
59
60static void DumpStat(size_t x, size_t y, const char* str) {
61 if (x == 0 && y == 0) {
62 return;
63 }
64 LOG(INFO) << Percentage(x, y) << "% of " << str << " for " << (x + y) << " cases";
65}
66
Ian Rogersc8b306f2012-02-17 21:34:44 -080067class AOTCompilationStats {
68 public:
69 AOTCompilationStats() : stats_lock_("AOT compilation statistics lock"),
70 types_in_dex_cache_(0), types_not_in_dex_cache_(0),
71 strings_in_dex_cache_(0), strings_not_in_dex_cache_(0),
72 resolved_types_(0), unresolved_types_(0),
73 resolved_instance_fields_(0), unresolved_instance_fields_(0),
Ian Rogers2ed3b952012-03-17 11:49:39 -070074 resolved_local_static_fields_(0), resolved_static_fields_(0), unresolved_static_fields_(0) {
75 for (size_t i = 0; i <= kMaxInvokeType; i++) {
Ian Rogersc8b306f2012-02-17 21:34:44 -080076 resolved_methods_[i] = 0;
77 unresolved_methods_[i] = 0;
Ian Rogers2ed3b952012-03-17 11:49:39 -070078 virtual_made_direct_[i] = 0;
79 direct_calls_to_boot_[i] = 0;
80 direct_methods_to_boot_[i] = 0;
Elliott Hughesb25c3f62012-03-26 16:35:06 -070081 }
Ian Rogersc8b306f2012-02-17 21:34:44 -080082 }
83
84 void Dump() {
85 DumpStat(types_in_dex_cache_, types_not_in_dex_cache_, "types known to be in dex cache");
86 DumpStat(strings_in_dex_cache_, strings_not_in_dex_cache_, "strings known to be in dex cache");
87 DumpStat(resolved_types_, unresolved_types_, "types resolved");
88 DumpStat(resolved_instance_fields_, unresolved_instance_fields_, "instance fields resolved");
89 DumpStat(resolved_local_static_fields_ + resolved_static_fields_, unresolved_static_fields_,
90 "static fields resolved");
91 DumpStat(resolved_local_static_fields_, resolved_static_fields_ + unresolved_static_fields_,
92 "static fields local to a class");
93
Ian Rogers2ed3b952012-03-17 11:49:39 -070094 for (size_t i = 0; i <= kMaxInvokeType; i++) {
Ian Rogersc8b306f2012-02-17 21:34:44 -080095 std::ostringstream oss;
Ian Rogers2ed3b952012-03-17 11:49:39 -070096 oss << static_cast<InvokeType>(i) << " methods were AOT resolved";
Ian Rogersc8b306f2012-02-17 21:34:44 -080097 DumpStat(resolved_methods_[i], unresolved_methods_[i], oss.str().c_str());
Ian Rogers2ed3b952012-03-17 11:49:39 -070098 if (virtual_made_direct_[i] > 0) {
99 std::ostringstream oss2;
100 oss2 << static_cast<InvokeType>(i) << " methods made direct";
101 DumpStat(virtual_made_direct_[i],
102 resolved_methods_[i] + unresolved_methods_[i] - virtual_made_direct_[i],
103 oss2.str().c_str());
104 }
105 if (direct_calls_to_boot_[i] > 0) {
106 std::ostringstream oss2;
107 oss2 << static_cast<InvokeType>(i) << " method calls are direct into boot";
108 DumpStat(direct_calls_to_boot_[i],
109 resolved_methods_[i] + unresolved_methods_[i] - direct_calls_to_boot_[i],
110 oss2.str().c_str());
111 }
112 if (direct_methods_to_boot_[i] > 0) {
113 std::ostringstream oss2;
114 oss2 << static_cast<InvokeType>(i) << " method calls have methods in boot";
115 DumpStat(direct_methods_to_boot_[i],
116 resolved_methods_[i] + unresolved_methods_[i] - direct_methods_to_boot_[i],
117 oss2.str().c_str());
118 }
Ian Rogersc8b306f2012-02-17 21:34:44 -0800119 }
120 }
Ian Rogers996cc582012-02-14 22:23:29 -0800121
122// Allow lossy statistics in non-debug builds
123#ifndef NDEBUG
124#define STATS_LOCK() MutexLock mu(stats_lock_)
125#else
126#define STATS_LOCK()
127#endif
128
Ian Rogersc8b306f2012-02-17 21:34:44 -0800129 void TypeInDexCache() {
130 STATS_LOCK();
131 types_in_dex_cache_++;
Ian Rogers996cc582012-02-14 22:23:29 -0800132 }
Ian Rogers996cc582012-02-14 22:23:29 -0800133
Ian Rogersc8b306f2012-02-17 21:34:44 -0800134 void TypeNotInDexCache() {
135 STATS_LOCK();
136 types_not_in_dex_cache_++;
Ian Rogers996cc582012-02-14 22:23:29 -0800137 }
Ian Rogersc8b306f2012-02-17 21:34:44 -0800138
139 void StringInDexCache() {
140 STATS_LOCK();
141 strings_in_dex_cache_++;
142 }
143
144 void StringNotInDexCache() {
145 STATS_LOCK();
146 strings_not_in_dex_cache_++;
147 }
148
149 void TypeDoesntNeedAccessCheck() {
150 STATS_LOCK();
151 resolved_types_++;
152 }
153
154 void TypeNeedsAccessCheck() {
155 STATS_LOCK();
156 unresolved_types_++;
157 }
158
159 void ResolvedInstanceField() {
160 STATS_LOCK();
161 resolved_instance_fields_++;
162 }
163
Elliott Hughesb25c3f62012-03-26 16:35:06 -0700164 void UnresolvedInstanceField() {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800165 STATS_LOCK();
166 unresolved_instance_fields_++;
167 }
168
169 void ResolvedLocalStaticField() {
170 STATS_LOCK();
171 resolved_local_static_fields_++;
172 }
173
174 void ResolvedStaticField() {
175 STATS_LOCK();
176 resolved_static_fields_++;
177 }
178
179 void UnresolvedStaticField() {
180 STATS_LOCK();
181 unresolved_static_fields_++;
182 }
183
184 void ResolvedMethod(InvokeType type) {
185 DCHECK_LE(type, kMaxInvokeType);
186 STATS_LOCK();
187 resolved_methods_[type]++;
188 }
189
190 void UnresolvedMethod(InvokeType type) {
191 DCHECK_LE(type, kMaxInvokeType);
192 STATS_LOCK();
193 unresolved_methods_[type]++;
194 }
195
Ian Rogers2ed3b952012-03-17 11:49:39 -0700196 void VirtualMadeDirect(InvokeType type) {
197 DCHECK_LE(type, kMaxInvokeType);
Ian Rogersfb6adba2012-03-04 21:51:51 -0800198 STATS_LOCK();
Ian Rogers2ed3b952012-03-17 11:49:39 -0700199 virtual_made_direct_[type]++;
Ian Rogersfb6adba2012-03-04 21:51:51 -0800200 }
Ian Rogers2ed3b952012-03-17 11:49:39 -0700201
202 void DirectCallsToBoot(InvokeType type) {
203 DCHECK_LE(type, kMaxInvokeType);
204 STATS_LOCK();
205 direct_calls_to_boot_[type]++;
206 }
207
208 void DirectMethodsToBoot(InvokeType type) {
209 DCHECK_LE(type, kMaxInvokeType);
210 STATS_LOCK();
211 direct_methods_to_boot_[type]++;
212 }
213
Ian Rogersc8b306f2012-02-17 21:34:44 -0800214 private:
215 Mutex stats_lock_;
216
217 size_t types_in_dex_cache_;
218 size_t types_not_in_dex_cache_;
219
220 size_t strings_in_dex_cache_;
221 size_t strings_not_in_dex_cache_;
222
223 size_t resolved_types_;
224 size_t unresolved_types_;
225
226 size_t resolved_instance_fields_;
227 size_t unresolved_instance_fields_;
228
229 size_t resolved_local_static_fields_;
230 size_t resolved_static_fields_;
231 size_t unresolved_static_fields_;
232
233 size_t resolved_methods_[kMaxInvokeType + 1];
234 size_t unresolved_methods_[kMaxInvokeType + 1];
Ian Rogers2ed3b952012-03-17 11:49:39 -0700235 size_t virtual_made_direct_[kMaxInvokeType + 1];
236 size_t direct_calls_to_boot_[kMaxInvokeType + 1];
237 size_t direct_methods_to_boot_[kMaxInvokeType + 1];
Ian Rogersc8b306f2012-02-17 21:34:44 -0800238
Elliott Hughesb25c3f62012-03-26 16:35:06 -0700239 DISALLOW_COPY_AND_ASSIGN(AOTCompilationStats);
Ian Rogersc8b306f2012-02-17 21:34:44 -0800240};
Ian Rogers996cc582012-02-14 22:23:29 -0800241
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800242static std::string MakeCompilerSoName(InstructionSet instruction_set) {
243 // TODO: is the ARM/Thumb2 instruction set distinction really buying us anything,
244 // or just causing hassle like this?
245 if (instruction_set == kThumb2) {
246 instruction_set = kArm;
247 }
248
Elliott Hughes059d5c12012-03-12 17:39:18 -0700249 // Capitalize the instruction set, because that's what we do in the build system.
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800250 std::ostringstream instruction_set_name_os;
251 instruction_set_name_os << instruction_set;
252 std::string instruction_set_name(instruction_set_name_os.str());
253 for (size_t i = 0; i < instruction_set_name.size(); ++i) {
254 instruction_set_name[i] = toupper(instruction_set_name[i]);
255 }
Elliott Hughes059d5c12012-03-12 17:39:18 -0700256
257 // Bad things happen if we pull in the libartd-compiler to a libart dex2oat or vice versa,
258 // because we end up with both libart and libartd in the same address space!
Elliott Hughes67d92002012-03-26 15:08:51 -0700259 const char* suffix = (kIsDebugBuild ? "d" : "");
Elliott Hughes059d5c12012-03-12 17:39:18 -0700260
261 // Work out the filename for the compiler library.
Shih-wei Liaoc4c98812012-03-10 21:55:51 -0800262#if !defined(ART_USE_LLVM_COMPILER)
Elliott Hughes059d5c12012-03-12 17:39:18 -0700263 std::string library_name(StringPrintf("art%s-compiler-%s", suffix, instruction_set_name.c_str()));
Shih-wei Liaoc4c98812012-03-10 21:55:51 -0800264#else
265 std::string library_name(StringPrintf("art%s-compiler-llvm", suffix));
266#endif
Elliott Hughes059d5c12012-03-12 17:39:18 -0700267 std::string filename(StringPrintf(OS_SHARED_LIB_FORMAT_STR, library_name.c_str()));
268
269#if defined(__APPLE__)
270 // On Linux, dex2oat will have been built with an RPATH of $ORIGIN/../lib, so dlopen(3) will find
271 // the .so by itself. On Mac OS, there isn't really an equivalent, so we have to manually do the
272 // same work.
Elliott Hughes059d5c12012-03-12 17:39:18 -0700273 uint32_t executable_path_length = 0;
Elliott Hughes448e93c2012-03-28 22:30:06 -0700274 _NSGetExecutablePath(NULL, &executable_path_length);
275 std::string path(executable_path_length, static_cast<char>(0));
276 CHECK_EQ(_NSGetExecutablePath(&path[0], &executable_path_length), 0);
Elliott Hughes059d5c12012-03-12 17:39:18 -0700277
278 // Strip the "/dex2oat".
279 size_t last_slash = path.find_last_of('/');
280 CHECK_NE(last_slash, std::string::npos) << path;
281 path.resize(last_slash);
282
283 // Strip the "/bin".
284 last_slash = path.find_last_of('/');
285 path.resize(last_slash);
286
287 filename = path + "/lib/" + filename;
288#endif
289 return filename;
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800290}
291
Elliott Hughes46f060a2012-03-09 17:36:50 -0800292template<typename Fn>
293static Fn FindFunction(const std::string& compiler_so_name, void* library, const char* name) {
294 Fn fn = reinterpret_cast<Fn>(dlsym(library, name));
295 if (fn == NULL) {
296 LOG(FATAL) << "Couldn't find \"" << name << "\" in compiler library " << compiler_so_name << ": " << dlerror();
297 }
Elliott Hughes059d5c12012-03-12 17:39:18 -0700298 VLOG(compiler) << "Found \"" << name << "\" at " << reinterpret_cast<void*>(fn);
Elliott Hughes46f060a2012-03-09 17:36:50 -0800299 return fn;
300}
301
Elliott Hughes5523ee02012-02-03 18:18:34 -0800302Compiler::Compiler(InstructionSet instruction_set, bool image, size_t thread_count,
Brian Carlstromba0668e2012-03-26 13:14:07 -0700303 bool support_debugging, const std::set<std::string>* image_classes,
304 bool dump_stats, bool dump_timings)
Brian Carlstromaded5f72011-10-07 17:15:04 -0700305 : instruction_set_(instruction_set),
Elliott Hughesc225caa2012-02-03 15:43:37 -0800306 compiled_classes_lock_("compiled classes lock"),
307 compiled_methods_lock_("compiled method lock"),
308 compiled_invoke_stubs_lock_("compiled invoke stubs lock"),
Brian Carlstromaded5f72011-10-07 17:15:04 -0700309 image_(image),
Elliott Hughes5523ee02012-02-03 18:18:34 -0800310 thread_count_(thread_count),
Elliott Hughesde6e4cf2012-02-27 14:46:06 -0800311 support_debugging_(support_debugging),
Ian Rogersc8b306f2012-02-17 21:34:44 -0800312 stats_(new AOTCompilationStats),
Brian Carlstromba0668e2012-03-26 13:14:07 -0700313 dump_stats_(dump_stats),
314 dump_timings_(dump_timings),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800315 image_classes_(image_classes),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800316 compiler_library_(NULL),
Elliott Hughes46f060a2012-03-09 17:36:50 -0800317 compiler_(NULL),
Elliott Hughes6f4976c2012-03-13 21:19:01 -0700318 compiler_context_(NULL),
Elliott Hughes46f060a2012-03-09 17:36:50 -0800319 jni_compiler_(NULL),
Logan Chienf7015fd2012-03-18 01:19:37 +0800320 create_invoke_stub_(NULL)
321#if defined(ART_USE_LLVM_COMPILER)
322 , compiler_enable_auto_elf_loading_(NULL),
323 compiler_get_method_code_addr_(NULL),
324 compiler_get_method_invoke_stub_addr_(NULL)
325#endif
326{
Shih-wei Liaoc4c98812012-03-10 21:55:51 -0800327 std::string compiler_so_name(MakeCompilerSoName(instruction_set_));
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800328 compiler_library_ = dlopen(compiler_so_name.c_str(), RTLD_LAZY);
329 if (compiler_library_ == NULL) {
330 LOG(FATAL) << "Couldn't find compiler library " << compiler_so_name << ": " << dlerror();
331 }
332 VLOG(compiler) << "dlopen(\"" << compiler_so_name << "\", RTLD_LAZY) returned " << compiler_library_;
333
Logan Chien106b2a02012-03-18 04:41:38 +0800334#if defined(ART_USE_LLVM_COMPILER)
335 // Initialize compiler_context_
336 typedef void (*InitCompilerContextFn)(Compiler&);
337
338 InitCompilerContextFn init_compiler_context =
339 FindFunction<void (*)(Compiler&)>(compiler_so_name,
340 compiler_library_,
341 "ArtInitCompilerContext");
342
343 init_compiler_context(*this);
344#endif
345
Elliott Hughes3fa1b7e2012-03-13 17:06:22 -0700346 compiler_ = FindFunction<CompilerFn>(compiler_so_name, compiler_library_, "ArtCompileMethod");
Elliott Hughes46f060a2012-03-09 17:36:50 -0800347 jni_compiler_ = FindFunction<JniCompilerFn>(compiler_so_name, compiler_library_, "ArtJniCompileMethod");
348 create_invoke_stub_ = FindFunction<CreateInvokeStubFn>(compiler_so_name, compiler_library_, "ArtCreateInvokeStub");
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800349
Logan Chienf7015fd2012-03-18 01:19:37 +0800350#if defined(ART_USE_LLVM_COMPILER)
351 compiler_enable_auto_elf_loading_ = FindFunction<CompilerEnableAutoElfLoadingFn>(
352 compiler_so_name, compiler_library_, "compilerLLVMEnableAutoElfLoading");
353 compiler_get_method_code_addr_ = FindFunction<CompilerGetMethodCodeAddrFn>(
354 compiler_so_name, compiler_library_, "compilerLLVMGetMethodCodeAddr");
355 compiler_get_method_invoke_stub_addr_ = FindFunction<CompilerGetMethodInvokeStubAddrFn>(
356 compiler_so_name, compiler_library_, "compilerLLVMGetMethodInvokeStubAddr");
357#endif
358
Brian Carlstrom25c33252011-09-18 15:58:35 -0700359 CHECK(!Runtime::Current()->IsStarted());
Brian Carlstromae826982011-11-09 01:33:42 -0800360 if (!image_) {
361 CHECK(image_classes_ == NULL);
362 }
Shih-wei Liaoc486c112011-09-13 16:43:52 -0700363}
364
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700365Compiler::~Compiler() {
Elliott Hughesc225caa2012-02-03 15:43:37 -0800366 {
367 MutexLock mu(compiled_classes_lock_);
368 STLDeleteValues(&compiled_classes_);
369 }
370 {
371 MutexLock mu(compiled_methods_lock_);
372 STLDeleteValues(&compiled_methods_);
373 }
374 {
375 MutexLock mu(compiled_invoke_stubs_lock_);
376 STLDeleteValues(&compiled_invoke_stubs_);
Elliott Hughesbb551fa2012-01-25 16:35:29 -0800377 }
Brian Carlstromf5822582012-03-19 22:34:31 -0700378 {
379 MutexLock mu(compiled_methods_lock_);
380 STLDeleteElements(&code_to_patch_);
381 }
382 {
383 MutexLock mu(compiled_methods_lock_);
384 STLDeleteElements(&methods_to_patch_);
385 }
Shih-wei Liaoc4c98812012-03-10 21:55:51 -0800386#if defined(ART_USE_LLVM_COMPILER)
387 CompilerCallbackFn f = FindFunction<CompilerCallbackFn>(MakeCompilerSoName(instruction_set_),
388 compiler_library_,
389 "compilerLLVMDispose");
390 (*f)(*this);
391#endif
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800392 if (compiler_library_ != NULL) {
393 VLOG(compiler) << "dlclose(" << compiler_library_ << ")";
394 dlclose(compiler_library_);
395 }
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700396}
397
Ian Rogers1cb0a1d2011-10-06 15:24:35 -0700398ByteArray* Compiler::CreateResolutionStub(InstructionSet instruction_set,
399 Runtime::TrampolineType type) {
Ian Rogersad25ac52011-10-04 19:13:33 -0700400 if (instruction_set == kX86) {
Ian Rogers1cb0a1d2011-10-06 15:24:35 -0700401 return x86::X86CreateResolutionTrampoline(type);
Ian Rogersad25ac52011-10-04 19:13:33 -0700402 } else {
403 CHECK(instruction_set == kArm || instruction_set == kThumb2);
404 // Generates resolution stub using ARM instruction set
Ian Rogers1cb0a1d2011-10-06 15:24:35 -0700405 return arm::ArmCreateResolutionTrampoline(type);
Ian Rogersad25ac52011-10-04 19:13:33 -0700406 }
407}
408
Elliott Hughes8add92d2012-01-18 18:18:43 -0800409ByteArray* Compiler::CreateJniDlsymLookupStub(InstructionSet instruction_set) {
Ian Rogers169c9a72011-11-13 20:13:17 -0800410 switch (instruction_set) {
411 case kArm:
412 case kThumb2:
Elliott Hughes8add92d2012-01-18 18:18:43 -0800413 return arm::CreateJniDlsymLookupStub();
Ian Rogers169c9a72011-11-13 20:13:17 -0800414 case kX86:
Elliott Hughes8add92d2012-01-18 18:18:43 -0800415 return x86::CreateJniDlsymLookupStub();
Ian Rogers169c9a72011-11-13 20:13:17 -0800416 default:
Ian Rogers49c48942012-03-11 15:15:37 -0700417 LOG(FATAL) << "Unknown InstructionSet: " << instruction_set;
Ian Rogers169c9a72011-11-13 20:13:17 -0800418 return NULL;
419 }
420}
421
Ian Rogersad25ac52011-10-04 19:13:33 -0700422ByteArray* Compiler::CreateAbstractMethodErrorStub(InstructionSet instruction_set) {
423 if (instruction_set == kX86) {
424 return x86::CreateAbstractMethodErrorStub();
425 } else {
426 CHECK(instruction_set == kArm || instruction_set == kThumb2);
427 // Generates resolution stub using ARM instruction set
428 return arm::CreateAbstractMethodErrorStub();
429 }
430}
431
Jesse Wilson254db0f2011-11-16 16:44:11 -0500432void Compiler::CompileAll(const ClassLoader* class_loader,
Brian Carlstromae826982011-11-09 01:33:42 -0800433 const std::vector<const DexFile*>& dex_files) {
Brian Carlstrom25c33252011-09-18 15:58:35 -0700434 DCHECK(!Runtime::Current()->IsStarted());
Brian Carlstromae826982011-11-09 01:33:42 -0800435
Elliott Hughes601a1232012-02-02 17:47:38 -0800436 TimingLogger timings("compiler");
437
438 PreCompile(class_loader, dex_files, timings);
439
Brian Carlstromae826982011-11-09 01:33:42 -0800440 Compile(class_loader, dex_files);
Elliott Hughes601a1232012-02-02 17:47:38 -0800441 timings.AddSplit("Compile");
442
Brian Carlstromae826982011-11-09 01:33:42 -0800443 PostCompile(class_loader, dex_files);
Elliott Hughes601a1232012-02-02 17:47:38 -0800444 timings.AddSplit("PostCompile");
445
Brian Carlstromba0668e2012-03-26 13:14:07 -0700446 if (dump_timings_ && timings.GetTotalNs() > MsToNs(1000)) {
Elliott Hughes601a1232012-02-02 17:47:38 -0800447 timings.Dump();
448 }
Ian Rogers996cc582012-02-14 22:23:29 -0800449
Brian Carlstromba0668e2012-03-26 13:14:07 -0700450 if (dump_stats_) {
451 stats_->Dump();
452 }
Brian Carlstrom8a487412011-08-29 20:08:52 -0700453}
454
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700455void Compiler::CompileOne(const Method* method) {
Brian Carlstrom25c33252011-09-18 15:58:35 -0700456 DCHECK(!Runtime::Current()->IsStarted());
Brian Carlstromae826982011-11-09 01:33:42 -0800457
Brian Carlstrom8a487412011-08-29 20:08:52 -0700458 const ClassLoader* class_loader = method->GetDeclaringClass()->GetClassLoader();
Brian Carlstromae826982011-11-09 01:33:42 -0800459
Ian Rogers0571d352011-11-03 19:51:38 -0700460 // Find the dex_file
461 const DexCache* dex_cache = method->GetDeclaringClass()->GetDexCache();
462 const DexFile& dex_file = Runtime::Current()->GetClassLinker()->FindDexFile(dex_cache);
Brian Carlstromae826982011-11-09 01:33:42 -0800463 std::vector<const DexFile*> dex_files;
464 dex_files.push_back(&dex_file);
465
Elliott Hughes601a1232012-02-02 17:47:38 -0800466 TimingLogger timings("CompileOne");
467 PreCompile(class_loader, dex_files, timings);
Brian Carlstromae826982011-11-09 01:33:42 -0800468
Ian Rogers0571d352011-11-03 19:51:38 -0700469 uint32_t method_idx = method->GetDexMethodIndex();
Ian Rogersa3760aa2011-11-14 14:32:37 -0800470 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(method->GetCodeItemOffset());
471 CompileMethod(code_item, method->GetAccessFlags(), method_idx, class_loader, dex_file);
Brian Carlstromae826982011-11-09 01:33:42 -0800472
473 PostCompile(class_loader, dex_files);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700474}
475
Brian Carlstromae826982011-11-09 01:33:42 -0800476void Compiler::Resolve(const ClassLoader* class_loader,
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800477 const std::vector<const DexFile*>& dex_files, TimingLogger& timings) {
Brian Carlstromae826982011-11-09 01:33:42 -0800478 for (size_t i = 0; i != dex_files.size(); ++i) {
479 const DexFile* dex_file = dex_files[i];
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700480 CHECK(dex_file != NULL);
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800481 ResolveDexFile(class_loader, *dex_file, timings);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700482 }
483}
484
Brian Carlstromae826982011-11-09 01:33:42 -0800485void Compiler::PreCompile(const ClassLoader* class_loader,
Elliott Hughes601a1232012-02-02 17:47:38 -0800486 const std::vector<const DexFile*>& dex_files, TimingLogger& timings) {
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800487 Resolve(class_loader, dex_files, timings);
Elliott Hughes601a1232012-02-02 17:47:38 -0800488
Brian Carlstromae826982011-11-09 01:33:42 -0800489 Verify(class_loader, dex_files);
Elliott Hughes601a1232012-02-02 17:47:38 -0800490 timings.AddSplit("PreCompile.Verify");
491
Brian Carlstromae826982011-11-09 01:33:42 -0800492 InitializeClassesWithoutClinit(class_loader, dex_files);
Elliott Hughes601a1232012-02-02 17:47:38 -0800493 timings.AddSplit("PreCompile.InitializeClassesWithoutClinit");
Brian Carlstromae826982011-11-09 01:33:42 -0800494}
495
496void Compiler::PostCompile(const ClassLoader* class_loader,
497 const std::vector<const DexFile*>& dex_files) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -0800498 SetGcMaps(class_loader, dex_files);
Shih-wei Liaod1fec812012-02-13 09:51:10 -0800499#if defined(ART_USE_LLVM_COMPILER)
Shih-wei Liaoc4c98812012-03-10 21:55:51 -0800500 CompilerCallbackFn f = FindFunction<CompilerCallbackFn>(MakeCompilerSoName(instruction_set_),
501 compiler_library_,
502 "compilerLLVMMaterializeRemainder");
503 (*f)(*this);
Shih-wei Liaod1fec812012-02-13 09:51:10 -0800504#endif
Brian Carlstromae826982011-11-09 01:33:42 -0800505}
506
507bool Compiler::IsImageClass(const std::string& descriptor) const {
508 if (image_classes_ == NULL) {
509 return true;
510 }
511 return image_classes_->find(descriptor) != image_classes_->end();
512}
513
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800514bool Compiler::CanAssumeTypeIsPresentInDexCache(const DexCache* dex_cache,
Ian Rogers996cc582012-02-14 22:23:29 -0800515 uint32_t type_idx) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800516 if (!IsImage()) {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800517 stats_->TypeNotInDexCache();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800518 return false;
519 }
Ian Rogers1bddec32012-02-04 12:27:34 -0800520 Class* resolved_class = dex_cache->GetResolvedType(type_idx);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800521 if (resolved_class == NULL) {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800522 stats_->TypeNotInDexCache();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800523 return false;
524 }
Ian Rogers996cc582012-02-14 22:23:29 -0800525 bool result = IsImageClass(ClassHelper(resolved_class).GetDescriptor());
526 if (result) {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800527 stats_->TypeInDexCache();
Ian Rogers996cc582012-02-14 22:23:29 -0800528 } else {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800529 stats_->TypeNotInDexCache();
Ian Rogers996cc582012-02-14 22:23:29 -0800530 }
531 return result;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800532}
533
Ian Rogers1bddec32012-02-04 12:27:34 -0800534bool Compiler::CanAssumeStringIsPresentInDexCache(const DexCache* dex_cache,
Ian Rogers996cc582012-02-14 22:23:29 -0800535 uint32_t string_idx) {
Ian Rogers1bddec32012-02-04 12:27:34 -0800536 // TODO: Add support for loading strings referenced by image_classes_
537 // See also Compiler::ResolveDexFile
538
539 // The following is a test saying that if we're building the image without a restricted set of
540 // 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 -0800541 bool result = IsImage() && image_classes_ == NULL && dex_cache->GetResolvedString(string_idx) != NULL;
542 if (result) {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800543 stats_->StringInDexCache();
Ian Rogers996cc582012-02-14 22:23:29 -0800544 } else {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800545 stats_->StringNotInDexCache();
Ian Rogers996cc582012-02-14 22:23:29 -0800546 }
547 return result;
Ian Rogers1bddec32012-02-04 12:27:34 -0800548}
549
550bool Compiler::CanAccessTypeWithoutChecks(uint32_t referrer_idx, const DexCache* dex_cache,
Ian Rogers996cc582012-02-14 22:23:29 -0800551 const DexFile& dex_file, uint32_t type_idx) {
Ian Rogers1bddec32012-02-04 12:27:34 -0800552 // Get type from dex cache assuming it was populated by the verifier
553 Class* resolved_class = dex_cache->GetResolvedType(type_idx);
554 if (resolved_class == NULL) {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800555 stats_->TypeNeedsAccessCheck();
Ian Rogers1bddec32012-02-04 12:27:34 -0800556 return false; // Unknown class needs access checks.
557 }
558 const DexFile::MethodId& method_id = dex_file.GetMethodId(referrer_idx);
559 Class* referrer_class = dex_cache->GetResolvedType(method_id.class_idx_);
560 if (referrer_class == NULL) {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800561 stats_->TypeNeedsAccessCheck();
Ian Rogers1bddec32012-02-04 12:27:34 -0800562 return false; // Incomplete referrer knowledge needs access check.
563 }
564 // Perform access check, will return true if access is ok or false if we're going to have to
565 // check this at runtime (for example for class loaders).
Ian Rogers996cc582012-02-14 22:23:29 -0800566 bool result = referrer_class->CanAccess(resolved_class);
567 if (result) {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800568 stats_->TypeDoesntNeedAccessCheck();
Ian Rogers996cc582012-02-14 22:23:29 -0800569 } else {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800570 stats_->TypeNeedsAccessCheck();
Ian Rogers996cc582012-02-14 22:23:29 -0800571 }
572 return result;
Ian Rogers1bddec32012-02-04 12:27:34 -0800573}
574
575bool Compiler::CanAccessInstantiableTypeWithoutChecks(uint32_t referrer_idx,
576 const DexCache* dex_cache,
577 const DexFile& dex_file,
Ian Rogers996cc582012-02-14 22:23:29 -0800578 uint32_t type_idx) {
Ian Rogers1bddec32012-02-04 12:27:34 -0800579 // Get type from dex cache assuming it was populated by the verifier.
580 Class* resolved_class = dex_cache->GetResolvedType(type_idx);
581 if (resolved_class == NULL) {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800582 stats_->TypeNeedsAccessCheck();
Ian Rogers1bddec32012-02-04 12:27:34 -0800583 return false; // Unknown class needs access checks.
584 }
585 const DexFile::MethodId& method_id = dex_file.GetMethodId(referrer_idx);
586 Class* referrer_class = dex_cache->GetResolvedType(method_id.class_idx_);
587 if (referrer_class == NULL) {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800588 stats_->TypeNeedsAccessCheck();
Ian Rogers1bddec32012-02-04 12:27:34 -0800589 return false; // Incomplete referrer knowledge needs access check.
590 }
591 // Perform access and instantiable checks, will return true if access is ok or false if we're
592 // going to have to check this at runtime (for example for class loaders).
Ian Rogers996cc582012-02-14 22:23:29 -0800593 bool result = referrer_class->CanAccess(resolved_class) && resolved_class->IsInstantiable();
594 if (result) {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800595 stats_->TypeDoesntNeedAccessCheck();
Ian Rogers996cc582012-02-14 22:23:29 -0800596 } else {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800597 stats_->TypeNeedsAccessCheck();
Ian Rogers996cc582012-02-14 22:23:29 -0800598 }
599 return result;
Ian Rogers1bddec32012-02-04 12:27:34 -0800600}
601
Logan Chien4dd96f52012-02-29 01:26:58 +0800602static Class* ComputeReferrerClass(OatCompilationUnit* mUnit) {
603 const DexFile::MethodId& referrer_method_id =
604 mUnit->dex_file_->GetMethodId(mUnit->method_idx_);
605
606 return mUnit->class_linker_->ResolveType(
607 *mUnit->dex_file_, referrer_method_id.class_idx_,
608 mUnit->dex_cache_, mUnit->class_loader_);
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800609}
610
Logan Chien4dd96f52012-02-29 01:26:58 +0800611static Field* ComputeReferrerField(OatCompilationUnit* mUnit, uint32_t field_idx) {
612 return mUnit->class_linker_->ResolveField(
613 *mUnit->dex_file_, field_idx, mUnit->dex_cache_,
614 mUnit->class_loader_, false);
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800615}
616
Logan Chien4dd96f52012-02-29 01:26:58 +0800617static Method* ComputeReferrerMethod(OatCompilationUnit* mUnit, uint32_t method_idx) {
618 return mUnit->class_linker_->ResolveMethod(
619 *mUnit->dex_file_, method_idx, mUnit->dex_cache_,
620 mUnit->class_loader_, true);
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800621}
622
Logan Chien4dd96f52012-02-29 01:26:58 +0800623bool Compiler::ComputeInstanceFieldInfo(uint32_t field_idx, OatCompilationUnit* mUnit,
jeffhao8cd6dda2012-02-22 10:15:34 -0800624 int& field_offset, bool& is_volatile, bool is_put) {
Ian Rogers1bddec32012-02-04 12:27:34 -0800625 // Conservative defaults
626 field_offset = -1;
627 is_volatile = true;
628 // Try to resolve field
Logan Chien4dd96f52012-02-29 01:26:58 +0800629 Field* resolved_field = ComputeReferrerField(mUnit, field_idx);
Ian Rogers1bddec32012-02-04 12:27:34 -0800630 if (resolved_field != NULL) {
Logan Chien4dd96f52012-02-29 01:26:58 +0800631 Class* referrer_class = ComputeReferrerClass(mUnit);
Ian Rogers1bddec32012-02-04 12:27:34 -0800632 // Try to resolve referring class then access check, failure to pass the
633 Class* fields_class = resolved_field->GetDeclaringClass();
jeffhao8cd6dda2012-02-22 10:15:34 -0800634 bool is_write_to_final_from_wrong_class = is_put && resolved_field->IsFinal() &&
635 fields_class != referrer_class;
636 if (referrer_class != NULL && referrer_class->CanAccess(fields_class) &&
637 referrer_class->CanAccessMember(fields_class, resolved_field->GetAccessFlags()) &&
638 !is_write_to_final_from_wrong_class) {
Ian Rogers1bddec32012-02-04 12:27:34 -0800639 field_offset = resolved_field->GetOffset().Int32Value();
640 is_volatile = resolved_field->IsVolatile();
Ian Rogersc8b306f2012-02-17 21:34:44 -0800641 stats_->ResolvedInstanceField();
Ian Rogers1bddec32012-02-04 12:27:34 -0800642 return true; // Fast path.
643 }
644 }
645 // Clean up any exception left by field/type resolution
646 Thread* thread = Thread::Current();
647 if (thread->IsExceptionPending()) {
648 thread->ClearException();
649 }
Ian Rogersc8b306f2012-02-17 21:34:44 -0800650 stats_->UnresolvedInstanceField();
Ian Rogers1bddec32012-02-04 12:27:34 -0800651 return false; // Incomplete knowledge needs slow path.
652}
653
Logan Chien4dd96f52012-02-29 01:26:58 +0800654bool Compiler::ComputeStaticFieldInfo(uint32_t field_idx, OatCompilationUnit* mUnit,
Ian Rogers1bddec32012-02-04 12:27:34 -0800655 int& field_offset, int& ssb_index,
jeffhao8cd6dda2012-02-22 10:15:34 -0800656 bool& is_referrers_class, bool& is_volatile, bool is_put) {
Ian Rogers1bddec32012-02-04 12:27:34 -0800657 // Conservative defaults
658 field_offset = -1;
659 ssb_index = -1;
660 is_referrers_class = false;
661 is_volatile = true;
662 // Try to resolve field
Logan Chien4dd96f52012-02-29 01:26:58 +0800663 Field* resolved_field = ComputeReferrerField(mUnit, field_idx);
Ian Rogers1bddec32012-02-04 12:27:34 -0800664 if (resolved_field != NULL) {
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800665 DCHECK(resolved_field->IsStatic());
Logan Chien4dd96f52012-02-29 01:26:58 +0800666 Class* referrer_class = ComputeReferrerClass(mUnit);
Ian Rogers1bddec32012-02-04 12:27:34 -0800667 if (referrer_class != NULL) {
jeffhao8cd6dda2012-02-22 10:15:34 -0800668 Class* fields_class = resolved_field->GetDeclaringClass();
669 if (fields_class == referrer_class) {
Ian Rogers1bddec32012-02-04 12:27:34 -0800670 is_referrers_class = true; // implies no worrying about class initialization
671 field_offset = resolved_field->GetOffset().Int32Value();
672 is_volatile = resolved_field->IsVolatile();
Ian Rogersc8b306f2012-02-17 21:34:44 -0800673 stats_->ResolvedLocalStaticField();
Ian Rogers1bddec32012-02-04 12:27:34 -0800674 return true; // fast path
675 } else {
jeffhao8cd6dda2012-02-22 10:15:34 -0800676 bool is_write_to_final_from_wrong_class = is_put && resolved_field->IsFinal();
Ian Rogers1bddec32012-02-04 12:27:34 -0800677 if (referrer_class->CanAccess(fields_class) &&
jeffhao8cd6dda2012-02-22 10:15:34 -0800678 referrer_class->CanAccessMember(fields_class, resolved_field->GetAccessFlags()) &&
679 !is_write_to_final_from_wrong_class) {
Ian Rogers1bddec32012-02-04 12:27:34 -0800680 // We have the resolved field, we must make it into a ssbIndex for the referrer
681 // in its static storage base (which may fail if it doesn't have a slot for it)
Ian Rogers4103ad22012-02-06 09:18:25 -0800682 // TODO: for images we can elide the static storage base null check
683 // if we know there's a non-null entry in the image
Logan Chien4dd96f52012-02-29 01:26:58 +0800684 if (fields_class->GetDexCache() == mUnit->dex_cache_) {
Ian Rogers4103ad22012-02-06 09:18:25 -0800685 // common case where the dex cache of both the referrer and the field are the same,
686 // no need to search the dex file
687 ssb_index = fields_class->GetDexTypeIndex();
688 field_offset = resolved_field->GetOffset().Int32Value();
689 is_volatile = resolved_field->IsVolatile();
Ian Rogersc8b306f2012-02-17 21:34:44 -0800690 stats_->ResolvedStaticField();
Ian Rogers4103ad22012-02-06 09:18:25 -0800691 return true;
692 }
693 // Search dex file for localized ssb index
Ian Rogers1bddec32012-02-04 12:27:34 -0800694 std::string descriptor(FieldHelper(resolved_field).GetDeclaringClassDescriptor());
695 const DexFile::StringId* string_id =
Logan Chien4dd96f52012-02-29 01:26:58 +0800696 mUnit->dex_file_->FindStringId(descriptor);
Ian Rogers1bddec32012-02-04 12:27:34 -0800697 if (string_id != NULL) {
698 const DexFile::TypeId* type_id =
Logan Chien4dd96f52012-02-29 01:26:58 +0800699 mUnit->dex_file_->FindTypeId(mUnit->dex_file_->GetIndexForStringId(*string_id));
Elliott Hughesb25c3f62012-03-26 16:35:06 -0700700 if (type_id != NULL) {
Ian Rogers1bddec32012-02-04 12:27:34 -0800701 // medium path, needs check of static storage base being initialized
Logan Chien4dd96f52012-02-29 01:26:58 +0800702 ssb_index = mUnit->dex_file_->GetIndexForTypeId(*type_id);
Ian Rogers1bddec32012-02-04 12:27:34 -0800703 field_offset = resolved_field->GetOffset().Int32Value();
704 is_volatile = resolved_field->IsVolatile();
Ian Rogersc8b306f2012-02-17 21:34:44 -0800705 stats_->ResolvedStaticField();
Ian Rogers1bddec32012-02-04 12:27:34 -0800706 return true;
707 }
708 }
709 }
710 }
711 }
712 }
713 // Clean up any exception left by field/type resolution
714 Thread* thread = Thread::Current();
715 if (thread->IsExceptionPending()) {
716 thread->ClearException();
717 }
Ian Rogersc8b306f2012-02-17 21:34:44 -0800718 stats_->UnresolvedStaticField();
Ian Rogers1bddec32012-02-04 12:27:34 -0800719 return false; // Incomplete knowledge needs slow path.
720}
721
Ian Rogers2ed3b952012-03-17 11:49:39 -0700722void Compiler::GetCodeAndMethodForDirectCall(InvokeType type, InvokeType sharp_type, Method* method,
723 uintptr_t& direct_code, uintptr_t& direct_method) {
724 direct_code = 0;
725 direct_method = 0;
726 if (sharp_type != kStatic && sharp_type != kDirect) {
727 return;
728 }
Ian Rogers2ed3b952012-03-17 11:49:39 -0700729 bool method_code_in_boot = method->GetDeclaringClass()->GetClassLoader() == NULL;
730 if (!method_code_in_boot) {
731 return;
732 }
733 bool has_clinit_trampoline = method->IsStatic() && !method->GetDeclaringClass()->IsInitialized();
734 if (has_clinit_trampoline) {
735 return;
736 }
737 stats_->DirectCallsToBoot(type);
738 stats_->DirectMethodsToBoot(type);
Ian Rogers3fa13792012-03-18 15:53:45 -0700739 bool compiling_boot = Runtime::Current()->GetHeap()->GetSpaces().size() == 1;
740 if (compiling_boot) {
Brian Carlstrom0637e272012-03-20 01:07:52 -0700741 const bool kSupportBootImageFixup = true;
Ian Rogers3fa13792012-03-18 15:53:45 -0700742 if (kSupportBootImageFixup) {
743 MethodHelper mh(method);
744 if (IsImageClass(mh.GetDeclaringClassDescriptor())) {
Brian Carlstrom0637e272012-03-20 01:07:52 -0700745 // We can only branch directly to Methods that are resolved in the DexCache.
746 // Otherwise we won't invoke the resolution trampoline.
Ian Rogers3fa13792012-03-18 15:53:45 -0700747 direct_method = -1;
Brian Carlstrom0637e272012-03-20 01:07:52 -0700748 direct_code = -1;
Ian Rogers3fa13792012-03-18 15:53:45 -0700749 }
Ian Rogers3fa13792012-03-18 15:53:45 -0700750 }
751 } else {
752 if (Runtime::Current()->GetHeap()->GetImageSpace()->Contains(method)) {
753 direct_method = reinterpret_cast<uintptr_t>(method);
754 }
755 direct_code = reinterpret_cast<uintptr_t>(method->GetCode());
Ian Rogers2ed3b952012-03-17 11:49:39 -0700756 }
Ian Rogers2ed3b952012-03-17 11:49:39 -0700757}
758
Ian Rogersfb6adba2012-03-04 21:51:51 -0800759bool Compiler::ComputeInvokeInfo(uint32_t method_idx, OatCompilationUnit* mUnit, InvokeType& type,
Ian Rogers2ed3b952012-03-17 11:49:39 -0700760 int& vtable_idx, uintptr_t& direct_code,
761 uintptr_t& direct_method) {
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800762 vtable_idx = -1;
Ian Rogers2ed3b952012-03-17 11:49:39 -0700763 direct_code = 0;
764 direct_method = 0;
Logan Chien4dd96f52012-02-29 01:26:58 +0800765 Method* resolved_method = ComputeReferrerMethod(mUnit, method_idx);
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800766 if (resolved_method != NULL) {
Logan Chien4dd96f52012-02-29 01:26:58 +0800767 Class* referrer_class = ComputeReferrerClass(mUnit);
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800768 if (referrer_class != NULL) {
769 Class* methods_class = resolved_method->GetDeclaringClass();
770 if (!referrer_class->CanAccess(methods_class) ||
771 !referrer_class->CanAccessMember(methods_class,
Ian Rogers996cc582012-02-14 22:23:29 -0800772 resolved_method->GetAccessFlags())) {
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800773 // The referring class can't access the resolved method, this may occur as a result of a
774 // protected method being made public by implementing an interface that re-declares the
775 // method public. Resort to the dex file to determine the correct class for the access check
Logan Chien4dd96f52012-02-29 01:26:58 +0800776 const DexFile& dex_file = mUnit->class_linker_->FindDexFile(referrer_class->GetDexCache());
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800777 methods_class =
Logan Chien4dd96f52012-02-29 01:26:58 +0800778 mUnit->class_linker_->ResolveType(dex_file,
779 dex_file.GetMethodId(method_idx).class_idx_,
780 referrer_class);
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800781 }
782 if (referrer_class->CanAccess(methods_class) &&
783 referrer_class->CanAccessMember(methods_class,
784 resolved_method->GetAccessFlags())) {
785 vtable_idx = resolved_method->GetMethodIndex();
Ian Rogersf320b632012-03-13 18:47:47 -0700786 const bool kEnableSharpening = true;
Ian Rogers2ed3b952012-03-17 11:49:39 -0700787 // Sharpen a virtual call into a direct call when the target is known.
788 bool can_sharpen = type == kVirtual && (resolved_method->IsFinal() ||
789 methods_class->IsFinal());
790 // ensure the vtable index will be correct to dispatch in the vtable of the super class
jeffhao4155fcd2012-03-21 11:42:12 -0700791 can_sharpen = can_sharpen || (type == kSuper && referrer_class != methods_class &&
Ian Rogers2ed3b952012-03-17 11:49:39 -0700792 referrer_class->IsSubClass(methods_class) &&
jeffhao4155fcd2012-03-21 11:42:12 -0700793 vtable_idx < methods_class->GetVTable()->GetLength() &&
794 methods_class->GetVTable()->Get(vtable_idx) == resolved_method);
Ian Rogers2ed3b952012-03-17 11:49:39 -0700795 if (kEnableSharpening && can_sharpen) {
796 stats_->ResolvedMethod(type);
Ian Rogersfb6adba2012-03-04 21:51:51 -0800797 // Sharpen a virtual call into a direct call. The method_idx is into referrer's
798 // dex cache, check that this resolved method is where we expect it.
799 CHECK(referrer_class->GetDexCache()->GetResolvedMethod(method_idx) == resolved_method)
800 << PrettyMethod(resolved_method);
Ian Rogers2ed3b952012-03-17 11:49:39 -0700801 stats_->VirtualMadeDirect(type);
802 GetCodeAndMethodForDirectCall(type, kDirect, resolved_method, direct_code, direct_method);
803 type = kDirect;
804 return true;
805 } else if (type == kSuper) {
806 // Unsharpened super calls are suspicious so go slowpath.
807 } else {
808 stats_->ResolvedMethod(type);
809 GetCodeAndMethodForDirectCall(type, type, resolved_method, direct_code, direct_method);
810 return true;
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800811 }
812 }
813 }
814 }
815 // Clean up any exception left by method/type resolution
816 Thread* thread = Thread::Current();
817 if (thread->IsExceptionPending()) {
818 thread->ClearException();
819 }
Ian Rogersc8b306f2012-02-17 21:34:44 -0800820 stats_->UnresolvedMethod(type);
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800821 return false; // Incomplete knowledge needs slow path.
822}
823
Brian Carlstromf5822582012-03-19 22:34:31 -0700824void Compiler::AddCodePatch(DexCache* dex_cache,
825 const DexFile* dex_file,
826 uint32_t referrer_method_idx,
827 uint32_t referrer_access_flags,
828 uint32_t target_method_idx,
829 bool target_is_direct,
Ian Rogers3fa13792012-03-18 15:53:45 -0700830 size_t literal_offset) {
831 MutexLock mu(compiled_methods_lock_);
Brian Carlstromf5822582012-03-19 22:34:31 -0700832 code_to_patch_.push_back(new PatchInformation(dex_cache,
833 dex_file,
834 referrer_method_idx,
835 referrer_access_flags,
836 target_method_idx,
837 target_is_direct,
838 literal_offset));
Ian Rogers3fa13792012-03-18 15:53:45 -0700839}
Brian Carlstromf5822582012-03-19 22:34:31 -0700840void Compiler::AddMethodPatch(DexCache* dex_cache,
841 const DexFile* dex_file,
842 uint32_t referrer_method_idx,
843 uint32_t referrer_access_flags,
844 uint32_t target_method_idx,
845 bool target_is_direct,
Ian Rogers3fa13792012-03-18 15:53:45 -0700846 size_t literal_offset) {
847 MutexLock mu(compiled_methods_lock_);
Brian Carlstromf5822582012-03-19 22:34:31 -0700848 methods_to_patch_.push_back(new PatchInformation(dex_cache,
849 dex_file,
850 referrer_method_idx,
851 referrer_access_flags,
852 target_method_idx,
853 target_is_direct,
854 literal_offset));
Ian Rogers3fa13792012-03-18 15:53:45 -0700855}
856
Brian Carlstrom5ead0952011-11-28 22:55:52 -0800857// Return true if the class should be skipped during compilation. We
858// never skip classes in the boot class loader. However, if we have a
859// non-boot class loader and we can resolve the class in the boot
860// class loader, we do skip the class. This happens if an app bundles
861// classes found in the boot classpath. Since at runtime we will
862// select the class from the boot classpath, do not attempt to resolve
863// or compile it now.
864static bool SkipClass(const ClassLoader* class_loader,
865 const DexFile& dex_file,
866 const DexFile::ClassDef& class_def) {
867 if (class_loader == NULL) {
868 return false;
869 }
870 const char* descriptor = dex_file.GetClassDescriptor(class_def);
871 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
872 Class* klass = class_linker->FindClass(descriptor, NULL);
873 if (klass == NULL) {
874 Thread* self = Thread::Current();
875 CHECK(self->IsExceptionPending());
876 self->ClearException();
877 return false;
878 }
879 return true;
880}
881
Brian Carlstrom731b2ab2012-03-06 16:53:35 -0800882class Context {
883 public:
884 Context(ClassLinker* class_linker,
885 const ClassLoader* class_loader,
886 Compiler* compiler,
887 DexCache* dex_cache,
888 const DexFile* dex_file)
889 : class_linker_(class_linker),
890 class_loader_(class_loader),
891 compiler_(compiler),
892 dex_cache_(dex_cache),
893 dex_file_(dex_file) {}
894
895 ClassLinker* GetClassLinker() {
896 CHECK(class_linker_ != NULL);
897 return class_linker_;
898 }
899 const ClassLoader* GetClassLoader() {
900 return class_loader_;
901 }
902 Compiler* GetCompiler() {
903 CHECK(compiler_ != NULL);
904 return compiler_;
905 }
906 DexCache* GetDexCache() {
907 CHECK(dex_cache_ != NULL);
908 return dex_cache_;
909 }
910 const DexFile* GetDexFile() {
911 CHECK(dex_file_ != NULL);
912 return dex_file_;
913 }
914
915 private:
916 ClassLinker* class_linker_;
917 const ClassLoader* class_loader_;
918 Compiler* compiler_;
919 DexCache* dex_cache_;
920 const DexFile* dex_file_;
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800921};
922
923typedef void Callback(Context* context, size_t index);
924
925class WorkerThread {
926 public:
Elliott Hughes1e409252012-02-06 11:21:27 -0800927 WorkerThread(Context* context, size_t begin, size_t end, Callback callback, size_t stripe, bool spawn)
928 : spawn_(spawn), context_(context), begin_(begin), end_(end), callback_(callback), stripe_(stripe) {
929 if (spawn_) {
930 CHECK_PTHREAD_CALL(pthread_create, (&pthread_, NULL, &Go, this), "compiler worker thread");
931 }
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800932 }
933
934 ~WorkerThread() {
Elliott Hughes1e409252012-02-06 11:21:27 -0800935 if (spawn_) {
936 CHECK_PTHREAD_CALL(pthread_join, (pthread_, NULL), "compiler worker shutdown");
937 }
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800938 }
939
940 private:
Elliott Hughes1e409252012-02-06 11:21:27 -0800941 static void* Go(void* arg) {
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800942 WorkerThread* worker = reinterpret_cast<WorkerThread*>(arg);
943 Runtime* runtime = Runtime::Current();
Elliott Hughes1e409252012-02-06 11:21:27 -0800944 if (worker->spawn_) {
Elliott Hughes462c9442012-03-23 18:47:50 -0700945 runtime->AttachCurrentThread("Compiler Worker", true, NULL);
Elliott Hughes1e409252012-02-06 11:21:27 -0800946 }
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800947 Thread::Current()->SetState(Thread::kRunnable);
948 worker->Run();
Elliott Hughes1e409252012-02-06 11:21:27 -0800949 if (worker->spawn_) {
950 Thread::Current()->SetState(Thread::kNative);
951 runtime->DetachCurrentThread();
952 }
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800953 return NULL;
954 }
955
Elliott Hughes1e409252012-02-06 11:21:27 -0800956 void Go() {
957 Go(this);
958 }
959
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800960 void Run() {
Brian Carlstrom64277f32012-03-26 23:53:34 -0700961 Thread* self = Thread::Current();
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800962 for (size_t i = begin_; i < end_; i += stripe_) {
963 callback_(context_, i);
Brian Carlstrom64277f32012-03-26 23:53:34 -0700964 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException()) << " " << i;
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800965 }
966 }
967
968 pthread_t pthread_;
Elliott Hughes1e409252012-02-06 11:21:27 -0800969 bool spawn_;
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800970
971 Context* context_;
972 size_t begin_;
973 size_t end_;
974 Callback* callback_;
975 size_t stripe_;
Elliott Hughes1e409252012-02-06 11:21:27 -0800976
977 friend void ForAll(Context*, size_t, size_t, Callback, size_t);
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800978};
979
Elliott Hughes5523ee02012-02-03 18:18:34 -0800980void ForAll(Context* context, size_t begin, size_t end, Callback callback, size_t thread_count) {
Brian Carlstrom64277f32012-03-26 23:53:34 -0700981 Thread* self = Thread::Current();
982 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
Elliott Hughes1e409252012-02-06 11:21:27 -0800983 CHECK_GT(thread_count, 0U);
Elliott Hughes81d91512012-02-03 16:38:43 -0800984
Elliott Hughes1e409252012-02-06 11:21:27 -0800985 std::vector<WorkerThread*> threads;
Elliott Hughes81d91512012-02-03 16:38:43 -0800986 for (size_t i = 0; i < thread_count; ++i) {
Elliott Hughes1e409252012-02-06 11:21:27 -0800987 threads.push_back(new WorkerThread(context, begin + i, end, callback, thread_count, (i != 0)));
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800988 }
Elliott Hughes1e409252012-02-06 11:21:27 -0800989 threads[0]->Go();
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800990
Elliott Hughes81d91512012-02-03 16:38:43 -0800991 // Switch to kVmWait while we're blocked waiting for the other threads to finish.
Brian Carlstrom64277f32012-03-26 23:53:34 -0700992 ScopedThreadStateChange tsc(self, Thread::kVmWait);
Elliott Hughes81d91512012-02-03 16:38:43 -0800993 STLDeleteElements(&threads);
994}
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800995
996static void ResolveClassFieldsAndMethods(Context* context, size_t class_def_index) {
Brian Carlstrom731b2ab2012-03-06 16:53:35 -0800997 const DexFile& dex_file = *context->GetDexFile();
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800998
999 // Method and Field are the worst. We can't resolve without either
1000 // context from the code use (to disambiguate virtual vs direct
1001 // method and instance vs static field) or from class
1002 // definitions. While the compiler will resolve what it can as it
1003 // needs it, here we try to resolve fields and methods used in class
1004 // definitions, since many of them many never be referenced by
1005 // generated code.
1006 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001007 if (SkipClass(context->GetClassLoader(), dex_file, class_def)) {
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001008 return;
1009 }
1010
1011 // Note the class_data pointer advances through the headers,
1012 // static fields, instance fields, direct methods, and virtual
1013 // methods.
1014 const byte* class_data = dex_file.GetClassData(class_def);
1015 if (class_data == NULL) {
1016 // empty class such as a marker interface
1017 return;
1018 }
Brian Carlstrom5ead0952011-11-28 22:55:52 -08001019 Thread* self = Thread::Current();
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001020 ClassLinker* class_linker = context->GetClassLinker();
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001021 DexCache* dex_cache = class_linker->FindDexCache(dex_file);
1022 ClassDataItemIterator it(dex_file, class_data);
1023 while (it.HasNextStaticField()) {
1024 Field* field = class_linker->ResolveField(dex_file, it.GetMemberIndex(), dex_cache,
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001025 context->GetClassLoader(), true);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001026 if (field == NULL) {
1027 CHECK(self->IsExceptionPending());
1028 self->ClearException();
1029 }
1030 it.Next();
1031 }
1032 while (it.HasNextInstanceField()) {
1033 Field* field = class_linker->ResolveField(dex_file, it.GetMemberIndex(), dex_cache,
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001034 context->GetClassLoader(), false);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001035 if (field == NULL) {
1036 CHECK(self->IsExceptionPending());
1037 self->ClearException();
1038 }
1039 it.Next();
1040 }
1041 while (it.HasNextDirectMethod()) {
1042 Method* method = class_linker->ResolveMethod(dex_file, it.GetMemberIndex(), dex_cache,
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001043 context->GetClassLoader(), true);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001044 if (method == NULL) {
1045 CHECK(self->IsExceptionPending());
1046 self->ClearException();
1047 }
1048 it.Next();
1049 }
1050 while (it.HasNextVirtualMethod()) {
1051 Method* method = class_linker->ResolveMethod(dex_file, it.GetMemberIndex(), dex_cache,
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001052 context->GetClassLoader(), false);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001053 if (method == NULL) {
1054 CHECK(self->IsExceptionPending());
1055 self->ClearException();
1056 }
1057 it.Next();
1058 }
1059 DCHECK(!it.HasNext());
1060}
1061
1062static void ResolveType(Context* context, size_t type_idx) {
1063 // Class derived values are more complicated, they require the linker and loader.
1064 Thread* self = Thread::Current();
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001065 Class* klass = context->GetClassLinker()->ResolveType(*context->GetDexFile(),
1066 type_idx,
1067 context->GetDexCache(),
1068 context->GetClassLoader());
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001069 if (klass == NULL) {
1070 CHECK(self->IsExceptionPending());
1071 Thread::Current()->ClearException();
1072 }
1073}
1074
1075void Compiler::ResolveDexFile(const ClassLoader* class_loader, const DexFile& dex_file, TimingLogger& timings) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001076 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Brian Carlstromaded5f72011-10-07 17:15:04 -07001077 DexCache* dex_cache = class_linker->FindDexCache(dex_file);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001078
Brian Carlstromae826982011-11-09 01:33:42 -08001079 // Strings are easy in that they always are simply resolved to literals in the same file
1080 if (image_ && image_classes_ == NULL) {
1081 // TODO: Add support for loading strings referenced by image_classes_
1082 // See also Compiler::CanAssumeTypeIsPresentInDexCache.
Brian Carlstromaded5f72011-10-07 17:15:04 -07001083 for (size_t string_idx = 0; string_idx < dex_cache->NumStrings(); string_idx++) {
1084 class_linker->ResolveString(dex_file, string_idx, dex_cache);
1085 }
Elliott Hughesff738062012-02-03 15:00:42 -08001086 timings.AddSplit("Resolve " + dex_file.GetLocation() + " Strings");
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001087 }
1088
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001089 Context context(class_linker, class_loader, this, dex_cache, &dex_file);
Elliott Hughes5523ee02012-02-03 18:18:34 -08001090 ForAll(&context, 0, dex_cache->NumResolvedTypes(), ResolveType, thread_count_);
Elliott Hughesff738062012-02-03 15:00:42 -08001091 timings.AddSplit("Resolve " + dex_file.GetLocation() + " Types");
Brian Carlstrom845490b2011-09-19 15:56:53 -07001092
Elliott Hughes5523ee02012-02-03 18:18:34 -08001093 ForAll(&context, 0, dex_file.NumClassDefs(), ResolveClassFieldsAndMethods, thread_count_);
Elliott Hughesff738062012-02-03 15:00:42 -08001094 timings.AddSplit("Resolve " + dex_file.GetLocation() + " MethodsAndFields");
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001095}
1096
Brian Carlstromae826982011-11-09 01:33:42 -08001097void Compiler::Verify(const ClassLoader* class_loader,
1098 const std::vector<const DexFile*>& dex_files) {
1099 for (size_t i = 0; i != dex_files.size(); ++i) {
1100 const DexFile* dex_file = dex_files[i];
jeffhao98eacac2011-09-14 16:11:53 -07001101 CHECK(dex_file != NULL);
1102 VerifyDexFile(class_loader, *dex_file);
1103 }
1104}
1105
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001106static void VerifyClass(Context* context, size_t class_def_index) {
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001107 const DexFile::ClassDef& class_def = context->GetDexFile()->GetClassDef(class_def_index);
1108 const char* descriptor = context->GetDexFile()->GetClassDescriptor(class_def);
1109 Class* klass = context->GetClassLinker()->FindClass(descriptor, context->GetClassLoader());
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001110 if (klass == NULL) {
1111 Thread* self = Thread::Current();
1112 CHECK(self->IsExceptionPending());
1113 self->ClearException();
jeffhaof56197c2012-03-05 18:01:54 -08001114
1115 /*
1116 * At compile time, we can still structurally verify the class even if FindClass fails.
1117 * This is to ensure the class is structurally sound for compilation. An unsound class
1118 * will be rejected by the verifier and later skipped during compilation in the compiler.
1119 */
1120 std::string error_msg;
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001121 if (!verifier::DexVerifier::VerifyClass(context->GetDexFile(), context->GetDexCache(),
1122 context->GetClassLoader(), class_def_index, error_msg)) {
1123 const DexFile::ClassDef& class_def = context->GetDexFile()->GetClassDef(class_def_index);
jeffhaof56197c2012-03-05 18:01:54 -08001124 LOG(ERROR) << "Verification failed on class "
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001125 << PrettyDescriptor(context->GetDexFile()->GetClassDescriptor(class_def))
jeffhaof56197c2012-03-05 18:01:54 -08001126 << " because: " << error_msg;
1127 }
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001128 return;
1129 }
1130 CHECK(klass->IsResolved()) << PrettyClass(klass);
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001131 context->GetClassLinker()->VerifyClass(klass);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001132
1133 if (klass->IsErroneous()) {
1134 // ClassLinker::VerifyClass throws, which isn't useful in the compiler.
1135 CHECK(Thread::Current()->IsExceptionPending());
1136 Thread::Current()->ClearException();
jeffhao1ac29442012-03-26 11:37:32 -07001137 art::Compiler::ClassReference ref(context->GetDexFile(), class_def_index);
1138 if (!verifier::DexVerifier::IsClassRejected(ref)) {
1139 // If the erroneous class wasn't rejected by the verifier, it was a soft error. We want
1140 // to try verification again at run-time, so move back into the resolved state.
1141 klass->SetStatus(Class::kStatusResolved);
1142 }
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001143 }
1144
jeffhao1ac29442012-03-26 11:37:32 -07001145 CHECK(klass->IsVerified() || klass->IsResolved() || klass->IsErroneous()) << PrettyClass(klass);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001146 CHECK(!Thread::Current()->IsExceptionPending()) << PrettyTypeOf(Thread::Current()->GetException());
1147}
1148
jeffhao98eacac2011-09-14 16:11:53 -07001149void Compiler::VerifyDexFile(const ClassLoader* class_loader, const DexFile& dex_file) {
jeffhaob4df5142011-09-19 20:25:32 -07001150 dex_file.ChangePermissions(PROT_READ | PROT_WRITE);
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07001151
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001152 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1153 Context context(class_linker, class_loader, this, class_linker->FindDexCache(dex_file), &dex_file);
Elliott Hughes5523ee02012-02-03 18:18:34 -08001154 ForAll(&context, 0, dex_file.NumClassDefs(), VerifyClass, thread_count_);
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07001155
jeffhaob4df5142011-09-19 20:25:32 -07001156 dex_file.ChangePermissions(PROT_READ);
Brian Carlstroma5a97a22011-09-15 14:08:49 -07001157}
1158
Brian Carlstromae826982011-11-09 01:33:42 -08001159void Compiler::InitializeClassesWithoutClinit(const ClassLoader* class_loader,
1160 const std::vector<const DexFile*>& dex_files) {
1161 for (size_t i = 0; i != dex_files.size(); ++i) {
1162 const DexFile* dex_file = dex_files[i];
Brian Carlstroma5a97a22011-09-15 14:08:49 -07001163 CHECK(dex_file != NULL);
1164 InitializeClassesWithoutClinit(class_loader, *dex_file);
1165 }
1166}
1167
1168void Compiler::InitializeClassesWithoutClinit(const ClassLoader* class_loader, const DexFile& dex_file) {
1169 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Brian Carlstromffca45d2011-09-16 12:10:49 -07001170 for (size_t class_def_index = 0; class_def_index < dex_file.NumClassDefs(); class_def_index++) {
1171 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
Brian Carlstroma5a97a22011-09-15 14:08:49 -07001172 const char* descriptor = dex_file.GetClassDescriptor(class_def);
1173 Class* klass = class_linker->FindClass(descriptor, class_loader);
Brian Carlstrom27ec9612011-09-19 20:20:38 -07001174 if (klass != NULL) {
jeffhao1ac29442012-03-26 11:37:32 -07001175 if (klass->IsVerified()) {
1176 // Only try to initialize classes that were successfully verified.
1177 class_linker->EnsureInitialized(klass, false);
1178 }
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001179 // record the final class status if necessary
1180 Class::Status status = klass->GetStatus();
1181 ClassReference ref(&dex_file, class_def_index);
Elliott Hughesc225caa2012-02-03 15:43:37 -08001182 MutexLock mu(compiled_classes_lock_);
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001183 CompiledClass* compiled_class = GetCompiledClass(ref);
1184 if (compiled_class == NULL) {
1185 compiled_class = new CompiledClass(status);
1186 compiled_classes_[ref] = compiled_class;
1187 } else {
1188 DCHECK_EQ(status, compiled_class->GetStatus());
1189 }
Brian Carlstrom27ec9612011-09-19 20:20:38 -07001190 }
1191 // clear any class not found or verification exceptions
1192 Thread::Current()->ClearException();
Brian Carlstromffca45d2011-09-16 12:10:49 -07001193 }
1194
1195 DexCache* dex_cache = class_linker->FindDexCache(dex_file);
1196 for (size_t type_idx = 0; type_idx < dex_cache->NumResolvedTypes(); type_idx++) {
1197 Class* klass = class_linker->ResolveType(dex_file, type_idx, dex_cache, class_loader);
Brian Carlstrom27ec9612011-09-19 20:20:38 -07001198 if (klass == NULL) {
1199 Thread::Current()->ClearException();
1200 } else if (klass->IsInitialized()) {
Brian Carlstromffca45d2011-09-16 12:10:49 -07001201 dex_cache->GetInitializedStaticStorage()->Set(type_idx, klass);
1202 }
jeffhao98eacac2011-09-14 16:11:53 -07001203 }
1204}
1205
Brian Carlstromae826982011-11-09 01:33:42 -08001206void Compiler::Compile(const ClassLoader* class_loader,
1207 const std::vector<const DexFile*>& dex_files) {
1208 for (size_t i = 0; i != dex_files.size(); ++i) {
1209 const DexFile* dex_file = dex_files[i];
Brian Carlstrom83db7722011-08-26 17:32:56 -07001210 CHECK(dex_file != NULL);
1211 CompileDexFile(class_loader, *dex_file);
1212 }
1213}
1214
Elliott Hughesc225caa2012-02-03 15:43:37 -08001215void Compiler::CompileClass(Context* context, size_t class_def_index) {
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001216 const ClassLoader* class_loader = context->GetClassLoader();
1217 const DexFile& dex_file = *context->GetDexFile();
Elliott Hughesc225caa2012-02-03 15:43:37 -08001218 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
Logan Chien7f767612012-03-01 18:54:49 +08001219#if defined(ART_USE_LLVM_COMPILER)
Logan Chien7f767612012-03-01 18:54:49 +08001220 // TODO: Remove this. We should not lock the compiler_lock_ in CompileClass()
Shih-wei Liaoc4c98812012-03-10 21:55:51 -08001221 // However, without this mutex lock, we will get segmentation fault before
1222 // LLVM becomes multithreaded.
1223 Compiler* cmplr = context->GetCompiler();
1224 CompilerMutexLockFn f =
1225 FindFunction<CompilerMutexLockFn>(MakeCompilerSoName(cmplr->GetInstructionSet()),
1226 cmplr->compiler_library_,
1227 "compilerLLVMMutexLock");
1228 UniquePtr<MutexLock> GUARD((*f)(*cmplr));
Logan Chien7f767612012-03-01 18:54:49 +08001229#endif
1230
Brian Carlstrom5ead0952011-11-28 22:55:52 -08001231 if (SkipClass(class_loader, dex_file, class_def)) {
1232 return;
1233 }
jeffhaod1224c72012-02-29 13:43:08 -08001234 ClassReference ref(&dex_file, class_def_index);
1235 // Skip compiling classes with generic verifier failures since they will still fail at runtime
1236 if (verifier::DexVerifier::IsClassRejected(ref)) {
1237 return;
1238 }
Ian Rogers0571d352011-11-03 19:51:38 -07001239 const byte* class_data = dex_file.GetClassData(class_def);
1240 if (class_data == NULL) {
1241 // empty class, probably a marker interface
1242 return;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001243 }
Ian Rogers0571d352011-11-03 19:51:38 -07001244 ClassDataItemIterator it(dex_file, class_data);
1245 // Skip fields
1246 while (it.HasNextStaticField()) {
1247 it.Next();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001248 }
Ian Rogers0571d352011-11-03 19:51:38 -07001249 while (it.HasNextInstanceField()) {
1250 it.Next();
1251 }
1252 // Compile direct methods
1253 while (it.HasNextDirectMethod()) {
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001254 context->GetCompiler()->CompileMethod(it.GetMethodCodeItem(), it.GetMemberAccessFlags(),
1255 it.GetMemberIndex(), class_loader, dex_file);
Ian Rogers0571d352011-11-03 19:51:38 -07001256 it.Next();
1257 }
1258 // Compile virtual methods
1259 while (it.HasNextVirtualMethod()) {
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001260 context->GetCompiler()->CompileMethod(it.GetMethodCodeItem(), it.GetMemberAccessFlags(),
1261 it.GetMemberIndex(), class_loader, dex_file);
Ian Rogers0571d352011-11-03 19:51:38 -07001262 it.Next();
1263 }
1264 DCHECK(!it.HasNext());
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001265}
1266
Elliott Hughesc225caa2012-02-03 15:43:37 -08001267void Compiler::CompileDexFile(const ClassLoader* class_loader, const DexFile& dex_file) {
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001268 Context context(NULL, class_loader, this, NULL, &dex_file);
Elliott Hughes5523ee02012-02-03 18:18:34 -08001269 ForAll(&context, 0, dex_file.NumClassDefs(), Compiler::CompileClass, thread_count_);
Elliott Hughesc225caa2012-02-03 15:43:37 -08001270}
1271
Ian Rogersa3760aa2011-11-14 14:32:37 -08001272void Compiler::CompileMethod(const DexFile::CodeItem* code_item, uint32_t access_flags,
1273 uint32_t method_idx, const ClassLoader* class_loader,
1274 const DexFile& dex_file) {
Elliott Hughesf09afe82011-10-16 14:24:21 -07001275 CompiledMethod* compiled_method = NULL;
Elliott Hughesbb551fa2012-01-25 16:35:29 -08001276 uint64_t start_ns = NanoTime();
Logan Chien4dd96f52012-02-29 01:26:58 +08001277
Ian Rogers169c9a72011-11-13 20:13:17 -08001278 if ((access_flags & kAccNative) != 0) {
Elliott Hughes46f060a2012-03-09 17:36:50 -08001279 compiled_method = (*jni_compiler_)(*this, access_flags, method_idx, class_loader, dex_file);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07001280 CHECK(compiled_method != NULL);
Ian Rogers169c9a72011-11-13 20:13:17 -08001281 } else if ((access_flags & kAccAbstract) != 0) {
Brian Carlstrom2cc022b2011-08-25 10:05:39 -07001282 } else {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001283 compiled_method = (*compiler_)(*this, code_item, access_flags, method_idx, class_loader,
1284 dex_file);
Elliott Hughesbb551fa2012-01-25 16:35:29 -08001285 CHECK(compiled_method != NULL) << PrettyMethod(method_idx, dex_file);
1286 }
Ian Rogers3bb17a62012-01-27 23:56:44 -08001287 uint64_t duration_ns = NanoTime() - start_ns;
buzbee5abfa3e2012-01-31 17:01:43 -08001288 if (duration_ns > MsToNs(100)) {
Elliott Hughesbb551fa2012-01-25 16:35:29 -08001289 LOG(WARNING) << "Compilation of " << PrettyMethod(method_idx, dex_file)
Ian Rogers3bb17a62012-01-27 23:56:44 -08001290 << " took " << PrettyDuration(duration_ns);
Elliott Hughesf09afe82011-10-16 14:24:21 -07001291 }
1292
1293 if (compiled_method != NULL) {
Ian Rogers0571d352011-11-03 19:51:38 -07001294 MethodReference ref(&dex_file, method_idx);
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001295 CHECK(GetCompiledMethod(ref) == NULL) << PrettyMethod(method_idx, dex_file);
Elliott Hughesc225caa2012-02-03 15:43:37 -08001296 MutexLock mu(compiled_methods_lock_);
Ian Rogers0571d352011-11-03 19:51:38 -07001297 compiled_methods_[ref] = compiled_method;
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001298 DCHECK(GetCompiledMethod(ref) != NULL) << PrettyMethod(method_idx, dex_file);
Brian Carlstrom2cc022b2011-08-25 10:05:39 -07001299 }
Brian Carlstrom9baa4ae2011-09-01 21:14:14 -07001300
Ian Rogers45619fc2012-02-29 11:15:25 -08001301 uint32_t shorty_len;
1302 const char* shorty = dex_file.GetMethodShorty(dex_file.GetMethodId(method_idx), &shorty_len);
Ian Rogers169c9a72011-11-13 20:13:17 -08001303 bool is_static = (access_flags & kAccStatic) != 0;
Ian Rogers0571d352011-11-03 19:51:38 -07001304 const CompiledInvokeStub* compiled_invoke_stub = FindInvokeStub(is_static, shorty);
1305 if (compiled_invoke_stub == NULL) {
Shih-wei Liaoc4c98812012-03-10 21:55:51 -08001306 compiled_invoke_stub = (*create_invoke_stub_)(*this, is_static, shorty, shorty_len);
Ian Rogers0571d352011-11-03 19:51:38 -07001307 CHECK(compiled_invoke_stub != NULL);
1308 InsertInvokeStub(is_static, shorty, compiled_invoke_stub);
Ian Rogers2c8f6532011-09-02 17:16:34 -07001309 }
Ian Rogers0571d352011-11-03 19:51:38 -07001310 CHECK(!Thread::Current()->IsExceptionPending()) << PrettyMethod(method_idx, dex_file);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07001311}
1312
Ian Rogers0571d352011-11-03 19:51:38 -07001313static std::string MakeInvokeStubKey(bool is_static, const char* shorty) {
1314 std::string key(shorty);
1315 if (is_static) {
Elliott Hughesbb551fa2012-01-25 16:35:29 -08001316 key += "$"; // Must not be a shorty type character.
Brian Carlstrom3320cf42011-10-04 14:58:28 -07001317 }
Ian Rogers0571d352011-11-03 19:51:38 -07001318 return key;
Brian Carlstrom3320cf42011-10-04 14:58:28 -07001319}
1320
Ian Rogers0571d352011-11-03 19:51:38 -07001321const CompiledInvokeStub* Compiler::FindInvokeStub(bool is_static, const char* shorty) const {
Elliott Hughesc225caa2012-02-03 15:43:37 -08001322 MutexLock mu(compiled_invoke_stubs_lock_);
Elliott Hughes95572412011-12-13 18:14:20 -08001323 const std::string key(MakeInvokeStubKey(is_static, shorty));
Ian Rogers0571d352011-11-03 19:51:38 -07001324 InvokeStubTable::const_iterator it = compiled_invoke_stubs_.find(key);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07001325 if (it == compiled_invoke_stubs_.end()) {
1326 return NULL;
Ian Rogers0571d352011-11-03 19:51:38 -07001327 } else {
1328 DCHECK(it->second != NULL);
1329 return it->second;
1330 }
1331}
1332
1333void Compiler::InsertInvokeStub(bool is_static, const char* shorty,
1334 const CompiledInvokeStub* compiled_invoke_stub) {
Elliott Hughesc225caa2012-02-03 15:43:37 -08001335 MutexLock mu(compiled_invoke_stubs_lock_);
Elliott Hughes95572412011-12-13 18:14:20 -08001336 std::string key(MakeInvokeStubKey(is_static, shorty));
Ian Rogers0571d352011-11-03 19:51:38 -07001337 compiled_invoke_stubs_[key] = compiled_invoke_stub;
1338}
1339
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001340CompiledClass* Compiler::GetCompiledClass(ClassReference ref) const {
Elliott Hughesc225caa2012-02-03 15:43:37 -08001341 MutexLock mu(compiled_classes_lock_);
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001342 ClassTable::const_iterator it = compiled_classes_.find(ref);
1343 if (it == compiled_classes_.end()) {
1344 return NULL;
1345 }
1346 CHECK(it->second != NULL);
1347 return it->second;
1348}
1349
Ian Rogers0571d352011-11-03 19:51:38 -07001350CompiledMethod* Compiler::GetCompiledMethod(MethodReference ref) const {
Elliott Hughesc225caa2012-02-03 15:43:37 -08001351 MutexLock mu(compiled_methods_lock_);
Ian Rogers0571d352011-11-03 19:51:38 -07001352 MethodTable::const_iterator it = compiled_methods_.find(ref);
1353 if (it == compiled_methods_.end()) {
1354 return NULL;
Brian Carlstrom3320cf42011-10-04 14:58:28 -07001355 }
1356 CHECK(it->second != NULL);
1357 return it->second;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001358}
1359
Brian Carlstrome7d856b2012-01-11 18:10:55 -08001360void Compiler::SetGcMaps(const ClassLoader* class_loader, const std::vector<const DexFile*>& dex_files) {
1361 for (size_t i = 0; i != dex_files.size(); ++i) {
1362 const DexFile* dex_file = dex_files[i];
1363 CHECK(dex_file != NULL);
1364 SetGcMapsDexFile(class_loader, *dex_file);
1365 }
1366}
1367
1368void Compiler::SetGcMapsDexFile(const ClassLoader* class_loader, const DexFile& dex_file) {
1369 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1370 DexCache* dex_cache = class_linker->FindDexCache(dex_file);
1371 for (size_t class_def_index = 0; class_def_index < dex_file.NumClassDefs(); class_def_index++) {
1372 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
1373 const char* descriptor = dex_file.GetClassDescriptor(class_def);
1374 Class* klass = class_linker->FindClass(descriptor, class_loader);
1375 if (klass == NULL || !klass->IsVerified()) {
1376 Thread::Current()->ClearException();
1377 continue;
1378 }
1379 const byte* class_data = dex_file.GetClassData(class_def);
1380 if (class_data == NULL) {
1381 // empty class such as a marker interface
1382 continue;
1383 }
1384 ClassDataItemIterator it(dex_file, class_data);
1385 while (it.HasNextStaticField()) {
1386 it.Next();
1387 }
1388 while (it.HasNextInstanceField()) {
1389 it.Next();
1390 }
1391 while (it.HasNextDirectMethod()) {
1392 Method* method = class_linker->ResolveMethod(dex_file, it.GetMemberIndex(), dex_cache,
1393 class_loader, true);
1394 SetGcMapsMethod(dex_file, method);
1395 it.Next();
1396 }
1397 while (it.HasNextVirtualMethod()) {
1398 Method* method = class_linker->ResolveMethod(dex_file, it.GetMemberIndex(), dex_cache,
1399 class_loader, false);
1400 SetGcMapsMethod(dex_file, method);
1401 it.Next();
1402 }
1403 }
1404}
1405
1406void Compiler::SetGcMapsMethod(const DexFile& dex_file, Method* method) {
1407 if (method == NULL) {
1408 Thread::Current()->ClearException();
1409 return;
1410 }
1411 uint16_t method_idx = method->GetDexMethodIndex();
1412 MethodReference ref(&dex_file, method_idx);
1413 CompiledMethod* compiled_method = GetCompiledMethod(ref);
1414 if (compiled_method == NULL) {
1415 return;
1416 }
1417 const std::vector<uint8_t>* gc_map = verifier::DexVerifier::GetGcMap(ref);
1418 if (gc_map == NULL) {
1419 return;
1420 }
1421 compiled_method->SetGcMap(*gc_map);
1422}
1423
Logan Chien8b977d32012-02-21 19:14:55 +08001424#if defined(ART_USE_LLVM_COMPILER)
Logan Chien8b977d32012-02-21 19:14:55 +08001425void Compiler::SetBitcodeFileName(std::string const& filename) {
Logan Chien106b2a02012-03-18 04:41:38 +08001426 typedef void (*SetBitcodeFileNameFn)(Compiler&, std::string const&);
1427
1428 SetBitcodeFileNameFn set_bitcode_file_name =
1429 FindFunction<SetBitcodeFileNameFn>(MakeCompilerSoName(instruction_set_),
1430 compiler_library_,
1431 "compilerLLVMSetBitcodeFileName");
1432
1433 set_bitcode_file_name(*this, filename);
Logan Chien8b977d32012-02-21 19:14:55 +08001434}
Logan Chienf7015fd2012-03-18 01:19:37 +08001435
1436void Compiler::EnableAutoElfLoading() {
1437 compiler_enable_auto_elf_loading_(*this);
1438}
1439
1440const void* Compiler::GetMethodCodeAddr(const CompiledMethod* cm,
1441 const Method* method) const {
1442 return compiler_get_method_code_addr_(*this, cm, method);
1443}
1444
1445const Method::InvokeStub* Compiler::GetMethodInvokeStubAddr(const CompiledInvokeStub* cm,
1446 const Method* method) const {
1447 return compiler_get_method_invoke_stub_addr_(*this, cm, method);
1448}
Logan Chiendf576142012-03-20 17:36:32 +08001449
1450std::vector<ElfImage> Compiler::GetElfImages() const {
1451 typedef std::vector<ElfImage> (*GetElfImagesFn)(const Compiler&);
1452
1453 GetElfImagesFn get_elf_images =
1454 FindFunction<GetElfImagesFn>(MakeCompilerSoName(instruction_set_),
1455 compiler_library_,
1456 "compilerLLVMGetElfImages");
1457
1458 return get_elf_images(*this);
1459}
Logan Chien8b977d32012-02-21 19:14:55 +08001460#endif
1461
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001462} // namespace art