blob: 6a65b6941693013dab840d7225c00f702c39afdf [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) {
57 return 100.0 * ((double)x) / ((double)(x + y));
58}
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;
81 }
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
164 void UnresolvedInstanceField(){
165 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
239 DISALLOW_COPY_AND_ASSIGN(AOTCompilationStats);;
240};
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 Hughesb3bd5f02012-03-08 21:05:27 -0800259#ifndef NDEBUG
260 const char* suffix = "d";
261#else
262 const char* suffix = "";
263#endif
Elliott Hughes059d5c12012-03-12 17:39:18 -0700264
265 // Work out the filename for the compiler library.
Shih-wei Liaoc4c98812012-03-10 21:55:51 -0800266#if !defined(ART_USE_LLVM_COMPILER)
Elliott Hughes059d5c12012-03-12 17:39:18 -0700267 std::string library_name(StringPrintf("art%s-compiler-%s", suffix, instruction_set_name.c_str()));
Shih-wei Liaoc4c98812012-03-10 21:55:51 -0800268#else
269 std::string library_name(StringPrintf("art%s-compiler-llvm", suffix));
270#endif
Elliott Hughes059d5c12012-03-12 17:39:18 -0700271 std::string filename(StringPrintf(OS_SHARED_LIB_FORMAT_STR, library_name.c_str()));
272
273#if defined(__APPLE__)
274 // On Linux, dex2oat will have been built with an RPATH of $ORIGIN/../lib, so dlopen(3) will find
275 // the .so by itself. On Mac OS, there isn't really an equivalent, so we have to manually do the
276 // same work.
277 std::vector<char> executable_path(1);
278 uint32_t executable_path_length = 0;
279 _NSGetExecutablePath(&executable_path[0], &executable_path_length);
280 while (_NSGetExecutablePath(&executable_path[0], &executable_path_length) == -1) {
281 executable_path.resize(executable_path_length);
282 }
283
284 executable_path.resize(executable_path.size() - 1); // Strip trailing NUL.
285 std::string path(&executable_path[0]);
286
287 // Strip the "/dex2oat".
288 size_t last_slash = path.find_last_of('/');
289 CHECK_NE(last_slash, std::string::npos) << path;
290 path.resize(last_slash);
291
292 // Strip the "/bin".
293 last_slash = path.find_last_of('/');
294 path.resize(last_slash);
295
296 filename = path + "/lib/" + filename;
297#endif
298 return filename;
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800299}
300
Elliott Hughes46f060a2012-03-09 17:36:50 -0800301template<typename Fn>
302static Fn FindFunction(const std::string& compiler_so_name, void* library, const char* name) {
303 Fn fn = reinterpret_cast<Fn>(dlsym(library, name));
304 if (fn == NULL) {
305 LOG(FATAL) << "Couldn't find \"" << name << "\" in compiler library " << compiler_so_name << ": " << dlerror();
306 }
Elliott Hughes059d5c12012-03-12 17:39:18 -0700307 VLOG(compiler) << "Found \"" << name << "\" at " << reinterpret_cast<void*>(fn);
Elliott Hughes46f060a2012-03-09 17:36:50 -0800308 return fn;
309}
310
Elliott Hughes5523ee02012-02-03 18:18:34 -0800311Compiler::Compiler(InstructionSet instruction_set, bool image, size_t thread_count,
Elliott Hughesde6e4cf2012-02-27 14:46:06 -0800312 bool support_debugging, const std::set<std::string>* image_classes)
Brian Carlstromaded5f72011-10-07 17:15:04 -0700313 : instruction_set_(instruction_set),
Elliott Hughesc225caa2012-02-03 15:43:37 -0800314 compiled_classes_lock_("compiled classes lock"),
315 compiled_methods_lock_("compiled method lock"),
316 compiled_invoke_stubs_lock_("compiled invoke stubs lock"),
Brian Carlstromaded5f72011-10-07 17:15:04 -0700317 image_(image),
Elliott Hughes5523ee02012-02-03 18:18:34 -0800318 thread_count_(thread_count),
Elliott Hughesde6e4cf2012-02-27 14:46:06 -0800319 support_debugging_(support_debugging),
Ian Rogersc8b306f2012-02-17 21:34:44 -0800320 stats_(new AOTCompilationStats),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800321 image_classes_(image_classes),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800322 compiler_library_(NULL),
Elliott Hughes46f060a2012-03-09 17:36:50 -0800323 compiler_(NULL),
Elliott Hughes6f4976c2012-03-13 21:19:01 -0700324 compiler_context_(NULL),
Elliott Hughes46f060a2012-03-09 17:36:50 -0800325 jni_compiler_(NULL),
326 create_invoke_stub_(NULL)
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800327{
Shih-wei Liaoc4c98812012-03-10 21:55:51 -0800328 std::string compiler_so_name(MakeCompilerSoName(instruction_set_));
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800329 compiler_library_ = dlopen(compiler_so_name.c_str(), RTLD_LAZY);
330 if (compiler_library_ == NULL) {
331 LOG(FATAL) << "Couldn't find compiler library " << compiler_so_name << ": " << dlerror();
332 }
333 VLOG(compiler) << "dlopen(\"" << compiler_so_name << "\", RTLD_LAZY) returned " << compiler_library_;
334
Elliott Hughes3fa1b7e2012-03-13 17:06:22 -0700335 compiler_ = FindFunction<CompilerFn>(compiler_so_name, compiler_library_, "ArtCompileMethod");
Elliott Hughes46f060a2012-03-09 17:36:50 -0800336 jni_compiler_ = FindFunction<JniCompilerFn>(compiler_so_name, compiler_library_, "ArtJniCompileMethod");
337 create_invoke_stub_ = FindFunction<CreateInvokeStubFn>(compiler_so_name, compiler_library_, "ArtCreateInvokeStub");
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800338
Brian Carlstrom25c33252011-09-18 15:58:35 -0700339 CHECK(!Runtime::Current()->IsStarted());
Brian Carlstromae826982011-11-09 01:33:42 -0800340 if (!image_) {
341 CHECK(image_classes_ == NULL);
342 }
Shih-wei Liaoc486c112011-09-13 16:43:52 -0700343}
344
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700345Compiler::~Compiler() {
Elliott Hughesc225caa2012-02-03 15:43:37 -0800346 {
347 MutexLock mu(compiled_classes_lock_);
348 STLDeleteValues(&compiled_classes_);
349 }
350 {
351 MutexLock mu(compiled_methods_lock_);
352 STLDeleteValues(&compiled_methods_);
353 }
354 {
355 MutexLock mu(compiled_invoke_stubs_lock_);
356 STLDeleteValues(&compiled_invoke_stubs_);
Elliott Hughesbb551fa2012-01-25 16:35:29 -0800357 }
Shih-wei Liaoc4c98812012-03-10 21:55:51 -0800358#if defined(ART_USE_LLVM_COMPILER)
359 CompilerCallbackFn f = FindFunction<CompilerCallbackFn>(MakeCompilerSoName(instruction_set_),
360 compiler_library_,
361 "compilerLLVMDispose");
362 (*f)(*this);
363#endif
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800364 if (compiler_library_ != NULL) {
365 VLOG(compiler) << "dlclose(" << compiler_library_ << ")";
366 dlclose(compiler_library_);
367 }
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700368}
369
Ian Rogers1cb0a1d2011-10-06 15:24:35 -0700370ByteArray* Compiler::CreateResolutionStub(InstructionSet instruction_set,
371 Runtime::TrampolineType type) {
Ian Rogersad25ac52011-10-04 19:13:33 -0700372 if (instruction_set == kX86) {
Ian Rogers1cb0a1d2011-10-06 15:24:35 -0700373 return x86::X86CreateResolutionTrampoline(type);
Ian Rogersad25ac52011-10-04 19:13:33 -0700374 } else {
375 CHECK(instruction_set == kArm || instruction_set == kThumb2);
376 // Generates resolution stub using ARM instruction set
Ian Rogers1cb0a1d2011-10-06 15:24:35 -0700377 return arm::ArmCreateResolutionTrampoline(type);
Ian Rogersad25ac52011-10-04 19:13:33 -0700378 }
379}
380
Elliott Hughes8add92d2012-01-18 18:18:43 -0800381ByteArray* Compiler::CreateJniDlsymLookupStub(InstructionSet instruction_set) {
Ian Rogers169c9a72011-11-13 20:13:17 -0800382 switch (instruction_set) {
383 case kArm:
384 case kThumb2:
Elliott Hughes8add92d2012-01-18 18:18:43 -0800385 return arm::CreateJniDlsymLookupStub();
Ian Rogers169c9a72011-11-13 20:13:17 -0800386 case kX86:
Elliott Hughes8add92d2012-01-18 18:18:43 -0800387 return x86::CreateJniDlsymLookupStub();
Ian Rogers169c9a72011-11-13 20:13:17 -0800388 default:
Ian Rogers49c48942012-03-11 15:15:37 -0700389 LOG(FATAL) << "Unknown InstructionSet: " << instruction_set;
Ian Rogers169c9a72011-11-13 20:13:17 -0800390 return NULL;
391 }
392}
393
Ian Rogersad25ac52011-10-04 19:13:33 -0700394ByteArray* Compiler::CreateAbstractMethodErrorStub(InstructionSet instruction_set) {
395 if (instruction_set == kX86) {
396 return x86::CreateAbstractMethodErrorStub();
397 } else {
398 CHECK(instruction_set == kArm || instruction_set == kThumb2);
399 // Generates resolution stub using ARM instruction set
400 return arm::CreateAbstractMethodErrorStub();
401 }
402}
403
Jesse Wilson254db0f2011-11-16 16:44:11 -0500404void Compiler::CompileAll(const ClassLoader* class_loader,
Brian Carlstromae826982011-11-09 01:33:42 -0800405 const std::vector<const DexFile*>& dex_files) {
Brian Carlstrom25c33252011-09-18 15:58:35 -0700406 DCHECK(!Runtime::Current()->IsStarted());
Brian Carlstromae826982011-11-09 01:33:42 -0800407
Elliott Hughes601a1232012-02-02 17:47:38 -0800408 TimingLogger timings("compiler");
409
410 PreCompile(class_loader, dex_files, timings);
411
Brian Carlstromae826982011-11-09 01:33:42 -0800412 Compile(class_loader, dex_files);
Elliott Hughes601a1232012-02-02 17:47:38 -0800413 timings.AddSplit("Compile");
414
Brian Carlstromae826982011-11-09 01:33:42 -0800415 PostCompile(class_loader, dex_files);
Elliott Hughes601a1232012-02-02 17:47:38 -0800416 timings.AddSplit("PostCompile");
417
418 if (timings.GetTotalNs() > MsToNs(1000)) {
419 timings.Dump();
420 }
Ian Rogers996cc582012-02-14 22:23:29 -0800421
Ian Rogersc8b306f2012-02-17 21:34:44 -0800422 stats_->Dump();
Brian Carlstrom8a487412011-08-29 20:08:52 -0700423}
424
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700425void Compiler::CompileOne(const Method* method) {
Brian Carlstrom25c33252011-09-18 15:58:35 -0700426 DCHECK(!Runtime::Current()->IsStarted());
Brian Carlstromae826982011-11-09 01:33:42 -0800427
Brian Carlstrom8a487412011-08-29 20:08:52 -0700428 const ClassLoader* class_loader = method->GetDeclaringClass()->GetClassLoader();
Brian Carlstromae826982011-11-09 01:33:42 -0800429
Ian Rogers0571d352011-11-03 19:51:38 -0700430 // Find the dex_file
431 const DexCache* dex_cache = method->GetDeclaringClass()->GetDexCache();
432 const DexFile& dex_file = Runtime::Current()->GetClassLinker()->FindDexFile(dex_cache);
Brian Carlstromae826982011-11-09 01:33:42 -0800433 std::vector<const DexFile*> dex_files;
434 dex_files.push_back(&dex_file);
435
Elliott Hughes601a1232012-02-02 17:47:38 -0800436 TimingLogger timings("CompileOne");
437 PreCompile(class_loader, dex_files, timings);
Brian Carlstromae826982011-11-09 01:33:42 -0800438
Ian Rogers0571d352011-11-03 19:51:38 -0700439 uint32_t method_idx = method->GetDexMethodIndex();
Ian Rogersa3760aa2011-11-14 14:32:37 -0800440 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(method->GetCodeItemOffset());
441 CompileMethod(code_item, method->GetAccessFlags(), method_idx, class_loader, dex_file);
Brian Carlstromae826982011-11-09 01:33:42 -0800442
443 PostCompile(class_loader, dex_files);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700444}
445
Brian Carlstromae826982011-11-09 01:33:42 -0800446void Compiler::Resolve(const ClassLoader* class_loader,
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800447 const std::vector<const DexFile*>& dex_files, TimingLogger& timings) {
Brian Carlstromae826982011-11-09 01:33:42 -0800448 for (size_t i = 0; i != dex_files.size(); ++i) {
449 const DexFile* dex_file = dex_files[i];
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700450 CHECK(dex_file != NULL);
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800451 ResolveDexFile(class_loader, *dex_file, timings);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700452 }
453}
454
Brian Carlstromae826982011-11-09 01:33:42 -0800455void Compiler::PreCompile(const ClassLoader* class_loader,
Elliott Hughes601a1232012-02-02 17:47:38 -0800456 const std::vector<const DexFile*>& dex_files, TimingLogger& timings) {
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800457 Resolve(class_loader, dex_files, timings);
Elliott Hughes601a1232012-02-02 17:47:38 -0800458
Brian Carlstromae826982011-11-09 01:33:42 -0800459 Verify(class_loader, dex_files);
Elliott Hughes601a1232012-02-02 17:47:38 -0800460 timings.AddSplit("PreCompile.Verify");
461
Brian Carlstromae826982011-11-09 01:33:42 -0800462 InitializeClassesWithoutClinit(class_loader, dex_files);
Elliott Hughes601a1232012-02-02 17:47:38 -0800463 timings.AddSplit("PreCompile.InitializeClassesWithoutClinit");
Brian Carlstromae826982011-11-09 01:33:42 -0800464}
465
466void Compiler::PostCompile(const ClassLoader* class_loader,
467 const std::vector<const DexFile*>& dex_files) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -0800468 SetGcMaps(class_loader, dex_files);
Shih-wei Liaod1fec812012-02-13 09:51:10 -0800469#if defined(ART_USE_LLVM_COMPILER)
Shih-wei Liaoc4c98812012-03-10 21:55:51 -0800470 CompilerCallbackFn f = FindFunction<CompilerCallbackFn>(MakeCompilerSoName(instruction_set_),
471 compiler_library_,
472 "compilerLLVMMaterializeRemainder");
473 (*f)(*this);
Shih-wei Liaod1fec812012-02-13 09:51:10 -0800474#endif
Brian Carlstromae826982011-11-09 01:33:42 -0800475}
476
477bool Compiler::IsImageClass(const std::string& descriptor) const {
478 if (image_classes_ == NULL) {
479 return true;
480 }
481 return image_classes_->find(descriptor) != image_classes_->end();
482}
483
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800484bool Compiler::CanAssumeTypeIsPresentInDexCache(const DexCache* dex_cache,
Ian Rogers996cc582012-02-14 22:23:29 -0800485 uint32_t type_idx) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800486 if (!IsImage()) {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800487 stats_->TypeNotInDexCache();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800488 return false;
489 }
Ian Rogers1bddec32012-02-04 12:27:34 -0800490 Class* resolved_class = dex_cache->GetResolvedType(type_idx);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800491 if (resolved_class == NULL) {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800492 stats_->TypeNotInDexCache();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800493 return false;
494 }
Ian Rogers996cc582012-02-14 22:23:29 -0800495 bool result = IsImageClass(ClassHelper(resolved_class).GetDescriptor());
496 if (result) {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800497 stats_->TypeInDexCache();
Ian Rogers996cc582012-02-14 22:23:29 -0800498 } else {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800499 stats_->TypeNotInDexCache();
Ian Rogers996cc582012-02-14 22:23:29 -0800500 }
501 return result;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800502}
503
Ian Rogers1bddec32012-02-04 12:27:34 -0800504bool Compiler::CanAssumeStringIsPresentInDexCache(const DexCache* dex_cache,
Ian Rogers996cc582012-02-14 22:23:29 -0800505 uint32_t string_idx) {
Ian Rogers1bddec32012-02-04 12:27:34 -0800506 // TODO: Add support for loading strings referenced by image_classes_
507 // See also Compiler::ResolveDexFile
508
509 // The following is a test saying that if we're building the image without a restricted set of
510 // 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 -0800511 bool result = IsImage() && image_classes_ == NULL && dex_cache->GetResolvedString(string_idx) != NULL;
512 if (result) {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800513 stats_->StringInDexCache();
Ian Rogers996cc582012-02-14 22:23:29 -0800514 } else {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800515 stats_->StringNotInDexCache();
Ian Rogers996cc582012-02-14 22:23:29 -0800516 }
517 return result;
Ian Rogers1bddec32012-02-04 12:27:34 -0800518}
519
520bool Compiler::CanAccessTypeWithoutChecks(uint32_t referrer_idx, const DexCache* dex_cache,
Ian Rogers996cc582012-02-14 22:23:29 -0800521 const DexFile& dex_file, uint32_t type_idx) {
Ian Rogers1bddec32012-02-04 12:27:34 -0800522 // Get type from dex cache assuming it was populated by the verifier
523 Class* resolved_class = dex_cache->GetResolvedType(type_idx);
524 if (resolved_class == NULL) {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800525 stats_->TypeNeedsAccessCheck();
Ian Rogers1bddec32012-02-04 12:27:34 -0800526 return false; // Unknown class needs access checks.
527 }
528 const DexFile::MethodId& method_id = dex_file.GetMethodId(referrer_idx);
529 Class* referrer_class = dex_cache->GetResolvedType(method_id.class_idx_);
530 if (referrer_class == NULL) {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800531 stats_->TypeNeedsAccessCheck();
Ian Rogers1bddec32012-02-04 12:27:34 -0800532 return false; // Incomplete referrer knowledge needs access check.
533 }
534 // Perform access check, will return true if access is ok or false if we're going to have to
535 // check this at runtime (for example for class loaders).
Ian Rogers996cc582012-02-14 22:23:29 -0800536 bool result = referrer_class->CanAccess(resolved_class);
537 if (result) {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800538 stats_->TypeDoesntNeedAccessCheck();
Ian Rogers996cc582012-02-14 22:23:29 -0800539 } else {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800540 stats_->TypeNeedsAccessCheck();
Ian Rogers996cc582012-02-14 22:23:29 -0800541 }
542 return result;
Ian Rogers1bddec32012-02-04 12:27:34 -0800543}
544
545bool Compiler::CanAccessInstantiableTypeWithoutChecks(uint32_t referrer_idx,
546 const DexCache* dex_cache,
547 const DexFile& dex_file,
Ian Rogers996cc582012-02-14 22:23:29 -0800548 uint32_t type_idx) {
Ian Rogers1bddec32012-02-04 12:27:34 -0800549 // Get type from dex cache assuming it was populated by the verifier.
550 Class* resolved_class = dex_cache->GetResolvedType(type_idx);
551 if (resolved_class == NULL) {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800552 stats_->TypeNeedsAccessCheck();
Ian Rogers1bddec32012-02-04 12:27:34 -0800553 return false; // Unknown class needs access checks.
554 }
555 const DexFile::MethodId& method_id = dex_file.GetMethodId(referrer_idx);
556 Class* referrer_class = dex_cache->GetResolvedType(method_id.class_idx_);
557 if (referrer_class == NULL) {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800558 stats_->TypeNeedsAccessCheck();
Ian Rogers1bddec32012-02-04 12:27:34 -0800559 return false; // Incomplete referrer knowledge needs access check.
560 }
561 // Perform access and instantiable checks, will return true if access is ok or false if we're
562 // going to have to check this at runtime (for example for class loaders).
Ian Rogers996cc582012-02-14 22:23:29 -0800563 bool result = referrer_class->CanAccess(resolved_class) && resolved_class->IsInstantiable();
564 if (result) {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800565 stats_->TypeDoesntNeedAccessCheck();
Ian Rogers996cc582012-02-14 22:23:29 -0800566 } else {
Ian Rogersc8b306f2012-02-17 21:34:44 -0800567 stats_->TypeNeedsAccessCheck();
Ian Rogers996cc582012-02-14 22:23:29 -0800568 }
569 return result;
Ian Rogers1bddec32012-02-04 12:27:34 -0800570}
571
Logan Chien4dd96f52012-02-29 01:26:58 +0800572static Class* ComputeReferrerClass(OatCompilationUnit* mUnit) {
573 const DexFile::MethodId& referrer_method_id =
574 mUnit->dex_file_->GetMethodId(mUnit->method_idx_);
575
576 return mUnit->class_linker_->ResolveType(
577 *mUnit->dex_file_, referrer_method_id.class_idx_,
578 mUnit->dex_cache_, mUnit->class_loader_);
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800579}
580
Logan Chien4dd96f52012-02-29 01:26:58 +0800581static Field* ComputeReferrerField(OatCompilationUnit* mUnit, uint32_t field_idx) {
582 return mUnit->class_linker_->ResolveField(
583 *mUnit->dex_file_, field_idx, mUnit->dex_cache_,
584 mUnit->class_loader_, false);
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800585}
586
Logan Chien4dd96f52012-02-29 01:26:58 +0800587static Method* ComputeReferrerMethod(OatCompilationUnit* mUnit, uint32_t method_idx) {
588 return mUnit->class_linker_->ResolveMethod(
589 *mUnit->dex_file_, method_idx, mUnit->dex_cache_,
590 mUnit->class_loader_, true);
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800591}
592
Logan Chien4dd96f52012-02-29 01:26:58 +0800593bool Compiler::ComputeInstanceFieldInfo(uint32_t field_idx, OatCompilationUnit* mUnit,
jeffhao8cd6dda2012-02-22 10:15:34 -0800594 int& field_offset, bool& is_volatile, bool is_put) {
Ian Rogers1bddec32012-02-04 12:27:34 -0800595 // Conservative defaults
596 field_offset = -1;
597 is_volatile = true;
598 // Try to resolve field
Logan Chien4dd96f52012-02-29 01:26:58 +0800599 Field* resolved_field = ComputeReferrerField(mUnit, field_idx);
Ian Rogers1bddec32012-02-04 12:27:34 -0800600 if (resolved_field != NULL) {
Logan Chien4dd96f52012-02-29 01:26:58 +0800601 Class* referrer_class = ComputeReferrerClass(mUnit);
Ian Rogers1bddec32012-02-04 12:27:34 -0800602 // Try to resolve referring class then access check, failure to pass the
603 Class* fields_class = resolved_field->GetDeclaringClass();
jeffhao8cd6dda2012-02-22 10:15:34 -0800604 bool is_write_to_final_from_wrong_class = is_put && resolved_field->IsFinal() &&
605 fields_class != referrer_class;
606 if (referrer_class != NULL && referrer_class->CanAccess(fields_class) &&
607 referrer_class->CanAccessMember(fields_class, resolved_field->GetAccessFlags()) &&
608 !is_write_to_final_from_wrong_class) {
Ian Rogers1bddec32012-02-04 12:27:34 -0800609 field_offset = resolved_field->GetOffset().Int32Value();
610 is_volatile = resolved_field->IsVolatile();
Ian Rogersc8b306f2012-02-17 21:34:44 -0800611 stats_->ResolvedInstanceField();
Ian Rogers1bddec32012-02-04 12:27:34 -0800612 return true; // Fast path.
613 }
614 }
615 // Clean up any exception left by field/type resolution
616 Thread* thread = Thread::Current();
617 if (thread->IsExceptionPending()) {
618 thread->ClearException();
619 }
Ian Rogersc8b306f2012-02-17 21:34:44 -0800620 stats_->UnresolvedInstanceField();
Ian Rogers1bddec32012-02-04 12:27:34 -0800621 return false; // Incomplete knowledge needs slow path.
622}
623
Logan Chien4dd96f52012-02-29 01:26:58 +0800624bool Compiler::ComputeStaticFieldInfo(uint32_t field_idx, OatCompilationUnit* mUnit,
Ian Rogers1bddec32012-02-04 12:27:34 -0800625 int& field_offset, int& ssb_index,
jeffhao8cd6dda2012-02-22 10:15:34 -0800626 bool& is_referrers_class, bool& is_volatile, bool is_put) {
Ian Rogers1bddec32012-02-04 12:27:34 -0800627 // Conservative defaults
628 field_offset = -1;
629 ssb_index = -1;
630 is_referrers_class = false;
631 is_volatile = true;
632 // Try to resolve field
Logan Chien4dd96f52012-02-29 01:26:58 +0800633 Field* resolved_field = ComputeReferrerField(mUnit, field_idx);
Ian Rogers1bddec32012-02-04 12:27:34 -0800634 if (resolved_field != NULL) {
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800635 DCHECK(resolved_field->IsStatic());
Logan Chien4dd96f52012-02-29 01:26:58 +0800636 Class* referrer_class = ComputeReferrerClass(mUnit);
Ian Rogers1bddec32012-02-04 12:27:34 -0800637 if (referrer_class != NULL) {
jeffhao8cd6dda2012-02-22 10:15:34 -0800638 Class* fields_class = resolved_field->GetDeclaringClass();
639 if (fields_class == referrer_class) {
Ian Rogers1bddec32012-02-04 12:27:34 -0800640 is_referrers_class = true; // implies no worrying about class initialization
641 field_offset = resolved_field->GetOffset().Int32Value();
642 is_volatile = resolved_field->IsVolatile();
Ian Rogersc8b306f2012-02-17 21:34:44 -0800643 stats_->ResolvedLocalStaticField();
Ian Rogers1bddec32012-02-04 12:27:34 -0800644 return true; // fast path
645 } else {
jeffhao8cd6dda2012-02-22 10:15:34 -0800646 bool is_write_to_final_from_wrong_class = is_put && resolved_field->IsFinal();
Ian Rogers1bddec32012-02-04 12:27:34 -0800647 if (referrer_class->CanAccess(fields_class) &&
jeffhao8cd6dda2012-02-22 10:15:34 -0800648 referrer_class->CanAccessMember(fields_class, resolved_field->GetAccessFlags()) &&
649 !is_write_to_final_from_wrong_class) {
Ian Rogers1bddec32012-02-04 12:27:34 -0800650 // We have the resolved field, we must make it into a ssbIndex for the referrer
651 // in its static storage base (which may fail if it doesn't have a slot for it)
Ian Rogers4103ad22012-02-06 09:18:25 -0800652 // TODO: for images we can elide the static storage base null check
653 // if we know there's a non-null entry in the image
Logan Chien4dd96f52012-02-29 01:26:58 +0800654 if (fields_class->GetDexCache() == mUnit->dex_cache_) {
Ian Rogers4103ad22012-02-06 09:18:25 -0800655 // common case where the dex cache of both the referrer and the field are the same,
656 // no need to search the dex file
657 ssb_index = fields_class->GetDexTypeIndex();
658 field_offset = resolved_field->GetOffset().Int32Value();
659 is_volatile = resolved_field->IsVolatile();
Ian Rogersc8b306f2012-02-17 21:34:44 -0800660 stats_->ResolvedStaticField();
Ian Rogers4103ad22012-02-06 09:18:25 -0800661 return true;
662 }
663 // Search dex file for localized ssb index
Ian Rogers1bddec32012-02-04 12:27:34 -0800664 std::string descriptor(FieldHelper(resolved_field).GetDeclaringClassDescriptor());
665 const DexFile::StringId* string_id =
Logan Chien4dd96f52012-02-29 01:26:58 +0800666 mUnit->dex_file_->FindStringId(descriptor);
Ian Rogers1bddec32012-02-04 12:27:34 -0800667 if (string_id != NULL) {
668 const DexFile::TypeId* type_id =
Logan Chien4dd96f52012-02-29 01:26:58 +0800669 mUnit->dex_file_->FindTypeId(mUnit->dex_file_->GetIndexForStringId(*string_id));
Ian Rogers1bddec32012-02-04 12:27:34 -0800670 if(type_id != NULL) {
671 // medium path, needs check of static storage base being initialized
Logan Chien4dd96f52012-02-29 01:26:58 +0800672 ssb_index = mUnit->dex_file_->GetIndexForTypeId(*type_id);
Ian Rogers1bddec32012-02-04 12:27:34 -0800673 field_offset = resolved_field->GetOffset().Int32Value();
674 is_volatile = resolved_field->IsVolatile();
Ian Rogersc8b306f2012-02-17 21:34:44 -0800675 stats_->ResolvedStaticField();
Ian Rogers1bddec32012-02-04 12:27:34 -0800676 return true;
677 }
678 }
679 }
680 }
681 }
682 }
683 // Clean up any exception left by field/type resolution
684 Thread* thread = Thread::Current();
685 if (thread->IsExceptionPending()) {
686 thread->ClearException();
687 }
Ian Rogersc8b306f2012-02-17 21:34:44 -0800688 stats_->UnresolvedStaticField();
Ian Rogers1bddec32012-02-04 12:27:34 -0800689 return false; // Incomplete knowledge needs slow path.
690}
691
Ian Rogers2ed3b952012-03-17 11:49:39 -0700692void Compiler::GetCodeAndMethodForDirectCall(InvokeType type, InvokeType sharp_type, Method* method,
693 uintptr_t& direct_code, uintptr_t& direct_method) {
694 direct_code = 0;
695 direct_method = 0;
696 if (sharp_type != kStatic && sharp_type != kDirect) {
697 return;
698 }
Ian Rogers2ed3b952012-03-17 11:49:39 -0700699 bool method_code_in_boot = method->GetDeclaringClass()->GetClassLoader() == NULL;
700 if (!method_code_in_boot) {
701 return;
702 }
703 bool has_clinit_trampoline = method->IsStatic() && !method->GetDeclaringClass()->IsInitialized();
704 if (has_clinit_trampoline) {
705 return;
706 }
707 stats_->DirectCallsToBoot(type);
708 stats_->DirectMethodsToBoot(type);
Ian Rogers3fa13792012-03-18 15:53:45 -0700709 bool compiling_boot = Runtime::Current()->GetHeap()->GetSpaces().size() == 1;
710 if (compiling_boot) {
711 const bool kSupportBootImageFixup = false;
712 if (kSupportBootImageFixup) {
713 MethodHelper mh(method);
714 if (IsImageClass(mh.GetDeclaringClassDescriptor())) {
715 direct_method = -1;
716 }
717 direct_code = -1;
718 }
719 } else {
720 if (Runtime::Current()->GetHeap()->GetImageSpace()->Contains(method)) {
721 direct_method = reinterpret_cast<uintptr_t>(method);
722 }
723 direct_code = reinterpret_cast<uintptr_t>(method->GetCode());
Ian Rogers2ed3b952012-03-17 11:49:39 -0700724 }
Ian Rogers2ed3b952012-03-17 11:49:39 -0700725}
726
Ian Rogersfb6adba2012-03-04 21:51:51 -0800727bool Compiler::ComputeInvokeInfo(uint32_t method_idx, OatCompilationUnit* mUnit, InvokeType& type,
Ian Rogers2ed3b952012-03-17 11:49:39 -0700728 int& vtable_idx, uintptr_t& direct_code,
729 uintptr_t& direct_method) {
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800730 vtable_idx = -1;
Ian Rogers2ed3b952012-03-17 11:49:39 -0700731 direct_code = 0;
732 direct_method = 0;
Logan Chien4dd96f52012-02-29 01:26:58 +0800733 Method* resolved_method = ComputeReferrerMethod(mUnit, method_idx);
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800734 if (resolved_method != NULL) {
Logan Chien4dd96f52012-02-29 01:26:58 +0800735 Class* referrer_class = ComputeReferrerClass(mUnit);
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800736 if (referrer_class != NULL) {
737 Class* methods_class = resolved_method->GetDeclaringClass();
738 if (!referrer_class->CanAccess(methods_class) ||
739 !referrer_class->CanAccessMember(methods_class,
Ian Rogers996cc582012-02-14 22:23:29 -0800740 resolved_method->GetAccessFlags())) {
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800741 // The referring class can't access the resolved method, this may occur as a result of a
742 // protected method being made public by implementing an interface that re-declares the
743 // method public. Resort to the dex file to determine the correct class for the access check
Logan Chien4dd96f52012-02-29 01:26:58 +0800744 const DexFile& dex_file = mUnit->class_linker_->FindDexFile(referrer_class->GetDexCache());
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800745 methods_class =
Logan Chien4dd96f52012-02-29 01:26:58 +0800746 mUnit->class_linker_->ResolveType(dex_file,
747 dex_file.GetMethodId(method_idx).class_idx_,
748 referrer_class);
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800749
750 }
751 if (referrer_class->CanAccess(methods_class) &&
752 referrer_class->CanAccessMember(methods_class,
753 resolved_method->GetAccessFlags())) {
754 vtable_idx = resolved_method->GetMethodIndex();
Ian Rogersf320b632012-03-13 18:47:47 -0700755 const bool kEnableSharpening = true;
Ian Rogers2ed3b952012-03-17 11:49:39 -0700756 // Sharpen a virtual call into a direct call when the target is known.
757 bool can_sharpen = type == kVirtual && (resolved_method->IsFinal() ||
758 methods_class->IsFinal());
759 // ensure the vtable index will be correct to dispatch in the vtable of the super class
760 can_sharpen = can_sharpen || (type == kSuper &&
761 referrer_class->IsSubClass(methods_class) &&
762 vtable_idx < methods_class->GetVTable()->GetLength());
763 if (kEnableSharpening && can_sharpen) {
764 stats_->ResolvedMethod(type);
Ian Rogersfb6adba2012-03-04 21:51:51 -0800765 // Sharpen a virtual call into a direct call. The method_idx is into referrer's
766 // dex cache, check that this resolved method is where we expect it.
767 CHECK(referrer_class->GetDexCache()->GetResolvedMethod(method_idx) == resolved_method)
768 << PrettyMethod(resolved_method);
Ian Rogers2ed3b952012-03-17 11:49:39 -0700769 if (type == kSuper) {
770 CHECK(methods_class->GetVTable()->Get(vtable_idx) == resolved_method)
771 << PrettyMethod(resolved_method);
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800772 }
Ian Rogers2ed3b952012-03-17 11:49:39 -0700773 stats_->VirtualMadeDirect(type);
774 GetCodeAndMethodForDirectCall(type, kDirect, resolved_method, direct_code, direct_method);
775 type = kDirect;
776 return true;
777 } else if (type == kSuper) {
778 // Unsharpened super calls are suspicious so go slowpath.
779 } else {
780 stats_->ResolvedMethod(type);
781 GetCodeAndMethodForDirectCall(type, type, resolved_method, direct_code, direct_method);
782 return true;
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800783 }
784 }
785 }
786 }
787 // Clean up any exception left by method/type resolution
788 Thread* thread = Thread::Current();
789 if (thread->IsExceptionPending()) {
790 thread->ClearException();
791 }
Ian Rogersc8b306f2012-02-17 21:34:44 -0800792 stats_->UnresolvedMethod(type);
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800793 return false; // Incomplete knowledge needs slow path.
794}
795
Ian Rogers3fa13792012-03-18 15:53:45 -0700796void Compiler::AddCodePatch(DexCache* dex_cache, const DexFile* dex_file,
797 uint32_t referrer_method_idx, uint32_t target_method_idx,
798 size_t literal_offset) {
799 MutexLock mu(compiled_methods_lock_);
800 code_to_patch_.push_back(new PatchInformation(dex_cache, dex_file, referrer_method_idx,
801 target_method_idx, literal_offset));
802}
803void Compiler::AddMethodPatch(DexCache* dex_cache, const DexFile* dex_file,
804 uint32_t referrer_method_idx, uint32_t target_method_idx,
805 size_t literal_offset) {
806 MutexLock mu(compiled_methods_lock_);
807 methods_to_patch_.push_back(new PatchInformation(dex_cache, dex_file, referrer_method_idx,
808 target_method_idx, literal_offset));
809}
810
Brian Carlstrom5ead0952011-11-28 22:55:52 -0800811// Return true if the class should be skipped during compilation. We
812// never skip classes in the boot class loader. However, if we have a
813// non-boot class loader and we can resolve the class in the boot
814// class loader, we do skip the class. This happens if an app bundles
815// classes found in the boot classpath. Since at runtime we will
816// select the class from the boot classpath, do not attempt to resolve
817// or compile it now.
818static bool SkipClass(const ClassLoader* class_loader,
819 const DexFile& dex_file,
820 const DexFile::ClassDef& class_def) {
821 if (class_loader == NULL) {
822 return false;
823 }
824 const char* descriptor = dex_file.GetClassDescriptor(class_def);
825 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
826 Class* klass = class_linker->FindClass(descriptor, NULL);
827 if (klass == NULL) {
828 Thread* self = Thread::Current();
829 CHECK(self->IsExceptionPending());
830 self->ClearException();
831 return false;
832 }
833 return true;
834}
835
Brian Carlstrom731b2ab2012-03-06 16:53:35 -0800836class Context {
837 public:
838 Context(ClassLinker* class_linker,
839 const ClassLoader* class_loader,
840 Compiler* compiler,
841 DexCache* dex_cache,
842 const DexFile* dex_file)
843 : class_linker_(class_linker),
844 class_loader_(class_loader),
845 compiler_(compiler),
846 dex_cache_(dex_cache),
847 dex_file_(dex_file) {}
848
849 ClassLinker* GetClassLinker() {
850 CHECK(class_linker_ != NULL);
851 return class_linker_;
852 }
853 const ClassLoader* GetClassLoader() {
854 return class_loader_;
855 }
856 Compiler* GetCompiler() {
857 CHECK(compiler_ != NULL);
858 return compiler_;
859 }
860 DexCache* GetDexCache() {
861 CHECK(dex_cache_ != NULL);
862 return dex_cache_;
863 }
864 const DexFile* GetDexFile() {
865 CHECK(dex_file_ != NULL);
866 return dex_file_;
867 }
868
869 private:
870 ClassLinker* class_linker_;
871 const ClassLoader* class_loader_;
872 Compiler* compiler_;
873 DexCache* dex_cache_;
874 const DexFile* dex_file_;
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800875};
876
877typedef void Callback(Context* context, size_t index);
878
879class WorkerThread {
880 public:
Elliott Hughes1e409252012-02-06 11:21:27 -0800881 WorkerThread(Context* context, size_t begin, size_t end, Callback callback, size_t stripe, bool spawn)
882 : spawn_(spawn), context_(context), begin_(begin), end_(end), callback_(callback), stripe_(stripe) {
883 if (spawn_) {
884 CHECK_PTHREAD_CALL(pthread_create, (&pthread_, NULL, &Go, this), "compiler worker thread");
885 }
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800886 }
887
888 ~WorkerThread() {
Elliott Hughes1e409252012-02-06 11:21:27 -0800889 if (spawn_) {
890 CHECK_PTHREAD_CALL(pthread_join, (pthread_, NULL), "compiler worker shutdown");
891 }
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800892 }
893
894 private:
Elliott Hughes1e409252012-02-06 11:21:27 -0800895 static void* Go(void* arg) {
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800896 WorkerThread* worker = reinterpret_cast<WorkerThread*>(arg);
897 Runtime* runtime = Runtime::Current();
Elliott Hughes1e409252012-02-06 11:21:27 -0800898 if (worker->spawn_) {
899 runtime->AttachCurrentThread("Compiler Worker", true);
900 }
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800901 Thread::Current()->SetState(Thread::kRunnable);
902 worker->Run();
Elliott Hughes1e409252012-02-06 11:21:27 -0800903 if (worker->spawn_) {
904 Thread::Current()->SetState(Thread::kNative);
905 runtime->DetachCurrentThread();
906 }
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800907 return NULL;
908 }
909
Elliott Hughes1e409252012-02-06 11:21:27 -0800910 void Go() {
911 Go(this);
912 }
913
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800914 void Run() {
915 for (size_t i = begin_; i < end_; i += stripe_) {
916 callback_(context_, i);
917 }
918 }
919
920 pthread_t pthread_;
Elliott Hughes1e409252012-02-06 11:21:27 -0800921 bool spawn_;
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800922
923 Context* context_;
924 size_t begin_;
925 size_t end_;
926 Callback* callback_;
927 size_t stripe_;
Elliott Hughes1e409252012-02-06 11:21:27 -0800928
929 friend void ForAll(Context*, size_t, size_t, Callback, size_t);
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800930};
931
Elliott Hughes5523ee02012-02-03 18:18:34 -0800932void ForAll(Context* context, size_t begin, size_t end, Callback callback, size_t thread_count) {
Elliott Hughes1e409252012-02-06 11:21:27 -0800933 CHECK_GT(thread_count, 0U);
Elliott Hughes81d91512012-02-03 16:38:43 -0800934
Elliott Hughes1e409252012-02-06 11:21:27 -0800935 std::vector<WorkerThread*> threads;
Elliott Hughes81d91512012-02-03 16:38:43 -0800936 for (size_t i = 0; i < thread_count; ++i) {
Elliott Hughes1e409252012-02-06 11:21:27 -0800937 threads.push_back(new WorkerThread(context, begin + i, end, callback, thread_count, (i != 0)));
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800938 }
Elliott Hughes1e409252012-02-06 11:21:27 -0800939 threads[0]->Go();
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800940
Elliott Hughes81d91512012-02-03 16:38:43 -0800941 // Switch to kVmWait while we're blocked waiting for the other threads to finish.
942 ScopedThreadStateChange tsc(Thread::Current(), Thread::kVmWait);
943 STLDeleteElements(&threads);
944}
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800945
946static void ResolveClassFieldsAndMethods(Context* context, size_t class_def_index) {
Brian Carlstrom731b2ab2012-03-06 16:53:35 -0800947 const DexFile& dex_file = *context->GetDexFile();
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800948
949 // Method and Field are the worst. We can't resolve without either
950 // context from the code use (to disambiguate virtual vs direct
951 // method and instance vs static field) or from class
952 // definitions. While the compiler will resolve what it can as it
953 // needs it, here we try to resolve fields and methods used in class
954 // definitions, since many of them many never be referenced by
955 // generated code.
956 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
Brian Carlstrom731b2ab2012-03-06 16:53:35 -0800957 if (SkipClass(context->GetClassLoader(), dex_file, class_def)) {
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800958 return;
959 }
960
961 // Note the class_data pointer advances through the headers,
962 // static fields, instance fields, direct methods, and virtual
963 // methods.
964 const byte* class_data = dex_file.GetClassData(class_def);
965 if (class_data == NULL) {
966 // empty class such as a marker interface
967 return;
968 }
Brian Carlstrom5ead0952011-11-28 22:55:52 -0800969 Thread* self = Thread::Current();
Brian Carlstrom731b2ab2012-03-06 16:53:35 -0800970 ClassLinker* class_linker = context->GetClassLinker();
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800971 DexCache* dex_cache = class_linker->FindDexCache(dex_file);
972 ClassDataItemIterator it(dex_file, class_data);
973 while (it.HasNextStaticField()) {
974 Field* field = class_linker->ResolveField(dex_file, it.GetMemberIndex(), dex_cache,
Brian Carlstrom731b2ab2012-03-06 16:53:35 -0800975 context->GetClassLoader(), true);
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800976 if (field == NULL) {
977 CHECK(self->IsExceptionPending());
978 self->ClearException();
979 }
980 it.Next();
981 }
982 while (it.HasNextInstanceField()) {
983 Field* field = class_linker->ResolveField(dex_file, it.GetMemberIndex(), dex_cache,
Brian Carlstrom731b2ab2012-03-06 16:53:35 -0800984 context->GetClassLoader(), false);
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800985 if (field == NULL) {
986 CHECK(self->IsExceptionPending());
987 self->ClearException();
988 }
989 it.Next();
990 }
991 while (it.HasNextDirectMethod()) {
992 Method* method = class_linker->ResolveMethod(dex_file, it.GetMemberIndex(), dex_cache,
Brian Carlstrom731b2ab2012-03-06 16:53:35 -0800993 context->GetClassLoader(), true);
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800994 if (method == NULL) {
995 CHECK(self->IsExceptionPending());
996 self->ClearException();
997 }
998 it.Next();
999 }
1000 while (it.HasNextVirtualMethod()) {
1001 Method* method = class_linker->ResolveMethod(dex_file, it.GetMemberIndex(), dex_cache,
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001002 context->GetClassLoader(), false);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001003 if (method == NULL) {
1004 CHECK(self->IsExceptionPending());
1005 self->ClearException();
1006 }
1007 it.Next();
1008 }
1009 DCHECK(!it.HasNext());
1010}
1011
1012static void ResolveType(Context* context, size_t type_idx) {
1013 // Class derived values are more complicated, they require the linker and loader.
1014 Thread* self = Thread::Current();
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001015 Class* klass = context->GetClassLinker()->ResolveType(*context->GetDexFile(),
1016 type_idx,
1017 context->GetDexCache(),
1018 context->GetClassLoader());
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001019 if (klass == NULL) {
1020 CHECK(self->IsExceptionPending());
1021 Thread::Current()->ClearException();
1022 }
1023}
1024
1025void Compiler::ResolveDexFile(const ClassLoader* class_loader, const DexFile& dex_file, TimingLogger& timings) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001026 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Brian Carlstromaded5f72011-10-07 17:15:04 -07001027 DexCache* dex_cache = class_linker->FindDexCache(dex_file);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001028
Brian Carlstromae826982011-11-09 01:33:42 -08001029 // Strings are easy in that they always are simply resolved to literals in the same file
1030 if (image_ && image_classes_ == NULL) {
1031 // TODO: Add support for loading strings referenced by image_classes_
1032 // See also Compiler::CanAssumeTypeIsPresentInDexCache.
Brian Carlstromaded5f72011-10-07 17:15:04 -07001033 for (size_t string_idx = 0; string_idx < dex_cache->NumStrings(); string_idx++) {
1034 class_linker->ResolveString(dex_file, string_idx, dex_cache);
1035 }
Elliott Hughesff738062012-02-03 15:00:42 -08001036 timings.AddSplit("Resolve " + dex_file.GetLocation() + " Strings");
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001037 }
1038
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001039 Context context(class_linker, class_loader, this, dex_cache, &dex_file);
Elliott Hughes5523ee02012-02-03 18:18:34 -08001040 ForAll(&context, 0, dex_cache->NumResolvedTypes(), ResolveType, thread_count_);
Elliott Hughesff738062012-02-03 15:00:42 -08001041 timings.AddSplit("Resolve " + dex_file.GetLocation() + " Types");
Brian Carlstrom845490b2011-09-19 15:56:53 -07001042
Elliott Hughes5523ee02012-02-03 18:18:34 -08001043 ForAll(&context, 0, dex_file.NumClassDefs(), ResolveClassFieldsAndMethods, thread_count_);
Elliott Hughesff738062012-02-03 15:00:42 -08001044 timings.AddSplit("Resolve " + dex_file.GetLocation() + " MethodsAndFields");
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001045}
1046
Brian Carlstromae826982011-11-09 01:33:42 -08001047void Compiler::Verify(const ClassLoader* class_loader,
1048 const std::vector<const DexFile*>& dex_files) {
1049 for (size_t i = 0; i != dex_files.size(); ++i) {
1050 const DexFile* dex_file = dex_files[i];
jeffhao98eacac2011-09-14 16:11:53 -07001051 CHECK(dex_file != NULL);
1052 VerifyDexFile(class_loader, *dex_file);
1053 }
1054}
1055
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001056static void VerifyClass(Context* context, size_t class_def_index) {
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001057 const DexFile::ClassDef& class_def = context->GetDexFile()->GetClassDef(class_def_index);
1058 const char* descriptor = context->GetDexFile()->GetClassDescriptor(class_def);
1059 Class* klass = context->GetClassLinker()->FindClass(descriptor, context->GetClassLoader());
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001060 if (klass == NULL) {
1061 Thread* self = Thread::Current();
1062 CHECK(self->IsExceptionPending());
1063 self->ClearException();
jeffhaof56197c2012-03-05 18:01:54 -08001064
1065 /*
1066 * At compile time, we can still structurally verify the class even if FindClass fails.
1067 * This is to ensure the class is structurally sound for compilation. An unsound class
1068 * will be rejected by the verifier and later skipped during compilation in the compiler.
1069 */
1070 std::string error_msg;
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001071 if (!verifier::DexVerifier::VerifyClass(context->GetDexFile(), context->GetDexCache(),
1072 context->GetClassLoader(), class_def_index, error_msg)) {
1073 const DexFile::ClassDef& class_def = context->GetDexFile()->GetClassDef(class_def_index);
jeffhaof56197c2012-03-05 18:01:54 -08001074 LOG(ERROR) << "Verification failed on class "
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001075 << PrettyDescriptor(context->GetDexFile()->GetClassDescriptor(class_def))
jeffhaof56197c2012-03-05 18:01:54 -08001076 << " because: " << error_msg;
1077 }
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001078 return;
1079 }
1080 CHECK(klass->IsResolved()) << PrettyClass(klass);
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001081 context->GetClassLinker()->VerifyClass(klass);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001082
1083 if (klass->IsErroneous()) {
1084 // ClassLinker::VerifyClass throws, which isn't useful in the compiler.
1085 CHECK(Thread::Current()->IsExceptionPending());
1086 Thread::Current()->ClearException();
1087 // We want to try verification again at run-time, so move back into the resolved state.
1088 klass->SetStatus(Class::kStatusResolved);
1089 }
1090
1091 CHECK(klass->IsVerified() || klass->IsResolved()) << PrettyClass(klass);
1092 CHECK(!Thread::Current()->IsExceptionPending()) << PrettyTypeOf(Thread::Current()->GetException());
1093}
1094
jeffhao98eacac2011-09-14 16:11:53 -07001095void Compiler::VerifyDexFile(const ClassLoader* class_loader, const DexFile& dex_file) {
jeffhaob4df5142011-09-19 20:25:32 -07001096 dex_file.ChangePermissions(PROT_READ | PROT_WRITE);
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07001097
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001098 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1099 Context context(class_linker, class_loader, this, class_linker->FindDexCache(dex_file), &dex_file);
Elliott Hughes5523ee02012-02-03 18:18:34 -08001100 ForAll(&context, 0, dex_file.NumClassDefs(), VerifyClass, thread_count_);
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07001101
jeffhaob4df5142011-09-19 20:25:32 -07001102 dex_file.ChangePermissions(PROT_READ);
Brian Carlstroma5a97a22011-09-15 14:08:49 -07001103}
1104
Brian Carlstromae826982011-11-09 01:33:42 -08001105void Compiler::InitializeClassesWithoutClinit(const ClassLoader* class_loader,
1106 const std::vector<const DexFile*>& dex_files) {
1107 for (size_t i = 0; i != dex_files.size(); ++i) {
1108 const DexFile* dex_file = dex_files[i];
Brian Carlstroma5a97a22011-09-15 14:08:49 -07001109 CHECK(dex_file != NULL);
1110 InitializeClassesWithoutClinit(class_loader, *dex_file);
1111 }
1112}
1113
1114void Compiler::InitializeClassesWithoutClinit(const ClassLoader* class_loader, const DexFile& dex_file) {
1115 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Brian Carlstromffca45d2011-09-16 12:10:49 -07001116 for (size_t class_def_index = 0; class_def_index < dex_file.NumClassDefs(); class_def_index++) {
1117 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
Brian Carlstroma5a97a22011-09-15 14:08:49 -07001118 const char* descriptor = dex_file.GetClassDescriptor(class_def);
1119 Class* klass = class_linker->FindClass(descriptor, class_loader);
Brian Carlstrom27ec9612011-09-19 20:20:38 -07001120 if (klass != NULL) {
1121 class_linker->EnsureInitialized(klass, false);
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001122 // record the final class status if necessary
1123 Class::Status status = klass->GetStatus();
1124 ClassReference ref(&dex_file, class_def_index);
Elliott Hughesc225caa2012-02-03 15:43:37 -08001125 MutexLock mu(compiled_classes_lock_);
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001126 CompiledClass* compiled_class = GetCompiledClass(ref);
1127 if (compiled_class == NULL) {
1128 compiled_class = new CompiledClass(status);
1129 compiled_classes_[ref] = compiled_class;
1130 } else {
1131 DCHECK_EQ(status, compiled_class->GetStatus());
1132 }
Brian Carlstrom27ec9612011-09-19 20:20:38 -07001133 }
1134 // clear any class not found or verification exceptions
1135 Thread::Current()->ClearException();
Brian Carlstromffca45d2011-09-16 12:10:49 -07001136 }
1137
1138 DexCache* dex_cache = class_linker->FindDexCache(dex_file);
1139 for (size_t type_idx = 0; type_idx < dex_cache->NumResolvedTypes(); type_idx++) {
1140 Class* klass = class_linker->ResolveType(dex_file, type_idx, dex_cache, class_loader);
Brian Carlstrom27ec9612011-09-19 20:20:38 -07001141 if (klass == NULL) {
1142 Thread::Current()->ClearException();
1143 } else if (klass->IsInitialized()) {
Brian Carlstromffca45d2011-09-16 12:10:49 -07001144 dex_cache->GetInitializedStaticStorage()->Set(type_idx, klass);
1145 }
jeffhao98eacac2011-09-14 16:11:53 -07001146 }
1147}
1148
Brian Carlstromae826982011-11-09 01:33:42 -08001149void Compiler::Compile(const ClassLoader* class_loader,
1150 const std::vector<const DexFile*>& dex_files) {
1151 for (size_t i = 0; i != dex_files.size(); ++i) {
1152 const DexFile* dex_file = dex_files[i];
Brian Carlstrom83db7722011-08-26 17:32:56 -07001153 CHECK(dex_file != NULL);
1154 CompileDexFile(class_loader, *dex_file);
1155 }
1156}
1157
Elliott Hughesc225caa2012-02-03 15:43:37 -08001158void Compiler::CompileClass(Context* context, size_t class_def_index) {
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001159 const ClassLoader* class_loader = context->GetClassLoader();
1160 const DexFile& dex_file = *context->GetDexFile();
Elliott Hughesc225caa2012-02-03 15:43:37 -08001161 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
Logan Chien7f767612012-03-01 18:54:49 +08001162#if defined(ART_USE_LLVM_COMPILER)
Logan Chien7f767612012-03-01 18:54:49 +08001163 // TODO: Remove this. We should not lock the compiler_lock_ in CompileClass()
Shih-wei Liaoc4c98812012-03-10 21:55:51 -08001164 // However, without this mutex lock, we will get segmentation fault before
1165 // LLVM becomes multithreaded.
1166 Compiler* cmplr = context->GetCompiler();
1167 CompilerMutexLockFn f =
1168 FindFunction<CompilerMutexLockFn>(MakeCompilerSoName(cmplr->GetInstructionSet()),
1169 cmplr->compiler_library_,
1170 "compilerLLVMMutexLock");
1171 UniquePtr<MutexLock> GUARD((*f)(*cmplr));
Logan Chien7f767612012-03-01 18:54:49 +08001172#endif
1173
Brian Carlstrom5ead0952011-11-28 22:55:52 -08001174 if (SkipClass(class_loader, dex_file, class_def)) {
1175 return;
1176 }
jeffhaod1224c72012-02-29 13:43:08 -08001177 ClassReference ref(&dex_file, class_def_index);
1178 // Skip compiling classes with generic verifier failures since they will still fail at runtime
1179 if (verifier::DexVerifier::IsClassRejected(ref)) {
1180 return;
1181 }
Ian Rogers0571d352011-11-03 19:51:38 -07001182 const byte* class_data = dex_file.GetClassData(class_def);
1183 if (class_data == NULL) {
1184 // empty class, probably a marker interface
1185 return;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001186 }
Ian Rogers0571d352011-11-03 19:51:38 -07001187 ClassDataItemIterator it(dex_file, class_data);
1188 // Skip fields
1189 while (it.HasNextStaticField()) {
1190 it.Next();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001191 }
Ian Rogers0571d352011-11-03 19:51:38 -07001192 while (it.HasNextInstanceField()) {
1193 it.Next();
1194 }
1195 // Compile direct methods
1196 while (it.HasNextDirectMethod()) {
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001197 context->GetCompiler()->CompileMethod(it.GetMethodCodeItem(), it.GetMemberAccessFlags(),
1198 it.GetMemberIndex(), class_loader, dex_file);
Ian Rogers0571d352011-11-03 19:51:38 -07001199 it.Next();
1200 }
1201 // Compile virtual methods
1202 while (it.HasNextVirtualMethod()) {
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001203 context->GetCompiler()->CompileMethod(it.GetMethodCodeItem(), it.GetMemberAccessFlags(),
1204 it.GetMemberIndex(), class_loader, dex_file);
Ian Rogers0571d352011-11-03 19:51:38 -07001205 it.Next();
1206 }
1207 DCHECK(!it.HasNext());
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001208}
1209
Elliott Hughesc225caa2012-02-03 15:43:37 -08001210void Compiler::CompileDexFile(const ClassLoader* class_loader, const DexFile& dex_file) {
Brian Carlstrom731b2ab2012-03-06 16:53:35 -08001211 Context context(NULL, class_loader, this, NULL, &dex_file);
Elliott Hughes5523ee02012-02-03 18:18:34 -08001212 ForAll(&context, 0, dex_file.NumClassDefs(), Compiler::CompileClass, thread_count_);
Elliott Hughesc225caa2012-02-03 15:43:37 -08001213}
1214
Ian Rogersa3760aa2011-11-14 14:32:37 -08001215void Compiler::CompileMethod(const DexFile::CodeItem* code_item, uint32_t access_flags,
1216 uint32_t method_idx, const ClassLoader* class_loader,
1217 const DexFile& dex_file) {
Elliott Hughesf09afe82011-10-16 14:24:21 -07001218 CompiledMethod* compiled_method = NULL;
Elliott Hughesbb551fa2012-01-25 16:35:29 -08001219 uint64_t start_ns = NanoTime();
Logan Chien4dd96f52012-02-29 01:26:58 +08001220
Ian Rogers169c9a72011-11-13 20:13:17 -08001221 if ((access_flags & kAccNative) != 0) {
Elliott Hughes46f060a2012-03-09 17:36:50 -08001222 compiled_method = (*jni_compiler_)(*this, access_flags, method_idx, class_loader, dex_file);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07001223 CHECK(compiled_method != NULL);
Ian Rogers169c9a72011-11-13 20:13:17 -08001224 } else if ((access_flags & kAccAbstract) != 0) {
Brian Carlstrom2cc022b2011-08-25 10:05:39 -07001225 } else {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001226 compiled_method = (*compiler_)(*this, code_item, access_flags, method_idx, class_loader,
1227 dex_file);
Elliott Hughesbb551fa2012-01-25 16:35:29 -08001228 CHECK(compiled_method != NULL) << PrettyMethod(method_idx, dex_file);
1229 }
Ian Rogers3bb17a62012-01-27 23:56:44 -08001230 uint64_t duration_ns = NanoTime() - start_ns;
buzbee5abfa3e2012-01-31 17:01:43 -08001231 if (duration_ns > MsToNs(100)) {
Elliott Hughesbb551fa2012-01-25 16:35:29 -08001232 LOG(WARNING) << "Compilation of " << PrettyMethod(method_idx, dex_file)
Ian Rogers3bb17a62012-01-27 23:56:44 -08001233 << " took " << PrettyDuration(duration_ns);
Elliott Hughesf09afe82011-10-16 14:24:21 -07001234 }
1235
1236 if (compiled_method != NULL) {
Ian Rogers0571d352011-11-03 19:51:38 -07001237 MethodReference ref(&dex_file, method_idx);
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001238 CHECK(GetCompiledMethod(ref) == NULL) << PrettyMethod(method_idx, dex_file);
Elliott Hughesc225caa2012-02-03 15:43:37 -08001239 MutexLock mu(compiled_methods_lock_);
Ian Rogers0571d352011-11-03 19:51:38 -07001240 compiled_methods_[ref] = compiled_method;
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001241 DCHECK(GetCompiledMethod(ref) != NULL) << PrettyMethod(method_idx, dex_file);
Brian Carlstrom2cc022b2011-08-25 10:05:39 -07001242 }
Brian Carlstrom9baa4ae2011-09-01 21:14:14 -07001243
Ian Rogers45619fc2012-02-29 11:15:25 -08001244 uint32_t shorty_len;
1245 const char* shorty = dex_file.GetMethodShorty(dex_file.GetMethodId(method_idx), &shorty_len);
Ian Rogers169c9a72011-11-13 20:13:17 -08001246 bool is_static = (access_flags & kAccStatic) != 0;
Ian Rogers0571d352011-11-03 19:51:38 -07001247 const CompiledInvokeStub* compiled_invoke_stub = FindInvokeStub(is_static, shorty);
1248 if (compiled_invoke_stub == NULL) {
Shih-wei Liaoc4c98812012-03-10 21:55:51 -08001249 compiled_invoke_stub = (*create_invoke_stub_)(*this, is_static, shorty, shorty_len);
Ian Rogers0571d352011-11-03 19:51:38 -07001250 CHECK(compiled_invoke_stub != NULL);
1251 InsertInvokeStub(is_static, shorty, compiled_invoke_stub);
Ian Rogers2c8f6532011-09-02 17:16:34 -07001252 }
Ian Rogers0571d352011-11-03 19:51:38 -07001253 CHECK(!Thread::Current()->IsExceptionPending()) << PrettyMethod(method_idx, dex_file);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07001254}
1255
Ian Rogers0571d352011-11-03 19:51:38 -07001256static std::string MakeInvokeStubKey(bool is_static, const char* shorty) {
1257 std::string key(shorty);
1258 if (is_static) {
Elliott Hughesbb551fa2012-01-25 16:35:29 -08001259 key += "$"; // Must not be a shorty type character.
Brian Carlstrom3320cf42011-10-04 14:58:28 -07001260 }
Ian Rogers0571d352011-11-03 19:51:38 -07001261 return key;
Brian Carlstrom3320cf42011-10-04 14:58:28 -07001262}
1263
Ian Rogers0571d352011-11-03 19:51:38 -07001264const CompiledInvokeStub* Compiler::FindInvokeStub(bool is_static, const char* shorty) const {
Elliott Hughesc225caa2012-02-03 15:43:37 -08001265 MutexLock mu(compiled_invoke_stubs_lock_);
Elliott Hughes95572412011-12-13 18:14:20 -08001266 const std::string key(MakeInvokeStubKey(is_static, shorty));
Ian Rogers0571d352011-11-03 19:51:38 -07001267 InvokeStubTable::const_iterator it = compiled_invoke_stubs_.find(key);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07001268 if (it == compiled_invoke_stubs_.end()) {
1269 return NULL;
Ian Rogers0571d352011-11-03 19:51:38 -07001270 } else {
1271 DCHECK(it->second != NULL);
1272 return it->second;
1273 }
1274}
1275
1276void Compiler::InsertInvokeStub(bool is_static, const char* shorty,
1277 const CompiledInvokeStub* compiled_invoke_stub) {
Elliott Hughesc225caa2012-02-03 15:43:37 -08001278 MutexLock mu(compiled_invoke_stubs_lock_);
Elliott Hughes95572412011-12-13 18:14:20 -08001279 std::string key(MakeInvokeStubKey(is_static, shorty));
Ian Rogers0571d352011-11-03 19:51:38 -07001280 compiled_invoke_stubs_[key] = compiled_invoke_stub;
1281}
1282
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001283CompiledClass* Compiler::GetCompiledClass(ClassReference ref) const {
Elliott Hughesc225caa2012-02-03 15:43:37 -08001284 MutexLock mu(compiled_classes_lock_);
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001285 ClassTable::const_iterator it = compiled_classes_.find(ref);
1286 if (it == compiled_classes_.end()) {
1287 return NULL;
1288 }
1289 CHECK(it->second != NULL);
1290 return it->second;
1291}
1292
Ian Rogers0571d352011-11-03 19:51:38 -07001293CompiledMethod* Compiler::GetCompiledMethod(MethodReference ref) const {
Elliott Hughesc225caa2012-02-03 15:43:37 -08001294 MutexLock mu(compiled_methods_lock_);
Ian Rogers0571d352011-11-03 19:51:38 -07001295 MethodTable::const_iterator it = compiled_methods_.find(ref);
1296 if (it == compiled_methods_.end()) {
1297 return NULL;
Brian Carlstrom3320cf42011-10-04 14:58:28 -07001298 }
1299 CHECK(it->second != NULL);
1300 return it->second;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001301}
1302
Brian Carlstrome7d856b2012-01-11 18:10:55 -08001303void Compiler::SetGcMaps(const ClassLoader* class_loader, const std::vector<const DexFile*>& dex_files) {
1304 for (size_t i = 0; i != dex_files.size(); ++i) {
1305 const DexFile* dex_file = dex_files[i];
1306 CHECK(dex_file != NULL);
1307 SetGcMapsDexFile(class_loader, *dex_file);
1308 }
1309}
1310
1311void Compiler::SetGcMapsDexFile(const ClassLoader* class_loader, const DexFile& dex_file) {
1312 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1313 DexCache* dex_cache = class_linker->FindDexCache(dex_file);
1314 for (size_t class_def_index = 0; class_def_index < dex_file.NumClassDefs(); class_def_index++) {
1315 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
1316 const char* descriptor = dex_file.GetClassDescriptor(class_def);
1317 Class* klass = class_linker->FindClass(descriptor, class_loader);
1318 if (klass == NULL || !klass->IsVerified()) {
1319 Thread::Current()->ClearException();
1320 continue;
1321 }
1322 const byte* class_data = dex_file.GetClassData(class_def);
1323 if (class_data == NULL) {
1324 // empty class such as a marker interface
1325 continue;
1326 }
1327 ClassDataItemIterator it(dex_file, class_data);
1328 while (it.HasNextStaticField()) {
1329 it.Next();
1330 }
1331 while (it.HasNextInstanceField()) {
1332 it.Next();
1333 }
1334 while (it.HasNextDirectMethod()) {
1335 Method* method = class_linker->ResolveMethod(dex_file, it.GetMemberIndex(), dex_cache,
1336 class_loader, true);
1337 SetGcMapsMethod(dex_file, method);
1338 it.Next();
1339 }
1340 while (it.HasNextVirtualMethod()) {
1341 Method* method = class_linker->ResolveMethod(dex_file, it.GetMemberIndex(), dex_cache,
1342 class_loader, false);
1343 SetGcMapsMethod(dex_file, method);
1344 it.Next();
1345 }
1346 }
1347}
1348
1349void Compiler::SetGcMapsMethod(const DexFile& dex_file, Method* method) {
1350 if (method == NULL) {
1351 Thread::Current()->ClearException();
1352 return;
1353 }
1354 uint16_t method_idx = method->GetDexMethodIndex();
1355 MethodReference ref(&dex_file, method_idx);
1356 CompiledMethod* compiled_method = GetCompiledMethod(ref);
1357 if (compiled_method == NULL) {
1358 return;
1359 }
1360 const std::vector<uint8_t>* gc_map = verifier::DexVerifier::GetGcMap(ref);
1361 if (gc_map == NULL) {
1362 return;
1363 }
1364 compiled_method->SetGcMap(*gc_map);
1365}
1366
Logan Chien8b977d32012-02-21 19:14:55 +08001367#if defined(ART_USE_LLVM_COMPILER)
1368void Compiler::SetElfFileName(std::string const& filename) {
Shih-wei Liaoc4c98812012-03-10 21:55:51 -08001369 elf_filename_ = filename;
Logan Chien8b977d32012-02-21 19:14:55 +08001370}
1371
1372void Compiler::SetBitcodeFileName(std::string const& filename) {
Shih-wei Liaoc4c98812012-03-10 21:55:51 -08001373 bitcode_filename_ = filename;
1374}
1375std::string const& Compiler::GetElfFileName() {
1376 return elf_filename_;
1377}
1378std::string const& Compiler::GetBitcodeFileName() {
1379 return bitcode_filename_;
Logan Chien8b977d32012-02-21 19:14:55 +08001380}
1381#endif
1382
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001383} // namespace art