blob: 7fadfc905e16030655a2ec8ecd81d96785a9550c [file] [log] [blame]
Brian Carlstrom7940e442013-07-12 13:46:57 -07001/*
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 */
16
17#include "compiler_driver.h"
18
Anwar Ghuloum67f99412013-08-12 14:19:48 -070019#define ATRACE_TAG ATRACE_TAG_DALVIK
20#include <utils/Trace.h>
Brian Carlstrom7940e442013-07-12 13:46:57 -070021
Calin Juravlef6a4cee2014-04-02 17:03:08 +010022#include <fstream>
Anwar Ghuloum67f99412013-08-12 14:19:48 -070023#include <vector>
Brian Carlstrom7940e442013-07-12 13:46:57 -070024#include <unistd.h>
Calin Juravlef6a4cee2014-04-02 17:03:08 +010025#include <utility>
Brian Carlstrom7940e442013-07-12 13:46:57 -070026
27#include "base/stl_util.h"
28#include "base/timing_logger.h"
29#include "class_linker.h"
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +000030#include "compiler.h"
Vladimir Markobe0e5462014-02-26 11:24:15 +000031#include "compiler_driver-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070032#include "dex_compilation_unit.h"
33#include "dex_file-inl.h"
Vladimir Markoc7f83202014-01-24 17:55:18 +000034#include "dex/verification_results.h"
Vladimir Marko2730db02014-01-27 11:15:17 +000035#include "dex/verified_method.h"
Vladimir Marko2bc47802014-02-10 09:43:07 +000036#include "dex/quick/dex_file_method_inliner.h"
Mark Mendellae9fd932014-02-10 16:14:35 -080037#include "driver/compiler_options.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070038#include "jni_internal.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070039#include "object_utils.h"
40#include "runtime.h"
41#include "gc/accounting/card_table-inl.h"
42#include "gc/accounting/heap_bitmap.h"
43#include "gc/space/space.h"
Brian Carlstromea46f952013-07-30 01:26:50 -070044#include "mirror/art_field-inl.h"
45#include "mirror/art_method-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070046#include "mirror/class_loader.h"
47#include "mirror/class-inl.h"
48#include "mirror/dex_cache-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070049#include "mirror/object-inl.h"
50#include "mirror/object_array-inl.h"
51#include "mirror/throwable.h"
52#include "scoped_thread_state_change.h"
53#include "ScopedLocalRef.h"
Mathieu Chartierc645f1d2014-03-06 18:11:53 -080054#include "sirt_ref-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070055#include "thread.h"
56#include "thread_pool.h"
Ian Rogers848871b2013-08-05 10:56:33 -070057#include "trampolines/trampoline_compiler.h"
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +010058#include "transaction.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070059#include "verifier/method_verifier.h"
Vladimir Marko2bc47802014-02-10 09:43:07 +000060#include "verifier/method_verifier-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070061
Calin Juravle04ff2262014-04-02 19:08:47 +010062#ifdef HAVE_ANDROID_OS
63#include "cutils/properties.h"
64#endif
65
Brian Carlstrom7940e442013-07-12 13:46:57 -070066namespace art {
67
68static double Percentage(size_t x, size_t y) {
69 return 100.0 * (static_cast<double>(x)) / (static_cast<double>(x + y));
70}
71
72static void DumpStat(size_t x, size_t y, const char* str) {
73 if (x == 0 && y == 0) {
74 return;
75 }
Ian Rogerse732ef12013-10-09 15:22:24 -070076 LOG(INFO) << Percentage(x, y) << "% of " << str << " for " << (x + y) << " cases";
Brian Carlstrom7940e442013-07-12 13:46:57 -070077}
78
Vladimir Markof096aad2014-01-23 15:51:58 +000079class CompilerDriver::AOTCompilationStats {
Brian Carlstrom7940e442013-07-12 13:46:57 -070080 public:
81 AOTCompilationStats()
82 : stats_lock_("AOT compilation statistics lock"),
83 types_in_dex_cache_(0), types_not_in_dex_cache_(0),
84 strings_in_dex_cache_(0), strings_not_in_dex_cache_(0),
85 resolved_types_(0), unresolved_types_(0),
86 resolved_instance_fields_(0), unresolved_instance_fields_(0),
87 resolved_local_static_fields_(0), resolved_static_fields_(0), unresolved_static_fields_(0),
88 type_based_devirtualization_(0),
89 safe_casts_(0), not_safe_casts_(0) {
90 for (size_t i = 0; i <= kMaxInvokeType; i++) {
91 resolved_methods_[i] = 0;
92 unresolved_methods_[i] = 0;
93 virtual_made_direct_[i] = 0;
94 direct_calls_to_boot_[i] = 0;
95 direct_methods_to_boot_[i] = 0;
96 }
97 }
98
99 void Dump() {
100 DumpStat(types_in_dex_cache_, types_not_in_dex_cache_, "types known to be in dex cache");
101 DumpStat(strings_in_dex_cache_, strings_not_in_dex_cache_, "strings known to be in dex cache");
102 DumpStat(resolved_types_, unresolved_types_, "types resolved");
103 DumpStat(resolved_instance_fields_, unresolved_instance_fields_, "instance fields resolved");
104 DumpStat(resolved_local_static_fields_ + resolved_static_fields_, unresolved_static_fields_,
105 "static fields resolved");
106 DumpStat(resolved_local_static_fields_, resolved_static_fields_ + unresolved_static_fields_,
107 "static fields local to a class");
108 DumpStat(safe_casts_, not_safe_casts_, "check-casts removed based on type information");
109 // Note, the code below subtracts the stat value so that when added to the stat value we have
110 // 100% of samples. TODO: clean this up.
111 DumpStat(type_based_devirtualization_,
112 resolved_methods_[kVirtual] + unresolved_methods_[kVirtual] +
113 resolved_methods_[kInterface] + unresolved_methods_[kInterface] -
114 type_based_devirtualization_,
115 "virtual/interface calls made direct based on type information");
116
117 for (size_t i = 0; i <= kMaxInvokeType; i++) {
118 std::ostringstream oss;
119 oss << static_cast<InvokeType>(i) << " methods were AOT resolved";
120 DumpStat(resolved_methods_[i], unresolved_methods_[i], oss.str().c_str());
121 if (virtual_made_direct_[i] > 0) {
122 std::ostringstream oss2;
123 oss2 << static_cast<InvokeType>(i) << " methods made direct";
124 DumpStat(virtual_made_direct_[i],
125 resolved_methods_[i] + unresolved_methods_[i] - virtual_made_direct_[i],
126 oss2.str().c_str());
127 }
128 if (direct_calls_to_boot_[i] > 0) {
129 std::ostringstream oss2;
130 oss2 << static_cast<InvokeType>(i) << " method calls are direct into boot";
131 DumpStat(direct_calls_to_boot_[i],
132 resolved_methods_[i] + unresolved_methods_[i] - direct_calls_to_boot_[i],
133 oss2.str().c_str());
134 }
135 if (direct_methods_to_boot_[i] > 0) {
136 std::ostringstream oss2;
137 oss2 << static_cast<InvokeType>(i) << " method calls have methods in boot";
138 DumpStat(direct_methods_to_boot_[i],
139 resolved_methods_[i] + unresolved_methods_[i] - direct_methods_to_boot_[i],
140 oss2.str().c_str());
141 }
142 }
143 }
144
145// Allow lossy statistics in non-debug builds.
146#ifndef NDEBUG
147#define STATS_LOCK() MutexLock mu(Thread::Current(), stats_lock_)
148#else
149#define STATS_LOCK()
150#endif
151
152 void TypeInDexCache() {
153 STATS_LOCK();
154 types_in_dex_cache_++;
155 }
156
157 void TypeNotInDexCache() {
158 STATS_LOCK();
159 types_not_in_dex_cache_++;
160 }
161
162 void StringInDexCache() {
163 STATS_LOCK();
164 strings_in_dex_cache_++;
165 }
166
167 void StringNotInDexCache() {
168 STATS_LOCK();
169 strings_not_in_dex_cache_++;
170 }
171
172 void TypeDoesntNeedAccessCheck() {
173 STATS_LOCK();
174 resolved_types_++;
175 }
176
177 void TypeNeedsAccessCheck() {
178 STATS_LOCK();
179 unresolved_types_++;
180 }
181
182 void ResolvedInstanceField() {
183 STATS_LOCK();
184 resolved_instance_fields_++;
185 }
186
187 void UnresolvedInstanceField() {
188 STATS_LOCK();
189 unresolved_instance_fields_++;
190 }
191
192 void ResolvedLocalStaticField() {
193 STATS_LOCK();
194 resolved_local_static_fields_++;
195 }
196
197 void ResolvedStaticField() {
198 STATS_LOCK();
199 resolved_static_fields_++;
200 }
201
202 void UnresolvedStaticField() {
203 STATS_LOCK();
204 unresolved_static_fields_++;
205 }
206
207 // Indicate that type information from the verifier led to devirtualization.
208 void PreciseTypeDevirtualization() {
209 STATS_LOCK();
210 type_based_devirtualization_++;
211 }
212
213 // Indicate that a method of the given type was resolved at compile time.
214 void ResolvedMethod(InvokeType type) {
215 DCHECK_LE(type, kMaxInvokeType);
216 STATS_LOCK();
217 resolved_methods_[type]++;
218 }
219
220 // Indicate that a method of the given type was unresolved at compile time as it was in an
221 // unknown dex file.
222 void UnresolvedMethod(InvokeType type) {
223 DCHECK_LE(type, kMaxInvokeType);
224 STATS_LOCK();
225 unresolved_methods_[type]++;
226 }
227
228 // Indicate that a type of virtual method dispatch has been converted into a direct method
229 // dispatch.
230 void VirtualMadeDirect(InvokeType type) {
231 DCHECK(type == kVirtual || type == kInterface || type == kSuper);
232 STATS_LOCK();
233 virtual_made_direct_[type]++;
234 }
235
236 // Indicate that a method of the given type was able to call directly into boot.
237 void DirectCallsToBoot(InvokeType type) {
238 DCHECK_LE(type, kMaxInvokeType);
239 STATS_LOCK();
240 direct_calls_to_boot_[type]++;
241 }
242
243 // Indicate that a method of the given type was able to be resolved directly from boot.
244 void DirectMethodsToBoot(InvokeType type) {
245 DCHECK_LE(type, kMaxInvokeType);
246 STATS_LOCK();
247 direct_methods_to_boot_[type]++;
248 }
249
Vladimir Markof096aad2014-01-23 15:51:58 +0000250 void ProcessedInvoke(InvokeType type, int flags) {
251 STATS_LOCK();
252 if (flags == 0) {
253 unresolved_methods_[type]++;
254 } else {
255 DCHECK_NE((flags & kFlagMethodResolved), 0);
256 resolved_methods_[type]++;
257 if ((flags & kFlagVirtualMadeDirect) != 0) {
258 virtual_made_direct_[type]++;
259 if ((flags & kFlagPreciseTypeDevirtualization) != 0) {
260 type_based_devirtualization_++;
261 }
262 } else {
263 DCHECK_EQ((flags & kFlagPreciseTypeDevirtualization), 0);
264 }
265 if ((flags & kFlagDirectCallToBoot) != 0) {
266 direct_calls_to_boot_[type]++;
267 }
268 if ((flags & kFlagDirectMethodToBoot) != 0) {
269 direct_methods_to_boot_[type]++;
270 }
271 }
272 }
273
Brian Carlstrom7940e442013-07-12 13:46:57 -0700274 // A check-cast could be eliminated due to verifier type analysis.
275 void SafeCast() {
276 STATS_LOCK();
277 safe_casts_++;
278 }
279
280 // A check-cast couldn't be eliminated due to verifier type analysis.
281 void NotASafeCast() {
282 STATS_LOCK();
283 not_safe_casts_++;
284 }
285
286 private:
287 Mutex stats_lock_;
288
289 size_t types_in_dex_cache_;
290 size_t types_not_in_dex_cache_;
291
292 size_t strings_in_dex_cache_;
293 size_t strings_not_in_dex_cache_;
294
295 size_t resolved_types_;
296 size_t unresolved_types_;
297
298 size_t resolved_instance_fields_;
299 size_t unresolved_instance_fields_;
300
301 size_t resolved_local_static_fields_;
302 size_t resolved_static_fields_;
303 size_t unresolved_static_fields_;
304 // Type based devirtualization for invoke interface and virtual.
305 size_t type_based_devirtualization_;
306
307 size_t resolved_methods_[kMaxInvokeType + 1];
308 size_t unresolved_methods_[kMaxInvokeType + 1];
309 size_t virtual_made_direct_[kMaxInvokeType + 1];
310 size_t direct_calls_to_boot_[kMaxInvokeType + 1];
311 size_t direct_methods_to_boot_[kMaxInvokeType + 1];
312
313 size_t safe_casts_;
314 size_t not_safe_casts_;
315
316 DISALLOW_COPY_AND_ASSIGN(AOTCompilationStats);
317};
318
Brian Carlstrom7940e442013-07-12 13:46:57 -0700319
320extern "C" art::CompiledMethod* ArtCompileDEX(art::CompilerDriver& compiler,
321 const art::DexFile::CodeItem* code_item,
322 uint32_t access_flags,
323 art::InvokeType invoke_type,
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700324 uint16_t class_def_idx,
Brian Carlstrom7940e442013-07-12 13:46:57 -0700325 uint32_t method_idx,
326 jobject class_loader,
327 const art::DexFile& dex_file);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700328
Brian Carlstrom6449c622014-02-10 23:48:36 -0800329CompilerDriver::CompilerDriver(const CompilerOptions* compiler_options,
330 VerificationResults* verification_results,
Vladimir Marko5816ed42013-11-27 17:04:20 +0000331 DexFileToMethodInlinerMap* method_inliner_map,
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +0000332 Compiler::Kind compiler_kind,
Nicolas Geoffrayf5df8972014-02-14 18:37:08 +0000333 InstructionSet instruction_set,
Dave Allison70202782013-10-22 17:52:19 -0700334 InstructionSetFeatures instruction_set_features,
buzbeea024a062013-07-31 10:47:37 -0700335 bool image, DescriptorSet* image_classes, size_t thread_count,
Dave Allison39c3bfb2014-01-28 18:33:52 -0800336 bool dump_stats, bool dump_passes, CumulativeLogger* timer,
337 std::string profile_file)
338 : profile_ok_(false), compiler_options_(compiler_options),
Brian Carlstrom6449c622014-02-10 23:48:36 -0800339 verification_results_(verification_results),
Vladimir Marko5816ed42013-11-27 17:04:20 +0000340 method_inliner_map_(method_inliner_map),
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +0000341 compiler_(Compiler::Create(compiler_kind)),
Brian Carlstrom7940e442013-07-12 13:46:57 -0700342 instruction_set_(instruction_set),
Dave Allison70202782013-10-22 17:52:19 -0700343 instruction_set_features_(instruction_set_features),
Brian Carlstrom7940e442013-07-12 13:46:57 -0700344 freezing_constructor_lock_("freezing constructor lock"),
345 compiled_classes_lock_("compiled classes lock"),
346 compiled_methods_lock_("compiled method lock"),
347 image_(image),
348 image_classes_(image_classes),
349 thread_count_(thread_count),
Brian Carlstrom7940e442013-07-12 13:46:57 -0700350 start_ns_(0),
351 stats_(new AOTCompilationStats),
352 dump_stats_(dump_stats),
Nicolas Geoffrayea3fa0b2014-02-10 11:59:41 +0000353 dump_passes_(dump_passes),
354 timings_logger_(timer),
Brian Carlstrom7940e442013-07-12 13:46:57 -0700355 compiler_library_(NULL),
Brian Carlstrom7940e442013-07-12 13:46:57 -0700356 compiler_context_(NULL),
Brian Carlstrom7940e442013-07-12 13:46:57 -0700357 compiler_enable_auto_elf_loading_(NULL),
358 compiler_get_method_code_addr_(NULL),
Mark Mendell55d0eac2014-02-06 11:02:52 -0800359 support_boot_image_fixup_(instruction_set != kMips),
Mark Mendellae9fd932014-02-10 16:14:35 -0800360 cfi_info_(nullptr),
Ian Rogersd133b972013-09-05 11:01:30 -0700361 dedupe_code_("dedupe code"),
362 dedupe_mapping_table_("dedupe mapping table"),
363 dedupe_vmap_table_("dedupe vmap table"),
Mark Mendellae9fd932014-02-10 16:14:35 -0800364 dedupe_gc_map_("dedupe gc map"),
365 dedupe_cfi_info_("dedupe cfi info") {
Brian Carlstrom6449c622014-02-10 23:48:36 -0800366 DCHECK(compiler_options_ != nullptr);
367 DCHECK(verification_results_ != nullptr);
368 DCHECK(method_inliner_map_ != nullptr);
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700369
Brian Carlstrom7940e442013-07-12 13:46:57 -0700370 CHECK_PTHREAD_CALL(pthread_key_create, (&tls_key_, NULL), "compiler tls key");
371
Dave Allison39c3bfb2014-01-28 18:33:52 -0800372 // Read the profile file if one is provided.
373 if (profile_file != "") {
374 profile_ok_ = ReadProfile(profile_file);
375 }
376
Sebastien Hertz75021222013-07-16 18:34:50 +0200377 dex_to_dex_compiler_ = reinterpret_cast<DexToDexCompilerFn>(ArtCompileDEX);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700378
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +0000379 compiler_->Init(*this);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700380
381 CHECK(!Runtime::Current()->IsStarted());
382 if (!image_) {
383 CHECK(image_classes_.get() == NULL);
384 }
Mark Mendellae9fd932014-02-10 16:14:35 -0800385
386 // Are we generating CFI information?
387 if (compiler_options->GetGenerateGDBInformation()) {
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +0000388 cfi_info_.reset(compiler_->GetCallFrameInformationInitialization(*this));
Mark Mendellae9fd932014-02-10 16:14:35 -0800389 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700390}
391
Mathieu Chartier193bad92013-08-29 18:46:00 -0700392std::vector<uint8_t>* CompilerDriver::DeduplicateCode(const std::vector<uint8_t>& code) {
393 return dedupe_code_.Add(Thread::Current(), code);
394}
395
396std::vector<uint8_t>* CompilerDriver::DeduplicateMappingTable(const std::vector<uint8_t>& code) {
397 return dedupe_mapping_table_.Add(Thread::Current(), code);
398}
399
400std::vector<uint8_t>* CompilerDriver::DeduplicateVMapTable(const std::vector<uint8_t>& code) {
401 return dedupe_vmap_table_.Add(Thread::Current(), code);
402}
403
404std::vector<uint8_t>* CompilerDriver::DeduplicateGCMap(const std::vector<uint8_t>& code) {
405 return dedupe_gc_map_.Add(Thread::Current(), code);
406}
407
Mark Mendellae9fd932014-02-10 16:14:35 -0800408std::vector<uint8_t>* CompilerDriver::DeduplicateCFIInfo(const std::vector<uint8_t>* cfi_info) {
409 if (cfi_info == nullptr) {
410 return nullptr;
411 }
412 return dedupe_cfi_info_.Add(Thread::Current(), *cfi_info);
413}
414
Brian Carlstrom7940e442013-07-12 13:46:57 -0700415CompilerDriver::~CompilerDriver() {
416 Thread* self = Thread::Current();
417 {
418 MutexLock mu(self, compiled_classes_lock_);
419 STLDeleteValues(&compiled_classes_);
420 }
421 {
422 MutexLock mu(self, compiled_methods_lock_);
423 STLDeleteValues(&compiled_methods_);
424 }
425 {
426 MutexLock mu(self, compiled_methods_lock_);
427 STLDeleteElements(&code_to_patch_);
428 }
429 {
430 MutexLock mu(self, compiled_methods_lock_);
431 STLDeleteElements(&methods_to_patch_);
432 }
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -0800433 {
434 MutexLock mu(self, compiled_methods_lock_);
435 STLDeleteElements(&classes_to_patch_);
436 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700437 CHECK_PTHREAD_CALL(pthread_key_delete, (tls_key_), "delete tls key");
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +0000438 compiler_->UnInit(*this);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700439}
440
441CompilerTls* CompilerDriver::GetTls() {
442 // Lazily create thread-local storage
443 CompilerTls* res = static_cast<CompilerTls*>(pthread_getspecific(tls_key_));
444 if (res == NULL) {
445 res = new CompilerTls();
446 CHECK_PTHREAD_CALL(pthread_setspecific, (tls_key_, res), "compiler tls");
447 }
448 return res;
449}
450
Ian Rogers848871b2013-08-05 10:56:33 -0700451const std::vector<uint8_t>* CompilerDriver::CreateInterpreterToInterpreterBridge() const {
452 return CreateTrampoline(instruction_set_, kInterpreterAbi,
453 INTERPRETER_ENTRYPOINT_OFFSET(pInterpreterToInterpreterBridge));
454}
455
456const std::vector<uint8_t>* CompilerDriver::CreateInterpreterToCompiledCodeBridge() const {
457 return CreateTrampoline(instruction_set_, kInterpreterAbi,
458 INTERPRETER_ENTRYPOINT_OFFSET(pInterpreterToCompiledCodeBridge));
459}
460
461const std::vector<uint8_t>* CompilerDriver::CreateJniDlsymLookup() const {
462 return CreateTrampoline(instruction_set_, kJniAbi, JNI_ENTRYPOINT_OFFSET(pDlsymLookup));
463}
464
Jeff Hao88474b42013-10-23 16:24:40 -0700465const std::vector<uint8_t>* CompilerDriver::CreatePortableImtConflictTrampoline() const {
466 return CreateTrampoline(instruction_set_, kPortableAbi,
467 PORTABLE_ENTRYPOINT_OFFSET(pPortableImtConflictTrampoline));
468}
469
Brian Carlstrom7940e442013-07-12 13:46:57 -0700470const std::vector<uint8_t>* CompilerDriver::CreatePortableResolutionTrampoline() const {
Ian Rogers848871b2013-08-05 10:56:33 -0700471 return CreateTrampoline(instruction_set_, kPortableAbi,
472 PORTABLE_ENTRYPOINT_OFFSET(pPortableResolutionTrampoline));
473}
474
475const std::vector<uint8_t>* CompilerDriver::CreatePortableToInterpreterBridge() const {
476 return CreateTrampoline(instruction_set_, kPortableAbi,
477 PORTABLE_ENTRYPOINT_OFFSET(pPortableToInterpreterBridge));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700478}
479
Andreas Gampe2da88232014-02-27 12:26:20 -0800480const std::vector<uint8_t>* CompilerDriver::CreateQuickGenericJniTrampoline() const {
481 return CreateTrampoline(instruction_set_, kQuickAbi,
482 QUICK_ENTRYPOINT_OFFSET(pQuickGenericJniTrampoline));
483}
484
Jeff Hao88474b42013-10-23 16:24:40 -0700485const std::vector<uint8_t>* CompilerDriver::CreateQuickImtConflictTrampoline() const {
486 return CreateTrampoline(instruction_set_, kQuickAbi,
487 QUICK_ENTRYPOINT_OFFSET(pQuickImtConflictTrampoline));
488}
489
Brian Carlstrom7940e442013-07-12 13:46:57 -0700490const std::vector<uint8_t>* CompilerDriver::CreateQuickResolutionTrampoline() const {
Ian Rogers848871b2013-08-05 10:56:33 -0700491 return CreateTrampoline(instruction_set_, kQuickAbi,
492 QUICK_ENTRYPOINT_OFFSET(pQuickResolutionTrampoline));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700493}
494
Ian Rogers848871b2013-08-05 10:56:33 -0700495const std::vector<uint8_t>* CompilerDriver::CreateQuickToInterpreterBridge() const {
496 return CreateTrampoline(instruction_set_, kQuickAbi,
497 QUICK_ENTRYPOINT_OFFSET(pQuickToInterpreterBridge));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700498}
499
500void CompilerDriver::CompileAll(jobject class_loader,
Brian Carlstrom45602482013-07-21 22:07:55 -0700501 const std::vector<const DexFile*>& dex_files,
Ian Rogers3d504072014-03-01 09:16:49 -0800502 TimingLogger* timings) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700503 DCHECK(!Runtime::Current()->IsStarted());
Mathieu Chartierbcd5e9d2013-11-13 14:33:28 -0800504 UniquePtr<ThreadPool> thread_pool(new ThreadPool("Compiler driver thread pool", thread_count_ - 1));
Ian Rogers3d504072014-03-01 09:16:49 -0800505 PreCompile(class_loader, dex_files, thread_pool.get(), timings);
506 Compile(class_loader, dex_files, thread_pool.get(), timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700507 if (dump_stats_) {
508 stats_->Dump();
509 }
510}
511
Mathieu Chartier590fee92013-09-13 13:46:47 -0700512static DexToDexCompilationLevel GetDexToDexCompilationlevel(
Ian Rogers98379392014-02-24 16:53:16 -0800513 Thread* self, SirtRef<mirror::ClassLoader>& class_loader, const DexFile& dex_file,
Mathieu Chartier590fee92013-09-13 13:46:47 -0700514 const DexFile::ClassDef& class_def) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700515 const char* descriptor = dex_file.GetClassDescriptor(class_def);
516 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Ian Rogers98379392014-02-24 16:53:16 -0800517 mirror::Class* klass = class_linker->FindClass(self, descriptor, class_loader);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700518 if (klass == NULL) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700519 CHECK(self->IsExceptionPending());
520 self->ClearException();
Sebastien Hertz75021222013-07-16 18:34:50 +0200521 return kDontDexToDexCompile;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700522 }
Sebastien Hertz75021222013-07-16 18:34:50 +0200523 // The verifier can only run on "quick" instructions at runtime (see usage of
524 // FindAccessedFieldAtDexPc and FindInvokedMethodAtDexPc in ThrowNullPointerExceptionFromDexPC
525 // function). Since image classes can be verified again while compiling an application,
526 // we must prevent the DEX-to-DEX compiler from introducing them.
527 // TODO: find a way to enable "quick" instructions for image classes and remove this check.
Mathieu Chartier590fee92013-09-13 13:46:47 -0700528 bool compiling_image_classes = class_loader.get() == nullptr;
Sebastien Hertz75021222013-07-16 18:34:50 +0200529 if (compiling_image_classes) {
530 return kRequired;
531 } else if (klass->IsVerified()) {
532 // Class is verified so we can enable DEX-to-DEX compilation for performance.
533 return kOptimize;
534 } else if (klass->IsCompileTimeVerified()) {
535 // Class verification has soft-failed. Anyway, ensure at least correctness.
536 DCHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime);
537 return kRequired;
538 } else {
539 // Class verification has failed: do not run DEX-to-DEX compilation.
540 return kDontDexToDexCompile;
541 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700542}
543
Ian Rogers3d504072014-03-01 09:16:49 -0800544void CompilerDriver::CompileOne(mirror::ArtMethod* method, TimingLogger* timings) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700545 DCHECK(!Runtime::Current()->IsStarted());
546 Thread* self = Thread::Current();
547 jobject jclass_loader;
548 const DexFile* dex_file;
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700549 uint16_t class_def_idx;
Ian Rogersef7d42f2014-01-06 12:55:46 -0800550 uint32_t method_idx = method->GetDexMethodIndex();
551 uint32_t access_flags = method->GetAccessFlags();
552 InvokeType invoke_type = method->GetInvokeType();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700553 {
554 ScopedObjectAccessUnchecked soa(self);
555 ScopedLocalRef<jobject>
556 local_class_loader(soa.Env(),
557 soa.AddLocalReference<jobject>(method->GetDeclaringClass()->GetClassLoader()));
558 jclass_loader = soa.Env()->NewGlobalRef(local_class_loader.get());
559 // Find the dex_file
560 MethodHelper mh(method);
561 dex_file = &mh.GetDexFile();
562 class_def_idx = mh.GetClassDefIndex();
563 }
Ian Rogersef7d42f2014-01-06 12:55:46 -0800564 const DexFile::CodeItem* code_item = dex_file->GetCodeItem(method->GetCodeItemOffset());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700565 self->TransitionFromRunnableToSuspended(kNative);
566
567 std::vector<const DexFile*> dex_files;
568 dex_files.push_back(dex_file);
569
Mathieu Chartierbcd5e9d2013-11-13 14:33:28 -0800570 UniquePtr<ThreadPool> thread_pool(new ThreadPool("Compiler driver thread pool", 0U));
Ian Rogers3d504072014-03-01 09:16:49 -0800571 PreCompile(jclass_loader, dex_files, thread_pool.get(), timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700572
Brian Carlstrom7940e442013-07-12 13:46:57 -0700573 // Can we run DEX-to-DEX compiler on this class ?
Sebastien Hertz75021222013-07-16 18:34:50 +0200574 DexToDexCompilationLevel dex_to_dex_compilation_level = kDontDexToDexCompile;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700575 {
576 ScopedObjectAccess soa(Thread::Current());
577 const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_idx);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700578 SirtRef<mirror::ClassLoader> class_loader(soa.Self(),
579 soa.Decode<mirror::ClassLoader*>(jclass_loader));
Ian Rogers98379392014-02-24 16:53:16 -0800580 dex_to_dex_compilation_level = GetDexToDexCompilationlevel(self, class_loader, *dex_file,
581 class_def);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700582 }
Ian Rogersef7d42f2014-01-06 12:55:46 -0800583 CompileMethod(code_item, access_flags, invoke_type, class_def_idx, method_idx, jclass_loader,
584 *dex_file, dex_to_dex_compilation_level);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700585
586 self->GetJniEnv()->DeleteGlobalRef(jclass_loader);
587
588 self->TransitionFromSuspendedToRunnable();
589}
590
591void CompilerDriver::Resolve(jobject class_loader, const std::vector<const DexFile*>& dex_files,
Ian Rogers3d504072014-03-01 09:16:49 -0800592 ThreadPool* thread_pool, TimingLogger* timings) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700593 for (size_t i = 0; i != dex_files.size(); ++i) {
594 const DexFile* dex_file = dex_files[i];
595 CHECK(dex_file != NULL);
596 ResolveDexFile(class_loader, *dex_file, thread_pool, timings);
597 }
598}
599
600void CompilerDriver::PreCompile(jobject class_loader, const std::vector<const DexFile*>& dex_files,
Ian Rogers3d504072014-03-01 09:16:49 -0800601 ThreadPool* thread_pool, TimingLogger* timings) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700602 LoadImageClasses(timings);
603
604 Resolve(class_loader, dex_files, thread_pool, timings);
605
606 Verify(class_loader, dex_files, thread_pool, timings);
607
608 InitializeClasses(class_loader, dex_files, thread_pool, timings);
609
610 UpdateImageClasses(timings);
611}
612
Ian Rogersdfb325e2013-10-30 01:00:44 -0700613bool CompilerDriver::IsImageClass(const char* descriptor) const {
Ian Rogerse6bb3b22013-08-19 21:51:45 -0700614 if (!IsImage()) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700615 return true;
Ian Rogerse6bb3b22013-08-19 21:51:45 -0700616 } else {
Ian Rogersdfb325e2013-10-30 01:00:44 -0700617 return image_classes_->find(descriptor) != image_classes_->end();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700618 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700619}
620
621static void ResolveExceptionsForMethod(MethodHelper* mh,
622 std::set<std::pair<uint16_t, const DexFile*> >& exceptions_to_resolve)
623 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
624 const DexFile::CodeItem* code_item = mh->GetCodeItem();
625 if (code_item == NULL) {
626 return; // native or abstract method
627 }
628 if (code_item->tries_size_ == 0) {
629 return; // nothing to process
630 }
631 const byte* encoded_catch_handler_list = DexFile::GetCatchHandlerData(*code_item, 0);
632 size_t num_encoded_catch_handlers = DecodeUnsignedLeb128(&encoded_catch_handler_list);
633 for (size_t i = 0; i < num_encoded_catch_handlers; i++) {
634 int32_t encoded_catch_handler_size = DecodeSignedLeb128(&encoded_catch_handler_list);
635 bool has_catch_all = false;
636 if (encoded_catch_handler_size <= 0) {
637 encoded_catch_handler_size = -encoded_catch_handler_size;
638 has_catch_all = true;
639 }
640 for (int32_t j = 0; j < encoded_catch_handler_size; j++) {
641 uint16_t encoded_catch_handler_handlers_type_idx =
642 DecodeUnsignedLeb128(&encoded_catch_handler_list);
643 // Add to set of types to resolve if not already in the dex cache resolved types
644 if (!mh->IsResolvedTypeIdx(encoded_catch_handler_handlers_type_idx)) {
645 exceptions_to_resolve.insert(
646 std::pair<uint16_t, const DexFile*>(encoded_catch_handler_handlers_type_idx,
647 &mh->GetDexFile()));
648 }
649 // ignore address associated with catch handler
650 DecodeUnsignedLeb128(&encoded_catch_handler_list);
651 }
652 if (has_catch_all) {
653 // ignore catch all address
654 DecodeUnsignedLeb128(&encoded_catch_handler_list);
655 }
656 }
657}
658
659static bool ResolveCatchBlockExceptionsClassVisitor(mirror::Class* c, void* arg)
660 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
661 std::set<std::pair<uint16_t, const DexFile*> >* exceptions_to_resolve =
662 reinterpret_cast<std::set<std::pair<uint16_t, const DexFile*> >*>(arg);
663 MethodHelper mh;
664 for (size_t i = 0; i < c->NumVirtualMethods(); ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -0700665 mirror::ArtMethod* m = c->GetVirtualMethod(i);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700666 mh.ChangeMethod(m);
667 ResolveExceptionsForMethod(&mh, *exceptions_to_resolve);
668 }
669 for (size_t i = 0; i < c->NumDirectMethods(); ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -0700670 mirror::ArtMethod* m = c->GetDirectMethod(i);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700671 mh.ChangeMethod(m);
672 ResolveExceptionsForMethod(&mh, *exceptions_to_resolve);
673 }
674 return true;
675}
676
677static bool RecordImageClassesVisitor(mirror::Class* klass, void* arg)
678 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
679 CompilerDriver::DescriptorSet* image_classes =
680 reinterpret_cast<CompilerDriver::DescriptorSet*>(arg);
681 image_classes->insert(ClassHelper(klass).GetDescriptor());
682 return true;
683}
684
685// Make a list of descriptors for classes to include in the image
Ian Rogers3d504072014-03-01 09:16:49 -0800686void CompilerDriver::LoadImageClasses(TimingLogger* timings)
Brian Carlstrom7940e442013-07-12 13:46:57 -0700687 LOCKS_EXCLUDED(Locks::mutator_lock_) {
Ian Rogerse6bb3b22013-08-19 21:51:45 -0700688 if (!IsImage()) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700689 return;
690 }
691
Ian Rogers3d504072014-03-01 09:16:49 -0800692 timings->NewSplit("LoadImageClasses");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700693 // Make a first class to load all classes explicitly listed in the file
694 Thread* self = Thread::Current();
695 ScopedObjectAccess soa(self);
696 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Mathieu Chartier02e25112013-08-14 16:14:24 -0700697 for (auto it = image_classes_->begin(), end = image_classes_->end(); it != end;) {
Vladimir Markoe9c36b32013-11-21 15:49:16 +0000698 const std::string& descriptor(*it);
Ian Rogers98379392014-02-24 16:53:16 -0800699 SirtRef<mirror::Class> klass(self, class_linker->FindSystemClass(self, descriptor.c_str()));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700700 if (klass.get() == NULL) {
Ian Rogerse6bb3b22013-08-19 21:51:45 -0700701 VLOG(compiler) << "Failed to find class " << descriptor;
Vladimir Markoe9c36b32013-11-21 15:49:16 +0000702 image_classes_->erase(it++);
Ian Rogersa436fde2013-08-27 23:34:06 -0700703 self->ClearException();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700704 } else {
705 ++it;
706 }
707 }
708
709 // Resolve exception classes referenced by the loaded classes. The catch logic assumes
710 // exceptions are resolved by the verifier when there is a catch block in an interested method.
711 // Do this here so that exception classes appear to have been specified image classes.
712 std::set<std::pair<uint16_t, const DexFile*> > unresolved_exception_types;
713 SirtRef<mirror::Class> java_lang_Throwable(self,
Ian Rogers98379392014-02-24 16:53:16 -0800714 class_linker->FindSystemClass(self, "Ljava/lang/Throwable;"));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700715 do {
716 unresolved_exception_types.clear();
717 class_linker->VisitClasses(ResolveCatchBlockExceptionsClassVisitor,
718 &unresolved_exception_types);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700719 for (const std::pair<uint16_t, const DexFile*>& exception_type : unresolved_exception_types) {
720 uint16_t exception_type_idx = exception_type.first;
721 const DexFile* dex_file = exception_type.second;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700722 SirtRef<mirror::DexCache> dex_cache(self, class_linker->FindDexCache(*dex_file));
723 SirtRef<mirror::ClassLoader> class_loader(self, nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700724 SirtRef<mirror::Class> klass(self, class_linker->ResolveType(*dex_file, exception_type_idx,
725 dex_cache, class_loader));
726 if (klass.get() == NULL) {
727 const DexFile::TypeId& type_id = dex_file->GetTypeId(exception_type_idx);
728 const char* descriptor = dex_file->GetTypeDescriptor(type_id);
729 LOG(FATAL) << "Failed to resolve class " << descriptor;
730 }
731 DCHECK(java_lang_Throwable->IsAssignableFrom(klass.get()));
732 }
733 // Resolving exceptions may load classes that reference more exceptions, iterate until no
734 // more are found
735 } while (!unresolved_exception_types.empty());
736
737 // We walk the roots looking for classes so that we'll pick up the
738 // above classes plus any classes them depend on such super
739 // classes, interfaces, and the required ClassLinker roots.
740 class_linker->VisitClasses(RecordImageClassesVisitor, image_classes_.get());
741
742 CHECK_NE(image_classes_->size(), 0U);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700743}
744
745static void MaybeAddToImageClasses(mirror::Class* klass, CompilerDriver::DescriptorSet* image_classes)
746 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
747 while (!klass->IsObjectClass()) {
748 ClassHelper kh(klass);
749 const char* descriptor = kh.GetDescriptor();
750 std::pair<CompilerDriver::DescriptorSet::iterator, bool> result =
751 image_classes->insert(descriptor);
752 if (result.second) {
Anwar Ghuloum75a43f12013-08-13 17:22:14 -0700753 VLOG(compiler) << "Adding " << descriptor << " to image classes";
Brian Carlstrom7940e442013-07-12 13:46:57 -0700754 } else {
755 return;
756 }
757 for (size_t i = 0; i < kh.NumDirectInterfaces(); ++i) {
758 MaybeAddToImageClasses(kh.GetDirectInterface(i), image_classes);
759 }
760 if (klass->IsArrayClass()) {
761 MaybeAddToImageClasses(klass->GetComponentType(), image_classes);
762 }
763 klass = klass->GetSuperClass();
764 }
765}
766
767void CompilerDriver::FindClinitImageClassesCallback(mirror::Object* object, void* arg) {
768 DCHECK(object != NULL);
769 DCHECK(arg != NULL);
770 CompilerDriver* compiler_driver = reinterpret_cast<CompilerDriver*>(arg);
771 MaybeAddToImageClasses(object->GetClass(), compiler_driver->image_classes_.get());
772}
773
Ian Rogers3d504072014-03-01 09:16:49 -0800774void CompilerDriver::UpdateImageClasses(TimingLogger* timings) {
Ian Rogerse6bb3b22013-08-19 21:51:45 -0700775 if (IsImage()) {
Ian Rogers3d504072014-03-01 09:16:49 -0800776 timings->NewSplit("UpdateImageClasses");
Ian Rogerse6bb3b22013-08-19 21:51:45 -0700777
778 // Update image_classes_ with classes for objects created by <clinit> methods.
779 Thread* self = Thread::Current();
780 const char* old_cause = self->StartAssertNoThreadSuspension("ImageWriter");
781 gc::Heap* heap = Runtime::Current()->GetHeap();
782 // TODO: Image spaces only?
Mathieu Chartier590fee92013-09-13 13:46:47 -0700783 ScopedObjectAccess soa(Thread::Current());
Ian Rogerse6bb3b22013-08-19 21:51:45 -0700784 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700785 heap->VisitObjects(FindClinitImageClassesCallback, this);
Ian Rogerse6bb3b22013-08-19 21:51:45 -0700786 self->EndAssertNoThreadSuspension(old_cause);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700787 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700788}
789
Mathieu Chartier590fee92013-09-13 13:46:47 -0700790bool CompilerDriver::CanAssumeTypeIsPresentInDexCache(const DexFile& dex_file, uint32_t type_idx) {
Ian Rogersfc0e94b2013-09-23 23:51:32 -0700791 if (IsImage() &&
Ian Rogersdfb325e2013-10-30 01:00:44 -0700792 IsImageClass(dex_file.StringDataByIdx(dex_file.GetTypeId(type_idx).descriptor_idx_))) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700793 if (kIsDebugBuild) {
794 ScopedObjectAccess soa(Thread::Current());
795 mirror::DexCache* dex_cache = Runtime::Current()->GetClassLinker()->FindDexCache(dex_file);
796 mirror::Class* resolved_class = dex_cache->GetResolvedType(type_idx);
797 CHECK(resolved_class != NULL);
798 }
799 stats_->TypeInDexCache();
800 return true;
801 } else {
802 stats_->TypeNotInDexCache();
803 return false;
804 }
805}
806
807bool CompilerDriver::CanAssumeStringIsPresentInDexCache(const DexFile& dex_file,
808 uint32_t string_idx) {
809 // See also Compiler::ResolveDexFile
810
811 bool result = false;
812 if (IsImage()) {
813 // We resolve all const-string strings when building for the image.
814 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartier590fee92013-09-13 13:46:47 -0700815 SirtRef<mirror::DexCache> dex_cache(soa.Self(), Runtime::Current()->GetClassLinker()->FindDexCache(dex_file));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700816 Runtime::Current()->GetClassLinker()->ResolveString(dex_file, string_idx, dex_cache);
817 result = true;
818 }
819 if (result) {
820 stats_->StringInDexCache();
821 } else {
822 stats_->StringNotInDexCache();
823 }
824 return result;
825}
826
827bool CompilerDriver::CanAccessTypeWithoutChecks(uint32_t referrer_idx, const DexFile& dex_file,
828 uint32_t type_idx,
829 bool* type_known_final, bool* type_known_abstract,
830 bool* equals_referrers_class) {
831 if (type_known_final != NULL) {
832 *type_known_final = false;
833 }
834 if (type_known_abstract != NULL) {
835 *type_known_abstract = false;
836 }
837 if (equals_referrers_class != NULL) {
838 *equals_referrers_class = false;
839 }
840 ScopedObjectAccess soa(Thread::Current());
841 mirror::DexCache* dex_cache = Runtime::Current()->GetClassLinker()->FindDexCache(dex_file);
842 // Get type from dex cache assuming it was populated by the verifier
843 mirror::Class* resolved_class = dex_cache->GetResolvedType(type_idx);
844 if (resolved_class == NULL) {
845 stats_->TypeNeedsAccessCheck();
846 return false; // Unknown class needs access checks.
847 }
848 const DexFile::MethodId& method_id = dex_file.GetMethodId(referrer_idx);
849 if (equals_referrers_class != NULL) {
850 *equals_referrers_class = (method_id.class_idx_ == type_idx);
851 }
852 mirror::Class* referrer_class = dex_cache->GetResolvedType(method_id.class_idx_);
853 if (referrer_class == NULL) {
854 stats_->TypeNeedsAccessCheck();
855 return false; // Incomplete referrer knowledge needs access check.
856 }
857 // Perform access check, will return true if access is ok or false if we're going to have to
858 // check this at runtime (for example for class loaders).
859 bool result = referrer_class->CanAccess(resolved_class);
860 if (result) {
861 stats_->TypeDoesntNeedAccessCheck();
862 if (type_known_final != NULL) {
863 *type_known_final = resolved_class->IsFinal() && !resolved_class->IsArrayClass();
864 }
865 if (type_known_abstract != NULL) {
866 *type_known_abstract = resolved_class->IsAbstract() && !resolved_class->IsArrayClass();
867 }
868 } else {
869 stats_->TypeNeedsAccessCheck();
870 }
871 return result;
872}
873
874bool CompilerDriver::CanAccessInstantiableTypeWithoutChecks(uint32_t referrer_idx,
875 const DexFile& dex_file,
876 uint32_t type_idx) {
877 ScopedObjectAccess soa(Thread::Current());
878 mirror::DexCache* dex_cache = Runtime::Current()->GetClassLinker()->FindDexCache(dex_file);
879 // Get type from dex cache assuming it was populated by the verifier.
880 mirror::Class* resolved_class = dex_cache->GetResolvedType(type_idx);
881 if (resolved_class == NULL) {
882 stats_->TypeNeedsAccessCheck();
883 return false; // Unknown class needs access checks.
884 }
885 const DexFile::MethodId& method_id = dex_file.GetMethodId(referrer_idx);
886 mirror::Class* referrer_class = dex_cache->GetResolvedType(method_id.class_idx_);
887 if (referrer_class == NULL) {
888 stats_->TypeNeedsAccessCheck();
889 return false; // Incomplete referrer knowledge needs access check.
890 }
891 // Perform access and instantiable checks, will return true if access is ok or false if we're
892 // going to have to check this at runtime (for example for class loaders).
893 bool result = referrer_class->CanAccess(resolved_class) && resolved_class->IsInstantiable();
894 if (result) {
895 stats_->TypeDoesntNeedAccessCheck();
896 } else {
897 stats_->TypeNeedsAccessCheck();
898 }
899 return result;
900}
901
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -0800902bool CompilerDriver::CanEmbedTypeInCode(const DexFile& dex_file, uint32_t type_idx,
903 bool* is_type_initialized, bool* use_direct_type_ptr,
904 uintptr_t* direct_type_ptr) {
905 ScopedObjectAccess soa(Thread::Current());
906 mirror::DexCache* dex_cache = Runtime::Current()->GetClassLinker()->FindDexCache(dex_file);
907 mirror::Class* resolved_class = dex_cache->GetResolvedType(type_idx);
908 if (resolved_class == nullptr) {
909 return false;
910 }
911 const bool compiling_boot = Runtime::Current()->GetHeap()->IsCompilingBoot();
912 if (compiling_boot) {
913 // boot -> boot class pointers.
914 // True if the class is in the image at boot compiling time.
915 const bool is_image_class = IsImage() && IsImageClass(
916 dex_file.StringDataByIdx(dex_file.GetTypeId(type_idx).descriptor_idx_));
917 // True if pc relative load works.
918 const bool support_boot_image_fixup = GetSupportBootImageFixup();
919 if (is_image_class && support_boot_image_fixup) {
920 *is_type_initialized = resolved_class->IsInitialized();
921 *use_direct_type_ptr = false;
922 *direct_type_ptr = 0;
923 return true;
924 } else {
925 return false;
926 }
927 } else {
928 // True if the class is in the image at app compiling time.
929 const bool class_in_image =
930 Runtime::Current()->GetHeap()->FindSpaceFromObject(resolved_class, false)->IsImageSpace();
931 if (class_in_image) {
932 // boot -> app class pointers.
933 *is_type_initialized = resolved_class->IsInitialized();
934 *use_direct_type_ptr = true;
935 *direct_type_ptr = reinterpret_cast<uintptr_t>(resolved_class);
936 return true;
937 } else {
938 // app -> app class pointers.
939 // Give up because app does not have an image and class
940 // isn't created at compile time. TODO: implement this
941 // if/when each app gets an image.
942 return false;
943 }
944 }
945}
946
Vladimir Markobe0e5462014-02-26 11:24:15 +0000947void CompilerDriver::ProcessedInstanceField(bool resolved) {
948 if (!resolved) {
949 stats_->UnresolvedInstanceField();
950 } else {
951 stats_->ResolvedInstanceField();
952 }
953}
954
955void CompilerDriver::ProcessedStaticField(bool resolved, bool local) {
956 if (!resolved) {
957 stats_->UnresolvedStaticField();
958 } else if (local) {
959 stats_->ResolvedLocalStaticField();
960 } else {
961 stats_->ResolvedStaticField();
962 }
963}
964
Vladimir Markof096aad2014-01-23 15:51:58 +0000965void CompilerDriver::ProcessedInvoke(InvokeType invoke_type, int flags) {
966 stats_->ProcessedInvoke(invoke_type, flags);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700967}
968
969bool CompilerDriver::ComputeInstanceFieldInfo(uint32_t field_idx, const DexCompilationUnit* mUnit,
Vladimir Markobe0e5462014-02-26 11:24:15 +0000970 bool is_put, MemberOffset* field_offset,
971 bool* is_volatile) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700972 ScopedObjectAccess soa(Thread::Current());
Vladimir Markobe0e5462014-02-26 11:24:15 +0000973 // Try to resolve the field and compiling method's class.
974 mirror::ArtField* resolved_field;
975 mirror::Class* referrer_class;
976 mirror::DexCache* dex_cache;
977 {
978 SirtRef<mirror::DexCache> dex_cache_sirt(soa.Self(),
979 mUnit->GetClassLinker()->FindDexCache(*mUnit->GetDexFile()));
980 SirtRef<mirror::ClassLoader> class_loader_sirt(soa.Self(),
981 soa.Decode<mirror::ClassLoader*>(mUnit->GetClassLoader()));
982 SirtRef<mirror::ArtField> resolved_field_sirt(soa.Self(),
983 ResolveField(soa, dex_cache_sirt, class_loader_sirt, mUnit, field_idx, false));
984 referrer_class = (resolved_field_sirt.get() != nullptr)
985 ? ResolveCompilingMethodsClass(soa, dex_cache_sirt, class_loader_sirt, mUnit) : nullptr;
986 resolved_field = resolved_field_sirt.get();
987 dex_cache = dex_cache_sirt.get();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700988 }
Vladimir Markobe0e5462014-02-26 11:24:15 +0000989 bool result = false;
990 if (resolved_field != nullptr && referrer_class != nullptr) {
991 *is_volatile = IsFieldVolatile(resolved_field);
992 std::pair<bool, bool> fast_path = IsFastInstanceField(
993 dex_cache, referrer_class, resolved_field, field_idx, field_offset);
994 result = is_put ? fast_path.second : fast_path.first;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700995 }
Vladimir Markobe0e5462014-02-26 11:24:15 +0000996 if (!result) {
997 // Conservative defaults.
998 *is_volatile = true;
999 *field_offset = MemberOffset(static_cast<size_t>(-1));
1000 }
1001 ProcessedInstanceField(result);
1002 return result;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001003}
1004
1005bool CompilerDriver::ComputeStaticFieldInfo(uint32_t field_idx, const DexCompilationUnit* mUnit,
Vladimir Markobe0e5462014-02-26 11:24:15 +00001006 bool is_put, MemberOffset* field_offset,
1007 uint32_t* storage_index, bool* is_referrers_class,
1008 bool* is_volatile, bool* is_initialized) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001009 ScopedObjectAccess soa(Thread::Current());
Vladimir Markobe0e5462014-02-26 11:24:15 +00001010 // Try to resolve the field and compiling method's class.
1011 mirror::ArtField* resolved_field;
1012 mirror::Class* referrer_class;
1013 mirror::DexCache* dex_cache;
1014 {
1015 SirtRef<mirror::DexCache> dex_cache_sirt(soa.Self(),
1016 mUnit->GetClassLinker()->FindDexCache(*mUnit->GetDexFile()));
1017 SirtRef<mirror::ClassLoader> class_loader_sirt(soa.Self(),
1018 soa.Decode<mirror::ClassLoader*>(mUnit->GetClassLoader()));
1019 SirtRef<mirror::ArtField> resolved_field_sirt(soa.Self(),
1020 ResolveField(soa, dex_cache_sirt, class_loader_sirt, mUnit, field_idx, true));
1021 referrer_class = (resolved_field_sirt.get() != nullptr)
1022 ? ResolveCompilingMethodsClass(soa, dex_cache_sirt, class_loader_sirt, mUnit) : nullptr;
1023 resolved_field = resolved_field_sirt.get();
1024 dex_cache = dex_cache_sirt.get();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001025 }
Vladimir Markobe0e5462014-02-26 11:24:15 +00001026 bool result = false;
1027 if (resolved_field != nullptr && referrer_class != nullptr) {
1028 *is_volatile = IsFieldVolatile(resolved_field);
1029 std::pair<bool, bool> fast_path = IsFastStaticField(
1030 dex_cache, referrer_class, resolved_field, field_idx, field_offset,
1031 storage_index, is_referrers_class, is_initialized);
1032 result = is_put ? fast_path.second : fast_path.first;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001033 }
Vladimir Markobe0e5462014-02-26 11:24:15 +00001034 if (!result) {
1035 // Conservative defaults.
1036 *is_volatile = true;
1037 *field_offset = MemberOffset(static_cast<size_t>(-1));
1038 *storage_index = -1;
1039 *is_referrers_class = false;
1040 *is_initialized = false;
1041 }
1042 ProcessedStaticField(result, *is_referrers_class);
1043 return result;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001044}
1045
Ian Rogers83883d72013-10-21 21:07:24 -07001046void CompilerDriver::GetCodeAndMethodForDirectCall(InvokeType* type, InvokeType sharp_type,
1047 bool no_guarantee_of_dex_cache_entry,
Brian Carlstrom7940e442013-07-12 13:46:57 -07001048 mirror::Class* referrer_class,
Brian Carlstromea46f952013-07-30 01:26:50 -07001049 mirror::ArtMethod* method,
Vladimir Markof096aad2014-01-23 15:51:58 +00001050 int* stats_flags,
Ian Rogers83883d72013-10-21 21:07:24 -07001051 MethodReference* target_method,
Ian Rogers65ec92c2013-09-06 10:49:58 -07001052 uintptr_t* direct_code,
1053 uintptr_t* direct_method) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001054 // For direct and static methods compute possible direct_code and direct_method values, ie
1055 // an address for the Method* being invoked and an address of the code for that Method*.
1056 // For interface calls compute a value for direct_method that is the interface method being
1057 // invoked, so this can be passed to the out-of-line runtime support code.
Ian Rogers65ec92c2013-09-06 10:49:58 -07001058 *direct_code = 0;
1059 *direct_method = 0;
Ian Rogers83883d72013-10-21 21:07:24 -07001060 bool use_dex_cache = false;
Mathieu Chartier590fee92013-09-13 13:46:47 -07001061 const bool compiling_boot = Runtime::Current()->GetHeap()->IsCompilingBoot();
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +00001062 if (compiler_->IsPortable()) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001063 if (sharp_type != kStatic && sharp_type != kDirect) {
1064 return;
1065 }
Ian Rogers83883d72013-10-21 21:07:24 -07001066 use_dex_cache = true;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001067 } else {
Jeff Hao88474b42013-10-23 16:24:40 -07001068 if (sharp_type != kStatic && sharp_type != kDirect) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001069 return;
1070 }
Ian Rogers83883d72013-10-21 21:07:24 -07001071 // TODO: support patching on all architectures.
1072 use_dex_cache = compiling_boot && !support_boot_image_fixup_;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001073 }
Ian Rogers83883d72013-10-21 21:07:24 -07001074 bool method_code_in_boot = (method->GetDeclaringClass()->GetClassLoader() == nullptr);
1075 if (!use_dex_cache) {
1076 if (!method_code_in_boot) {
1077 use_dex_cache = true;
1078 } else {
1079 bool has_clinit_trampoline =
1080 method->IsStatic() && !method->GetDeclaringClass()->IsInitialized();
1081 if (has_clinit_trampoline && (method->GetDeclaringClass() != referrer_class)) {
1082 // Ensure we run the clinit trampoline unless we are invoking a static method in the same
1083 // class.
1084 use_dex_cache = true;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001085 }
1086 }
Ian Rogers83883d72013-10-21 21:07:24 -07001087 }
Vladimir Markof096aad2014-01-23 15:51:58 +00001088 if (method_code_in_boot) {
1089 *stats_flags |= kFlagDirectCallToBoot | kFlagDirectMethodToBoot;
Ian Rogers83883d72013-10-21 21:07:24 -07001090 }
1091 if (!use_dex_cache && compiling_boot) {
1092 MethodHelper mh(method);
Ian Rogersdfb325e2013-10-30 01:00:44 -07001093 if (!IsImageClass(mh.GetDeclaringClassDescriptor())) {
Ian Rogers83883d72013-10-21 21:07:24 -07001094 // We can only branch directly to Methods that are resolved in the DexCache.
1095 // Otherwise we won't invoke the resolution trampoline.
1096 use_dex_cache = true;
1097 }
1098 }
1099 // The method is defined not within this dex file. We need a dex cache slot within the current
1100 // dex file or direct pointers.
1101 bool must_use_direct_pointers = false;
1102 if (target_method->dex_file == method->GetDeclaringClass()->GetDexCache()->GetDexFile()) {
1103 target_method->dex_method_index = method->GetDexMethodIndex();
1104 } else {
Ian Rogers83883d72013-10-21 21:07:24 -07001105 if (no_guarantee_of_dex_cache_entry) {
1106 // See if the method is also declared in this dex cache.
1107 uint32_t dex_method_idx = MethodHelper(method).FindDexMethodIndexInOtherDexFile(
Vladimir Markobbcc0c02014-02-03 14:08:42 +00001108 *target_method->dex_file, target_method->dex_method_index);
Ian Rogers83883d72013-10-21 21:07:24 -07001109 if (dex_method_idx != DexFile::kDexNoIndex) {
1110 target_method->dex_method_index = dex_method_idx;
1111 } else {
Jeff Hao49161ce2014-03-12 11:05:25 -07001112 if (compiling_boot) {
1113 target_method->dex_method_index = method->GetDexMethodIndex();
1114 target_method->dex_file = method->GetDeclaringClass()->GetDexCache()->GetDexFile();
1115 }
Ian Rogers83883d72013-10-21 21:07:24 -07001116 must_use_direct_pointers = true;
1117 }
1118 }
1119 }
1120 if (use_dex_cache) {
1121 if (must_use_direct_pointers) {
1122 // Fail. Test above showed the only safe dispatch was via the dex cache, however, the direct
1123 // pointers are required as the dex cache lacks an appropriate entry.
1124 VLOG(compiler) << "Dex cache devirtualization failed for: " << PrettyMethod(method);
1125 } else {
1126 *type = sharp_type;
1127 }
1128 } else {
1129 if (compiling_boot) {
1130 *type = sharp_type;
1131 *direct_method = -1;
Jeff Hao88474b42013-10-23 16:24:40 -07001132 *direct_code = -1;
Ian Rogers83883d72013-10-21 21:07:24 -07001133 } else {
1134 bool method_in_image =
1135 Runtime::Current()->GetHeap()->FindSpaceFromObject(method, false)->IsImageSpace();
1136 if (method_in_image) {
Jeff Hao88474b42013-10-23 16:24:40 -07001137 CHECK(!method->IsAbstract());
Ian Rogers83883d72013-10-21 21:07:24 -07001138 *type = sharp_type;
1139 *direct_method = reinterpret_cast<uintptr_t>(method);
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +00001140 *direct_code = compiler_->GetEntryPointOf(method);
Ian Rogers83883d72013-10-21 21:07:24 -07001141 target_method->dex_file = method->GetDeclaringClass()->GetDexCache()->GetDexFile();
1142 target_method->dex_method_index = method->GetDexMethodIndex();
1143 } else if (!must_use_direct_pointers) {
1144 // Set the code and rely on the dex cache for the method.
1145 *type = sharp_type;
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +00001146 *direct_code = compiler_->GetEntryPointOf(method);
Ian Rogers83883d72013-10-21 21:07:24 -07001147 } else {
1148 // Direct pointers were required but none were available.
1149 VLOG(compiler) << "Dex cache devirtualization failed for: " << PrettyMethod(method);
1150 }
1151 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001152 }
1153}
1154
1155bool CompilerDriver::ComputeInvokeInfo(const DexCompilationUnit* mUnit, const uint32_t dex_pc,
Ian Rogers65ec92c2013-09-06 10:49:58 -07001156 bool update_stats, bool enable_devirtualization,
1157 InvokeType* invoke_type, MethodReference* target_method,
1158 int* vtable_idx, uintptr_t* direct_code,
1159 uintptr_t* direct_method) {
Vladimir Markof096aad2014-01-23 15:51:58 +00001160 InvokeType orig_invoke_type = *invoke_type;
1161 int stats_flags = 0;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001162 ScopedObjectAccess soa(Thread::Current());
Vladimir Markof096aad2014-01-23 15:51:58 +00001163 // Try to resolve the method and compiling method's class.
1164 mirror::ArtMethod* resolved_method;
1165 mirror::Class* referrer_class;
1166 SirtRef<mirror::DexCache> dex_cache(soa.Self(),
1167 mUnit->GetClassLinker()->FindDexCache(*mUnit->GetDexFile()));
1168 SirtRef<mirror::ClassLoader> class_loader(soa.Self(),
1169 soa.Decode<mirror::ClassLoader*>(mUnit->GetClassLoader()));
1170 {
1171 uint32_t method_idx = target_method->dex_method_index;
1172 SirtRef<mirror::ArtMethod> resolved_method_sirt(soa.Self(),
1173 ResolveMethod(soa, dex_cache, class_loader, mUnit, method_idx, orig_invoke_type));
1174 referrer_class = (resolved_method_sirt.get() != nullptr)
1175 ? ResolveCompilingMethodsClass(soa, dex_cache, class_loader, mUnit) : nullptr;
1176 resolved_method = resolved_method_sirt.get();
1177 }
1178 bool result = false;
1179 if (resolved_method != nullptr) {
1180 *vtable_idx = GetResolvedMethodVTableIndex(resolved_method, orig_invoke_type);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001181
Vladimir Markof096aad2014-01-23 15:51:58 +00001182 if (enable_devirtualization) {
1183 DCHECK(mUnit->GetVerifiedMethod() != nullptr);
1184 const MethodReference* devirt_target = mUnit->GetVerifiedMethod()->GetDevirtTarget(dex_pc);
1185
1186 stats_flags = IsFastInvoke(
1187 soa, dex_cache, class_loader, mUnit, referrer_class, resolved_method,
1188 invoke_type, target_method, devirt_target, direct_code, direct_method);
1189 result = stats_flags != 0;
1190 } else {
1191 // Devirtualization not enabled. Inline IsFastInvoke(), dropping the devirtualization parts.
1192 if (UNLIKELY(referrer_class == nullptr) ||
1193 UNLIKELY(!referrer_class->CanAccessResolvedMethod(resolved_method->GetDeclaringClass(),
1194 resolved_method, dex_cache.get(),
1195 target_method->dex_method_index)) ||
1196 *invoke_type == kSuper) {
1197 // Slow path. (Without devirtualization, all super calls go slow path as well.)
1198 } else {
1199 // Sharpening failed so generate a regular resolved method dispatch.
1200 stats_flags = kFlagMethodResolved;
1201 GetCodeAndMethodForDirectCall(invoke_type, *invoke_type, false, referrer_class, resolved_method,
1202 &stats_flags, target_method, direct_code, direct_method);
1203 result = true;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001204 }
1205 }
1206 }
Vladimir Markof096aad2014-01-23 15:51:58 +00001207 if (!result) {
1208 // Conservative defaults.
1209 *vtable_idx = -1;
1210 *direct_code = 0u;
1211 *direct_method = 0u;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001212 }
1213 if (update_stats) {
Vladimir Markof096aad2014-01-23 15:51:58 +00001214 ProcessedInvoke(orig_invoke_type, stats_flags);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001215 }
Vladimir Markof096aad2014-01-23 15:51:58 +00001216 return result;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001217}
1218
Vladimir Marko2730db02014-01-27 11:15:17 +00001219const VerifiedMethod* CompilerDriver::GetVerifiedMethod(const DexFile* dex_file,
1220 uint32_t method_idx) const {
1221 MethodReference ref(dex_file, method_idx);
1222 return verification_results_->GetVerifiedMethod(ref);
1223}
1224
1225bool CompilerDriver::IsSafeCast(const DexCompilationUnit* mUnit, uint32_t dex_pc) {
1226 DCHECK(mUnit->GetVerifiedMethod() != nullptr);
1227 bool result = mUnit->GetVerifiedMethod()->IsSafeCast(dex_pc);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001228 if (result) {
1229 stats_->SafeCast();
1230 } else {
1231 stats_->NotASafeCast();
1232 }
1233 return result;
1234}
1235
Brian Carlstrom7940e442013-07-12 13:46:57 -07001236void CompilerDriver::AddCodePatch(const DexFile* dex_file,
Ian Rogers8b2c0b92013-09-19 02:56:49 -07001237 uint16_t referrer_class_def_idx,
1238 uint32_t referrer_method_idx,
1239 InvokeType referrer_invoke_type,
1240 uint32_t target_method_idx,
Jeff Hao49161ce2014-03-12 11:05:25 -07001241 const DexFile* target_dex_file,
Ian Rogers8b2c0b92013-09-19 02:56:49 -07001242 InvokeType target_invoke_type,
1243 size_t literal_offset) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001244 MutexLock mu(Thread::Current(), compiled_methods_lock_);
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001245 code_to_patch_.push_back(new CallPatchInformation(dex_file,
1246 referrer_class_def_idx,
1247 referrer_method_idx,
1248 referrer_invoke_type,
1249 target_method_idx,
Jeff Hao49161ce2014-03-12 11:05:25 -07001250 target_dex_file,
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001251 target_invoke_type,
1252 literal_offset));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001253}
Mark Mendell55d0eac2014-02-06 11:02:52 -08001254void CompilerDriver::AddRelativeCodePatch(const DexFile* dex_file,
1255 uint16_t referrer_class_def_idx,
1256 uint32_t referrer_method_idx,
1257 InvokeType referrer_invoke_type,
1258 uint32_t target_method_idx,
Jeff Hao49161ce2014-03-12 11:05:25 -07001259 const DexFile* target_dex_file,
Mark Mendell55d0eac2014-02-06 11:02:52 -08001260 InvokeType target_invoke_type,
1261 size_t literal_offset,
1262 int32_t pc_relative_offset) {
1263 MutexLock mu(Thread::Current(), compiled_methods_lock_);
1264 code_to_patch_.push_back(new RelativeCallPatchInformation(dex_file,
1265 referrer_class_def_idx,
1266 referrer_method_idx,
1267 referrer_invoke_type,
1268 target_method_idx,
Jeff Hao49161ce2014-03-12 11:05:25 -07001269 target_dex_file,
Mark Mendell55d0eac2014-02-06 11:02:52 -08001270 target_invoke_type,
1271 literal_offset,
1272 pc_relative_offset));
1273}
Brian Carlstrom7940e442013-07-12 13:46:57 -07001274void CompilerDriver::AddMethodPatch(const DexFile* dex_file,
Ian Rogers8b2c0b92013-09-19 02:56:49 -07001275 uint16_t referrer_class_def_idx,
1276 uint32_t referrer_method_idx,
1277 InvokeType referrer_invoke_type,
1278 uint32_t target_method_idx,
Jeff Hao49161ce2014-03-12 11:05:25 -07001279 const DexFile* target_dex_file,
Ian Rogers8b2c0b92013-09-19 02:56:49 -07001280 InvokeType target_invoke_type,
1281 size_t literal_offset) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001282 MutexLock mu(Thread::Current(), compiled_methods_lock_);
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001283 methods_to_patch_.push_back(new CallPatchInformation(dex_file,
1284 referrer_class_def_idx,
1285 referrer_method_idx,
1286 referrer_invoke_type,
1287 target_method_idx,
Jeff Hao49161ce2014-03-12 11:05:25 -07001288 target_dex_file,
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001289 target_invoke_type,
1290 literal_offset));
1291}
1292void CompilerDriver::AddClassPatch(const DexFile* dex_file,
1293 uint16_t referrer_class_def_idx,
1294 uint32_t referrer_method_idx,
1295 uint32_t target_type_idx,
1296 size_t literal_offset) {
1297 MutexLock mu(Thread::Current(), compiled_methods_lock_);
1298 classes_to_patch_.push_back(new TypePatchInformation(dex_file,
1299 referrer_class_def_idx,
1300 referrer_method_idx,
1301 target_type_idx,
1302 literal_offset));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001303}
1304
1305class ParallelCompilationManager {
1306 public:
1307 typedef void Callback(const ParallelCompilationManager* manager, size_t index);
1308
1309 ParallelCompilationManager(ClassLinker* class_linker,
1310 jobject class_loader,
1311 CompilerDriver* compiler,
1312 const DexFile* dex_file,
Ian Rogers3d504072014-03-01 09:16:49 -08001313 ThreadPool* thread_pool)
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001314 : index_(0),
1315 class_linker_(class_linker),
Brian Carlstrom7940e442013-07-12 13:46:57 -07001316 class_loader_(class_loader),
1317 compiler_(compiler),
1318 dex_file_(dex_file),
Ian Rogers3d504072014-03-01 09:16:49 -08001319 thread_pool_(thread_pool) {}
Brian Carlstrom7940e442013-07-12 13:46:57 -07001320
1321 ClassLinker* GetClassLinker() const {
1322 CHECK(class_linker_ != NULL);
1323 return class_linker_;
1324 }
1325
1326 jobject GetClassLoader() const {
1327 return class_loader_;
1328 }
1329
1330 CompilerDriver* GetCompiler() const {
1331 CHECK(compiler_ != NULL);
1332 return compiler_;
1333 }
1334
1335 const DexFile* GetDexFile() const {
1336 CHECK(dex_file_ != NULL);
1337 return dex_file_;
1338 }
1339
1340 void ForAll(size_t begin, size_t end, Callback callback, size_t work_units) {
1341 Thread* self = Thread::Current();
1342 self->AssertNoPendingException();
1343 CHECK_GT(work_units, 0U);
1344
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001345 index_ = begin;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001346 for (size_t i = 0; i < work_units; ++i) {
Sebastien Hertz501baec2013-12-13 12:02:36 +01001347 thread_pool_->AddTask(self, new ForAllClosure(this, end, callback));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001348 }
1349 thread_pool_->StartWorkers(self);
1350
1351 // Ensure we're suspended while we're blocked waiting for the other threads to finish (worker
1352 // thread destructor's called below perform join).
1353 CHECK_NE(self->GetState(), kRunnable);
1354
1355 // Wait for all the worker threads to finish.
1356 thread_pool_->Wait(self, true, false);
1357 }
1358
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001359 size_t NextIndex() {
Ian Rogersb122a4b2013-11-19 18:00:50 -08001360 return index_.FetchAndAdd(1);
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001361 }
1362
Brian Carlstrom7940e442013-07-12 13:46:57 -07001363 private:
Brian Carlstrom7940e442013-07-12 13:46:57 -07001364 class ForAllClosure : public Task {
1365 public:
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001366 ForAllClosure(ParallelCompilationManager* manager, size_t end, Callback* callback)
Brian Carlstrom7940e442013-07-12 13:46:57 -07001367 : manager_(manager),
Brian Carlstrom7940e442013-07-12 13:46:57 -07001368 end_(end),
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001369 callback_(callback) {}
Brian Carlstrom7940e442013-07-12 13:46:57 -07001370
1371 virtual void Run(Thread* self) {
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001372 while (true) {
1373 const size_t index = manager_->NextIndex();
1374 if (UNLIKELY(index >= end_)) {
1375 break;
1376 }
1377 callback_(manager_, index);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001378 self->AssertNoPendingException();
1379 }
1380 }
1381
1382 virtual void Finalize() {
1383 delete this;
1384 }
Brian Carlstrom0cd7ec22013-07-17 23:40:20 -07001385
Brian Carlstrom7940e442013-07-12 13:46:57 -07001386 private:
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001387 ParallelCompilationManager* const manager_;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001388 const size_t end_;
Bernhard Rosenkränzer46053622013-12-12 02:15:52 +01001389 Callback* const callback_;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001390 };
1391
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001392 AtomicInteger index_;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001393 ClassLinker* const class_linker_;
1394 const jobject class_loader_;
1395 CompilerDriver* const compiler_;
1396 const DexFile* const dex_file_;
1397 ThreadPool* const thread_pool_;
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001398
1399 DISALLOW_COPY_AND_ASSIGN(ParallelCompilationManager);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001400};
1401
Jeff Hao0e49b422013-11-08 12:16:56 -08001402// Return true if the class should be skipped during compilation.
1403//
1404// The first case where we skip is for redundant class definitions in
1405// the boot classpath. We skip all but the first definition in that case.
1406//
1407// The second case where we skip is when an app bundles classes found
1408// in the boot classpath. Since at runtime we will select the class from
1409// the boot classpath, we ignore the one from the app.
Ian Rogersbe7149f2013-08-20 09:29:39 -07001410static bool SkipClass(ClassLinker* class_linker, jobject class_loader, const DexFile& dex_file,
1411 const DexFile::ClassDef& class_def) {
Jeff Hao0e49b422013-11-08 12:16:56 -08001412 const char* descriptor = dex_file.GetClassDescriptor(class_def);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001413 if (class_loader == NULL) {
Jeff Hao0e49b422013-11-08 12:16:56 -08001414 DexFile::ClassPathEntry pair = DexFile::FindInClassPath(descriptor, class_linker->GetBootClassPath());
1415 CHECK(pair.second != NULL);
1416 if (pair.first != &dex_file) {
1417 LOG(WARNING) << "Skipping class " << descriptor << " from " << dex_file.GetLocation()
1418 << " previously found in " << pair.first->GetLocation();
1419 return true;
1420 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001421 return false;
1422 }
Ian Rogersbe7149f2013-08-20 09:29:39 -07001423 return class_linker->IsInBootClassPath(descriptor);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001424}
1425
Jeff Hao0e49b422013-11-08 12:16:56 -08001426// A fast version of SkipClass above if the class pointer is available
1427// that avoids the expensive FindInClassPath search.
1428static bool SkipClass(jobject class_loader, const DexFile& dex_file, mirror::Class* klass)
1429 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1430 DCHECK(klass != NULL);
1431 const DexFile& original_dex_file = *klass->GetDexCache()->GetDexFile();
1432 if (&dex_file != &original_dex_file) {
1433 if (class_loader == NULL) {
1434 LOG(WARNING) << "Skipping class " << PrettyDescriptor(klass) << " from "
1435 << dex_file.GetLocation() << " previously found in "
1436 << original_dex_file.GetLocation();
1437 }
1438 return true;
1439 }
1440 return false;
1441}
1442
Ian Rogerse6bb3b22013-08-19 21:51:45 -07001443static void ResolveClassFieldsAndMethods(const ParallelCompilationManager* manager,
1444 size_t class_def_index)
Brian Carlstrom7940e442013-07-12 13:46:57 -07001445 LOCKS_EXCLUDED(Locks::mutator_lock_) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07001446 ATRACE_CALL();
Ian Rogersbe7149f2013-08-20 09:29:39 -07001447 Thread* self = Thread::Current();
1448 jobject jclass_loader = manager->GetClassLoader();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001449 const DexFile& dex_file = *manager->GetDexFile();
Ian Rogersbe7149f2013-08-20 09:29:39 -07001450 ClassLinker* class_linker = manager->GetClassLinker();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001451
Ian Rogerse6bb3b22013-08-19 21:51:45 -07001452 // If an instance field is final then we need to have a barrier on the return, static final
1453 // fields are assigned within the lock held for class initialization. Conservatively assume
1454 // constructor barriers are always required.
1455 bool requires_constructor_barrier = true;
1456
Brian Carlstrom7940e442013-07-12 13:46:57 -07001457 // Method and Field are the worst. We can't resolve without either
1458 // context from the code use (to disambiguate virtual vs direct
1459 // method and instance vs static field) or from class
1460 // definitions. While the compiler will resolve what it can as it
1461 // needs it, here we try to resolve fields and methods used in class
1462 // definitions, since many of them many never be referenced by
1463 // generated code.
1464 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
Ian Rogersbe7149f2013-08-20 09:29:39 -07001465 if (!SkipClass(class_linker, jclass_loader, dex_file, class_def)) {
Brian Carlstromcb5f5e52013-09-23 17:48:16 -07001466 ScopedObjectAccess soa(self);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001467 SirtRef<mirror::ClassLoader> class_loader(soa.Self(), soa.Decode<mirror::ClassLoader*>(jclass_loader));
1468 SirtRef<mirror::DexCache> dex_cache(soa.Self(), class_linker->FindDexCache(dex_file));
Brian Carlstromcb5f5e52013-09-23 17:48:16 -07001469 // Resolve the class.
1470 mirror::Class* klass = class_linker->ResolveType(dex_file, class_def.class_idx_, dex_cache,
1471 class_loader);
Brian Carlstromcb5f5e52013-09-23 17:48:16 -07001472 bool resolve_fields_and_methods;
1473 if (klass == NULL) {
1474 // Class couldn't be resolved, for example, super-class is in a different dex file. Don't
1475 // attempt to resolve methods and fields when there is no declaring class.
1476 CHECK(soa.Self()->IsExceptionPending());
1477 soa.Self()->ClearException();
1478 resolve_fields_and_methods = false;
1479 } else {
1480 resolve_fields_and_methods = manager->GetCompiler()->IsImage();
1481 }
Ian Rogerse6bb3b22013-08-19 21:51:45 -07001482 // Note the class_data pointer advances through the headers,
1483 // static fields, instance fields, direct methods, and virtual
1484 // methods.
1485 const byte* class_data = dex_file.GetClassData(class_def);
1486 if (class_data == NULL) {
1487 // Empty class such as a marker interface.
1488 requires_constructor_barrier = false;
1489 } else {
Ian Rogerse6bb3b22013-08-19 21:51:45 -07001490 ClassDataItemIterator it(dex_file, class_data);
1491 while (it.HasNextStaticField()) {
1492 if (resolve_fields_and_methods) {
1493 mirror::ArtField* field = class_linker->ResolveField(dex_file, it.GetMemberIndex(),
1494 dex_cache, class_loader, true);
1495 if (field == NULL) {
1496 CHECK(soa.Self()->IsExceptionPending());
1497 soa.Self()->ClearException();
1498 }
1499 }
1500 it.Next();
1501 }
1502 // We require a constructor barrier if there are final instance fields.
1503 requires_constructor_barrier = false;
1504 while (it.HasNextInstanceField()) {
1505 if ((it.GetMemberAccessFlags() & kAccFinal) != 0) {
1506 requires_constructor_barrier = true;
1507 }
1508 if (resolve_fields_and_methods) {
1509 mirror::ArtField* field = class_linker->ResolveField(dex_file, it.GetMemberIndex(),
1510 dex_cache, class_loader, false);
1511 if (field == NULL) {
1512 CHECK(soa.Self()->IsExceptionPending());
1513 soa.Self()->ClearException();
1514 }
1515 }
1516 it.Next();
1517 }
1518 if (resolve_fields_and_methods) {
1519 while (it.HasNextDirectMethod()) {
1520 mirror::ArtMethod* method = class_linker->ResolveMethod(dex_file, it.GetMemberIndex(),
1521 dex_cache, class_loader, NULL,
1522 it.GetMethodInvokeType(class_def));
1523 if (method == NULL) {
1524 CHECK(soa.Self()->IsExceptionPending());
1525 soa.Self()->ClearException();
1526 }
1527 it.Next();
1528 }
1529 while (it.HasNextVirtualMethod()) {
1530 mirror::ArtMethod* method = class_linker->ResolveMethod(dex_file, it.GetMemberIndex(),
1531 dex_cache, class_loader, NULL,
1532 it.GetMethodInvokeType(class_def));
1533 if (method == NULL) {
1534 CHECK(soa.Self()->IsExceptionPending());
1535 soa.Self()->ClearException();
1536 }
1537 it.Next();
1538 }
1539 DCHECK(!it.HasNext());
1540 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001541 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001542 }
1543 if (requires_constructor_barrier) {
Ian Rogersbe7149f2013-08-20 09:29:39 -07001544 manager->GetCompiler()->AddRequiresConstructorBarrier(self, &dex_file, class_def_index);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001545 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001546}
1547
1548static void ResolveType(const ParallelCompilationManager* manager, size_t type_idx)
1549 LOCKS_EXCLUDED(Locks::mutator_lock_) {
1550 // Class derived values are more complicated, they require the linker and loader.
1551 ScopedObjectAccess soa(Thread::Current());
1552 ClassLinker* class_linker = manager->GetClassLinker();
1553 const DexFile& dex_file = *manager->GetDexFile();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001554 SirtRef<mirror::DexCache> dex_cache(soa.Self(), class_linker->FindDexCache(dex_file));
Mathieu Chartierc528dba2013-11-26 12:00:11 -08001555 SirtRef<mirror::ClassLoader> class_loader(
1556 soa.Self(), soa.Decode<mirror::ClassLoader*>(manager->GetClassLoader()));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001557 mirror::Class* klass = class_linker->ResolveType(dex_file, type_idx, dex_cache, class_loader);
1558
1559 if (klass == NULL) {
1560 CHECK(soa.Self()->IsExceptionPending());
Ian Rogersa436fde2013-08-27 23:34:06 -07001561 mirror::Throwable* exception = soa.Self()->GetException(NULL);
1562 VLOG(compiler) << "Exception during type resolution: " << exception->Dump();
Ian Rogersdfb325e2013-10-30 01:00:44 -07001563 if (strcmp("Ljava/lang/OutOfMemoryError;",
1564 ClassHelper(exception->GetClass()).GetDescriptor()) == 0) {
Ian Rogersa436fde2013-08-27 23:34:06 -07001565 // There's little point continuing compilation if the heap is exhausted.
1566 LOG(FATAL) << "Out of memory during type resolution for compilation";
1567 }
1568 soa.Self()->ClearException();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001569 }
1570}
1571
1572void CompilerDriver::ResolveDexFile(jobject class_loader, const DexFile& dex_file,
Ian Rogers3d504072014-03-01 09:16:49 -08001573 ThreadPool* thread_pool, TimingLogger* timings) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001574 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1575
1576 // TODO: we could resolve strings here, although the string table is largely filled with class
1577 // and method names.
1578
1579 ParallelCompilationManager context(class_linker, class_loader, this, &dex_file, thread_pool);
Ian Rogerse6bb3b22013-08-19 21:51:45 -07001580 if (IsImage()) {
1581 // For images we resolve all types, such as array, whereas for applications just those with
1582 // classdefs are resolved by ResolveClassFieldsAndMethods.
Ian Rogers3d504072014-03-01 09:16:49 -08001583 timings->NewSplit("Resolve Types");
Ian Rogerse6bb3b22013-08-19 21:51:45 -07001584 context.ForAll(0, dex_file.NumTypeIds(), ResolveType, thread_count_);
1585 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001586
Ian Rogers3d504072014-03-01 09:16:49 -08001587 timings->NewSplit("Resolve MethodsAndFields");
Brian Carlstrom7940e442013-07-12 13:46:57 -07001588 context.ForAll(0, dex_file.NumClassDefs(), ResolveClassFieldsAndMethods, thread_count_);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001589}
1590
1591void CompilerDriver::Verify(jobject class_loader, const std::vector<const DexFile*>& dex_files,
Ian Rogers3d504072014-03-01 09:16:49 -08001592 ThreadPool* thread_pool, TimingLogger* timings) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001593 for (size_t i = 0; i != dex_files.size(); ++i) {
1594 const DexFile* dex_file = dex_files[i];
1595 CHECK(dex_file != NULL);
1596 VerifyDexFile(class_loader, *dex_file, thread_pool, timings);
1597 }
1598}
1599
1600static void VerifyClass(const ParallelCompilationManager* manager, size_t class_def_index)
1601 LOCKS_EXCLUDED(Locks::mutator_lock_) {
Anwar Ghuloum67f99412013-08-12 14:19:48 -07001602 ATRACE_CALL();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001603 ScopedObjectAccess soa(Thread::Current());
Jeff Hao0e49b422013-11-08 12:16:56 -08001604 const DexFile& dex_file = *manager->GetDexFile();
1605 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
1606 const char* descriptor = dex_file.GetClassDescriptor(class_def);
1607 ClassLinker* class_linker = manager->GetClassLinker();
1608 jobject jclass_loader = manager->GetClassLoader();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001609 SirtRef<mirror::ClassLoader> class_loader(
1610 soa.Self(), soa.Decode<mirror::ClassLoader*>(jclass_loader));
Ian Rogers98379392014-02-24 16:53:16 -08001611 SirtRef<mirror::Class> klass(soa.Self(), class_linker->FindClass(soa.Self(), descriptor,
1612 class_loader));
Mathieu Chartierc528dba2013-11-26 12:00:11 -08001613 if (klass.get() == nullptr) {
Ian Rogerse6bb3b22013-08-19 21:51:45 -07001614 CHECK(soa.Self()->IsExceptionPending());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001615 soa.Self()->ClearException();
1616
1617 /*
1618 * At compile time, we can still structurally verify the class even if FindClass fails.
1619 * This is to ensure the class is structurally sound for compilation. An unsound class
1620 * will be rejected by the verifier and later skipped during compilation in the compiler.
1621 */
Mathieu Chartier590fee92013-09-13 13:46:47 -07001622 SirtRef<mirror::DexCache> dex_cache(soa.Self(), class_linker->FindDexCache(dex_file));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001623 std::string error_msg;
Mathieu Chartier590fee92013-09-13 13:46:47 -07001624 if (verifier::MethodVerifier::VerifyClass(&dex_file, dex_cache, class_loader, &class_def, true,
1625 &error_msg) ==
Brian Carlstrom7940e442013-07-12 13:46:57 -07001626 verifier::MethodVerifier::kHardFailure) {
Jeff Hao0e49b422013-11-08 12:16:56 -08001627 LOG(ERROR) << "Verification failed on class " << PrettyDescriptor(descriptor)
Brian Carlstrom7940e442013-07-12 13:46:57 -07001628 << " because: " << error_msg;
1629 }
Mathieu Chartierc528dba2013-11-26 12:00:11 -08001630 } else if (!SkipClass(jclass_loader, dex_file, klass.get())) {
1631 CHECK(klass->IsResolved()) << PrettyClass(klass.get());
Jeff Hao0e49b422013-11-08 12:16:56 -08001632 class_linker->VerifyClass(klass);
Ian Rogerse6bb3b22013-08-19 21:51:45 -07001633
1634 if (klass->IsErroneous()) {
1635 // ClassLinker::VerifyClass throws, which isn't useful in the compiler.
1636 CHECK(soa.Self()->IsExceptionPending());
1637 soa.Self()->ClearException();
1638 }
1639
1640 CHECK(klass->IsCompileTimeVerified() || klass->IsErroneous())
Mathieu Chartierc528dba2013-11-26 12:00:11 -08001641 << PrettyDescriptor(klass.get()) << ": state=" << klass->GetStatus();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001642 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001643 soa.Self()->AssertNoPendingException();
1644}
1645
1646void CompilerDriver::VerifyDexFile(jobject class_loader, const DexFile& dex_file,
Ian Rogers3d504072014-03-01 09:16:49 -08001647 ThreadPool* thread_pool, TimingLogger* timings) {
1648 timings->NewSplit("Verify Dex File");
Brian Carlstrom7940e442013-07-12 13:46:57 -07001649 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1650 ParallelCompilationManager context(class_linker, class_loader, this, &dex_file, thread_pool);
1651 context.ForAll(0, dex_file.NumClassDefs(), VerifyClass, thread_count_);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001652}
1653
Brian Carlstrom7940e442013-07-12 13:46:57 -07001654static void InitializeClass(const ParallelCompilationManager* manager, size_t class_def_index)
1655 LOCKS_EXCLUDED(Locks::mutator_lock_) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07001656 ATRACE_CALL();
Jeff Hao0e49b422013-11-08 12:16:56 -08001657 jobject jclass_loader = manager->GetClassLoader();
1658 const DexFile& dex_file = *manager->GetDexFile();
1659 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
Jeff Haobcdbbfe2013-11-08 18:03:22 -08001660 const DexFile::TypeId& class_type_id = dex_file.GetTypeId(class_def.class_idx_);
1661 const char* descriptor = dex_file.StringDataByIdx(class_type_id.descriptor_idx_);
Ian Rogersfc0e94b2013-09-23 23:51:32 -07001662
Brian Carlstrom7940e442013-07-12 13:46:57 -07001663 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartier590fee92013-09-13 13:46:47 -07001664 SirtRef<mirror::ClassLoader> class_loader(soa.Self(),
1665 soa.Decode<mirror::ClassLoader*>(jclass_loader));
Mathieu Chartierc528dba2013-11-26 12:00:11 -08001666 SirtRef<mirror::Class> klass(soa.Self(),
Ian Rogers98379392014-02-24 16:53:16 -08001667 manager->GetClassLinker()->FindClass(soa.Self(), descriptor,
1668 class_loader));
Jeff Hao0e49b422013-11-08 12:16:56 -08001669
Mathieu Chartierc528dba2013-11-26 12:00:11 -08001670 if (klass.get() != nullptr && !SkipClass(jclass_loader, dex_file, klass.get())) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001671 // Only try to initialize classes that were successfully verified.
1672 if (klass->IsVerified()) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07001673 // Attempt to initialize the class but bail if we either need to initialize the super-class
1674 // or static fields.
1675 manager->GetClassLinker()->EnsureInitialized(klass, false, false);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001676 if (!klass->IsInitialized()) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07001677 // We don't want non-trivial class initialization occurring on multiple threads due to
1678 // deadlock problems. For example, a parent class is initialized (holding its lock) that
1679 // refers to a sub-class in its static/class initializer causing it to try to acquire the
1680 // sub-class' lock. While on a second thread the sub-class is initialized (holding its lock)
1681 // after first initializing its parents, whose locks are acquired. This leads to a
1682 // parent-to-child and a child-to-parent lock ordering and consequent potential deadlock.
1683 // We need to use an ObjectLock due to potential suspension in the interpreting code. Rather
1684 // than use a special Object for the purpose we use the Class of java.lang.Class.
Mathieu Chartierc528dba2013-11-26 12:00:11 -08001685 SirtRef<mirror::Class> sirt_klass(soa.Self(), klass->GetClass());
1686 ObjectLock<mirror::Class> lock(soa.Self(), &sirt_klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07001687 // Attempt to initialize allowing initialization of parent classes but still not static
1688 // fields.
1689 manager->GetClassLinker()->EnsureInitialized(klass, false, true);
1690 if (!klass->IsInitialized()) {
1691 // We need to initialize static fields, we only do this for image classes that aren't
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001692 // marked with the $NoPreloadHolder (which implies this should not be initialized early).
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07001693 bool can_init_static_fields = manager->GetCompiler()->IsImage() &&
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001694 manager->GetCompiler()->IsImageClass(descriptor) &&
1695 !StringPiece(descriptor).ends_with("$NoPreloadHolder;");
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07001696 if (can_init_static_fields) {
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001697 VLOG(compiler) << "Initializing: " << descriptor;
1698 if (strcmp("Ljava/lang/Void;", descriptor) == 0) {
1699 // Hand initialize j.l.Void to avoid Dex file operations in un-started runtime.
1700 ObjectLock<mirror::Class> lock(soa.Self(), &klass);
1701 mirror::ObjectArray<mirror::ArtField>* fields = klass->GetSFields();
1702 CHECK_EQ(fields->GetLength(), 1);
1703 fields->Get(0)->SetObj<false>(klass.get(),
1704 manager->GetClassLinker()->FindPrimitiveClass('V'));
1705 klass->SetStatus(mirror::Class::kStatusInitialized, soa.Self());
1706 } else {
1707 // TODO multithreading support. We should ensure the current compilation thread has
1708 // exclusive access to the runtime and the transaction. To achieve this, we could use
1709 // a ReaderWriterMutex but we're holding the mutator lock so we fail mutex sanity
1710 // checks in Thread::AssertThreadSuspensionIsAllowable.
1711 Runtime* const runtime = Runtime::Current();
1712 Transaction transaction;
1713
1714 // Run the class initializer in transaction mode.
1715 runtime->EnterTransactionMode(&transaction);
1716 const mirror::Class::Status old_status = klass->GetStatus();
1717 bool success = manager->GetClassLinker()->EnsureInitialized(klass, true, true);
1718 // TODO we detach transaction from runtime to indicate we quit the transactional
1719 // mode which prevents the GC from visiting objects modified during the transaction.
1720 // Ensure GC is not run so don't access freed objects when aborting transaction.
1721 const char* old_casue = soa.Self()->StartAssertNoThreadSuspension("Transaction end");
1722 runtime->ExitTransactionMode();
1723
1724 if (!success) {
1725 CHECK(soa.Self()->IsExceptionPending());
1726 ThrowLocation throw_location;
1727 mirror::Throwable* exception = soa.Self()->GetException(&throw_location);
1728 VLOG(compiler) << "Initialization of " << descriptor << " aborted because of "
1729 << exception->Dump();
1730 soa.Self()->ClearException();
1731 transaction.Abort();
1732 CHECK_EQ(old_status, klass->GetStatus()) << "Previous class status not restored";
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07001733 }
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001734 soa.Self()->EndAssertNoThreadSuspension(old_casue);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001735 }
1736 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001737 }
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07001738 soa.Self()->AssertNoPendingException();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001739 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001740 }
1741 // Record the final class status if necessary.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001742 ClassReference ref(manager->GetDexFile(), class_def_index);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07001743 manager->GetCompiler()->RecordClassStatus(ref, klass->GetStatus());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001744 }
1745 // Clear any class not found or verification exceptions.
1746 soa.Self()->ClearException();
1747}
1748
1749void CompilerDriver::InitializeClasses(jobject jni_class_loader, const DexFile& dex_file,
Ian Rogers3d504072014-03-01 09:16:49 -08001750 ThreadPool* thread_pool, TimingLogger* timings) {
1751 timings->NewSplit("InitializeNoClinit");
Brian Carlstrom7940e442013-07-12 13:46:57 -07001752 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1753 ParallelCompilationManager context(class_linker, jni_class_loader, this, &dex_file, thread_pool);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001754 size_t thread_count;
1755 if (IsImage()) {
1756 // TODO: remove this when transactional mode supports multithreading.
1757 thread_count = 1U;
1758 } else {
1759 thread_count = thread_count_;
1760 }
1761 context.ForAll(0, dex_file.NumClassDefs(), InitializeClass, thread_count);
1762 if (IsImage()) {
1763 // Prune garbage objects created during aborted transactions.
1764 Runtime::Current()->GetHeap()->CollectGarbage(true);
1765 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001766}
1767
1768void CompilerDriver::InitializeClasses(jobject class_loader,
1769 const std::vector<const DexFile*>& dex_files,
Ian Rogers3d504072014-03-01 09:16:49 -08001770 ThreadPool* thread_pool, TimingLogger* timings) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001771 for (size_t i = 0; i != dex_files.size(); ++i) {
1772 const DexFile* dex_file = dex_files[i];
1773 CHECK(dex_file != NULL);
1774 InitializeClasses(class_loader, *dex_file, thread_pool, timings);
1775 }
1776}
1777
1778void CompilerDriver::Compile(jobject class_loader, const std::vector<const DexFile*>& dex_files,
Ian Rogers3d504072014-03-01 09:16:49 -08001779 ThreadPool* thread_pool, TimingLogger* timings) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001780 for (size_t i = 0; i != dex_files.size(); ++i) {
1781 const DexFile* dex_file = dex_files[i];
1782 CHECK(dex_file != NULL);
1783 CompileDexFile(class_loader, *dex_file, thread_pool, timings);
1784 }
1785}
1786
1787void CompilerDriver::CompileClass(const ParallelCompilationManager* manager, size_t class_def_index) {
Anwar Ghuloum67f99412013-08-12 14:19:48 -07001788 ATRACE_CALL();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001789 jobject jclass_loader = manager->GetClassLoader();
1790 const DexFile& dex_file = *manager->GetDexFile();
1791 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
Ian Rogersbe7149f2013-08-20 09:29:39 -07001792 ClassLinker* class_linker = manager->GetClassLinker();
1793 if (SkipClass(class_linker, jclass_loader, dex_file, class_def)) {
1794 return;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001795 }
1796 ClassReference ref(&dex_file, class_def_index);
1797 // Skip compiling classes with generic verifier failures since they will still fail at runtime
Vladimir Markoc7f83202014-01-24 17:55:18 +00001798 if (manager->GetCompiler()->verification_results_->IsClassRejected(ref)) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001799 return;
1800 }
1801 const byte* class_data = dex_file.GetClassData(class_def);
1802 if (class_data == NULL) {
1803 // empty class, probably a marker interface
1804 return;
1805 }
Anwar Ghuloum67f99412013-08-12 14:19:48 -07001806
Brian Carlstrom7940e442013-07-12 13:46:57 -07001807 // Can we run DEX-to-DEX compiler on this class ?
Sebastien Hertz75021222013-07-16 18:34:50 +02001808 DexToDexCompilationLevel dex_to_dex_compilation_level = kDontDexToDexCompile;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001809 {
1810 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartier590fee92013-09-13 13:46:47 -07001811 SirtRef<mirror::ClassLoader> class_loader(soa.Self(),
1812 soa.Decode<mirror::ClassLoader*>(jclass_loader));
Ian Rogers98379392014-02-24 16:53:16 -08001813 dex_to_dex_compilation_level = GetDexToDexCompilationlevel(soa.Self(), class_loader, dex_file,
1814 class_def);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001815 }
1816 ClassDataItemIterator it(dex_file, class_data);
1817 // Skip fields
1818 while (it.HasNextStaticField()) {
1819 it.Next();
1820 }
1821 while (it.HasNextInstanceField()) {
1822 it.Next();
1823 }
Ian Rogersbe7149f2013-08-20 09:29:39 -07001824 CompilerDriver* driver = manager->GetCompiler();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001825 // Compile direct methods
1826 int64_t previous_direct_method_idx = -1;
1827 while (it.HasNextDirectMethod()) {
1828 uint32_t method_idx = it.GetMemberIndex();
1829 if (method_idx == previous_direct_method_idx) {
1830 // smali can create dex files with two encoded_methods sharing the same method_idx
1831 // http://code.google.com/p/smali/issues/detail?id=119
1832 it.Next();
1833 continue;
1834 }
1835 previous_direct_method_idx = method_idx;
Ian Rogersbe7149f2013-08-20 09:29:39 -07001836 driver->CompileMethod(it.GetMethodCodeItem(), it.GetMemberAccessFlags(),
1837 it.GetMethodInvokeType(class_def), class_def_index,
1838 method_idx, jclass_loader, dex_file, dex_to_dex_compilation_level);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001839 it.Next();
1840 }
1841 // Compile virtual methods
1842 int64_t previous_virtual_method_idx = -1;
1843 while (it.HasNextVirtualMethod()) {
1844 uint32_t method_idx = it.GetMemberIndex();
1845 if (method_idx == previous_virtual_method_idx) {
1846 // smali can create dex files with two encoded_methods sharing the same method_idx
1847 // http://code.google.com/p/smali/issues/detail?id=119
1848 it.Next();
1849 continue;
1850 }
1851 previous_virtual_method_idx = method_idx;
Ian Rogersbe7149f2013-08-20 09:29:39 -07001852 driver->CompileMethod(it.GetMethodCodeItem(), it.GetMemberAccessFlags(),
1853 it.GetMethodInvokeType(class_def), class_def_index,
1854 method_idx, jclass_loader, dex_file, dex_to_dex_compilation_level);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001855 it.Next();
1856 }
1857 DCHECK(!it.HasNext());
1858}
1859
1860void CompilerDriver::CompileDexFile(jobject class_loader, const DexFile& dex_file,
Ian Rogers3d504072014-03-01 09:16:49 -08001861 ThreadPool* thread_pool, TimingLogger* timings) {
1862 timings->NewSplit("Compile Dex File");
Ian Rogersbe7149f2013-08-20 09:29:39 -07001863 ParallelCompilationManager context(Runtime::Current()->GetClassLinker(), class_loader, this,
1864 &dex_file, thread_pool);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001865 context.ForAll(0, dex_file.NumClassDefs(), CompilerDriver::CompileClass, thread_count_);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001866}
1867
1868void CompilerDriver::CompileMethod(const DexFile::CodeItem* code_item, uint32_t access_flags,
Ian Rogers8b2c0b92013-09-19 02:56:49 -07001869 InvokeType invoke_type, uint16_t class_def_idx,
Brian Carlstrom7940e442013-07-12 13:46:57 -07001870 uint32_t method_idx, jobject class_loader,
1871 const DexFile& dex_file,
Sebastien Hertz75021222013-07-16 18:34:50 +02001872 DexToDexCompilationLevel dex_to_dex_compilation_level) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001873 CompiledMethod* compiled_method = NULL;
1874 uint64_t start_ns = NanoTime();
1875
1876 if ((access_flags & kAccNative) != 0) {
Ian Rogers0188ab72014-03-17 16:51:53 -07001877 // Are we interpreting only and have support for generic JNI down calls?
Ian Rogers5b271492014-03-14 13:20:26 -07001878 if ((compiler_options_->GetCompilerFilter() == CompilerOptions::kInterpretOnly) &&
Stuart Monteithb95a5342014-03-12 13:32:32 +00001879 (instruction_set_ == kX86_64 || instruction_set_ == kArm64)) {
Ian Rogers5b271492014-03-14 13:20:26 -07001880 // Leaving this empty will trigger the generic JNI version
1881 } else {
1882 compiled_method = compiler_->JniCompile(*this, access_flags, method_idx, dex_file);
1883 CHECK(compiled_method != NULL);
1884 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001885 } else if ((access_flags & kAccAbstract) != 0) {
1886 } else {
Dragos Sbirlea90af14d2013-08-15 17:50:16 -07001887 MethodReference method_ref(&dex_file, method_idx);
Brian Carlstrom6449c622014-02-10 23:48:36 -08001888 bool compile = verification_results_->IsCandidateForCompilation(method_ref, access_flags);
Sebastien Hertz4d4adb12013-07-24 16:14:19 +02001889 if (compile) {
buzbeea024a062013-07-31 10:47:37 -07001890 // NOTE: if compiler declines to compile this method, it will return NULL.
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +00001891 compiled_method = compiler_->Compile(
Nicolas Geoffrayf5df8972014-02-14 18:37:08 +00001892 *this, code_item, access_flags, invoke_type, class_def_idx,
1893 method_idx, class_loader, dex_file);
Sebastien Hertz75021222013-07-16 18:34:50 +02001894 } else if (dex_to_dex_compilation_level != kDontDexToDexCompile) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001895 // TODO: add a mode to disable DEX-to-DEX compilation ?
Sebastien Hertz75021222013-07-16 18:34:50 +02001896 (*dex_to_dex_compiler_)(*this, code_item, access_flags,
1897 invoke_type, class_def_idx,
1898 method_idx, class_loader, dex_file,
1899 dex_to_dex_compilation_level);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001900 }
1901 }
1902 uint64_t duration_ns = NanoTime() - start_ns;
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +00001903 if (duration_ns > MsToNs(compiler_->GetMaximumCompilationTimeBeforeWarning())) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001904 LOG(WARNING) << "Compilation of " << PrettyMethod(method_idx, dex_file)
1905 << " took " << PrettyDuration(duration_ns);
1906 }
1907
1908 Thread* self = Thread::Current();
1909 if (compiled_method != NULL) {
1910 MethodReference ref(&dex_file, method_idx);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07001911 DCHECK(GetCompiledMethod(ref) == NULL) << PrettyMethod(method_idx, dex_file);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001912 {
1913 MutexLock mu(self, compiled_methods_lock_);
1914 compiled_methods_.Put(ref, compiled_method);
1915 }
1916 DCHECK(GetCompiledMethod(ref) != NULL) << PrettyMethod(method_idx, dex_file);
1917 }
1918
1919 if (self->IsExceptionPending()) {
1920 ScopedObjectAccess soa(self);
1921 LOG(FATAL) << "Unexpected exception compiling: " << PrettyMethod(method_idx, dex_file) << "\n"
1922 << self->GetException(NULL)->Dump();
1923 }
1924}
1925
1926CompiledClass* CompilerDriver::GetCompiledClass(ClassReference ref) const {
1927 MutexLock mu(Thread::Current(), compiled_classes_lock_);
1928 ClassTable::const_iterator it = compiled_classes_.find(ref);
1929 if (it == compiled_classes_.end()) {
1930 return NULL;
1931 }
1932 CHECK(it->second != NULL);
1933 return it->second;
1934}
1935
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07001936void CompilerDriver::RecordClassStatus(ClassReference ref, mirror::Class::Status status) {
1937 MutexLock mu(Thread::Current(), compiled_classes_lock_);
1938 auto it = compiled_classes_.find(ref);
1939 if (it == compiled_classes_.end() || it->second->GetStatus() != status) {
1940 // An entry doesn't exist or the status is lower than the new status.
1941 if (it != compiled_classes_.end()) {
1942 CHECK_GT(status, it->second->GetStatus());
1943 delete it->second;
1944 }
1945 switch (status) {
1946 case mirror::Class::kStatusNotReady:
1947 case mirror::Class::kStatusError:
1948 case mirror::Class::kStatusRetryVerificationAtRuntime:
1949 case mirror::Class::kStatusVerified:
1950 case mirror::Class::kStatusInitialized:
1951 break; // Expected states.
1952 default:
1953 LOG(FATAL) << "Unexpected class status for class "
1954 << PrettyDescriptor(ref.first->GetClassDescriptor(ref.first->GetClassDef(ref.second)))
1955 << " of " << status;
1956 }
1957 CompiledClass* compiled_class = new CompiledClass(status);
1958 compiled_classes_.Overwrite(ref, compiled_class);
1959 }
1960}
1961
Brian Carlstrom7940e442013-07-12 13:46:57 -07001962CompiledMethod* CompilerDriver::GetCompiledMethod(MethodReference ref) const {
1963 MutexLock mu(Thread::Current(), compiled_methods_lock_);
1964 MethodTable::const_iterator it = compiled_methods_.find(ref);
1965 if (it == compiled_methods_.end()) {
1966 return NULL;
1967 }
1968 CHECK(it->second != NULL);
1969 return it->second;
1970}
1971
Brian Carlstrom7940e442013-07-12 13:46:57 -07001972void CompilerDriver::AddRequiresConstructorBarrier(Thread* self, const DexFile* dex_file,
Ian Rogers8b2c0b92013-09-19 02:56:49 -07001973 uint16_t class_def_index) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07001974 WriterMutexLock mu(self, freezing_constructor_lock_);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001975 freezing_constructor_classes_.insert(ClassReference(dex_file, class_def_index));
1976}
1977
1978bool CompilerDriver::RequiresConstructorBarrier(Thread* self, const DexFile* dex_file,
Ian Rogers8b2c0b92013-09-19 02:56:49 -07001979 uint16_t class_def_index) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07001980 ReaderMutexLock mu(self, freezing_constructor_lock_);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001981 return freezing_constructor_classes_.count(ClassReference(dex_file, class_def_index)) != 0;
1982}
1983
1984bool CompilerDriver::WriteElf(const std::string& android_root,
1985 bool is_host,
1986 const std::vector<const art::DexFile*>& dex_files,
Ian Rogers3d504072014-03-01 09:16:49 -08001987 OatWriter* oat_writer,
Brian Carlstrom7940e442013-07-12 13:46:57 -07001988 art::File* file)
1989 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +00001990 return compiler_->WriteElf(file, oat_writer, dex_files, android_root, is_host, *this);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001991}
1992void CompilerDriver::InstructionSetToLLVMTarget(InstructionSet instruction_set,
Ian Rogers3d504072014-03-01 09:16:49 -08001993 std::string* target_triple,
1994 std::string* target_cpu,
1995 std::string* target_attr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001996 switch (instruction_set) {
1997 case kThumb2:
Ian Rogers3d504072014-03-01 09:16:49 -08001998 *target_triple = "thumb-none-linux-gnueabi";
1999 *target_cpu = "cortex-a9";
2000 *target_attr = "+thumb2,+neon,+neonfp,+vfp3,+db";
Brian Carlstrom7940e442013-07-12 13:46:57 -07002001 break;
2002
2003 case kArm:
Ian Rogers3d504072014-03-01 09:16:49 -08002004 *target_triple = "armv7-none-linux-gnueabi";
Brian Carlstrom7940e442013-07-12 13:46:57 -07002005 // TODO: Fix for Nexus S.
Ian Rogers3d504072014-03-01 09:16:49 -08002006 *target_cpu = "cortex-a9";
Brian Carlstrom7940e442013-07-12 13:46:57 -07002007 // TODO: Fix for Xoom.
Ian Rogers3d504072014-03-01 09:16:49 -08002008 *target_attr = "+v7,+neon,+neonfp,+vfp3,+db";
Brian Carlstrom7940e442013-07-12 13:46:57 -07002009 break;
2010
2011 case kX86:
Ian Rogers3d504072014-03-01 09:16:49 -08002012 *target_triple = "i386-pc-linux-gnu";
2013 *target_attr = "";
Brian Carlstrom7940e442013-07-12 13:46:57 -07002014 break;
2015
2016 case kMips:
Ian Rogers3d504072014-03-01 09:16:49 -08002017 *target_triple = "mipsel-unknown-linux";
2018 *target_attr = "mips32r2";
Brian Carlstrom7940e442013-07-12 13:46:57 -07002019 break;
2020
2021 default:
2022 LOG(FATAL) << "Unknown instruction set: " << instruction_set;
2023 }
2024 }
Dave Allison39c3bfb2014-01-28 18:33:52 -08002025
2026bool CompilerDriver::ReadProfile(const std::string& filename) {
2027 VLOG(compiler) << "reading profile file " << filename;
2028 struct stat st;
2029 int err = stat(filename.c_str(), &st);
2030 if (err == -1) {
2031 VLOG(compiler) << "not found";
2032 return false;
2033 }
2034 std::ifstream in(filename.c_str());
2035 if (!in) {
2036 VLOG(compiler) << "profile file " << filename << " exists but can't be opened";
2037 VLOG(compiler) << "file owner: " << st.st_uid << ":" << st.st_gid;
2038 VLOG(compiler) << "me: " << getuid() << ":" << getgid();
2039 VLOG(compiler) << "file permissions: " << std::oct << st.st_mode;
2040 VLOG(compiler) << "errno: " << errno;
2041 return false;
2042 }
2043 // The first line contains summary information.
2044 std::string line;
2045 std::getline(in, line);
2046 if (in.eof()) {
2047 return false;
2048 }
2049 std::vector<std::string> summary_info;
2050 Split(line, '/', summary_info);
2051 if (summary_info.size() != 3) {
Calin Juravle04ff2262014-04-02 19:08:47 +01002052 // Bad summary info. It should be count/total/bootpath.
Dave Allison39c3bfb2014-01-28 18:33:52 -08002053 return false;
2054 }
2055 // This is the number of hits in all methods.
2056 uint32_t total_count = 0;
2057 for (int i = 0 ; i < 3; ++i) {
Calin Juravleea1e5202014-04-02 15:41:43 +01002058 total_count += atoi(summary_info[i].c_str());
Dave Allison39c3bfb2014-01-28 18:33:52 -08002059 }
2060
Calin Juravle04ff2262014-04-02 19:08:47 +01002061 // Now read each line until the end of file. Each line consists of 3 fields separated by '/'.
2062 // Store the info in descending order given by the most used methods.
Calin Juravlef6a4cee2014-04-02 17:03:08 +01002063 typedef std::set<std::pair<int, std::vector<std::string>>> ProfileSet;
2064 ProfileSet countSet;
Dave Allison39c3bfb2014-01-28 18:33:52 -08002065 while (!in.eof()) {
2066 std::getline(in, line);
2067 if (in.eof()) {
2068 break;
2069 }
2070 std::vector<std::string> info;
2071 Split(line, '/', info);
2072 if (info.size() != 3) {
2073 // Malformed.
2074 break;
2075 }
Calin Juravlef6a4cee2014-04-02 17:03:08 +01002076 int count = atoi(info[1].c_str());
2077 countSet.insert(std::make_pair(-count, info));
2078 }
2079
2080 uint32_t curTotalCount = 0;
2081 ProfileSet::iterator end = countSet.end();
2082 const ProfileData* prevData = nullptr;
2083 for (ProfileSet::iterator it = countSet.begin(); it != end ; it++) {
2084 const std::string& methodname = it->second[0];
2085 uint32_t count = -it->first;
2086 uint32_t size = atoi(it->second[2].c_str());
2087 double usedPercent = (count * 100.0) / total_count;
2088
2089 curTotalCount += count;
Calin Juravle04ff2262014-04-02 19:08:47 +01002090 // Methods with the same count should be part of the same top K percentage bucket.
Calin Juravlef6a4cee2014-04-02 17:03:08 +01002091 double topKPercentage = (prevData != nullptr) && (prevData->GetCount() == count)
2092 ? prevData->GetTopKUsedPercentage()
2093 : 100 * static_cast<double>(curTotalCount) / static_cast<double>(total_count);
2094
Calin Juravle04ff2262014-04-02 19:08:47 +01002095 // Add it to the profile map.
Calin Juravlef6a4cee2014-04-02 17:03:08 +01002096 ProfileData curData = ProfileData(methodname, count, size, usedPercent, topKPercentage);
2097 profile_map_[methodname] = curData;
2098 prevData = &curData;
Dave Allison39c3bfb2014-01-28 18:33:52 -08002099 }
2100 return true;
2101}
2102
2103bool CompilerDriver::SkipCompilation(const std::string& method_name) {
2104 if (!profile_ok_) {
2105 return true;
2106 }
Calin Juravle04ff2262014-04-02 19:08:47 +01002107 // Methods that comprise topKPercentThreshold % of the total samples will be compiled.
2108 double topKPercentThreshold = 90.0;
2109#ifdef HAVE_ANDROID_OS
2110 char buf[PROP_VALUE_MAX];
2111 property_get("dalvik.vm.profile.compile_thr", buf, "90.0");
2112 topKPercentThreshold = strtod(buf, nullptr);
2113#endif
2114 // Test for reasonable thresholds.
2115 if (topKPercentThreshold < 10.0 || topKPercentThreshold > 90.0) {
2116 topKPercentThreshold = 90.0;
2117 }
Dave Allison39c3bfb2014-01-28 18:33:52 -08002118
2119 // First find the method in the profile map.
2120 ProfileMap::iterator i = profile_map_.find(method_name);
2121 if (i == profile_map_.end()) {
2122 // Not in profile, no information can be determined.
2123 VLOG(compiler) << "not compiling " << method_name << " because it's not in the profile";
2124 return true;
2125 }
2126 const ProfileData& data = i->second;
Calin Juravle04ff2262014-04-02 19:08:47 +01002127
Calin Juravlef6a4cee2014-04-02 17:03:08 +01002128 // Compare against the start of the topK percentage bucket just in case the threshold
Calin Juravle04ff2262014-04-02 19:08:47 +01002129 // falls inside a bucket.
2130 bool compile = data.GetTopKUsedPercentage() - data.GetUsedPercent() <= topKPercentThreshold;
Dave Allison39c3bfb2014-01-28 18:33:52 -08002131 if (compile) {
Calin Juravlef6a4cee2014-04-02 17:03:08 +01002132 LOG(INFO) << "compiling method " << method_name << " because its usage is part of top "
2133 << data.GetTopKUsedPercentage() << "% with a percent of " << data.GetUsedPercent() << "%";
Dave Allison39c3bfb2014-01-28 18:33:52 -08002134 } else {
Calin Juravle04ff2262014-04-02 19:08:47 +01002135 VLOG(compiler) << "not compiling method " << method_name << " because it's not part of leading "
2136 << topKPercentThreshold << "% samples)";
Dave Allison39c3bfb2014-01-28 18:33:52 -08002137 }
2138 return !compile;
2139}
Brian Carlstrom7940e442013-07-12 13:46:57 -07002140} // namespace art