blob: 35108bb69842e479facd18de991cc7d84ef3d2ea [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
Brian Carlstrom27ec9612011-09-19 20:20:38 -070021#include <sys/mman.h>
Elliott Hughesd9c67be2012-02-02 19:54:06 -080022#include <unistd.h>
Brian Carlstrom27ec9612011-09-19 20:20:38 -070023
Brian Carlstrom2cc022b2011-08-25 10:05:39 -070024#include "assembler.h"
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -070025#include "class_linker.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -070026#include "class_loader.h"
Ian Rogers1bddec32012-02-04 12:27:34 -080027#include "compiler/CompilerIR.h"
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -070028#include "dex_cache.h"
Brian Carlstrom2cc022b2011-08-25 10:05:39 -070029#include "jni_compiler.h"
Brian Carlstrom9baa4ae2011-09-01 21:14:14 -070030#include "jni_internal.h"
Brian Carlstrom3320cf42011-10-04 14:58:28 -070031#include "oat_file.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080032#include "object_utils.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -070033#include "runtime.h"
Brian Carlstrom3320cf42011-10-04 14:58:28 -070034#include "stl_util.h"
Elliott Hughes601a1232012-02-02 17:47:38 -080035#include "timing_logger.h"
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -070036
Shih-wei Liaod1fec812012-02-13 09:51:10 -080037#if defined(ART_USE_LLVM_COMPILER)
38#include "compiler_llvm/compiler_llvm.h"
39#endif
40
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -070041namespace art {
42
Shih-wei Liaod1fec812012-02-13 09:51:10 -080043#if !defined(ART_USE_LLVM_COMPILER)
Ian Rogers996cc582012-02-14 22:23:29 -080044CompiledMethod* oatCompileMethod(Compiler& compiler, const DexFile::CodeItem* code_item,
Elliott Hughes11d1b0c2012-01-23 16:57:47 -080045 uint32_t access_flags, uint32_t method_idx,
46 const ClassLoader* class_loader,
47 const DexFile& dex_file, InstructionSet);
Shih-wei Liaod1fec812012-02-13 09:51:10 -080048#endif
Elliott Hughes11d1b0c2012-01-23 16:57:47 -080049
Shih-wei Liaoc486c112011-09-13 16:43:52 -070050namespace arm {
Ian Rogersbdb03912011-09-14 00:55:44 -070051 ByteArray* CreateAbstractMethodErrorStub();
Ian Rogers0571d352011-11-03 19:51:38 -070052 CompiledInvokeStub* ArmCreateInvokeStub(bool is_static, const char* shorty);
Ian Rogers1cb0a1d2011-10-06 15:24:35 -070053 ByteArray* ArmCreateResolutionTrampoline(Runtime::TrampolineType type);
Elliott Hughes8add92d2012-01-18 18:18:43 -080054 ByteArray* CreateJniDlsymLookupStub();
Shih-wei Liaoc486c112011-09-13 16:43:52 -070055}
Shih-wei Liaoc486c112011-09-13 16:43:52 -070056namespace x86 {
Ian Rogersbdb03912011-09-14 00:55:44 -070057 ByteArray* CreateAbstractMethodErrorStub();
Ian Rogers0571d352011-11-03 19:51:38 -070058 CompiledInvokeStub* X86CreateInvokeStub(bool is_static, const char* shorty);
Ian Rogers1cb0a1d2011-10-06 15:24:35 -070059 ByteArray* X86CreateResolutionTrampoline(Runtime::TrampolineType type);
Elliott Hughes8add92d2012-01-18 18:18:43 -080060 ByteArray* CreateJniDlsymLookupStub();
Brian Carlstrome24fa612011-09-29 00:53:55 -070061}
62
Ian Rogers996cc582012-02-14 22:23:29 -080063static double Percentage(size_t x, size_t y) {
64 return 100.0 * ((double)x) / ((double)(x + y));
65}
66
67static void DumpStat(size_t x, size_t y, const char* str) {
68 if (x == 0 && y == 0) {
69 return;
70 }
71 LOG(INFO) << Percentage(x, y) << "% of " << str << " for " << (x + y) << " cases";
72}
73
74void AOTCompilationStats::Dump() {
75 DumpStat(types_in_dex_cache_, types_not_in_dex_cache_, "types known to be in dex cache");
76 DumpStat(strings_in_dex_cache_, strings_not_in_dex_cache_, "strings known to be in dex cache");
77 DumpStat(resolved_types_, unresolved_types_, "types resolved");
78 DumpStat(resolved_instance_fields_, unresolved_instance_fields_, "instance fields resolved");
79 DumpStat(resolved_local_static_fields_ + resolved_static_fields_, unresolved_static_fields_,
80 "static fields resolved");
81 DumpStat(resolved_local_static_fields_, resolved_static_fields_ + unresolved_static_fields_,
82 "static fields local to a class");
83 DumpStat(resolved_virtual_methods_, unresolved_virtual_methods_, "resolved virtual methods");
84 DumpStat(resolved_super_methods_, unresolved_super_methods_, "resolved super-class methods");
85 DumpStat(resolved_interface_methods_, unresolved_interface_methods_, "resolved interface methods");
86}
87
88// Allow lossy statistics in non-debug builds
89#ifndef NDEBUG
90#define STATS_LOCK() MutexLock mu(stats_lock_)
91#else
92#define STATS_LOCK()
93#endif
94
95void AOTCompilationStats::TypeInDexCache() {
96 STATS_LOCK();
97 types_in_dex_cache_++;
98}
99
100void AOTCompilationStats::TypeNotInDexCache() {
101 STATS_LOCK();
102 types_not_in_dex_cache_++;
103}
104
105void AOTCompilationStats::StringInDexCache() {
106 STATS_LOCK();
107 strings_in_dex_cache_++;
108}
109
110void AOTCompilationStats::StringNotInDexCache() {
111 STATS_LOCK();
112 strings_not_in_dex_cache_++;
113}
114
115void AOTCompilationStats::TypeDoesntNeedAccessCheck() {
116 STATS_LOCK();
117 resolved_types_++;
118}
119
120void AOTCompilationStats::TypeNeedsAccessCheck() {
121 STATS_LOCK();
122 unresolved_types_++;
123}
124
125void AOTCompilationStats::ResolvedInstanceField() {
126 STATS_LOCK();
127 resolved_instance_fields_++;
128}
129
130void AOTCompilationStats::UnresolvedInstanceField(){
131 STATS_LOCK();
132 unresolved_instance_fields_++;
133}
134
135void AOTCompilationStats::ResolvedLocalStaticField() {
136 STATS_LOCK();
137 resolved_local_static_fields_++;
138}
139
140void AOTCompilationStats::ResolvedStaticField() {
141 STATS_LOCK();
142 resolved_static_fields_++;
143}
144
145void AOTCompilationStats::UnresolvedStaticField() {
146 STATS_LOCK();
147 unresolved_static_fields_++;
148}
149
150void AOTCompilationStats::ResolvedMethod(bool is_interface, bool is_super) {
151 STATS_LOCK();
152 if (is_interface) {
153 resolved_interface_methods_++;
154 } else if (is_super) {
155 resolved_super_methods_++;
156 } else {
157 resolved_virtual_methods_++;
158 }
159}
160
161void AOTCompilationStats::UnresolvedMethod(bool is_interface, bool is_super) {
162 STATS_LOCK();
163 if (is_interface) {
164 unresolved_interface_methods_++;
165 } else if (is_super) {
166 unresolved_super_methods_++;
167 } else {
168 unresolved_virtual_methods_++;
169 }
170}
171
Elliott Hughes5523ee02012-02-03 18:18:34 -0800172Compiler::Compiler(InstructionSet instruction_set, bool image, size_t thread_count,
Brian Carlstromae826982011-11-09 01:33:42 -0800173 const std::set<std::string>* image_classes)
Brian Carlstromaded5f72011-10-07 17:15:04 -0700174 : instruction_set_(instruction_set),
175 jni_compiler_(instruction_set),
Elliott Hughesc225caa2012-02-03 15:43:37 -0800176 compiled_classes_lock_("compiled classes lock"),
177 compiled_methods_lock_("compiled method lock"),
178 compiled_invoke_stubs_lock_("compiled invoke stubs lock"),
Brian Carlstromaded5f72011-10-07 17:15:04 -0700179 image_(image),
Elliott Hughes5523ee02012-02-03 18:18:34 -0800180 thread_count_(thread_count),
Shih-wei Liaod1fec812012-02-13 09:51:10 -0800181 image_classes_(image_classes)
182#if defined(ART_USE_LLVM_COMPILER)
183 ,
184 compiler_llvm_(new compiler_llvm::CompilerLLVM(this, instruction_set))
185#endif
186 {
Brian Carlstrom25c33252011-09-18 15:58:35 -0700187 CHECK(!Runtime::Current()->IsStarted());
Brian Carlstromae826982011-11-09 01:33:42 -0800188 if (!image_) {
189 CHECK(image_classes_ == NULL);
190 }
Shih-wei Liaoc486c112011-09-13 16:43:52 -0700191}
192
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700193Compiler::~Compiler() {
Elliott Hughesc225caa2012-02-03 15:43:37 -0800194 {
195 MutexLock mu(compiled_classes_lock_);
196 STLDeleteValues(&compiled_classes_);
197 }
198 {
199 MutexLock mu(compiled_methods_lock_);
200 STLDeleteValues(&compiled_methods_);
201 }
202 {
203 MutexLock mu(compiled_invoke_stubs_lock_);
204 STLDeleteValues(&compiled_invoke_stubs_);
Elliott Hughesbb551fa2012-01-25 16:35:29 -0800205 }
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700206}
207
Ian Rogers1cb0a1d2011-10-06 15:24:35 -0700208ByteArray* Compiler::CreateResolutionStub(InstructionSet instruction_set,
209 Runtime::TrampolineType type) {
Ian Rogersad25ac52011-10-04 19:13:33 -0700210 if (instruction_set == kX86) {
Ian Rogers1cb0a1d2011-10-06 15:24:35 -0700211 return x86::X86CreateResolutionTrampoline(type);
Ian Rogersad25ac52011-10-04 19:13:33 -0700212 } else {
213 CHECK(instruction_set == kArm || instruction_set == kThumb2);
214 // Generates resolution stub using ARM instruction set
Ian Rogers1cb0a1d2011-10-06 15:24:35 -0700215 return arm::ArmCreateResolutionTrampoline(type);
Ian Rogersad25ac52011-10-04 19:13:33 -0700216 }
217}
218
Elliott Hughes8add92d2012-01-18 18:18:43 -0800219ByteArray* Compiler::CreateJniDlsymLookupStub(InstructionSet instruction_set) {
Ian Rogers169c9a72011-11-13 20:13:17 -0800220 switch (instruction_set) {
221 case kArm:
222 case kThumb2:
Elliott Hughes8add92d2012-01-18 18:18:43 -0800223 return arm::CreateJniDlsymLookupStub();
Ian Rogers169c9a72011-11-13 20:13:17 -0800224 case kX86:
Elliott Hughes8add92d2012-01-18 18:18:43 -0800225 return x86::CreateJniDlsymLookupStub();
Ian Rogers169c9a72011-11-13 20:13:17 -0800226 default:
Elliott Hughesba8eee12012-01-24 20:25:24 -0800227 LOG(FATAL) << "Unknown InstructionSet: " << static_cast<int>(instruction_set);
Ian Rogers169c9a72011-11-13 20:13:17 -0800228 return NULL;
229 }
230}
231
Ian Rogersad25ac52011-10-04 19:13:33 -0700232ByteArray* Compiler::CreateAbstractMethodErrorStub(InstructionSet instruction_set) {
233 if (instruction_set == kX86) {
234 return x86::CreateAbstractMethodErrorStub();
235 } else {
236 CHECK(instruction_set == kArm || instruction_set == kThumb2);
237 // Generates resolution stub using ARM instruction set
238 return arm::CreateAbstractMethodErrorStub();
239 }
240}
241
Jesse Wilson254db0f2011-11-16 16:44:11 -0500242void Compiler::CompileAll(const ClassLoader* class_loader,
Brian Carlstromae826982011-11-09 01:33:42 -0800243 const std::vector<const DexFile*>& dex_files) {
Brian Carlstrom25c33252011-09-18 15:58:35 -0700244 DCHECK(!Runtime::Current()->IsStarted());
Brian Carlstromae826982011-11-09 01:33:42 -0800245
Elliott Hughes601a1232012-02-02 17:47:38 -0800246 TimingLogger timings("compiler");
247
248 PreCompile(class_loader, dex_files, timings);
249
Brian Carlstromae826982011-11-09 01:33:42 -0800250 Compile(class_loader, dex_files);
Elliott Hughes601a1232012-02-02 17:47:38 -0800251 timings.AddSplit("Compile");
252
Brian Carlstromae826982011-11-09 01:33:42 -0800253 PostCompile(class_loader, dex_files);
Elliott Hughes601a1232012-02-02 17:47:38 -0800254 timings.AddSplit("PostCompile");
255
256 if (timings.GetTotalNs() > MsToNs(1000)) {
257 timings.Dump();
258 }
Ian Rogers996cc582012-02-14 22:23:29 -0800259
260 stats_.Dump();
Brian Carlstrom8a487412011-08-29 20:08:52 -0700261}
262
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700263void Compiler::CompileOne(const Method* method) {
Brian Carlstrom25c33252011-09-18 15:58:35 -0700264 DCHECK(!Runtime::Current()->IsStarted());
Brian Carlstromae826982011-11-09 01:33:42 -0800265
Brian Carlstrom8a487412011-08-29 20:08:52 -0700266 const ClassLoader* class_loader = method->GetDeclaringClass()->GetClassLoader();
Brian Carlstromae826982011-11-09 01:33:42 -0800267
Ian Rogers0571d352011-11-03 19:51:38 -0700268 // Find the dex_file
269 const DexCache* dex_cache = method->GetDeclaringClass()->GetDexCache();
270 const DexFile& dex_file = Runtime::Current()->GetClassLinker()->FindDexFile(dex_cache);
Brian Carlstromae826982011-11-09 01:33:42 -0800271 std::vector<const DexFile*> dex_files;
272 dex_files.push_back(&dex_file);
273
Elliott Hughes601a1232012-02-02 17:47:38 -0800274 TimingLogger timings("CompileOne");
275 PreCompile(class_loader, dex_files, timings);
Brian Carlstromae826982011-11-09 01:33:42 -0800276
Ian Rogers0571d352011-11-03 19:51:38 -0700277 uint32_t method_idx = method->GetDexMethodIndex();
Ian Rogersa3760aa2011-11-14 14:32:37 -0800278 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(method->GetCodeItemOffset());
279 CompileMethod(code_item, method->GetAccessFlags(), method_idx, class_loader, dex_file);
Brian Carlstromae826982011-11-09 01:33:42 -0800280
281 PostCompile(class_loader, dex_files);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700282}
283
Brian Carlstromae826982011-11-09 01:33:42 -0800284void Compiler::Resolve(const ClassLoader* class_loader,
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800285 const std::vector<const DexFile*>& dex_files, TimingLogger& timings) {
Brian Carlstromae826982011-11-09 01:33:42 -0800286 for (size_t i = 0; i != dex_files.size(); ++i) {
287 const DexFile* dex_file = dex_files[i];
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700288 CHECK(dex_file != NULL);
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800289 ResolveDexFile(class_loader, *dex_file, timings);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700290 }
291}
292
Brian Carlstromae826982011-11-09 01:33:42 -0800293void Compiler::PreCompile(const ClassLoader* class_loader,
Elliott Hughes601a1232012-02-02 17:47:38 -0800294 const std::vector<const DexFile*>& dex_files, TimingLogger& timings) {
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800295 Resolve(class_loader, dex_files, timings);
Elliott Hughes601a1232012-02-02 17:47:38 -0800296
Brian Carlstromae826982011-11-09 01:33:42 -0800297 Verify(class_loader, dex_files);
Elliott Hughes601a1232012-02-02 17:47:38 -0800298 timings.AddSplit("PreCompile.Verify");
299
Brian Carlstromae826982011-11-09 01:33:42 -0800300 InitializeClassesWithoutClinit(class_loader, dex_files);
Elliott Hughes601a1232012-02-02 17:47:38 -0800301 timings.AddSplit("PreCompile.InitializeClassesWithoutClinit");
Brian Carlstromae826982011-11-09 01:33:42 -0800302}
303
304void Compiler::PostCompile(const ClassLoader* class_loader,
305 const std::vector<const DexFile*>& dex_files) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -0800306 SetGcMaps(class_loader, dex_files);
Shih-wei Liaod1fec812012-02-13 09:51:10 -0800307#if defined(ART_USE_LLVM_COMPILER)
308 compiler_llvm_->MaterializeLLVMModule();
309#endif
Brian Carlstromae826982011-11-09 01:33:42 -0800310 SetCodeAndDirectMethods(dex_files);
311}
312
313bool Compiler::IsImageClass(const std::string& descriptor) const {
314 if (image_classes_ == NULL) {
315 return true;
316 }
317 return image_classes_->find(descriptor) != image_classes_->end();
318}
319
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800320bool Compiler::CanAssumeTypeIsPresentInDexCache(const DexCache* dex_cache,
Ian Rogers996cc582012-02-14 22:23:29 -0800321 uint32_t type_idx) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800322 if (!IsImage()) {
Ian Rogers996cc582012-02-14 22:23:29 -0800323 stats_.TypeNotInDexCache();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800324 return false;
325 }
Ian Rogers1bddec32012-02-04 12:27:34 -0800326 Class* resolved_class = dex_cache->GetResolvedType(type_idx);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800327 if (resolved_class == NULL) {
Ian Rogers996cc582012-02-14 22:23:29 -0800328 stats_.TypeNotInDexCache();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800329 return false;
330 }
Ian Rogers996cc582012-02-14 22:23:29 -0800331 bool result = IsImageClass(ClassHelper(resolved_class).GetDescriptor());
332 if (result) {
333 stats_.TypeInDexCache();
334 } else {
335 stats_.TypeNotInDexCache();
336 }
337 return result;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800338}
339
Ian Rogers1bddec32012-02-04 12:27:34 -0800340bool Compiler::CanAssumeStringIsPresentInDexCache(const DexCache* dex_cache,
Ian Rogers996cc582012-02-14 22:23:29 -0800341 uint32_t string_idx) {
Ian Rogers1bddec32012-02-04 12:27:34 -0800342 // TODO: Add support for loading strings referenced by image_classes_
343 // See also Compiler::ResolveDexFile
344
345 // The following is a test saying that if we're building the image without a restricted set of
346 // 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 -0800347 bool result = IsImage() && image_classes_ == NULL && dex_cache->GetResolvedString(string_idx) != NULL;
348 if (result) {
349 stats_.StringInDexCache();
350 } else {
351 stats_.StringNotInDexCache();
352 }
353 return result;
Ian Rogers1bddec32012-02-04 12:27:34 -0800354}
355
356bool Compiler::CanAccessTypeWithoutChecks(uint32_t referrer_idx, const DexCache* dex_cache,
Ian Rogers996cc582012-02-14 22:23:29 -0800357 const DexFile& dex_file, uint32_t type_idx) {
Ian Rogers1bddec32012-02-04 12:27:34 -0800358 // Get type from dex cache assuming it was populated by the verifier
359 Class* resolved_class = dex_cache->GetResolvedType(type_idx);
360 if (resolved_class == NULL) {
Ian Rogers996cc582012-02-14 22:23:29 -0800361 stats_.TypeNeedsAccessCheck();
Ian Rogers1bddec32012-02-04 12:27:34 -0800362 return false; // Unknown class needs access checks.
363 }
364 const DexFile::MethodId& method_id = dex_file.GetMethodId(referrer_idx);
365 Class* referrer_class = dex_cache->GetResolvedType(method_id.class_idx_);
366 if (referrer_class == NULL) {
Ian Rogers996cc582012-02-14 22:23:29 -0800367 stats_.TypeNeedsAccessCheck();
Ian Rogers1bddec32012-02-04 12:27:34 -0800368 return false; // Incomplete referrer knowledge needs access check.
369 }
370 // Perform access check, will return true if access is ok or false if we're going to have to
371 // check this at runtime (for example for class loaders).
Ian Rogers996cc582012-02-14 22:23:29 -0800372 bool result = referrer_class->CanAccess(resolved_class);
373 if (result) {
374 stats_.TypeDoesntNeedAccessCheck();
375 } else {
376 stats_.TypeNeedsAccessCheck();
377 }
378 return result;
Ian Rogers1bddec32012-02-04 12:27:34 -0800379}
380
381bool Compiler::CanAccessInstantiableTypeWithoutChecks(uint32_t referrer_idx,
382 const DexCache* dex_cache,
383 const DexFile& dex_file,
Ian Rogers996cc582012-02-14 22:23:29 -0800384 uint32_t type_idx) {
Ian Rogers1bddec32012-02-04 12:27:34 -0800385 // Get type from dex cache assuming it was populated by the verifier.
386 Class* resolved_class = dex_cache->GetResolvedType(type_idx);
387 if (resolved_class == NULL) {
Ian Rogers996cc582012-02-14 22:23:29 -0800388 stats_.TypeNeedsAccessCheck();
Ian Rogers1bddec32012-02-04 12:27:34 -0800389 return false; // Unknown class needs access checks.
390 }
391 const DexFile::MethodId& method_id = dex_file.GetMethodId(referrer_idx);
392 Class* referrer_class = dex_cache->GetResolvedType(method_id.class_idx_);
393 if (referrer_class == NULL) {
Ian Rogers996cc582012-02-14 22:23:29 -0800394 stats_.TypeNeedsAccessCheck();
Ian Rogers1bddec32012-02-04 12:27:34 -0800395 return false; // Incomplete referrer knowledge needs access check.
396 }
397 // Perform access and instantiable checks, will return true if access is ok or false if we're
398 // going to have to check this at runtime (for example for class loaders).
Ian Rogers996cc582012-02-14 22:23:29 -0800399 bool result = referrer_class->CanAccess(resolved_class) && resolved_class->IsInstantiable();
400 if (result) {
401 stats_.TypeDoesntNeedAccessCheck();
402 } else {
403 stats_.TypeNeedsAccessCheck();
404 }
405 return result;
Ian Rogers1bddec32012-02-04 12:27:34 -0800406}
407
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800408static Class* ComputeReferrerClass(CompilationUnit* cUnit) {
409 const DexFile::MethodId& referrer_method_id = cUnit->dex_file->GetMethodId(cUnit->method_idx);
410 return cUnit->class_linker->ResolveType(*cUnit->dex_file, referrer_method_id.class_idx_,
411 cUnit->dex_cache, cUnit->class_loader);
412}
413
414static Field* ComputeReferrerField(CompilationUnit* cUnit, uint32_t field_idx) {
415 return cUnit->class_linker->ResolveField(*cUnit->dex_file, field_idx, cUnit->dex_cache,
416 cUnit->class_loader, false);
417
418}
419
420static Method* ComputeReferrerMethod(CompilationUnit* cUnit, uint32_t method_idx) {
421 return cUnit->class_linker->ResolveMethod(*cUnit->dex_file, method_idx, cUnit->dex_cache,
422 cUnit->class_loader, true);
423}
424
Ian Rogers1bddec32012-02-04 12:27:34 -0800425bool Compiler::ComputeInstanceFieldInfo(uint32_t field_idx, CompilationUnit* cUnit,
Ian Rogers996cc582012-02-14 22:23:29 -0800426 int& field_offset, bool& is_volatile) {
Ian Rogers1bddec32012-02-04 12:27:34 -0800427 // Conservative defaults
428 field_offset = -1;
429 is_volatile = true;
430 // Try to resolve field
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800431 Field* resolved_field = ComputeReferrerField(cUnit, field_idx);
Ian Rogers1bddec32012-02-04 12:27:34 -0800432 if (resolved_field != NULL) {
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800433 Class* referrer_class = ComputeReferrerClass(cUnit);
Ian Rogers1bddec32012-02-04 12:27:34 -0800434 // Try to resolve referring class then access check, failure to pass the
435 Class* fields_class = resolved_field->GetDeclaringClass();
436 if (referrer_class != NULL &&
437 referrer_class->CanAccess(fields_class) &&
438 referrer_class->CanAccessMember(fields_class,
439 resolved_field->GetAccessFlags())) {
440 field_offset = resolved_field->GetOffset().Int32Value();
441 is_volatile = resolved_field->IsVolatile();
Ian Rogers996cc582012-02-14 22:23:29 -0800442 stats_.ResolvedInstanceField();
Ian Rogers1bddec32012-02-04 12:27:34 -0800443 return true; // Fast path.
444 }
445 }
446 // Clean up any exception left by field/type resolution
447 Thread* thread = Thread::Current();
448 if (thread->IsExceptionPending()) {
449 thread->ClearException();
450 }
Ian Rogers996cc582012-02-14 22:23:29 -0800451 stats_.UnresolvedInstanceField();
Ian Rogers1bddec32012-02-04 12:27:34 -0800452 return false; // Incomplete knowledge needs slow path.
453}
454
455bool Compiler::ComputeStaticFieldInfo(uint32_t field_idx, CompilationUnit* cUnit,
456 int& field_offset, int& ssb_index,
Ian Rogers996cc582012-02-14 22:23:29 -0800457 bool& is_referrers_class, bool& is_volatile) {
Ian Rogers1bddec32012-02-04 12:27:34 -0800458 // Conservative defaults
459 field_offset = -1;
460 ssb_index = -1;
461 is_referrers_class = false;
462 is_volatile = true;
463 // Try to resolve field
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800464 Field* resolved_field = ComputeReferrerField(cUnit, field_idx);
Ian Rogers1bddec32012-02-04 12:27:34 -0800465 if (resolved_field != NULL) {
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800466 DCHECK(resolved_field->IsStatic());
467 Class* referrer_class = ComputeReferrerClass(cUnit);
Ian Rogers1bddec32012-02-04 12:27:34 -0800468 if (referrer_class != NULL) {
469 if (resolved_field->GetDeclaringClass() == referrer_class) {
470 is_referrers_class = true; // implies no worrying about class initialization
471 field_offset = resolved_field->GetOffset().Int32Value();
472 is_volatile = resolved_field->IsVolatile();
Ian Rogers996cc582012-02-14 22:23:29 -0800473 stats_.ResolvedLocalStaticField();
Ian Rogers1bddec32012-02-04 12:27:34 -0800474 return true; // fast path
475 } else {
476 Class* fields_class = resolved_field->GetDeclaringClass();
477 if (referrer_class->CanAccess(fields_class) &&
478 referrer_class->CanAccessMember(fields_class,
479 resolved_field->GetAccessFlags())) {
480 // We have the resolved field, we must make it into a ssbIndex for the referrer
481 // in its static storage base (which may fail if it doesn't have a slot for it)
Ian Rogers4103ad22012-02-06 09:18:25 -0800482 // TODO: for images we can elide the static storage base null check
483 // if we know there's a non-null entry in the image
484 if (fields_class->GetDexCache() == cUnit->dex_cache) {
485 // common case where the dex cache of both the referrer and the field are the same,
486 // no need to search the dex file
487 ssb_index = fields_class->GetDexTypeIndex();
488 field_offset = resolved_field->GetOffset().Int32Value();
489 is_volatile = resolved_field->IsVolatile();
Ian Rogers996cc582012-02-14 22:23:29 -0800490 stats_.ResolvedStaticField();
Ian Rogers4103ad22012-02-06 09:18:25 -0800491 return true;
492 }
493 // Search dex file for localized ssb index
Ian Rogers1bddec32012-02-04 12:27:34 -0800494 std::string descriptor(FieldHelper(resolved_field).GetDeclaringClassDescriptor());
495 const DexFile::StringId* string_id =
496 cUnit->dex_file->FindStringId(descriptor);
497 if (string_id != NULL) {
498 const DexFile::TypeId* type_id =
499 cUnit->dex_file->FindTypeId(cUnit->dex_file->GetIndexForStringId(*string_id));
500 if(type_id != NULL) {
501 // medium path, needs check of static storage base being initialized
Ian Rogers1bddec32012-02-04 12:27:34 -0800502 ssb_index = cUnit->dex_file->GetIndexForTypeId(*type_id);
503 field_offset = resolved_field->GetOffset().Int32Value();
504 is_volatile = resolved_field->IsVolatile();
Ian Rogers996cc582012-02-14 22:23:29 -0800505 stats_.ResolvedStaticField();
Ian Rogers1bddec32012-02-04 12:27:34 -0800506 return true;
507 }
508 }
509 }
510 }
511 }
512 }
513 // Clean up any exception left by field/type resolution
514 Thread* thread = Thread::Current();
515 if (thread->IsExceptionPending()) {
516 thread->ClearException();
517 }
Ian Rogers996cc582012-02-14 22:23:29 -0800518 stats_.UnresolvedStaticField();
Ian Rogers1bddec32012-02-04 12:27:34 -0800519 return false; // Incomplete knowledge needs slow path.
520}
521
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800522bool Compiler::ComputeInvokeInfo(uint32_t method_idx, CompilationUnit* cUnit,
523 bool is_interface, bool is_super,
Ian Rogers996cc582012-02-14 22:23:29 -0800524 int& vtable_idx) {
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800525 vtable_idx = -1;
526 Method* resolved_method = ComputeReferrerMethod(cUnit, method_idx);
527 if (resolved_method != NULL) {
528 Class* referrer_class = ComputeReferrerClass(cUnit);
529 if (referrer_class != NULL) {
530 Class* methods_class = resolved_method->GetDeclaringClass();
531 if (!referrer_class->CanAccess(methods_class) ||
532 !referrer_class->CanAccessMember(methods_class,
Ian Rogers996cc582012-02-14 22:23:29 -0800533 resolved_method->GetAccessFlags())) {
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800534 // The referring class can't access the resolved method, this may occur as a result of a
535 // protected method being made public by implementing an interface that re-declares the
536 // method public. Resort to the dex file to determine the correct class for the access check
537 const DexFile& dex_file = cUnit->class_linker->FindDexFile(referrer_class->GetDexCache());
538 methods_class =
539 cUnit->class_linker->ResolveType(dex_file,
540 dex_file.GetMethodId(method_idx).class_idx_,
541 referrer_class);
542
543 }
544 if (referrer_class->CanAccess(methods_class) &&
545 referrer_class->CanAccessMember(methods_class,
546 resolved_method->GetAccessFlags())) {
547 vtable_idx = resolved_method->GetMethodIndex();
Ian Rogers996cc582012-02-14 22:23:29 -0800548 if (is_interface || !is_super) {
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800549 // nothing left to do for virtual/interface dispatch
Ian Rogers996cc582012-02-14 22:23:29 -0800550 stats_.ResolvedMethod(is_interface, is_super);
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800551 return true;
552 } else {
553 // ensure the vtable index will be correct to dispatch in the vtable of the super class
Ian Rogers996cc582012-02-14 22:23:29 -0800554 if (referrer_class->IsSubClass(methods_class) &&
555 vtable_idx < methods_class->GetVTable()->GetLength()) {
556 stats_.ResolvedMethod(is_interface, is_super);
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800557 return true;
558 }
559 }
560 }
561 }
562 }
563 // Clean up any exception left by method/type resolution
564 Thread* thread = Thread::Current();
565 if (thread->IsExceptionPending()) {
566 thread->ClearException();
567 }
Ian Rogers996cc582012-02-14 22:23:29 -0800568 stats_.UnresolvedMethod(is_interface, is_super);
Ian Rogersa32a6fd2012-02-06 20:18:44 -0800569 return false; // Incomplete knowledge needs slow path.
570}
571
Brian Carlstrom5ead0952011-11-28 22:55:52 -0800572// Return true if the class should be skipped during compilation. We
573// never skip classes in the boot class loader. However, if we have a
574// non-boot class loader and we can resolve the class in the boot
575// class loader, we do skip the class. This happens if an app bundles
576// classes found in the boot classpath. Since at runtime we will
577// select the class from the boot classpath, do not attempt to resolve
578// or compile it now.
579static bool SkipClass(const ClassLoader* class_loader,
580 const DexFile& dex_file,
581 const DexFile::ClassDef& class_def) {
582 if (class_loader == NULL) {
583 return false;
584 }
585 const char* descriptor = dex_file.GetClassDescriptor(class_def);
586 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
587 Class* klass = class_linker->FindClass(descriptor, NULL);
588 if (klass == NULL) {
589 Thread* self = Thread::Current();
590 CHECK(self->IsExceptionPending());
591 self->ClearException();
592 return false;
593 }
594 return true;
595}
596
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800597struct Context {
598 ClassLinker* class_linker;
599 const ClassLoader* class_loader;
Elliott Hughesc225caa2012-02-03 15:43:37 -0800600 Compiler* compiler;
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800601 DexCache* dex_cache;
602 const DexFile* dex_file;
603};
604
605typedef void Callback(Context* context, size_t index);
606
607class WorkerThread {
608 public:
Elliott Hughes1e409252012-02-06 11:21:27 -0800609 WorkerThread(Context* context, size_t begin, size_t end, Callback callback, size_t stripe, bool spawn)
610 : spawn_(spawn), context_(context), begin_(begin), end_(end), callback_(callback), stripe_(stripe) {
611 if (spawn_) {
612 CHECK_PTHREAD_CALL(pthread_create, (&pthread_, NULL, &Go, this), "compiler worker thread");
613 }
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800614 }
615
616 ~WorkerThread() {
Elliott Hughes1e409252012-02-06 11:21:27 -0800617 if (spawn_) {
618 CHECK_PTHREAD_CALL(pthread_join, (pthread_, NULL), "compiler worker shutdown");
619 }
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800620 }
621
622 private:
Elliott Hughes1e409252012-02-06 11:21:27 -0800623 static void* Go(void* arg) {
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800624 WorkerThread* worker = reinterpret_cast<WorkerThread*>(arg);
625 Runtime* runtime = Runtime::Current();
Elliott Hughes1e409252012-02-06 11:21:27 -0800626 if (worker->spawn_) {
627 runtime->AttachCurrentThread("Compiler Worker", true);
628 }
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800629 Thread::Current()->SetState(Thread::kRunnable);
630 worker->Run();
Elliott Hughes1e409252012-02-06 11:21:27 -0800631 if (worker->spawn_) {
632 Thread::Current()->SetState(Thread::kNative);
633 runtime->DetachCurrentThread();
634 }
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800635 return NULL;
636 }
637
Elliott Hughes1e409252012-02-06 11:21:27 -0800638 void Go() {
639 Go(this);
640 }
641
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800642 void Run() {
643 for (size_t i = begin_; i < end_; i += stripe_) {
644 callback_(context_, i);
645 }
646 }
647
648 pthread_t pthread_;
Elliott Hughes1e409252012-02-06 11:21:27 -0800649 bool spawn_;
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800650
651 Context* context_;
652 size_t begin_;
653 size_t end_;
654 Callback* callback_;
655 size_t stripe_;
Elliott Hughes1e409252012-02-06 11:21:27 -0800656
657 friend void ForAll(Context*, size_t, size_t, Callback, size_t);
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800658};
659
Elliott Hughes5523ee02012-02-03 18:18:34 -0800660void ForAll(Context* context, size_t begin, size_t end, Callback callback, size_t thread_count) {
Elliott Hughes1e409252012-02-06 11:21:27 -0800661 CHECK_GT(thread_count, 0U);
Elliott Hughes81d91512012-02-03 16:38:43 -0800662
Elliott Hughes1e409252012-02-06 11:21:27 -0800663 std::vector<WorkerThread*> threads;
Elliott Hughes81d91512012-02-03 16:38:43 -0800664 for (size_t i = 0; i < thread_count; ++i) {
Elliott Hughes1e409252012-02-06 11:21:27 -0800665 threads.push_back(new WorkerThread(context, begin + i, end, callback, thread_count, (i != 0)));
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800666 }
Elliott Hughes1e409252012-02-06 11:21:27 -0800667 threads[0]->Go();
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800668
Elliott Hughes81d91512012-02-03 16:38:43 -0800669 // Switch to kVmWait while we're blocked waiting for the other threads to finish.
670 ScopedThreadStateChange tsc(Thread::Current(), Thread::kVmWait);
671 STLDeleteElements(&threads);
672}
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800673
674static void ResolveClassFieldsAndMethods(Context* context, size_t class_def_index) {
675 const DexFile& dex_file = *context->dex_file;
676
677 // Method and Field are the worst. We can't resolve without either
678 // context from the code use (to disambiguate virtual vs direct
679 // method and instance vs static field) or from class
680 // definitions. While the compiler will resolve what it can as it
681 // needs it, here we try to resolve fields and methods used in class
682 // definitions, since many of them many never be referenced by
683 // generated code.
684 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
685 if (SkipClass(context->class_loader, dex_file, class_def)) {
686 return;
687 }
688
689 // Note the class_data pointer advances through the headers,
690 // static fields, instance fields, direct methods, and virtual
691 // methods.
692 const byte* class_data = dex_file.GetClassData(class_def);
693 if (class_data == NULL) {
694 // empty class such as a marker interface
695 return;
696 }
Brian Carlstrom5ead0952011-11-28 22:55:52 -0800697 Thread* self = Thread::Current();
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800698 ClassLinker* class_linker = context->class_linker;
699 DexCache* dex_cache = class_linker->FindDexCache(dex_file);
700 ClassDataItemIterator it(dex_file, class_data);
701 while (it.HasNextStaticField()) {
702 Field* field = class_linker->ResolveField(dex_file, it.GetMemberIndex(), dex_cache,
703 context->class_loader, true);
704 if (field == NULL) {
705 CHECK(self->IsExceptionPending());
706 self->ClearException();
707 }
708 it.Next();
709 }
710 while (it.HasNextInstanceField()) {
711 Field* field = class_linker->ResolveField(dex_file, it.GetMemberIndex(), dex_cache,
712 context->class_loader, false);
713 if (field == NULL) {
714 CHECK(self->IsExceptionPending());
715 self->ClearException();
716 }
717 it.Next();
718 }
719 while (it.HasNextDirectMethod()) {
720 Method* method = class_linker->ResolveMethod(dex_file, it.GetMemberIndex(), dex_cache,
721 context->class_loader, true);
722 if (method == NULL) {
723 CHECK(self->IsExceptionPending());
724 self->ClearException();
725 }
726 it.Next();
727 }
728 while (it.HasNextVirtualMethod()) {
729 Method* method = class_linker->ResolveMethod(dex_file, it.GetMemberIndex(), dex_cache,
730 context->class_loader, false);
731 if (method == NULL) {
732 CHECK(self->IsExceptionPending());
733 self->ClearException();
734 }
735 it.Next();
736 }
737 DCHECK(!it.HasNext());
738}
739
740static void ResolveType(Context* context, size_t type_idx) {
741 // Class derived values are more complicated, they require the linker and loader.
742 Thread* self = Thread::Current();
743 ClassLinker* class_linker = context->class_linker;
744 const DexFile& dex_file = *context->dex_file;
745 Class* klass = class_linker->ResolveType(dex_file, type_idx, context->dex_cache, context->class_loader);
746 if (klass == NULL) {
747 CHECK(self->IsExceptionPending());
748 Thread::Current()->ClearException();
749 }
750}
751
752void Compiler::ResolveDexFile(const ClassLoader* class_loader, const DexFile& dex_file, TimingLogger& timings) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700753 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Brian Carlstromaded5f72011-10-07 17:15:04 -0700754 DexCache* dex_cache = class_linker->FindDexCache(dex_file);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700755
Brian Carlstromae826982011-11-09 01:33:42 -0800756 // Strings are easy in that they always are simply resolved to literals in the same file
757 if (image_ && image_classes_ == NULL) {
758 // TODO: Add support for loading strings referenced by image_classes_
759 // See also Compiler::CanAssumeTypeIsPresentInDexCache.
Brian Carlstromaded5f72011-10-07 17:15:04 -0700760 for (size_t string_idx = 0; string_idx < dex_cache->NumStrings(); string_idx++) {
761 class_linker->ResolveString(dex_file, string_idx, dex_cache);
762 }
Elliott Hughesff738062012-02-03 15:00:42 -0800763 timings.AddSplit("Resolve " + dex_file.GetLocation() + " Strings");
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700764 }
765
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800766 Context context;
767 context.class_linker = class_linker;
768 context.class_loader = class_loader;
769 context.dex_cache = dex_cache;
770 context.dex_file = &dex_file;
771
Elliott Hughes5523ee02012-02-03 18:18:34 -0800772 ForAll(&context, 0, dex_cache->NumResolvedTypes(), ResolveType, thread_count_);
Elliott Hughesff738062012-02-03 15:00:42 -0800773 timings.AddSplit("Resolve " + dex_file.GetLocation() + " Types");
Brian Carlstrom845490b2011-09-19 15:56:53 -0700774
Elliott Hughes5523ee02012-02-03 18:18:34 -0800775 ForAll(&context, 0, dex_file.NumClassDefs(), ResolveClassFieldsAndMethods, thread_count_);
Elliott Hughesff738062012-02-03 15:00:42 -0800776 timings.AddSplit("Resolve " + dex_file.GetLocation() + " MethodsAndFields");
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700777}
778
Brian Carlstromae826982011-11-09 01:33:42 -0800779void Compiler::Verify(const ClassLoader* class_loader,
780 const std::vector<const DexFile*>& dex_files) {
781 for (size_t i = 0; i != dex_files.size(); ++i) {
782 const DexFile* dex_file = dex_files[i];
jeffhao98eacac2011-09-14 16:11:53 -0700783 CHECK(dex_file != NULL);
784 VerifyDexFile(class_loader, *dex_file);
785 }
786}
787
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800788static void VerifyClass(Context* context, size_t class_def_index) {
789 const DexFile::ClassDef& class_def = context->dex_file->GetClassDef(class_def_index);
790 const char* descriptor = context->dex_file->GetClassDescriptor(class_def);
791 Class* klass = context->class_linker->FindClass(descriptor, context->class_loader);
792 if (klass == NULL) {
793 Thread* self = Thread::Current();
794 CHECK(self->IsExceptionPending());
795 self->ClearException();
796 return;
797 }
798 CHECK(klass->IsResolved()) << PrettyClass(klass);
799 context->class_linker->VerifyClass(klass);
800
801 if (klass->IsErroneous()) {
802 // ClassLinker::VerifyClass throws, which isn't useful in the compiler.
803 CHECK(Thread::Current()->IsExceptionPending());
804 Thread::Current()->ClearException();
805 // We want to try verification again at run-time, so move back into the resolved state.
806 klass->SetStatus(Class::kStatusResolved);
807 }
808
809 CHECK(klass->IsVerified() || klass->IsResolved()) << PrettyClass(klass);
810 CHECK(!Thread::Current()->IsExceptionPending()) << PrettyTypeOf(Thread::Current()->GetException());
811}
812
jeffhao98eacac2011-09-14 16:11:53 -0700813void Compiler::VerifyDexFile(const ClassLoader* class_loader, const DexFile& dex_file) {
jeffhaob4df5142011-09-19 20:25:32 -0700814 dex_file.ChangePermissions(PROT_READ | PROT_WRITE);
Elliott Hughesd9cdfe92011-10-06 16:09:04 -0700815
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800816 Context context;
817 context.class_linker = Runtime::Current()->GetClassLinker();
818 context.class_loader = class_loader;
819 context.dex_file = &dex_file;
Elliott Hughes5523ee02012-02-03 18:18:34 -0800820 ForAll(&context, 0, dex_file.NumClassDefs(), VerifyClass, thread_count_);
Elliott Hughesd9cdfe92011-10-06 16:09:04 -0700821
jeffhaob4df5142011-09-19 20:25:32 -0700822 dex_file.ChangePermissions(PROT_READ);
Brian Carlstroma5a97a22011-09-15 14:08:49 -0700823}
824
Brian Carlstromae826982011-11-09 01:33:42 -0800825void Compiler::InitializeClassesWithoutClinit(const ClassLoader* class_loader,
826 const std::vector<const DexFile*>& dex_files) {
827 for (size_t i = 0; i != dex_files.size(); ++i) {
828 const DexFile* dex_file = dex_files[i];
Brian Carlstroma5a97a22011-09-15 14:08:49 -0700829 CHECK(dex_file != NULL);
830 InitializeClassesWithoutClinit(class_loader, *dex_file);
831 }
832}
833
834void Compiler::InitializeClassesWithoutClinit(const ClassLoader* class_loader, const DexFile& dex_file) {
835 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Brian Carlstromffca45d2011-09-16 12:10:49 -0700836 for (size_t class_def_index = 0; class_def_index < dex_file.NumClassDefs(); class_def_index++) {
837 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
Brian Carlstroma5a97a22011-09-15 14:08:49 -0700838 const char* descriptor = dex_file.GetClassDescriptor(class_def);
839 Class* klass = class_linker->FindClass(descriptor, class_loader);
Brian Carlstrom27ec9612011-09-19 20:20:38 -0700840 if (klass != NULL) {
841 class_linker->EnsureInitialized(klass, false);
Brian Carlstrom0755ec52012-01-11 15:19:46 -0800842 // record the final class status if necessary
843 Class::Status status = klass->GetStatus();
844 ClassReference ref(&dex_file, class_def_index);
Elliott Hughesc225caa2012-02-03 15:43:37 -0800845 MutexLock mu(compiled_classes_lock_);
Brian Carlstrom0755ec52012-01-11 15:19:46 -0800846 CompiledClass* compiled_class = GetCompiledClass(ref);
847 if (compiled_class == NULL) {
848 compiled_class = new CompiledClass(status);
849 compiled_classes_[ref] = compiled_class;
850 } else {
851 DCHECK_EQ(status, compiled_class->GetStatus());
852 }
Brian Carlstrom27ec9612011-09-19 20:20:38 -0700853 }
854 // clear any class not found or verification exceptions
855 Thread::Current()->ClearException();
Brian Carlstromffca45d2011-09-16 12:10:49 -0700856 }
857
858 DexCache* dex_cache = class_linker->FindDexCache(dex_file);
859 for (size_t type_idx = 0; type_idx < dex_cache->NumResolvedTypes(); type_idx++) {
860 Class* klass = class_linker->ResolveType(dex_file, type_idx, dex_cache, class_loader);
Brian Carlstrom27ec9612011-09-19 20:20:38 -0700861 if (klass == NULL) {
862 Thread::Current()->ClearException();
863 } else if (klass->IsInitialized()) {
Brian Carlstromffca45d2011-09-16 12:10:49 -0700864 dex_cache->GetInitializedStaticStorage()->Set(type_idx, klass);
865 }
jeffhao98eacac2011-09-14 16:11:53 -0700866 }
867}
868
Brian Carlstromae826982011-11-09 01:33:42 -0800869void Compiler::Compile(const ClassLoader* class_loader,
870 const std::vector<const DexFile*>& dex_files) {
871 for (size_t i = 0; i != dex_files.size(); ++i) {
872 const DexFile* dex_file = dex_files[i];
Brian Carlstrom83db7722011-08-26 17:32:56 -0700873 CHECK(dex_file != NULL);
874 CompileDexFile(class_loader, *dex_file);
875 }
876}
877
Elliott Hughesc225caa2012-02-03 15:43:37 -0800878void Compiler::CompileClass(Context* context, size_t class_def_index) {
879 const ClassLoader* class_loader = context->class_loader;
880 const DexFile& dex_file = *context->dex_file;
881 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
Brian Carlstrom5ead0952011-11-28 22:55:52 -0800882 if (SkipClass(class_loader, dex_file, class_def)) {
883 return;
884 }
Ian Rogers0571d352011-11-03 19:51:38 -0700885 const byte* class_data = dex_file.GetClassData(class_def);
886 if (class_data == NULL) {
887 // empty class, probably a marker interface
888 return;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700889 }
Ian Rogers0571d352011-11-03 19:51:38 -0700890 ClassDataItemIterator it(dex_file, class_data);
891 // Skip fields
892 while (it.HasNextStaticField()) {
893 it.Next();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700894 }
Ian Rogers0571d352011-11-03 19:51:38 -0700895 while (it.HasNextInstanceField()) {
896 it.Next();
897 }
898 // Compile direct methods
899 while (it.HasNextDirectMethod()) {
Elliott Hughesc225caa2012-02-03 15:43:37 -0800900 context->compiler->CompileMethod(it.GetMethodCodeItem(), it.GetMemberAccessFlags(),
901 it.GetMemberIndex(), class_loader, dex_file);
Ian Rogers0571d352011-11-03 19:51:38 -0700902 it.Next();
903 }
904 // Compile virtual methods
905 while (it.HasNextVirtualMethod()) {
Elliott Hughesc225caa2012-02-03 15:43:37 -0800906 context->compiler->CompileMethod(it.GetMethodCodeItem(), it.GetMemberAccessFlags(),
907 it.GetMemberIndex(), class_loader, dex_file);
Ian Rogers0571d352011-11-03 19:51:38 -0700908 it.Next();
909 }
910 DCHECK(!it.HasNext());
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700911}
912
Elliott Hughesc225caa2012-02-03 15:43:37 -0800913void Compiler::CompileDexFile(const ClassLoader* class_loader, const DexFile& dex_file) {
914 Context context;
915 context.class_loader = class_loader;
916 context.compiler = this;
917 context.dex_file = &dex_file;
Elliott Hughes5523ee02012-02-03 18:18:34 -0800918 ForAll(&context, 0, dex_file.NumClassDefs(), Compiler::CompileClass, thread_count_);
Elliott Hughesc225caa2012-02-03 15:43:37 -0800919}
920
Ian Rogersa3760aa2011-11-14 14:32:37 -0800921void Compiler::CompileMethod(const DexFile::CodeItem* code_item, uint32_t access_flags,
922 uint32_t method_idx, const ClassLoader* class_loader,
923 const DexFile& dex_file) {
Elliott Hughesf09afe82011-10-16 14:24:21 -0700924 CompiledMethod* compiled_method = NULL;
Elliott Hughesbb551fa2012-01-25 16:35:29 -0800925 uint64_t start_ns = NanoTime();
Ian Rogers169c9a72011-11-13 20:13:17 -0800926 if ((access_flags & kAccNative) != 0) {
927 compiled_method = jni_compiler_.Compile(access_flags, method_idx, class_loader, dex_file);
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700928 CHECK(compiled_method != NULL);
Ian Rogers169c9a72011-11-13 20:13:17 -0800929 } else if ((access_flags & kAccAbstract) != 0) {
Brian Carlstrom2cc022b2011-08-25 10:05:39 -0700930 } else {
Shih-wei Liaod1fec812012-02-13 09:51:10 -0800931#if defined(ART_USE_LLVM_COMPILER)
932 compiled_method =
933 compiler_llvm_->CompileDexMethod(code_item, access_flags, method_idx,
934 class_loader, dex_file);
935#else
Ian Rogersa3760aa2011-11-14 14:32:37 -0800936 compiled_method = oatCompileMethod(*this, code_item, access_flags, method_idx, class_loader,
937 dex_file, kThumb2);
Shih-wei Liaod1fec812012-02-13 09:51:10 -0800938#endif
Elliott Hughesbb551fa2012-01-25 16:35:29 -0800939 CHECK(compiled_method != NULL) << PrettyMethod(method_idx, dex_file);
940 }
Ian Rogers3bb17a62012-01-27 23:56:44 -0800941 uint64_t duration_ns = NanoTime() - start_ns;
buzbee5abfa3e2012-01-31 17:01:43 -0800942 if (duration_ns > MsToNs(100)) {
Elliott Hughesbb551fa2012-01-25 16:35:29 -0800943 LOG(WARNING) << "Compilation of " << PrettyMethod(method_idx, dex_file)
Ian Rogers3bb17a62012-01-27 23:56:44 -0800944 << " took " << PrettyDuration(duration_ns);
Elliott Hughesf09afe82011-10-16 14:24:21 -0700945 }
946
947 if (compiled_method != NULL) {
Ian Rogers0571d352011-11-03 19:51:38 -0700948 MethodReference ref(&dex_file, method_idx);
Brian Carlstrom0755ec52012-01-11 15:19:46 -0800949 CHECK(GetCompiledMethod(ref) == NULL) << PrettyMethod(method_idx, dex_file);
Elliott Hughesc225caa2012-02-03 15:43:37 -0800950 MutexLock mu(compiled_methods_lock_);
Ian Rogers0571d352011-11-03 19:51:38 -0700951 compiled_methods_[ref] = compiled_method;
Brian Carlstrom0755ec52012-01-11 15:19:46 -0800952 DCHECK(GetCompiledMethod(ref) != NULL) << PrettyMethod(method_idx, dex_file);
Brian Carlstrom2cc022b2011-08-25 10:05:39 -0700953 }
Brian Carlstrom9baa4ae2011-09-01 21:14:14 -0700954
Ian Rogers0571d352011-11-03 19:51:38 -0700955 const char* shorty = dex_file.GetMethodShorty(dex_file.GetMethodId(method_idx));
Ian Rogers169c9a72011-11-13 20:13:17 -0800956 bool is_static = (access_flags & kAccStatic) != 0;
Ian Rogers0571d352011-11-03 19:51:38 -0700957 const CompiledInvokeStub* compiled_invoke_stub = FindInvokeStub(is_static, shorty);
958 if (compiled_invoke_stub == NULL) {
959 if (instruction_set_ == kX86) {
Elliott Hughes11d1b0c2012-01-23 16:57:47 -0800960 compiled_invoke_stub = ::art::x86::X86CreateInvokeStub(is_static, shorty);
Ian Rogers0571d352011-11-03 19:51:38 -0700961 } else {
962 CHECK(instruction_set_ == kArm || instruction_set_ == kThumb2);
963 // Generates invocation stub using ARM instruction set
Elliott Hughes11d1b0c2012-01-23 16:57:47 -0800964 compiled_invoke_stub = ::art::arm::ArmCreateInvokeStub(is_static, shorty);
Ian Rogers0571d352011-11-03 19:51:38 -0700965 }
966 CHECK(compiled_invoke_stub != NULL);
967 InsertInvokeStub(is_static, shorty, compiled_invoke_stub);
Ian Rogers2c8f6532011-09-02 17:16:34 -0700968 }
Ian Rogers0571d352011-11-03 19:51:38 -0700969 CHECK(!Thread::Current()->IsExceptionPending()) << PrettyMethod(method_idx, dex_file);
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700970}
971
Ian Rogers0571d352011-11-03 19:51:38 -0700972static std::string MakeInvokeStubKey(bool is_static, const char* shorty) {
973 std::string key(shorty);
974 if (is_static) {
Elliott Hughesbb551fa2012-01-25 16:35:29 -0800975 key += "$"; // Must not be a shorty type character.
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700976 }
Ian Rogers0571d352011-11-03 19:51:38 -0700977 return key;
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700978}
979
Ian Rogers0571d352011-11-03 19:51:38 -0700980const CompiledInvokeStub* Compiler::FindInvokeStub(bool is_static, const char* shorty) const {
Elliott Hughesc225caa2012-02-03 15:43:37 -0800981 MutexLock mu(compiled_invoke_stubs_lock_);
Elliott Hughes95572412011-12-13 18:14:20 -0800982 const std::string key(MakeInvokeStubKey(is_static, shorty));
Ian Rogers0571d352011-11-03 19:51:38 -0700983 InvokeStubTable::const_iterator it = compiled_invoke_stubs_.find(key);
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700984 if (it == compiled_invoke_stubs_.end()) {
985 return NULL;
Ian Rogers0571d352011-11-03 19:51:38 -0700986 } else {
987 DCHECK(it->second != NULL);
988 return it->second;
989 }
990}
991
992void Compiler::InsertInvokeStub(bool is_static, const char* shorty,
993 const CompiledInvokeStub* compiled_invoke_stub) {
Elliott Hughesc225caa2012-02-03 15:43:37 -0800994 MutexLock mu(compiled_invoke_stubs_lock_);
Elliott Hughes95572412011-12-13 18:14:20 -0800995 std::string key(MakeInvokeStubKey(is_static, shorty));
Ian Rogers0571d352011-11-03 19:51:38 -0700996 compiled_invoke_stubs_[key] = compiled_invoke_stub;
997}
998
Brian Carlstrom0755ec52012-01-11 15:19:46 -0800999CompiledClass* Compiler::GetCompiledClass(ClassReference ref) const {
Elliott Hughesc225caa2012-02-03 15:43:37 -08001000 MutexLock mu(compiled_classes_lock_);
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001001 ClassTable::const_iterator it = compiled_classes_.find(ref);
1002 if (it == compiled_classes_.end()) {
1003 return NULL;
1004 }
1005 CHECK(it->second != NULL);
1006 return it->second;
1007}
1008
Ian Rogers0571d352011-11-03 19:51:38 -07001009CompiledMethod* Compiler::GetCompiledMethod(MethodReference ref) const {
Elliott Hughesc225caa2012-02-03 15:43:37 -08001010 MutexLock mu(compiled_methods_lock_);
Ian Rogers0571d352011-11-03 19:51:38 -07001011 MethodTable::const_iterator it = compiled_methods_.find(ref);
1012 if (it == compiled_methods_.end()) {
1013 return NULL;
Brian Carlstrom3320cf42011-10-04 14:58:28 -07001014 }
1015 CHECK(it->second != NULL);
1016 return it->second;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001017}
1018
Brian Carlstrome7d856b2012-01-11 18:10:55 -08001019void Compiler::SetGcMaps(const ClassLoader* class_loader, const std::vector<const DexFile*>& dex_files) {
1020 for (size_t i = 0; i != dex_files.size(); ++i) {
1021 const DexFile* dex_file = dex_files[i];
1022 CHECK(dex_file != NULL);
1023 SetGcMapsDexFile(class_loader, *dex_file);
1024 }
1025}
1026
1027void Compiler::SetGcMapsDexFile(const ClassLoader* class_loader, const DexFile& dex_file) {
1028 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1029 DexCache* dex_cache = class_linker->FindDexCache(dex_file);
1030 for (size_t class_def_index = 0; class_def_index < dex_file.NumClassDefs(); class_def_index++) {
1031 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
1032 const char* descriptor = dex_file.GetClassDescriptor(class_def);
1033 Class* klass = class_linker->FindClass(descriptor, class_loader);
1034 if (klass == NULL || !klass->IsVerified()) {
1035 Thread::Current()->ClearException();
1036 continue;
1037 }
1038 const byte* class_data = dex_file.GetClassData(class_def);
1039 if (class_data == NULL) {
1040 // empty class such as a marker interface
1041 continue;
1042 }
1043 ClassDataItemIterator it(dex_file, class_data);
1044 while (it.HasNextStaticField()) {
1045 it.Next();
1046 }
1047 while (it.HasNextInstanceField()) {
1048 it.Next();
1049 }
1050 while (it.HasNextDirectMethod()) {
1051 Method* method = class_linker->ResolveMethod(dex_file, it.GetMemberIndex(), dex_cache,
1052 class_loader, true);
1053 SetGcMapsMethod(dex_file, method);
1054 it.Next();
1055 }
1056 while (it.HasNextVirtualMethod()) {
1057 Method* method = class_linker->ResolveMethod(dex_file, it.GetMemberIndex(), dex_cache,
1058 class_loader, false);
1059 SetGcMapsMethod(dex_file, method);
1060 it.Next();
1061 }
1062 }
1063}
1064
Ian Rogers1bddec32012-02-04 12:27:34 -08001065namespace verifier {
1066 class DexVerifier {
1067 public:
1068 static const std::vector<uint8_t>* GetGcMap(Compiler::MethodReference ref);
1069 };
1070}
1071
Brian Carlstrome7d856b2012-01-11 18:10:55 -08001072void Compiler::SetGcMapsMethod(const DexFile& dex_file, Method* method) {
1073 if (method == NULL) {
1074 Thread::Current()->ClearException();
1075 return;
1076 }
1077 uint16_t method_idx = method->GetDexMethodIndex();
1078 MethodReference ref(&dex_file, method_idx);
1079 CompiledMethod* compiled_method = GetCompiledMethod(ref);
1080 if (compiled_method == NULL) {
1081 return;
1082 }
1083 const std::vector<uint8_t>* gc_map = verifier::DexVerifier::GetGcMap(ref);
1084 if (gc_map == NULL) {
1085 return;
1086 }
1087 compiled_method->SetGcMap(*gc_map);
1088}
1089
Brian Carlstromae826982011-11-09 01:33:42 -08001090void Compiler::SetCodeAndDirectMethods(const std::vector<const DexFile*>& dex_files) {
1091 for (size_t i = 0; i != dex_files.size(); ++i) {
1092 const DexFile* dex_file = dex_files[i];
Brian Carlstrom83db7722011-08-26 17:32:56 -07001093 CHECK(dex_file != NULL);
Brian Carlstrom8a487412011-08-29 20:08:52 -07001094 SetCodeAndDirectMethodsDexFile(*dex_file);
Brian Carlstrom83db7722011-08-26 17:32:56 -07001095 }
1096}
1097
Brian Carlstrom8a487412011-08-29 20:08:52 -07001098void Compiler::SetCodeAndDirectMethodsDexFile(const DexFile& dex_file) {
Ian Rogersad25ac52011-10-04 19:13:33 -07001099 Runtime* runtime = Runtime::Current();
1100 ClassLinker* class_linker = runtime->GetClassLinker();
Brian Carlstrom83db7722011-08-26 17:32:56 -07001101 DexCache* dex_cache = class_linker->FindDexCache(dex_file);
Brian Carlstrom9cc262e2011-08-28 12:45:30 -07001102 CodeAndDirectMethods* code_and_direct_methods = dex_cache->GetCodeAndDirectMethods();
Brian Carlstrom1caa2c22011-08-28 13:02:33 -07001103 for (size_t i = 0; i < dex_cache->NumResolvedMethods(); i++) {
Brian Carlstrom83db7722011-08-26 17:32:56 -07001104 Method* method = dex_cache->GetResolvedMethod(i);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07001105 if (method == NULL || method->IsDirect()) {
Ian Rogers1cb0a1d2011-10-06 15:24:35 -07001106 Runtime::TrampolineType type = Runtime::GetTrampolineType(method);
1107 ByteArray* res_trampoline = runtime->GetResolutionStubArray(type);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07001108 code_and_direct_methods->SetResolvedDirectMethodTrampoline(i, res_trampoline);
Brian Carlstrom9cc262e2011-08-28 12:45:30 -07001109 } else {
1110 // TODO: we currently leave the entry blank for resolved
1111 // non-direct methods. we could put in an error stub.
Brian Carlstrom83db7722011-08-26 17:32:56 -07001112 }
1113 }
1114}
1115
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001116} // namespace art