blob: 3720dda0f8c5c2589b5866b973f572af44534e35 [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
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070019#include <unistd.h>
Andreas Gampeb0f370e2014-09-25 22:51:40 -070020#include <unordered_set>
Anwar Ghuloum67f99412013-08-12 14:19:48 -070021#include <vector>
Brian Carlstrom7940e442013-07-12 13:46:57 -070022
Mathieu Chartierab972ef2014-12-03 17:38:22 -080023#ifndef __APPLE__
24#include <malloc.h> // For mallinfo
25#endif
26
Narayan Kamathe3eae5e2016-10-27 11:47:30 +010027#include "android-base/strings.h"
28
Mathieu Chartierc7853442015-03-27 14:35:38 -070029#include "art_field-inl.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070030#include "art_method-inl.h"
Andreas Gampef0446e92017-05-16 13:51:57 -070031#include "base/arena_allocator.h"
David Brazdild9c90372016-09-14 16:53:55 +010032#include "base/array_ref.h"
Vladimir Marko492a7fa2016-06-01 18:38:43 +010033#include "base/bit_vector.h"
Andreas Gampe542451c2016-07-26 09:02:02 -070034#include "base/enums.h"
Andreas Gampe170331f2017-12-07 18:41:03 -080035#include "base/logging.h" // For VLOG
Brian Carlstrom7940e442013-07-12 13:46:57 -070036#include "base/stl_util.h"
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -080037#include "base/systrace.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010038#include "base/time_utils.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070039#include "base/timing_logger.h"
Vladimir Marko3481ba22015-04-13 12:22:36 +010040#include "class_linker-inl.h"
Vladimir Markod8dbc8d2017-09-20 13:37:47 +010041#include "compiled_method-inl.h"
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +000042#include "compiler.h"
Nicolas Geoffray6bb7f1b2016-11-03 10:52:49 +000043#include "compiler_callbacks.h"
Vladimir Markobe0e5462014-02-26 11:24:15 +000044#include "compiler_driver-inl.h"
David Sehr9e734c72018-01-04 17:56:19 -080045#include "dex/dex_file-inl.h"
46#include "dex/dex_file_annotations.h"
47#include "dex/dex_instruction-inl.h"
Andreas Gampe5eb0d382015-07-23 01:19:26 -070048#include "dex/dex_to_dex_compiler.h"
Vladimir Markoc7f83202014-01-24 17:55:18 +000049#include "dex/verification_results.h"
Vladimir Marko2730db02014-01-27 11:15:17 +000050#include "dex/verified_method.h"
Steven Morelande431e272017-07-18 16:53:49 -070051#include "dex_compilation_unit.h"
Mark Mendellae9fd932014-02-10 16:14:35 -080052#include "driver/compiler_options.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070053#include "gc/accounting/card_table-inl.h"
54#include "gc/accounting/heap_bitmap.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070055#include "gc/space/image_space.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070056#include "gc/space/space.h"
Steven Morelande431e272017-07-18 16:53:49 -070057#include "handle_scope-inl.h"
58#include "intrinsics_enum.h"
Andreas Gampe3913e482018-01-22 18:58:01 -080059#include "jit/profile_compilation_info.h"
Steven Morelande431e272017-07-18 16:53:49 -070060#include "jni_internal.h"
Vladimir Markod8dbc8d2017-09-20 13:37:47 +010061#include "linker/linker_patch.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070062#include "mirror/class-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -070063#include "mirror/class_loader.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070064#include "mirror/dex_cache-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070065#include "mirror/object-inl.h"
Andreas Gampec6ea7d02017-02-01 16:46:28 -080066#include "mirror/object-refvisitor-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070067#include "mirror/object_array-inl.h"
68#include "mirror/throwable.h"
Steven Morelande431e272017-07-18 16:53:49 -070069#include "nativehelper/ScopedLocalRef.h"
70#include "object_lock.h"
71#include "runtime.h"
Orion Hodson26ef34c2017-11-01 13:32:41 +000072#include "runtime_intrinsics.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070073#include "scoped_thread_state_change-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070074#include "thread.h"
Andreas Gampeb0f370e2014-09-25 22:51:40 -070075#include "thread_list.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070076#include "thread_pool.h"
Ian Rogers848871b2013-08-05 10:56:33 -070077#include "trampolines/trampoline_compiler.h"
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +010078#include "transaction.h"
Mathieu Chartier93764b82017-07-17 14:51:53 -070079#include "utils/atomic_dex_ref_map-inl.h"
Vladimir Marko20f85592015-03-19 10:07:02 +000080#include "utils/dex_cache_arrays_layout-inl.h"
Andreas Gampee21dc3d2014-12-08 16:59:43 -080081#include "utils/swap_space.h"
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +000082#include "vdex_file.h"
Vladimir Marko2bc47802014-02-10 09:43:07 +000083#include "verifier/method_verifier-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -070084#include "verifier/method_verifier.h"
Nicolas Geoffray08025182016-10-25 17:20:18 +010085#include "verifier/verifier_deps.h"
Andreas Gampe6d7abbd2017-04-24 13:19:09 -070086#include "verifier/verifier_enums.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070087
Brian Carlstrom7940e442013-07-12 13:46:57 -070088namespace art {
89
Mathieu Chartier8e219ae2014-08-19 14:29:46 -070090static constexpr bool kTimeCompileMethod = !kIsDebugBuild;
91
Calin Juravle226501b2015-12-11 14:41:31 +000092// Print additional info during profile guided compilation.
93static constexpr bool kDebugProfileGuidedCompilation = false;
94
Chang Xing70f689d2017-06-08 17:16:12 -070095// Max encoded fields allowed for initializing app image. Hardcode the number for now
96// because 5000 should be large enough.
97static constexpr uint32_t kMaxEncodedFields = 5000;
98
Brian Carlstrom7940e442013-07-12 13:46:57 -070099static double Percentage(size_t x, size_t y) {
100 return 100.0 * (static_cast<double>(x)) / (static_cast<double>(x + y));
101}
102
103static void DumpStat(size_t x, size_t y, const char* str) {
104 if (x == 0 && y == 0) {
105 return;
106 }
Ian Rogerse732ef12013-10-09 15:22:24 -0700107 LOG(INFO) << Percentage(x, y) << "% of " << str << " for " << (x + y) << " cases";
Brian Carlstrom7940e442013-07-12 13:46:57 -0700108}
109
Vladimir Markof096aad2014-01-23 15:51:58 +0000110class CompilerDriver::AOTCompilationStats {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700111 public:
112 AOTCompilationStats()
113 : stats_lock_("AOT compilation statistics lock"),
Brian Carlstrom7940e442013-07-12 13:46:57 -0700114 resolved_types_(0), unresolved_types_(0),
115 resolved_instance_fields_(0), unresolved_instance_fields_(0),
116 resolved_local_static_fields_(0), resolved_static_fields_(0), unresolved_static_fields_(0),
117 type_based_devirtualization_(0),
118 safe_casts_(0), not_safe_casts_(0) {
119 for (size_t i = 0; i <= kMaxInvokeType; i++) {
120 resolved_methods_[i] = 0;
121 unresolved_methods_[i] = 0;
122 virtual_made_direct_[i] = 0;
123 direct_calls_to_boot_[i] = 0;
124 direct_methods_to_boot_[i] = 0;
125 }
126 }
127
128 void Dump() {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700129 DumpStat(resolved_types_, unresolved_types_, "types resolved");
130 DumpStat(resolved_instance_fields_, unresolved_instance_fields_, "instance fields resolved");
131 DumpStat(resolved_local_static_fields_ + resolved_static_fields_, unresolved_static_fields_,
132 "static fields resolved");
133 DumpStat(resolved_local_static_fields_, resolved_static_fields_ + unresolved_static_fields_,
134 "static fields local to a class");
135 DumpStat(safe_casts_, not_safe_casts_, "check-casts removed based on type information");
136 // Note, the code below subtracts the stat value so that when added to the stat value we have
137 // 100% of samples. TODO: clean this up.
138 DumpStat(type_based_devirtualization_,
139 resolved_methods_[kVirtual] + unresolved_methods_[kVirtual] +
140 resolved_methods_[kInterface] + unresolved_methods_[kInterface] -
141 type_based_devirtualization_,
142 "virtual/interface calls made direct based on type information");
143
144 for (size_t i = 0; i <= kMaxInvokeType; i++) {
145 std::ostringstream oss;
146 oss << static_cast<InvokeType>(i) << " methods were AOT resolved";
147 DumpStat(resolved_methods_[i], unresolved_methods_[i], oss.str().c_str());
148 if (virtual_made_direct_[i] > 0) {
149 std::ostringstream oss2;
150 oss2 << static_cast<InvokeType>(i) << " methods made direct";
151 DumpStat(virtual_made_direct_[i],
152 resolved_methods_[i] + unresolved_methods_[i] - virtual_made_direct_[i],
153 oss2.str().c_str());
154 }
155 if (direct_calls_to_boot_[i] > 0) {
156 std::ostringstream oss2;
157 oss2 << static_cast<InvokeType>(i) << " method calls are direct into boot";
158 DumpStat(direct_calls_to_boot_[i],
159 resolved_methods_[i] + unresolved_methods_[i] - direct_calls_to_boot_[i],
160 oss2.str().c_str());
161 }
162 if (direct_methods_to_boot_[i] > 0) {
163 std::ostringstream oss2;
164 oss2 << static_cast<InvokeType>(i) << " method calls have methods in boot";
165 DumpStat(direct_methods_to_boot_[i],
166 resolved_methods_[i] + unresolved_methods_[i] - direct_methods_to_boot_[i],
167 oss2.str().c_str());
168 }
169 }
170 }
171
172// Allow lossy statistics in non-debug builds.
173#ifndef NDEBUG
174#define STATS_LOCK() MutexLock mu(Thread::Current(), stats_lock_)
175#else
176#define STATS_LOCK()
177#endif
178
Mathieu Chartier90443472015-07-16 20:32:27 -0700179 void TypeDoesntNeedAccessCheck() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700180 STATS_LOCK();
181 resolved_types_++;
182 }
183
Mathieu Chartier90443472015-07-16 20:32:27 -0700184 void TypeNeedsAccessCheck() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700185 STATS_LOCK();
186 unresolved_types_++;
187 }
188
Mathieu Chartier90443472015-07-16 20:32:27 -0700189 void ResolvedInstanceField() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700190 STATS_LOCK();
191 resolved_instance_fields_++;
192 }
193
Mathieu Chartier90443472015-07-16 20:32:27 -0700194 void UnresolvedInstanceField() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700195 STATS_LOCK();
196 unresolved_instance_fields_++;
197 }
198
Mathieu Chartier90443472015-07-16 20:32:27 -0700199 void ResolvedLocalStaticField() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700200 STATS_LOCK();
201 resolved_local_static_fields_++;
202 }
203
Mathieu Chartier90443472015-07-16 20:32:27 -0700204 void ResolvedStaticField() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700205 STATS_LOCK();
206 resolved_static_fields_++;
207 }
208
Mathieu Chartier90443472015-07-16 20:32:27 -0700209 void UnresolvedStaticField() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700210 STATS_LOCK();
211 unresolved_static_fields_++;
212 }
213
214 // Indicate that type information from the verifier led to devirtualization.
Mathieu Chartier90443472015-07-16 20:32:27 -0700215 void PreciseTypeDevirtualization() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700216 STATS_LOCK();
217 type_based_devirtualization_++;
218 }
219
Brian Carlstrom7940e442013-07-12 13:46:57 -0700220 // A check-cast could be eliminated due to verifier type analysis.
Mathieu Chartier90443472015-07-16 20:32:27 -0700221 void SafeCast() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700222 STATS_LOCK();
223 safe_casts_++;
224 }
225
226 // A check-cast couldn't be eliminated due to verifier type analysis.
Mathieu Chartier90443472015-07-16 20:32:27 -0700227 void NotASafeCast() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700228 STATS_LOCK();
229 not_safe_casts_++;
230 }
231
232 private:
233 Mutex stats_lock_;
234
Brian Carlstrom7940e442013-07-12 13:46:57 -0700235 size_t resolved_types_;
236 size_t unresolved_types_;
237
238 size_t resolved_instance_fields_;
239 size_t unresolved_instance_fields_;
240
241 size_t resolved_local_static_fields_;
242 size_t resolved_static_fields_;
243 size_t unresolved_static_fields_;
244 // Type based devirtualization for invoke interface and virtual.
245 size_t type_based_devirtualization_;
246
247 size_t resolved_methods_[kMaxInvokeType + 1];
248 size_t unresolved_methods_[kMaxInvokeType + 1];
249 size_t virtual_made_direct_[kMaxInvokeType + 1];
250 size_t direct_calls_to_boot_[kMaxInvokeType + 1];
251 size_t direct_methods_to_boot_[kMaxInvokeType + 1];
252
253 size_t safe_casts_;
254 size_t not_safe_casts_;
255
256 DISALLOW_COPY_AND_ASSIGN(AOTCompilationStats);
257};
258
Jeff Haodcdc85b2015-12-04 14:06:18 -0800259CompilerDriver::CompilerDriver(
260 const CompilerOptions* compiler_options,
261 VerificationResults* verification_results,
Jeff Haodcdc85b2015-12-04 14:06:18 -0800262 Compiler::Kind compiler_kind,
263 InstructionSet instruction_set,
264 const InstructionSetFeatures* instruction_set_features,
Vladimir Marko944da602016-02-19 12:27:55 +0000265 std::unordered_set<std::string>* image_classes,
Jeff Haodcdc85b2015-12-04 14:06:18 -0800266 std::unordered_set<std::string>* compiled_classes,
267 std::unordered_set<std::string>* compiled_methods,
Vladimir Marko944da602016-02-19 12:27:55 +0000268 size_t thread_count,
Vladimir Marko944da602016-02-19 12:27:55 +0000269 int swap_fd,
Calin Juravle998c2162015-12-21 15:39:33 +0200270 const ProfileCompilationInfo* profile_compilation_info)
Calin Juravle226501b2015-12-11 14:41:31 +0000271 : compiler_options_(compiler_options),
Brian Carlstrom6449c622014-02-10 23:48:36 -0800272 verification_results_(verification_results),
Ian Rogers72d32622014-05-06 16:20:11 -0700273 compiler_(Compiler::Create(this, compiler_kind)),
Jeff Hao48699fb2015-04-06 14:21:37 -0700274 compiler_kind_(compiler_kind),
Vladimir Marko33bff252017-11-01 14:35:42 +0000275 instruction_set_(
276 instruction_set == InstructionSet::kArm ? InstructionSet::kThumb2 : instruction_set),
Dave Allison70202782013-10-22 17:52:19 -0700277 instruction_set_features_(instruction_set_features),
Mathieu Chartierc4ae9162016-04-07 13:19:19 -0700278 requires_constructor_barrier_lock_("constructor barrier lock"),
Vladimir Markof4da6752014-08-01 19:04:18 +0100279 non_relative_linker_patch_count_(0u),
Brian Carlstrom7940e442013-07-12 13:46:57 -0700280 image_classes_(image_classes),
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800281 classes_to_compile_(compiled_classes),
Andreas Gampe70bef0d2015-04-15 02:37:28 -0700282 methods_to_compile_(compiled_methods),
Andreas Gampef39208f2017-10-19 15:06:59 -0700283 number_of_soft_verifier_failures_(0),
Andreas Gampe6cf49e52015-03-05 13:08:45 -0800284 had_hard_verifier_failure_(false),
Andreas Gampeace0dc12016-01-20 13:33:13 -0800285 parallel_thread_count_(thread_count),
Brian Carlstrom7940e442013-07-12 13:46:57 -0700286 stats_(new AOTCompilationStats),
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700287 compiler_context_(nullptr),
Alexey Frunze19f6c692016-11-30 19:19:55 -0800288 support_boot_image_fixup_(true),
Calin Juravle998c2162015-12-21 15:39:33 +0200289 compiled_method_storage_(swap_fd),
Calin Juravle69158982016-03-16 11:53:41 +0000290 profile_compilation_info_(profile_compilation_info),
Vladimir Marko492a7fa2016-06-01 18:38:43 +0100291 max_arena_alloc_(0),
Mathieu Chartiera79efdb2018-01-18 16:31:01 -0800292 compiling_dex_to_dex_(false),
293 dex_to_dex_compiler_(this) {
Brian Carlstrom6449c622014-02-10 23:48:36 -0800294 DCHECK(compiler_options_ != nullptr);
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700295
Ian Rogers72d32622014-05-06 16:20:11 -0700296 compiler_->Init();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700297
Vladimir Markoaad75c62016-10-03 08:46:48 +0000298 if (GetCompilerOptions().IsBootImage()) {
Mathieu Chartierc5dd3192015-12-09 16:38:30 -0800299 CHECK(image_classes_.get() != nullptr) << "Expected image classes for boot image";
300 }
Andreas Gampecac31ad2017-11-06 20:01:17 -0800301
302 compiled_method_storage_.SetDedupeEnabled(compiler_options_->DeduplicateCode());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700303}
304
305CompilerDriver::~CompilerDriver() {
Mathieu Chartier93764b82017-07-17 14:51:53 -0700306 compiled_methods_.Visit([this](const DexFileReference& ref ATTRIBUTE_UNUSED,
Mathieu Chartieracab8d42016-11-23 13:45:58 -0800307 CompiledMethod* method) {
308 if (method != nullptr) {
309 CompiledMethod::ReleaseSwapAllocatedCompiledMethod(this, method);
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800310 }
Mathieu Chartieracab8d42016-11-23 13:45:58 -0800311 });
Ian Rogers72d32622014-05-06 16:20:11 -0700312 compiler_->UnInit();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700313}
314
Vladimir Marko35831e82015-09-11 11:59:18 +0100315
Ian Rogersdd7624d2014-03-14 17:43:00 -0700316#define CREATE_TRAMPOLINE(type, abi, offset) \
Andreas Gampeaf13ad92014-04-11 12:07:48 -0700317 if (Is64BitInstructionSet(instruction_set_)) { \
Ian Rogersdd7624d2014-03-14 17:43:00 -0700318 return CreateTrampoline64(instruction_set_, abi, \
Andreas Gampe542451c2016-07-26 09:02:02 -0700319 type ## _ENTRYPOINT_OFFSET(PointerSize::k64, offset)); \
Ian Rogersdd7624d2014-03-14 17:43:00 -0700320 } else { \
321 return CreateTrampoline32(instruction_set_, abi, \
Andreas Gampe542451c2016-07-26 09:02:02 -0700322 type ## _ENTRYPOINT_OFFSET(PointerSize::k32, offset)); \
Ian Rogersdd7624d2014-03-14 17:43:00 -0700323 }
324
Vladimir Marko93205e32016-04-13 11:59:46 +0100325std::unique_ptr<const std::vector<uint8_t>> CompilerDriver::CreateJniDlsymLookup() const {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700326 CREATE_TRAMPOLINE(JNI, kJniAbi, pDlsymLookup)
Ian Rogers848871b2013-08-05 10:56:33 -0700327}
328
Vladimir Marko93205e32016-04-13 11:59:46 +0100329std::unique_ptr<const std::vector<uint8_t>> CompilerDriver::CreateQuickGenericJniTrampoline()
330 const {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700331 CREATE_TRAMPOLINE(QUICK, kQuickAbi, pQuickGenericJniTrampoline)
Andreas Gampe2da88232014-02-27 12:26:20 -0800332}
333
Vladimir Marko93205e32016-04-13 11:59:46 +0100334std::unique_ptr<const std::vector<uint8_t>> CompilerDriver::CreateQuickImtConflictTrampoline()
335 const {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700336 CREATE_TRAMPOLINE(QUICK, kQuickAbi, pQuickImtConflictTrampoline)
Jeff Hao88474b42013-10-23 16:24:40 -0700337}
338
Vladimir Marko93205e32016-04-13 11:59:46 +0100339std::unique_ptr<const std::vector<uint8_t>> CompilerDriver::CreateQuickResolutionTrampoline()
340 const {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700341 CREATE_TRAMPOLINE(QUICK, kQuickAbi, pQuickResolutionTrampoline)
Brian Carlstrom7940e442013-07-12 13:46:57 -0700342}
343
Vladimir Marko93205e32016-04-13 11:59:46 +0100344std::unique_ptr<const std::vector<uint8_t>> CompilerDriver::CreateQuickToInterpreterBridge()
345 const {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700346 CREATE_TRAMPOLINE(QUICK, kQuickAbi, pQuickToInterpreterBridge)
Brian Carlstrom7940e442013-07-12 13:46:57 -0700347}
Ian Rogersdd7624d2014-03-14 17:43:00 -0700348#undef CREATE_TRAMPOLINE
Brian Carlstrom7940e442013-07-12 13:46:57 -0700349
350void CompilerDriver::CompileAll(jobject class_loader,
Brian Carlstrom45602482013-07-21 22:07:55 -0700351 const std::vector<const DexFile*>& dex_files,
Ian Rogers3d504072014-03-01 09:16:49 -0800352 TimingLogger* timings) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700353 DCHECK(!Runtime::Current()->IsStarted());
Andreas Gampeace0dc12016-01-20 13:33:13 -0800354
355 InitializeThreadPools();
356
Andreas Gampe8d295f82015-01-20 14:50:21 -0800357 VLOG(compiler) << "Before precompile " << GetMemoryUsageString(false);
Andreas Gampe740667a2015-09-15 17:55:06 -0700358 // Precompile:
359 // 1) Load image classes
360 // 2) Resolve all classes
361 // 3) Attempt to verify all classes
362 // 4) Attempt to initialize image classes, and trivially initialized classes
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000363 PreCompile(class_loader, dex_files, timings);
Vladimir Markoaad75c62016-10-03 08:46:48 +0000364 if (GetCompilerOptions().IsBootImage()) {
Nicolas Geoffray762869d2016-07-15 15:28:35 +0100365 // We don't need to setup the intrinsics for non boot image compilation, as
366 // those compilations will pick up a boot image that have the ArtMethod already
367 // set with the intrinsics flag.
Orion Hodson26ef34c2017-11-01 13:32:41 +0000368 InitializeIntrinsics();
Nicolas Geoffray762869d2016-07-15 15:28:35 +0100369 }
Andreas Gampe740667a2015-09-15 17:55:06 -0700370 // Compile:
371 // 1) Compile all classes and methods enabled for compilation. May fall back to dex-to-dex
372 // compilation.
Nicolas Geoffray49cda062017-04-21 13:08:25 +0100373 if (GetCompilerOptions().IsAnyCompilationEnabled()) {
Andreas Gampeace0dc12016-01-20 13:33:13 -0800374 Compile(class_loader, dex_files, timings);
Andreas Gampe740667a2015-09-15 17:55:06 -0700375 }
Nicolas Geoffray2d8801f2017-11-28 15:50:07 +0000376 if (GetCompilerOptions().GetDumpStats()) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700377 stats_->Dump();
378 }
Andreas Gampeace0dc12016-01-20 13:33:13 -0800379
380 FreeThreadPools();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700381}
382
Mathieu Chartiera79efdb2018-01-18 16:31:01 -0800383static optimizer::DexToDexCompiler::CompilationLevel GetDexToDexCompilationLevel(
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700384 Thread* self, const CompilerDriver& driver, Handle<mirror::ClassLoader> class_loader,
385 const DexFile& dex_file, const DexFile::ClassDef& class_def)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700386 REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffrayf3075272018-01-08 12:41:19 +0000387 // When the dex file is uncompressed in the APK, we do not generate a copy in the .vdex
388 // file. As a result, dex2oat will map the dex file read-only, and we only need to check
389 // that to know if we can do quickening.
390 if (dex_file.GetContainer() != nullptr && dex_file.GetContainer()->IsReadOnly()) {
391 return optimizer::DexToDexCompiler::CompilationLevel::kDontDexToDexCompile;
392 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800393 auto* const runtime = Runtime::Current();
Nicolas Geoffray49cda062017-04-21 13:08:25 +0100394 DCHECK(driver.GetCompilerOptions().IsQuickeningCompilationEnabled());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700395 const char* descriptor = dex_file.GetClassDescriptor(class_def);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800396 ClassLinker* class_linker = runtime->GetClassLinker();
Ian Rogers98379392014-02-24 16:53:16 -0800397 mirror::Class* klass = class_linker->FindClass(self, descriptor, class_loader);
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700398 if (klass == nullptr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700399 CHECK(self->IsExceptionPending());
400 self->ClearException();
Mathieu Chartiera79efdb2018-01-18 16:31:01 -0800401 return optimizer::DexToDexCompiler::CompilationLevel::kDontDexToDexCompile;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700402 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700403 // DexToDex at the kOptimize level may introduce quickened opcodes, which replace symbolic
404 // references with actual offsets. We cannot re-verify such instructions.
405 //
406 // We store the verification information in the class status in the oat file, which the linker
407 // can validate (checksums) and use to skip load-time verification. It is thus safe to
408 // optimize when a class has been fully verified before.
Mathieu Chartiera79efdb2018-01-18 16:31:01 -0800409 optimizer::DexToDexCompiler::CompilationLevel max_level =
410 optimizer::DexToDexCompiler::CompilationLevel::kOptimize;
Alex Lighte40dd382017-01-25 17:44:53 -0800411 if (driver.GetCompilerOptions().GetDebuggable()) {
412 // We are debuggable so definitions of classes might be changed. We don't want to do any
413 // optimizations that could break that.
Mathieu Chartiera79efdb2018-01-18 16:31:01 -0800414 max_level = optimizer::DexToDexCompiler::CompilationLevel::kDontDexToDexCompile;
Alex Lighte40dd382017-01-25 17:44:53 -0800415 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700416 if (klass->IsVerified()) {
Sebastien Hertz75021222013-07-16 18:34:50 +0200417 // Class is verified so we can enable DEX-to-DEX compilation for performance.
Alex Lighte40dd382017-01-25 17:44:53 -0800418 return max_level;
Sebastien Hertz75021222013-07-16 18:34:50 +0200419 } else {
Andreas Gampe1a4bc7f2017-03-27 14:57:30 -0700420 // Class verification has failed: do not run DEX-to-DEX optimizations.
Mathieu Chartiera79efdb2018-01-18 16:31:01 -0800421 return optimizer::DexToDexCompiler::CompilationLevel::kDontDexToDexCompile;
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700422 }
423}
424
Mathieu Chartiera79efdb2018-01-18 16:31:01 -0800425static optimizer::DexToDexCompiler::CompilationLevel GetDexToDexCompilationLevel(
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700426 Thread* self,
427 const CompilerDriver& driver,
428 jobject jclass_loader,
429 const DexFile& dex_file,
430 const DexFile::ClassDef& class_def) {
431 ScopedObjectAccess soa(self);
432 StackHandleScope<1> hs(soa.Self());
433 Handle<mirror::ClassLoader> class_loader(
Mathieu Chartier0795f232016-09-27 18:43:30 -0700434 hs.NewHandle(soa.Decode<mirror::ClassLoader>(jclass_loader)));
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700435 return GetDexToDexCompilationLevel(self, driver, class_loader, dex_file, class_def);
436}
437
438// Does the runtime for the InstructionSet provide an implementation returned by
439// GetQuickGenericJniStub allowing down calls that aren't compiled using a JNI compiler?
440static bool InstructionSetHasGenericJniStub(InstructionSet isa) {
441 switch (isa) {
Vladimir Marko33bff252017-11-01 14:35:42 +0000442 case InstructionSet::kArm:
443 case InstructionSet::kArm64:
444 case InstructionSet::kThumb2:
445 case InstructionSet::kMips:
446 case InstructionSet::kMips64:
447 case InstructionSet::kX86:
448 case InstructionSet::kX86_64: return true;
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700449 default: return false;
450 }
451}
452
453static void CompileMethod(Thread* self,
454 CompilerDriver* driver,
455 const DexFile::CodeItem* code_item,
456 uint32_t access_flags,
457 InvokeType invoke_type,
458 uint16_t class_def_idx,
459 uint32_t method_idx,
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000460 Handle<mirror::ClassLoader> class_loader,
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700461 const DexFile& dex_file,
Mathieu Chartiera79efdb2018-01-18 16:31:01 -0800462 optimizer::DexToDexCompiler::CompilationLevel dex_to_dex_compilation_level,
Mathieu Chartier736b5602015-09-02 14:54:11 -0700463 bool compilation_enabled,
Mathieu Chartieracab8d42016-11-23 13:45:58 -0800464 Handle<mirror::DexCache> dex_cache) {
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700465 DCHECK(driver != nullptr);
466 CompiledMethod* compiled_method = nullptr;
467 uint64_t start_ns = kTimeCompileMethod ? NanoTime() : 0;
468 MethodReference method_ref(&dex_file, method_idx);
469
Mathieu Chartiera79efdb2018-01-18 16:31:01 -0800470 if (driver->GetCompilingDexToDex()) {
471 optimizer::DexToDexCompiler* const compiler = &driver->GetDexToDexCompiler();
Vladimir Marko492a7fa2016-06-01 18:38:43 +0100472 // This is the second pass when we dex-to-dex compile previously marked methods.
473 // TODO: Refactor the compilation to avoid having to distinguish the two passes
474 // here. That should be done on a higher level. http://b/29089975
Mathieu Chartiera79efdb2018-01-18 16:31:01 -0800475 if (compiler->ShouldCompileMethod(method_ref)) {
Mathieu Chartier0733dc82017-07-17 14:05:28 -0700476 VerificationResults* results = driver->GetVerificationResults();
477 DCHECK(results != nullptr);
478 const VerifiedMethod* verified_method = results->GetVerifiedMethod(method_ref);
Vladimir Marko492a7fa2016-06-01 18:38:43 +0100479 // Do not optimize if a VerifiedMethod is missing. SafeCast elision,
480 // for example, relies on it.
Mathieu Chartiera79efdb2018-01-18 16:31:01 -0800481 compiled_method = compiler->CompileMethod(
Vladimir Marko492a7fa2016-06-01 18:38:43 +0100482 code_item,
483 access_flags,
484 invoke_type,
485 class_def_idx,
486 method_idx,
487 class_loader,
488 dex_file,
489 (verified_method != nullptr)
490 ? dex_to_dex_compilation_level
Mathieu Chartiera79efdb2018-01-18 16:31:01 -0800491 : optimizer::DexToDexCompiler::CompilationLevel::kDontDexToDexCompile);
Vladimir Marko492a7fa2016-06-01 18:38:43 +0100492 }
493 } else if ((access_flags & kAccNative) != 0) {
Goran Jakovljevic8d41c082016-09-28 08:49:46 +0000494 // Are we extracting only and have support for generic JNI down calls?
495 if (!driver->GetCompilerOptions().IsJniCompilationEnabled() &&
496 InstructionSetHasGenericJniStub(driver->GetInstructionSet())) {
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700497 // Leaving this empty will trigger the generic JNI version
498 } else {
Igor Murashkin367f3dd2016-09-01 17:00:24 -0700499 // Query any JNI optimization annotations such as @FastNative or @CriticalNative.
Vladimir Markob0a6aee2017-10-27 10:34:04 +0100500 access_flags |= annotations::GetNativeMethodAnnotationAccessFlags(
501 dex_file, dex_file.GetClassDef(class_def_idx), method_idx);
Igor Murashkin9d4b6da2016-07-29 09:51:58 -0700502
Vladimir Marko92f7f3c2017-10-31 11:38:30 +0000503 compiled_method = driver->GetCompiler()->JniCompile(
504 access_flags, method_idx, dex_file, dex_cache);
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700505 CHECK(compiled_method != nullptr);
506 }
507 } else if ((access_flags & kAccAbstract) != 0) {
508 // Abstract methods don't have code.
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000509 } else {
Mathieu Chartier0733dc82017-07-17 14:05:28 -0700510 VerificationResults* results = driver->GetVerificationResults();
511 DCHECK(results != nullptr);
512 const VerifiedMethod* verified_method = results->GetVerifiedMethod(method_ref);
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700513 bool compile = compilation_enabled &&
514 // Basic checks, e.g., not <clinit>.
Mathieu Chartier0733dc82017-07-17 14:05:28 -0700515 results->IsCandidateForCompilation(method_ref, access_flags) &&
Mathieu Chartiera79efdb2018-01-18 16:31:01 -0800516 // Did not fail to create VerifiedMethod metadcata.
Andreas Gampe0760a812015-08-26 17:12:51 -0700517 verified_method != nullptr &&
518 // Do not have failures that should punt to the interpreter.
519 !verified_method->HasRuntimeThrow() &&
520 (verified_method->GetEncounteredVerificationFailures() &
Andreas Gampea727e372015-08-25 09:22:37 -0700521 (verifier::VERIFY_ERROR_FORCE_INTERPRETER | verifier::VERIFY_ERROR_LOCKING)) == 0 &&
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700522 // Is eligable for compilation by methods-to-compile filter.
Calin Juravle226501b2015-12-11 14:41:31 +0000523 driver->IsMethodToCompile(method_ref) &&
524 driver->ShouldCompileBasedOnProfile(method_ref);
525
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700526 if (compile) {
527 // NOTE: if compiler declines to compile this method, it will return null.
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000528 compiled_method = driver->GetCompiler()->Compile(code_item,
529 access_flags,
530 invoke_type,
531 class_def_idx,
532 method_idx,
533 class_loader,
534 dex_file,
535 dex_cache);
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700536 }
537 if (compiled_method == nullptr &&
Mathieu Chartiera79efdb2018-01-18 16:31:01 -0800538 dex_to_dex_compilation_level !=
539 optimizer::DexToDexCompiler::CompilationLevel::kDontDexToDexCompile) {
Vladimir Marko492a7fa2016-06-01 18:38:43 +0100540 DCHECK(!Runtime::Current()->UseJitCompilation());
Mathieu Chartiera79efdb2018-01-18 16:31:01 -0800541 DCHECK(!driver->GetCompilingDexToDex());
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700542 // TODO: add a command-line option to disable DEX-to-DEX compilation ?
Mathieu Chartiera79efdb2018-01-18 16:31:01 -0800543 driver->GetDexToDexCompiler().MarkForCompilation(self, method_ref, code_item);
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700544 }
545 }
546 if (kTimeCompileMethod) {
547 uint64_t duration_ns = NanoTime() - start_ns;
548 if (duration_ns > MsToNs(driver->GetCompiler()->GetMaximumCompilationTimeBeforeWarning())) {
David Sehr709b0702016-10-13 09:12:37 -0700549 LOG(WARNING) << "Compilation of " << dex_file.PrettyMethod(method_idx)
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700550 << " took " << PrettyDuration(duration_ns);
551 }
552 }
553
554 if (compiled_method != nullptr) {
555 // Count non-relative linker patches.
556 size_t non_relative_linker_patch_count = 0u;
Vladimir Markod8dbc8d2017-09-20 13:37:47 +0100557 for (const linker::LinkerPatch& patch : compiled_method->GetPatches()) {
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700558 if (!patch.IsPcRelative()) {
559 ++non_relative_linker_patch_count;
560 }
561 }
562 bool compile_pic = driver->GetCompilerOptions().GetCompilePic(); // Off by default
563 // When compiling with PIC, there should be zero non-relative linker patches
564 CHECK(!compile_pic || non_relative_linker_patch_count == 0u);
565
566 driver->AddCompiledMethod(method_ref, compiled_method, non_relative_linker_patch_count);
567 }
568
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700569 if (self->IsExceptionPending()) {
570 ScopedObjectAccess soa(self);
David Sehr709b0702016-10-13 09:12:37 -0700571 LOG(FATAL) << "Unexpected exception compiling: " << dex_file.PrettyMethod(method_idx) << "\n"
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700572 << self->GetException()->Dump();
Sebastien Hertz75021222013-07-16 18:34:50 +0200573 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700574}
575
Mathieu Chartiere401d142015-04-22 13:56:20 -0700576void CompilerDriver::CompileOne(Thread* self, ArtMethod* method, TimingLogger* timings) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700577 DCHECK(!Runtime::Current()->IsStarted());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700578 jobject jclass_loader;
579 const DexFile* dex_file;
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700580 uint16_t class_def_idx;
Ian Rogersef7d42f2014-01-06 12:55:46 -0800581 uint32_t method_idx = method->GetDexMethodIndex();
582 uint32_t access_flags = method->GetAccessFlags();
583 InvokeType invoke_type = method->GetInvokeType();
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000584 StackHandleScope<2> hs(self);
Mathieu Chartier736b5602015-09-02 14:54:11 -0700585 Handle<mirror::DexCache> dex_cache(hs.NewHandle(method->GetDexCache()));
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000586 Handle<mirror::ClassLoader> class_loader(
587 hs.NewHandle(method->GetDeclaringClass()->GetClassLoader()));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700588 {
589 ScopedObjectAccessUnchecked soa(self);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800590 ScopedLocalRef<jobject> local_class_loader(
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000591 soa.Env(), soa.AddLocalReference<jobject>(class_loader.Get()));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700592 jclass_loader = soa.Env()->NewGlobalRef(local_class_loader.get());
593 // Find the dex_file
Mathieu Chartierbfd9a432014-05-21 17:43:44 -0700594 dex_file = method->GetDexFile();
595 class_def_idx = method->GetClassDefIndex();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700596 }
Ian Rogersef7d42f2014-01-06 12:55:46 -0800597 const DexFile::CodeItem* code_item = dex_file->GetCodeItem(method->GetCodeItemOffset());
Mathieu Chartier736b5602015-09-02 14:54:11 -0700598
599 // Go to native so that we don't block GC during compilation.
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700600 ScopedThreadSuspension sts(self, kNative);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700601
602 std::vector<const DexFile*> dex_files;
603 dex_files.push_back(dex_file);
604
Andreas Gampeace0dc12016-01-20 13:33:13 -0800605 InitializeThreadPools();
606
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000607 PreCompile(jclass_loader, dex_files, timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700608
Brian Carlstrom7940e442013-07-12 13:46:57 -0700609 // Can we run DEX-to-DEX compiler on this class ?
Mathieu Chartiera79efdb2018-01-18 16:31:01 -0800610 optimizer::DexToDexCompiler::CompilationLevel dex_to_dex_compilation_level =
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700611 GetDexToDexCompilationLevel(self,
612 *this,
613 jclass_loader,
614 *dex_file,
615 dex_file->GetClassDef(class_def_idx));
616
Mathieu Chartiera79efdb2018-01-18 16:31:01 -0800617 DCHECK(!compiling_dex_to_dex_);
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700618 CompileMethod(self,
619 this,
620 code_item,
621 access_flags,
622 invoke_type,
623 class_def_idx,
624 method_idx,
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000625 class_loader,
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700626 *dex_file,
627 dex_to_dex_compilation_level,
Mathieu Chartier736b5602015-09-02 14:54:11 -0700628 true,
629 dex_cache);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700630
Mathieu Chartiera79efdb2018-01-18 16:31:01 -0800631 const size_t num_methods = dex_to_dex_compiler_.NumUniqueCodeItems(self);
632 if (num_methods != 0) {
633 DCHECK_EQ(num_methods, 1u);
634 compiling_dex_to_dex_ = true;
Vladimir Marko492a7fa2016-06-01 18:38:43 +0100635 CompileMethod(self,
636 this,
637 code_item,
638 access_flags,
639 invoke_type,
640 class_def_idx,
641 method_idx,
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000642 class_loader,
Vladimir Marko492a7fa2016-06-01 18:38:43 +0100643 *dex_file,
644 dex_to_dex_compilation_level,
645 true,
646 dex_cache);
Mathieu Chartiera79efdb2018-01-18 16:31:01 -0800647 compiling_dex_to_dex_ = false;
648 dex_to_dex_compiler_.ClearState();
Vladimir Marko492a7fa2016-06-01 18:38:43 +0100649 }
650
Andreas Gampeace0dc12016-01-20 13:33:13 -0800651 FreeThreadPools();
652
Brian Carlstrom7940e442013-07-12 13:46:57 -0700653 self->GetJniEnv()->DeleteGlobalRef(jclass_loader);
Mathieu Chartier2535abe2015-02-17 10:38:49 -0800654}
655
Andreas Gampeace0dc12016-01-20 13:33:13 -0800656void CompilerDriver::Resolve(jobject class_loader,
657 const std::vector<const DexFile*>& dex_files,
658 TimingLogger* timings) {
659 // Resolution allocates classes and needs to run single-threaded to be deterministic.
660 bool force_determinism = GetCompilerOptions().IsForceDeterminism();
661 ThreadPool* resolve_thread_pool = force_determinism
662 ? single_thread_pool_.get()
663 : parallel_thread_pool_.get();
664 size_t resolve_thread_count = force_determinism ? 1U : parallel_thread_count_;
665
Brian Carlstrom7940e442013-07-12 13:46:57 -0700666 for (size_t i = 0; i != dex_files.size(); ++i) {
667 const DexFile* dex_file = dex_files[i];
Kenny Rootd5185342014-05-13 14:47:05 -0700668 CHECK(dex_file != nullptr);
Andreas Gampeace0dc12016-01-20 13:33:13 -0800669 ResolveDexFile(class_loader,
670 *dex_file,
671 dex_files,
672 resolve_thread_pool,
673 resolve_thread_count,
674 timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700675 }
676}
677
Andreas Gampeace0dc12016-01-20 13:33:13 -0800678// Resolve const-strings in the code. Done to have deterministic allocation behavior. Right now
679// this is single-threaded for simplicity.
680// TODO: Collect the relevant string indices in parallel, then allocate them sequentially in a
681// stable order.
682
Vladimir Markoeb0ebed2018-01-10 18:26:38 +0000683static void ResolveConstStrings(ClassLinker* class_linker,
684 Handle<mirror::DexCache> dex_cache,
Mathieu Chartier6238c832018-01-04 09:55:13 -0800685 const DexFile& dex_file,
Nicolas Geoffray571d2342016-10-12 13:03:15 +0000686 const DexFile::CodeItem* code_item)
687 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampeace0dc12016-01-20 13:33:13 -0800688 if (code_item == nullptr) {
689 // Abstract or native method.
690 return;
691 }
692
Mathieu Chartier698ebbc2018-01-05 11:00:42 -0800693 for (const DexInstructionPcPair& inst : CodeItemInstructionAccessor(dex_file, code_item)) {
Mathieu Chartier2b2bef22017-10-26 17:10:19 -0700694 switch (inst->Opcode()) {
Nicolas Geoffray571d2342016-10-12 13:03:15 +0000695 case Instruction::CONST_STRING:
Andreas Gampeace0dc12016-01-20 13:33:13 -0800696 case Instruction::CONST_STRING_JUMBO: {
Mathieu Chartier2b2bef22017-10-26 17:10:19 -0700697 dex::StringIndex string_index((inst->Opcode() == Instruction::CONST_STRING)
698 ? inst->VRegB_21c()
699 : inst->VRegB_31c());
Vladimir Markoa64b52d2017-12-08 16:27:49 +0000700 ObjPtr<mirror::String> string = class_linker->ResolveString(string_index, dex_cache);
Nicolas Geoffray571d2342016-10-12 13:03:15 +0000701 CHECK(string != nullptr) << "Could not allocate a string when forcing determinism";
Andreas Gampeace0dc12016-01-20 13:33:13 -0800702 break;
703 }
704
705 default:
706 break;
707 }
Andreas Gampeace0dc12016-01-20 13:33:13 -0800708 }
709}
710
711static void ResolveConstStrings(CompilerDriver* driver,
712 const std::vector<const DexFile*>& dex_files,
713 TimingLogger* timings) {
Nicolas Geoffray571d2342016-10-12 13:03:15 +0000714 ScopedObjectAccess soa(Thread::Current());
715 StackHandleScope<1> hs(soa.Self());
716 ClassLinker* const class_linker = Runtime::Current()->GetClassLinker();
717 MutableHandle<mirror::DexCache> dex_cache(hs.NewHandle<mirror::DexCache>(nullptr));
718
Andreas Gampeace0dc12016-01-20 13:33:13 -0800719 for (const DexFile* dex_file : dex_files) {
Vladimir Markocd556b02017-02-03 11:47:34 +0000720 dex_cache.Assign(class_linker->FindDexCache(soa.Self(), *dex_file));
Andreas Gampeace0dc12016-01-20 13:33:13 -0800721 TimingLogger::ScopedTiming t("Resolve const-string Strings", timings);
722
723 size_t class_def_count = dex_file->NumClassDefs();
724 for (size_t class_def_index = 0; class_def_index < class_def_count; ++class_def_index) {
725 const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_index);
726
727 const uint8_t* class_data = dex_file->GetClassData(class_def);
728 if (class_data == nullptr) {
729 // empty class, probably a marker interface
730 continue;
731 }
732
733 ClassDataItemIterator it(*dex_file, class_data);
Mathieu Chartiere17cf242017-06-19 11:05:51 -0700734 it.SkipAllFields();
Andreas Gampeace0dc12016-01-20 13:33:13 -0800735
736 bool compilation_enabled = driver->IsClassToCompile(
737 dex_file->StringByTypeIdx(class_def.class_idx_));
738 if (!compilation_enabled) {
739 // Compilation is skipped, do not resolve const-string in code of this class.
Vladimir Markoeb0ebed2018-01-10 18:26:38 +0000740 // FIXME: Make sure that inlining honors this. b/26687569
Andreas Gampeace0dc12016-01-20 13:33:13 -0800741 continue;
742 }
743
Mathieu Chartierb7c273c2017-11-10 18:07:56 -0800744 // Direct and virtual methods.
Mathieu Chartierb7c273c2017-11-10 18:07:56 -0800745 while (it.HasNextMethod()) {
Vladimir Markoeb0ebed2018-01-10 18:26:38 +0000746 ResolveConstStrings(class_linker, dex_cache, *dex_file, it.GetMethodCodeItem());
747 it.Next();
748 }
749 DCHECK(!it.HasNext());
750 }
751 }
752}
753
754// Initialize type check bit strings for check-cast and instance-of in the code. Done to have
755// deterministic allocation behavior. Right now this is single-threaded for simplicity.
756// TODO: Collect the relevant type indices in parallel, then process them sequentially in a
757// stable order.
758
759static void InitializeTypeCheckBitstrings(CompilerDriver* driver,
760 ClassLinker* class_linker,
761 Handle<mirror::DexCache> dex_cache,
762 const DexFile& dex_file,
763 const DexFile::CodeItem* code_item)
764 REQUIRES_SHARED(Locks::mutator_lock_) {
765 if (code_item == nullptr) {
766 // Abstract or native method.
767 return;
768 }
769
770 for (const DexInstructionPcPair& inst : CodeItemInstructionAccessor(dex_file, code_item)) {
771 switch (inst->Opcode()) {
772 case Instruction::CHECK_CAST:
773 case Instruction::INSTANCE_OF: {
774 dex::TypeIndex type_index(
775 (inst->Opcode() == Instruction::CHECK_CAST) ? inst->VRegB_21c() : inst->VRegC_22c());
776 const char* descriptor = dex_file.StringByTypeIdx(type_index);
777 // We currently do not use the bitstring type check for array or final (including
778 // primitive) classes. We may reconsider this in future if it's deemed to be beneficial.
779 // And we cannot use it for classes outside the boot image as we do not know the runtime
780 // value of their bitstring when compiling (it may not even get assigned at runtime).
781 if (descriptor[0] == 'L' && driver->IsImageClass(descriptor)) {
782 ObjPtr<mirror::Class> klass =
783 class_linker->LookupResolvedType(type_index,
784 dex_cache.Get(),
785 /* class_loader */ nullptr);
786 CHECK(klass != nullptr) << descriptor << " should have been previously resolved.";
787 // Now assign the bitstring if the class is not final. Keep this in sync with sharpening.
788 if (!klass->IsFinal()) {
789 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
790 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureAssigned(klass);
791 }
Andreas Gampeace0dc12016-01-20 13:33:13 -0800792 }
Vladimir Markoeb0ebed2018-01-10 18:26:38 +0000793 break;
794 }
795
796 default:
797 break;
798 }
799 }
800}
801
802static void InitializeTypeCheckBitstrings(CompilerDriver* driver,
803 const std::vector<const DexFile*>& dex_files,
804 TimingLogger* timings) {
805 ScopedObjectAccess soa(Thread::Current());
806 StackHandleScope<1> hs(soa.Self());
807 ClassLinker* const class_linker = Runtime::Current()->GetClassLinker();
808 MutableHandle<mirror::DexCache> dex_cache(hs.NewHandle<mirror::DexCache>(nullptr));
809
810 for (const DexFile* dex_file : dex_files) {
811 dex_cache.Assign(class_linker->FindDexCache(soa.Self(), *dex_file));
812 TimingLogger::ScopedTiming t("Initialize type check bitstrings", timings);
813
814 size_t class_def_count = dex_file->NumClassDefs();
815 for (size_t class_def_index = 0; class_def_index < class_def_count; ++class_def_index) {
816 const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_index);
817
818 const uint8_t* class_data = dex_file->GetClassData(class_def);
819 if (class_data == nullptr) {
820 // empty class, probably a marker interface
821 continue;
822 }
823
824 ClassDataItemIterator it(*dex_file, class_data);
825 it.SkipAllFields();
826
827 bool compilation_enabled = driver->IsClassToCompile(
828 dex_file->StringByTypeIdx(class_def.class_idx_));
829 if (!compilation_enabled) {
830 // Compilation is skipped, do not look for type checks in code of this class.
831 // FIXME: Make sure that inlining honors this. b/26687569
832 continue;
833 }
834
835 // Direct and virtual methods.
836 while (it.HasNextMethod()) {
837 InitializeTypeCheckBitstrings(
838 driver, class_linker, dex_cache, *dex_file, it.GetMethodCodeItem());
Andreas Gampeace0dc12016-01-20 13:33:13 -0800839 it.Next();
840 }
841 DCHECK(!it.HasNext());
842 }
843 }
844}
845
846inline void CompilerDriver::CheckThreadPools() {
847 DCHECK(parallel_thread_pool_ != nullptr);
848 DCHECK(single_thread_pool_ != nullptr);
849}
850
Nicolas Geoffray0a27fd02017-01-25 16:18:54 +0000851static void EnsureVerifiedOrVerifyAtRuntime(jobject jclass_loader,
852 const std::vector<const DexFile*>& dex_files) {
853 ScopedObjectAccess soa(Thread::Current());
854 StackHandleScope<2> hs(soa.Self());
855 Handle<mirror::ClassLoader> class_loader(
856 hs.NewHandle(soa.Decode<mirror::ClassLoader>(jclass_loader)));
857 MutableHandle<mirror::Class> cls(hs.NewHandle<mirror::Class>(nullptr));
858 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
859
860 for (const DexFile* dex_file : dex_files) {
861 for (uint32_t i = 0; i < dex_file->NumClassDefs(); ++i) {
862 const DexFile::ClassDef& class_def = dex_file->GetClassDef(i);
863 const char* descriptor = dex_file->GetClassDescriptor(class_def);
864 cls.Assign(class_linker->FindClass(soa.Self(), descriptor, class_loader));
Andreas Gampefa4333d2017-02-14 11:10:34 -0800865 if (cls == nullptr) {
Nicolas Geoffray0a27fd02017-01-25 16:18:54 +0000866 soa.Self()->ClearException();
867 } else if (&cls->GetDexFile() == dex_file) {
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +0000868 DCHECK(cls->IsErroneous() || cls->IsVerified() || cls->ShouldVerifyAtRuntime())
Nicolas Geoffray0a27fd02017-01-25 16:18:54 +0000869 << cls->PrettyClass()
870 << " " << cls->GetStatus();
871 }
872 }
873 }
874}
875
Andreas Gampeace0dc12016-01-20 13:33:13 -0800876void CompilerDriver::PreCompile(jobject class_loader,
877 const std::vector<const DexFile*>& dex_files,
878 TimingLogger* timings) {
879 CheckThreadPools();
880
Brian Carlstrom7940e442013-07-12 13:46:57 -0700881 LoadImageClasses(timings);
Andreas Gampe8d295f82015-01-20 14:50:21 -0800882 VLOG(compiler) << "LoadImageClasses: " << GetMemoryUsageString(false);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700883
Nicolas Geoffray49cda062017-04-21 13:08:25 +0100884 if (compiler_options_->IsAnyCompilationEnabled()) {
Mathieu Chartier88b74b62017-07-16 17:08:19 -0700885 // Avoid adding the dex files in the case where we aren't going to add compiled methods.
886 // This reduces RAM usage for this case.
887 for (const DexFile* dex_file : dex_files) {
888 // Can be already inserted if the caller is CompileOne. This happens for gtests.
889 if (!compiled_methods_.HaveDexFile(dex_file)) {
Mathieu Chartierfc8b4222017-09-17 13:44:24 -0700890 compiled_methods_.AddDexFile(dex_file);
Mathieu Chartier88b74b62017-07-16 17:08:19 -0700891 }
892 }
Nicolas Geoffray49cda062017-04-21 13:08:25 +0100893 // Resolve eagerly to prepare for compilation.
Andreas Gampeace0dc12016-01-20 13:33:13 -0800894 Resolve(class_loader, dex_files, timings);
Mathieu Chartiere86deef2015-03-19 13:43:37 -0700895 VLOG(compiler) << "Resolve: " << GetMemoryUsageString(false);
896 }
897
Nicolas Geoffray60ca9492016-12-20 21:15:00 +0000898 if (compiler_options_->AssumeClassesAreVerified()) {
Mathieu Chartierab972ef2014-12-03 17:38:22 -0800899 VLOG(compiler) << "Verify none mode specified, skipping verification.";
Andreas Gampeace0dc12016-01-20 13:33:13 -0800900 SetVerified(class_loader, dex_files, timings);
Mathieu Chartiere86deef2015-03-19 13:43:37 -0700901 }
902
Nicolas Geoffray60ca9492016-12-20 21:15:00 +0000903 if (!compiler_options_->IsVerificationEnabled()) {
Jeff Hao4a200f52014-04-01 14:58:49 -0700904 return;
905 }
906
Vladimir Markoaad75c62016-10-03 08:46:48 +0000907 if (GetCompilerOptions().IsForceDeterminism() && GetCompilerOptions().IsBootImage()) {
Andreas Gampeace0dc12016-01-20 13:33:13 -0800908 // Resolve strings from const-string. Do this now to have a deterministic image.
909 ResolveConstStrings(this, dex_files, timings);
910 VLOG(compiler) << "Resolve const-strings: " << GetMemoryUsageString(false);
911 }
912
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000913 Verify(class_loader, dex_files, timings);
Andreas Gampe8d295f82015-01-20 14:50:21 -0800914 VLOG(compiler) << "Verify: " << GetMemoryUsageString(false);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700915
Andreas Gampe6cf49e52015-03-05 13:08:45 -0800916 if (had_hard_verifier_failure_ && GetCompilerOptions().AbortOnHardVerifierFailure()) {
Andreas Gampefdfb4d42017-07-27 12:12:22 -0700917 // Avoid dumping threads. Even if we shut down the thread pools, there will still be three
918 // instances of this thread's stack.
919 LOG(FATAL_WITHOUT_ABORT) << "Had a hard failure verifying all classes, and was asked to abort "
920 << "in such situations. Please check the log.";
921 abort();
Andreas Gampef39208f2017-10-19 15:06:59 -0700922 } else if (number_of_soft_verifier_failures_ > 0 &&
923 GetCompilerOptions().AbortOnSoftVerifierFailure()) {
924 LOG(FATAL_WITHOUT_ABORT) << "Had " << number_of_soft_verifier_failures_ << " soft failure(s) "
925 << "verifying all classes, and was asked to abort in such situations. "
926 << "Please check the log.";
927 abort();
Andreas Gampe6cf49e52015-03-05 13:08:45 -0800928 }
929
Nicolas Geoffray49cda062017-04-21 13:08:25 +0100930 if (compiler_options_->IsAnyCompilationEnabled()) {
Nicolas Geoffray0a27fd02017-01-25 16:18:54 +0000931 if (kIsDebugBuild) {
932 EnsureVerifiedOrVerifyAtRuntime(class_loader, dex_files);
933 }
Nicolas Geoffrayade72d62016-12-15 13:20:02 +0000934 InitializeClasses(class_loader, dex_files, timings);
935 VLOG(compiler) << "InitializeClasses: " << GetMemoryUsageString(false);
936 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700937
938 UpdateImageClasses(timings);
Andreas Gampe8d295f82015-01-20 14:50:21 -0800939 VLOG(compiler) << "UpdateImageClasses: " << GetMemoryUsageString(false);
Vladimir Markoeb0ebed2018-01-10 18:26:38 +0000940
941 if (GetCompilerOptions().IsForceDeterminism() && GetCompilerOptions().IsBootImage()) {
942 // Initialize type check bit string used by check-cast and instanceof.
943 // Do this now to have a deterministic image.
944 // Note: This is done after UpdateImageClasses() at it relies on the image classes to be final.
945 InitializeTypeCheckBitstrings(this, dex_files, timings);
946 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700947}
948
Ian Rogersdfb325e2013-10-30 01:00:44 -0700949bool CompilerDriver::IsImageClass(const char* descriptor) const {
Mathieu Chartierc5dd3192015-12-09 16:38:30 -0800950 if (image_classes_ != nullptr) {
951 // If we have a set of image classes, use those.
Ian Rogersdfb325e2013-10-30 01:00:44 -0700952 return image_classes_->find(descriptor) != image_classes_->end();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700953 }
Mathieu Chartierc5dd3192015-12-09 16:38:30 -0800954 // No set of image classes, assume we include all the classes.
955 // NOTE: Currently only reachable from InitImageMethodVisitor for the app image case.
Vladimir Markoaad75c62016-10-03 08:46:48 +0000956 return !GetCompilerOptions().IsBootImage();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700957}
958
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800959bool CompilerDriver::IsClassToCompile(const char* descriptor) const {
Andreas Gampeb1fcead2015-04-20 18:53:51 -0700960 if (classes_to_compile_ == nullptr) {
961 return true;
962 }
963 return classes_to_compile_->find(descriptor) != classes_to_compile_->end();
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800964}
965
Andreas Gampe70bef0d2015-04-15 02:37:28 -0700966bool CompilerDriver::IsMethodToCompile(const MethodReference& method_ref) const {
Andreas Gampe70bef0d2015-04-15 02:37:28 -0700967 if (methods_to_compile_ == nullptr) {
968 return true;
969 }
970
Mathieu Chartierfc8b4222017-09-17 13:44:24 -0700971 std::string tmp = method_ref.PrettyMethod();
Andreas Gampe70bef0d2015-04-15 02:37:28 -0700972 return methods_to_compile_->find(tmp.c_str()) != methods_to_compile_->end();
973}
974
Calin Juravle226501b2015-12-11 14:41:31 +0000975bool CompilerDriver::ShouldCompileBasedOnProfile(const MethodReference& method_ref) const {
Mathieu Chartier97ab5e32017-02-22 13:35:44 -0800976 // Profile compilation info may be null if no profile is passed.
Mathieu Chartierd0af56c2017-02-17 12:56:25 -0800977 if (!CompilerFilter::DependsOnProfile(compiler_options_->GetCompilerFilter())) {
978 // Use the compiler filter instead of the presence of profile_compilation_info_ since
979 // we may want to have full speed compilation along with profile based layout optimizations.
Calin Juravle226501b2015-12-11 14:41:31 +0000980 return true;
981 }
Mathieu Chartier97ab5e32017-02-22 13:35:44 -0800982 // If we are using a profile filter but do not have a profile compilation info, compile nothing.
983 if (profile_compilation_info_ == nullptr) {
984 return false;
985 }
Mathieu Chartier7b135c82017-06-05 12:54:01 -0700986 // Compile only hot methods, it is the profile saver's job to decide what startup methods to mark
987 // as hot.
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -0700988 bool result = profile_compilation_info_->GetMethodHotness(method_ref).IsHot();
Calin Juravle226501b2015-12-11 14:41:31 +0000989
990 if (kDebugProfileGuidedCompilation) {
991 LOG(INFO) << "[ProfileGuidedCompilation] "
Mathieu Chartierfc8b4222017-09-17 13:44:24 -0700992 << (result ? "Compiled" : "Skipped") << " method:" << method_ref.PrettyMethod(true);
Calin Juravle226501b2015-12-11 14:41:31 +0000993 }
994 return result;
995}
996
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700997class ResolveCatchBlockExceptionsClassVisitor : public ClassVisitor {
998 public:
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000999 ResolveCatchBlockExceptionsClassVisitor() : classes_() {}
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001000
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001001 virtual bool operator()(ObjPtr<mirror::Class> c) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001002 classes_.push_back(c);
Mathieu Chartiere4275c02015-08-06 15:34:15 -07001003 return true;
1004 }
1005
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001006 void FindExceptionTypesToResolve(
1007 std::set<std::pair<dex::TypeIndex, const DexFile*>>* exceptions_to_resolve)
Vladimir Markobfb80d22017-02-14 14:08:12 +00001008 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001009 const auto pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
1010 for (ObjPtr<mirror::Class> klass : classes_) {
1011 for (ArtMethod& method : klass->GetMethods(pointer_size)) {
1012 FindExceptionTypesToResolveForMethod(&method, exceptions_to_resolve);
1013 }
1014 }
1015 }
1016
1017 private:
1018 void FindExceptionTypesToResolveForMethod(
1019 ArtMethod* method,
1020 std::set<std::pair<dex::TypeIndex, const DexFile*>>* exceptions_to_resolve)
1021 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier808c7a52017-12-15 11:19:33 -08001022 if (method->GetCodeItem() == nullptr) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001023 return; // native or abstract method
Brian Carlstrom7940e442013-07-12 13:46:57 -07001024 }
Mathieu Chartier808c7a52017-12-15 11:19:33 -08001025 CodeItemDataAccessor accessor(method);
1026 if (accessor.TriesSize() == 0) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001027 return; // nothing to process
1028 }
Mathieu Chartier808c7a52017-12-15 11:19:33 -08001029 const uint8_t* encoded_catch_handler_list = accessor.GetCatchHandlerData();
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001030 size_t num_encoded_catch_handlers = DecodeUnsignedLeb128(&encoded_catch_handler_list);
1031 for (size_t i = 0; i < num_encoded_catch_handlers; i++) {
1032 int32_t encoded_catch_handler_size = DecodeSignedLeb128(&encoded_catch_handler_list);
1033 bool has_catch_all = false;
1034 if (encoded_catch_handler_size <= 0) {
1035 encoded_catch_handler_size = -encoded_catch_handler_size;
1036 has_catch_all = true;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001037 }
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001038 for (int32_t j = 0; j < encoded_catch_handler_size; j++) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08001039 dex::TypeIndex encoded_catch_handler_handlers_type_idx =
1040 dex::TypeIndex(DecodeUnsignedLeb128(&encoded_catch_handler_list));
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001041 // Add to set of types to resolve if not already in the dex cache resolved types
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001042 if (!method->IsResolvedTypeIdx(encoded_catch_handler_handlers_type_idx)) {
1043 exceptions_to_resolve->emplace(encoded_catch_handler_handlers_type_idx,
1044 method->GetDexFile());
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001045 }
1046 // ignore address associated with catch handler
1047 DecodeUnsignedLeb128(&encoded_catch_handler_list);
1048 }
1049 if (has_catch_all) {
1050 // ignore catch all address
1051 DecodeUnsignedLeb128(&encoded_catch_handler_list);
1052 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001053 }
1054 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001055
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001056 std::vector<ObjPtr<mirror::Class>> classes_;
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001057};
1058
1059class RecordImageClassesVisitor : public ClassVisitor {
1060 public:
1061 explicit RecordImageClassesVisitor(std::unordered_set<std::string>* image_classes)
1062 : image_classes_(image_classes) {}
1063
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001064 bool operator()(ObjPtr<mirror::Class> klass) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001065 std::string temp;
1066 image_classes_->insert(klass->GetDescriptor(&temp));
1067 return true;
1068 }
1069
1070 private:
1071 std::unordered_set<std::string>* const image_classes_;
1072};
Brian Carlstrom7940e442013-07-12 13:46:57 -07001073
1074// Make a list of descriptors for classes to include in the image
Mathieu Chartier90443472015-07-16 20:32:27 -07001075void CompilerDriver::LoadImageClasses(TimingLogger* timings) {
Kenny Rootd5185342014-05-13 14:47:05 -07001076 CHECK(timings != nullptr);
Vladimir Markoaad75c62016-10-03 08:46:48 +00001077 if (!GetCompilerOptions().IsBootImage()) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001078 return;
1079 }
1080
Mathieu Chartierf5997b42014-06-20 10:37:54 -07001081 TimingLogger::ScopedTiming t("LoadImageClasses", timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001082 // Make a first class to load all classes explicitly listed in the file
1083 Thread* self = Thread::Current();
1084 ScopedObjectAccess soa(self);
1085 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Kenny Rootd5185342014-05-13 14:47:05 -07001086 CHECK(image_classes_.get() != nullptr);
Mathieu Chartier02e25112013-08-14 16:14:24 -07001087 for (auto it = image_classes_->begin(), end = image_classes_->end(); it != end;) {
Vladimir Markoe9c36b32013-11-21 15:49:16 +00001088 const std::string& descriptor(*it);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001089 StackHandleScope<1> hs(self);
1090 Handle<mirror::Class> klass(
1091 hs.NewHandle(class_linker->FindSystemClass(self, descriptor.c_str())));
Andreas Gampefa4333d2017-02-14 11:10:34 -08001092 if (klass == nullptr) {
Ian Rogerse6bb3b22013-08-19 21:51:45 -07001093 VLOG(compiler) << "Failed to find class " << descriptor;
Vladimir Markoe9c36b32013-11-21 15:49:16 +00001094 image_classes_->erase(it++);
Ian Rogersa436fde2013-08-27 23:34:06 -07001095 self->ClearException();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001096 } else {
1097 ++it;
1098 }
1099 }
1100
1101 // Resolve exception classes referenced by the loaded classes. The catch logic assumes
1102 // exceptions are resolved by the verifier when there is a catch block in an interested method.
1103 // Do this here so that exception classes appear to have been specified image classes.
Andreas Gampea5b09a62016-11-17 15:21:22 -08001104 std::set<std::pair<dex::TypeIndex, const DexFile*>> unresolved_exception_types;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001105 StackHandleScope<1> hs(self);
1106 Handle<mirror::Class> java_lang_Throwable(
1107 hs.NewHandle(class_linker->FindSystemClass(self, "Ljava/lang/Throwable;")));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001108 do {
1109 unresolved_exception_types.clear();
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001110 {
1111 // Thread suspension is not allowed while ResolveCatchBlockExceptionsClassVisitor
1112 // is using a std::vector<ObjPtr<mirror::Class>>.
1113 ScopedAssertNoThreadSuspension ants(__FUNCTION__);
1114 ResolveCatchBlockExceptionsClassVisitor visitor;
1115 class_linker->VisitClasses(&visitor);
1116 visitor.FindExceptionTypesToResolve(&unresolved_exception_types);
1117 }
Andreas Gampea5b09a62016-11-17 15:21:22 -08001118 for (const auto& exception_type : unresolved_exception_types) {
1119 dex::TypeIndex exception_type_idx = exception_type.first;
Mathieu Chartier02e25112013-08-14 16:14:24 -07001120 const DexFile* dex_file = exception_type.second;
Vladimir Marko666ee3d2017-12-11 18:37:36 +00001121 StackHandleScope<1> hs2(self);
Mathieu Chartierf284d442016-06-02 11:48:30 -07001122 Handle<mirror::DexCache> dex_cache(hs2.NewHandle(class_linker->RegisterDexFile(*dex_file,
1123 nullptr)));
Vladimir Marko666ee3d2017-12-11 18:37:36 +00001124 ObjPtr<mirror::Class> klass =
Andreas Gampefa4333d2017-02-14 11:10:34 -08001125 (dex_cache != nullptr)
Vladimir Marko666ee3d2017-12-11 18:37:36 +00001126 ? class_linker->ResolveType(exception_type_idx,
Vladimir Markocd556b02017-02-03 11:47:34 +00001127 dex_cache,
1128 ScopedNullHandle<mirror::ClassLoader>())
Vladimir Marko666ee3d2017-12-11 18:37:36 +00001129 : nullptr;
Andreas Gampefa4333d2017-02-14 11:10:34 -08001130 if (klass == nullptr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001131 const DexFile::TypeId& type_id = dex_file->GetTypeId(exception_type_idx);
1132 const char* descriptor = dex_file->GetTypeDescriptor(type_id);
1133 LOG(FATAL) << "Failed to resolve class " << descriptor;
1134 }
Vladimir Marko666ee3d2017-12-11 18:37:36 +00001135 DCHECK(java_lang_Throwable->IsAssignableFrom(klass));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001136 }
1137 // Resolving exceptions may load classes that reference more exceptions, iterate until no
1138 // more are found
1139 } while (!unresolved_exception_types.empty());
1140
1141 // We walk the roots looking for classes so that we'll pick up the
1142 // above classes plus any classes them depend on such super
1143 // classes, interfaces, and the required ClassLinker roots.
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001144 RecordImageClassesVisitor visitor(image_classes_.get());
1145 class_linker->VisitClasses(&visitor);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001146
1147 CHECK_NE(image_classes_->size(), 0U);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001148}
1149
Vladimir Marko19a4d372016-12-08 14:41:46 +00001150static void MaybeAddToImageClasses(Thread* self,
1151 ObjPtr<mirror::Class> klass,
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001152 std::unordered_set<std::string>* image_classes)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001153 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko19a4d372016-12-08 14:41:46 +00001154 DCHECK_EQ(self, Thread::Current());
Mathieu Chartierf8322842014-05-16 10:59:25 -07001155 StackHandleScope<1> hs(self);
Ian Rogers1ff3c982014-08-12 02:30:58 -07001156 std::string temp;
Andreas Gampe542451c2016-07-26 09:02:02 -07001157 const PointerSize pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001158 while (!klass->IsObjectClass()) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07001159 const char* descriptor = klass->GetDescriptor(&temp);
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001160 std::pair<std::unordered_set<std::string>::iterator, bool> result =
1161 image_classes->insert(descriptor);
Ian Rogers1ff3c982014-08-12 02:30:58 -07001162 if (!result.second) { // Previously inserted.
1163 break;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001164 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07001165 VLOG(compiler) << "Adding " << descriptor << " to image classes";
Vladimir Marko19a4d372016-12-08 14:41:46 +00001166 for (size_t i = 0, num_interfaces = klass->NumDirectInterfaces(); i != num_interfaces; ++i) {
1167 ObjPtr<mirror::Class> interface = mirror::Class::GetDirectInterface(self, klass, i);
1168 DCHECK(interface != nullptr);
1169 MaybeAddToImageClasses(self, interface, image_classes);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001170 }
Vladimir Marko19a4d372016-12-08 14:41:46 +00001171 for (auto& m : klass->GetVirtualMethods(pointer_size)) {
1172 MaybeAddToImageClasses(self, m.GetDeclaringClass(), image_classes);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001173 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001174 if (klass->IsArrayClass()) {
Vladimir Marko19a4d372016-12-08 14:41:46 +00001175 MaybeAddToImageClasses(self, klass->GetComponentType(), image_classes);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001176 }
Mathieu Chartierf8322842014-05-16 10:59:25 -07001177 klass.Assign(klass->GetSuperClass());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001178 }
1179}
1180
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001181// Keeps all the data for the update together. Also doubles as the reference visitor.
1182// Note: we can use object pointers because we suspend all threads.
1183class ClinitImageUpdate {
1184 public:
Mathieu Chartier31e88222016-10-14 18:43:19 -07001185 static ClinitImageUpdate* Create(VariableSizedHandleScope& hs,
1186 std::unordered_set<std::string>* image_class_descriptors,
1187 Thread* self,
1188 ClassLinker* linker) {
1189 std::unique_ptr<ClinitImageUpdate> res(new ClinitImageUpdate(hs,
1190 image_class_descriptors,
1191 self,
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001192 linker));
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001193 return res.release();
1194 }
1195
1196 ~ClinitImageUpdate() {
1197 // Allow others to suspend again.
1198 self_->EndAssertNoThreadSuspension(old_cause_);
1199 }
1200
1201 // Visitor for VisitReferences.
Mathieu Chartier31e88222016-10-14 18:43:19 -07001202 void operator()(ObjPtr<mirror::Object> object,
1203 MemberOffset field_offset,
1204 bool /* is_static */) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001205 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001206 mirror::Object* ref = object->GetFieldObject<mirror::Object>(field_offset);
1207 if (ref != nullptr) {
1208 VisitClinitClassesObject(ref);
1209 }
1210 }
1211
Roland Levillain5e8d5f02016-10-18 18:03:43 +01001212 // java.lang.ref.Reference visitor for VisitReferences.
Mathieu Chartier31e88222016-10-14 18:43:19 -07001213 void operator()(ObjPtr<mirror::Class> klass ATTRIBUTE_UNUSED,
1214 ObjPtr<mirror::Reference> ref ATTRIBUTE_UNUSED) const {}
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001215
1216 // Ignore class native roots.
1217 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED)
1218 const {}
1219 void VisitRoot(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED) const {}
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001220
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001221 void Walk() REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001222 // Use the initial classes as roots for a search.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001223 for (Handle<mirror::Class> klass_root : image_classes_) {
1224 VisitClinitClassesObject(klass_root.Get());
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001225 }
Vladimir Marko19a4d372016-12-08 14:41:46 +00001226 Thread* self = Thread::Current();
1227 ScopedAssertNoThreadSuspension ants(__FUNCTION__);
Mathieu Chartier31e88222016-10-14 18:43:19 -07001228 for (Handle<mirror::Class> h_klass : to_insert_) {
Vladimir Marko19a4d372016-12-08 14:41:46 +00001229 MaybeAddToImageClasses(self, h_klass.Get(), image_class_descriptors_);
Mathieu Chartier31e88222016-10-14 18:43:19 -07001230 }
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001231 }
1232
1233 private:
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001234 class FindImageClassesVisitor : public ClassVisitor {
1235 public:
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001236 explicit FindImageClassesVisitor(VariableSizedHandleScope& hs,
1237 ClinitImageUpdate* data)
1238 : data_(data),
1239 hs_(hs) {}
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001240
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001241 bool operator()(ObjPtr<mirror::Class> klass) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001242 std::string temp;
1243 const char* name = klass->GetDescriptor(&temp);
1244 if (data_->image_class_descriptors_->find(name) != data_->image_class_descriptors_->end()) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001245 data_->image_classes_.push_back(hs_.NewHandle(klass));
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001246 } else {
1247 // Check whether it is initialized and has a clinit. They must be kept, too.
1248 if (klass->IsInitialized() && klass->FindClassInitializer(
1249 Runtime::Current()->GetClassLinker()->GetImagePointerSize()) != nullptr) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001250 data_->image_classes_.push_back(hs_.NewHandle(klass));
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001251 }
1252 }
1253 return true;
1254 }
1255
1256 private:
1257 ClinitImageUpdate* const data_;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001258 VariableSizedHandleScope& hs_;
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001259 };
1260
Mathieu Chartier31e88222016-10-14 18:43:19 -07001261 ClinitImageUpdate(VariableSizedHandleScope& hs,
1262 std::unordered_set<std::string>* image_class_descriptors,
1263 Thread* self,
1264 ClassLinker* linker) REQUIRES_SHARED(Locks::mutator_lock_)
1265 : hs_(hs),
1266 image_class_descriptors_(image_class_descriptors),
1267 self_(self) {
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001268 CHECK(linker != nullptr);
1269 CHECK(image_class_descriptors != nullptr);
1270
1271 // Make sure nobody interferes with us.
1272 old_cause_ = self->StartAssertNoThreadSuspension("Boot image closure");
1273
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001274 // Find all the already-marked classes.
1275 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001276 FindImageClassesVisitor visitor(hs_, this);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001277 linker->VisitClasses(&visitor);
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001278 }
1279
1280 void VisitClinitClassesObject(mirror::Object* object) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001281 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001282 DCHECK(object != nullptr);
1283 if (marked_objects_.find(object) != marked_objects_.end()) {
1284 // Already processed.
1285 return;
1286 }
1287
1288 // Mark it.
1289 marked_objects_.insert(object);
1290
1291 if (object->IsClass()) {
Mathieu Chartier31e88222016-10-14 18:43:19 -07001292 // Add to the TODO list since MaybeAddToImageClasses may cause thread suspension. Thread
1293 // suspensionb is not safe to do in VisitObjects or VisitReferences.
1294 to_insert_.push_back(hs_.NewHandle(object->AsClass()));
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001295 } else {
1296 // Else visit the object's class.
1297 VisitClinitClassesObject(object->GetClass());
1298 }
1299
Mathieu Chartiere401d142015-04-22 13:56:20 -07001300 // If it is not a DexCache, visit all references.
Mathieu Chartier31e88222016-10-14 18:43:19 -07001301 if (!object->IsDexCache()) {
Mathieu Chartier059ef3d2015-08-18 13:54:21 -07001302 object->VisitReferences(*this, *this);
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001303 }
1304 }
1305
Mathieu Chartier31e88222016-10-14 18:43:19 -07001306 VariableSizedHandleScope& hs_;
1307 mutable std::vector<Handle<mirror::Class>> to_insert_;
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001308 mutable std::unordered_set<mirror::Object*> marked_objects_;
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001309 std::unordered_set<std::string>* const image_class_descriptors_;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001310 std::vector<Handle<mirror::Class>> image_classes_;
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001311 Thread* const self_;
1312 const char* old_cause_;
1313
1314 DISALLOW_COPY_AND_ASSIGN(ClinitImageUpdate);
1315};
Brian Carlstrom7940e442013-07-12 13:46:57 -07001316
Ian Rogers3d504072014-03-01 09:16:49 -08001317void CompilerDriver::UpdateImageClasses(TimingLogger* timings) {
Vladimir Markoaad75c62016-10-03 08:46:48 +00001318 if (GetCompilerOptions().IsBootImage()) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07001319 TimingLogger::ScopedTiming t("UpdateImageClasses", timings);
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001320
Mathieu Chartier4f55e222015-09-04 13:26:21 -07001321 Runtime* runtime = Runtime::Current();
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001322
1323 // Suspend all threads.
Mathieu Chartier4f55e222015-09-04 13:26:21 -07001324 ScopedSuspendAll ssa(__FUNCTION__);
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001325
Mathieu Chartier31e88222016-10-14 18:43:19 -07001326 VariableSizedHandleScope hs(Thread::Current());
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001327 std::string error_msg;
Mathieu Chartier31e88222016-10-14 18:43:19 -07001328 std::unique_ptr<ClinitImageUpdate> update(ClinitImageUpdate::Create(hs,
1329 image_classes_.get(),
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001330 Thread::Current(),
Mathieu Chartier31e88222016-10-14 18:43:19 -07001331 runtime->GetClassLinker()));
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001332
1333 // Do the marking.
1334 update->Walk();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001335 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001336}
1337
Vladimir Marko07785bb2015-06-15 18:52:54 +01001338bool CompilerDriver::CanAssumeClassIsLoaded(mirror::Class* klass) {
1339 Runtime* runtime = Runtime::Current();
1340 if (!runtime->IsAotCompiler()) {
Calin Juravleffc87072016-04-20 14:22:09 +01001341 DCHECK(runtime->UseJitCompilation());
Vladimir Marko07785bb2015-06-15 18:52:54 +01001342 // Having the klass reference here implies that the klass is already loaded.
1343 return true;
1344 }
Vladimir Markoaad75c62016-10-03 08:46:48 +00001345 if (!GetCompilerOptions().IsBootImage()) {
Vladimir Marko07785bb2015-06-15 18:52:54 +01001346 // Assume loaded only if klass is in the boot image. App classes cannot be assumed
1347 // loaded because we don't even know what class loader will be used to load them.
1348 bool class_in_image = runtime->GetHeap()->FindSpaceFromObject(klass, false)->IsImageSpace();
1349 return class_in_image;
1350 }
1351 std::string temp;
1352 const char* descriptor = klass->GetDescriptor(&temp);
1353 return IsImageClass(descriptor);
1354}
1355
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001356bool CompilerDriver::CanAccessTypeWithoutChecks(ObjPtr<mirror::Class> referrer_class,
1357 ObjPtr<mirror::Class> resolved_class) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001358 if (resolved_class == nullptr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001359 stats_->TypeNeedsAccessCheck();
1360 return false; // Unknown class needs access checks.
1361 }
David Brazdil38f64d32016-01-18 17:13:41 +00001362 bool is_accessible = resolved_class->IsPublic(); // Public classes are always accessible.
1363 if (!is_accessible) {
David Brazdil38f64d32016-01-18 17:13:41 +00001364 if (referrer_class == nullptr) {
1365 stats_->TypeNeedsAccessCheck();
1366 return false; // Incomplete referrer knowledge needs access check.
1367 }
1368 // Perform access check, will return true if access is ok or false if we're going to have to
1369 // check this at runtime (for example for class loaders).
1370 is_accessible = referrer_class->CanAccess(resolved_class);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001371 }
David Brazdil38f64d32016-01-18 17:13:41 +00001372 if (is_accessible) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001373 stats_->TypeDoesntNeedAccessCheck();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001374 } else {
1375 stats_->TypeNeedsAccessCheck();
1376 }
David Brazdil38f64d32016-01-18 17:13:41 +00001377 return is_accessible;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001378}
1379
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001380bool CompilerDriver::CanAccessInstantiableTypeWithoutChecks(ObjPtr<mirror::Class> referrer_class,
1381 ObjPtr<mirror::Class> resolved_class,
Mingyao Yangfb8464a2015-11-02 10:56:59 -08001382 bool* finalizable) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001383 if (resolved_class == nullptr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001384 stats_->TypeNeedsAccessCheck();
Mingyao Yangfb8464a2015-11-02 10:56:59 -08001385 // Be conservative.
1386 *finalizable = true;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001387 return false; // Unknown class needs access checks.
1388 }
Mingyao Yangfb8464a2015-11-02 10:56:59 -08001389 *finalizable = resolved_class->IsFinalizable();
David Brazdil38f64d32016-01-18 17:13:41 +00001390 bool is_accessible = resolved_class->IsPublic(); // Public classes are always accessible.
1391 if (!is_accessible) {
David Brazdil38f64d32016-01-18 17:13:41 +00001392 if (referrer_class == nullptr) {
1393 stats_->TypeNeedsAccessCheck();
1394 return false; // Incomplete referrer knowledge needs access check.
1395 }
1396 // Perform access and instantiable checks, will return true if access is ok or false if we're
1397 // going to have to check this at runtime (for example for class loaders).
1398 is_accessible = referrer_class->CanAccess(resolved_class);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001399 }
David Brazdil38f64d32016-01-18 17:13:41 +00001400 bool result = is_accessible && resolved_class->IsInstantiable();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001401 if (result) {
1402 stats_->TypeDoesntNeedAccessCheck();
1403 } else {
1404 stats_->TypeNeedsAccessCheck();
1405 }
1406 return result;
1407}
1408
Vladimir Markobe0e5462014-02-26 11:24:15 +00001409void CompilerDriver::ProcessedInstanceField(bool resolved) {
1410 if (!resolved) {
1411 stats_->UnresolvedInstanceField();
1412 } else {
1413 stats_->ResolvedInstanceField();
1414 }
1415}
1416
1417void CompilerDriver::ProcessedStaticField(bool resolved, bool local) {
1418 if (!resolved) {
1419 stats_->UnresolvedStaticField();
1420 } else if (local) {
1421 stats_->ResolvedLocalStaticField();
1422 } else {
1423 stats_->ResolvedStaticField();
1424 }
1425}
1426
Mathieu Chartierc7853442015-03-27 14:35:38 -07001427ArtField* CompilerDriver::ComputeInstanceFieldInfo(uint32_t field_idx,
Vladimir Markoe11dd502017-12-08 14:09:45 +00001428 const DexCompilationUnit* mUnit,
1429 bool is_put,
Mathieu Chartierc7853442015-03-27 14:35:38 -07001430 const ScopedObjectAccess& soa) {
Vladimir Markobe0e5462014-02-26 11:24:15 +00001431 // Try to resolve the field and compiling method's class.
Mathieu Chartierc7853442015-03-27 14:35:38 -07001432 ArtField* resolved_field;
Vladimir Marko28e012a2017-12-07 11:22:59 +00001433 ObjPtr<mirror::Class> referrer_class;
Mathieu Chartier736b5602015-09-02 14:54:11 -07001434 Handle<mirror::DexCache> dex_cache(mUnit->GetDexCache());
Vladimir Markobe0e5462014-02-26 11:24:15 +00001435 {
Vladimir Markoe11dd502017-12-08 14:09:45 +00001436 Handle<mirror::ClassLoader> class_loader = mUnit->GetClassLoader();
1437 resolved_field = ResolveField(soa, dex_cache, class_loader, field_idx, /* is_static */ false);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001438 referrer_class = resolved_field != nullptr
Vladimir Markoe11dd502017-12-08 14:09:45 +00001439 ? ResolveCompilingMethodsClass(soa, dex_cache, class_loader, mUnit) : nullptr;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001440 }
Nicolas Geoffraye5038322014-07-04 09:41:32 +01001441 bool can_link = false;
Vladimir Markobe0e5462014-02-26 11:24:15 +00001442 if (resolved_field != nullptr && referrer_class != nullptr) {
Vladimir Markobe0e5462014-02-26 11:24:15 +00001443 std::pair<bool, bool> fast_path = IsFastInstanceField(
Mathieu Chartier736b5602015-09-02 14:54:11 -07001444 dex_cache.Get(), referrer_class, resolved_field, field_idx);
Nicolas Geoffraye5038322014-07-04 09:41:32 +01001445 can_link = is_put ? fast_path.second : fast_path.first;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001446 }
Nicolas Geoffraye5038322014-07-04 09:41:32 +01001447 ProcessedInstanceField(can_link);
1448 return can_link ? resolved_field : nullptr;
1449}
1450
1451bool CompilerDriver::ComputeInstanceFieldInfo(uint32_t field_idx, const DexCompilationUnit* mUnit,
1452 bool is_put, MemberOffset* field_offset,
1453 bool* is_volatile) {
1454 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartierc7853442015-03-27 14:35:38 -07001455 ArtField* resolved_field = ComputeInstanceFieldInfo(field_idx, mUnit, is_put, soa);
Nicolas Geoffraye5038322014-07-04 09:41:32 +01001456
Mathieu Chartierc7853442015-03-27 14:35:38 -07001457 if (resolved_field == nullptr) {
Vladimir Markobe0e5462014-02-26 11:24:15 +00001458 // Conservative defaults.
1459 *is_volatile = true;
1460 *field_offset = MemberOffset(static_cast<size_t>(-1));
Nicolas Geoffraye5038322014-07-04 09:41:32 +01001461 return false;
1462 } else {
1463 *is_volatile = resolved_field->IsVolatile();
1464 *field_offset = resolved_field->GetOffset();
1465 return true;
Vladimir Markobe0e5462014-02-26 11:24:15 +00001466 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001467}
1468
Vladimir Marko2730db02014-01-27 11:15:17 +00001469const VerifiedMethod* CompilerDriver::GetVerifiedMethod(const DexFile* dex_file,
1470 uint32_t method_idx) const {
1471 MethodReference ref(dex_file, method_idx);
1472 return verification_results_->GetVerifiedMethod(ref);
1473}
1474
1475bool CompilerDriver::IsSafeCast(const DexCompilationUnit* mUnit, uint32_t dex_pc) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001476 if (!compiler_options_->IsVerificationEnabled()) {
1477 // If we didn't verify, every cast has to be treated as non-safe.
1478 return false;
1479 }
Vladimir Marko2730db02014-01-27 11:15:17 +00001480 DCHECK(mUnit->GetVerifiedMethod() != nullptr);
1481 bool result = mUnit->GetVerifiedMethod()->IsSafeCast(dex_pc);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001482 if (result) {
1483 stats_->SafeCast();
1484 } else {
1485 stats_->NotASafeCast();
1486 }
1487 return result;
1488}
1489
Mathieu Chartier90443472015-07-16 20:32:27 -07001490class CompilationVisitor {
1491 public:
1492 virtual ~CompilationVisitor() {}
1493 virtual void Visit(size_t index) = 0;
1494};
1495
Brian Carlstrom7940e442013-07-12 13:46:57 -07001496class ParallelCompilationManager {
1497 public:
Brian Carlstrom7940e442013-07-12 13:46:57 -07001498 ParallelCompilationManager(ClassLinker* class_linker,
1499 jobject class_loader,
1500 CompilerDriver* compiler,
1501 const DexFile* dex_file,
Andreas Gampede7b4362014-07-28 18:38:57 -07001502 const std::vector<const DexFile*>& dex_files,
Ian Rogers3d504072014-03-01 09:16:49 -08001503 ThreadPool* thread_pool)
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001504 : index_(0),
1505 class_linker_(class_linker),
Brian Carlstrom7940e442013-07-12 13:46:57 -07001506 class_loader_(class_loader),
1507 compiler_(compiler),
1508 dex_file_(dex_file),
Andreas Gampede7b4362014-07-28 18:38:57 -07001509 dex_files_(dex_files),
Ian Rogers3d504072014-03-01 09:16:49 -08001510 thread_pool_(thread_pool) {}
Brian Carlstrom7940e442013-07-12 13:46:57 -07001511
1512 ClassLinker* GetClassLinker() const {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001513 CHECK(class_linker_ != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001514 return class_linker_;
1515 }
1516
1517 jobject GetClassLoader() const {
1518 return class_loader_;
1519 }
1520
1521 CompilerDriver* GetCompiler() const {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001522 CHECK(compiler_ != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001523 return compiler_;
1524 }
1525
1526 const DexFile* GetDexFile() const {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001527 CHECK(dex_file_ != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001528 return dex_file_;
1529 }
1530
Andreas Gampede7b4362014-07-28 18:38:57 -07001531 const std::vector<const DexFile*>& GetDexFiles() const {
1532 return dex_files_;
1533 }
1534
Mathieu Chartier90443472015-07-16 20:32:27 -07001535 void ForAll(size_t begin, size_t end, CompilationVisitor* visitor, size_t work_units)
1536 REQUIRES(!*Locks::mutator_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001537 Thread* self = Thread::Current();
1538 self->AssertNoPendingException();
1539 CHECK_GT(work_units, 0U);
1540
Ian Rogers3e5cf302014-05-20 16:40:37 -07001541 index_.StoreRelaxed(begin);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001542 for (size_t i = 0; i < work_units; ++i) {
Mathieu Chartier90443472015-07-16 20:32:27 -07001543 thread_pool_->AddTask(self, new ForAllClosure(this, end, visitor));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001544 }
1545 thread_pool_->StartWorkers(self);
1546
1547 // Ensure we're suspended while we're blocked waiting for the other threads to finish (worker
1548 // thread destructor's called below perform join).
1549 CHECK_NE(self->GetState(), kRunnable);
1550
1551 // Wait for all the worker threads to finish.
1552 thread_pool_->Wait(self, true, false);
Andreas Gampeace0dc12016-01-20 13:33:13 -08001553
1554 // And stop the workers accepting jobs.
1555 thread_pool_->StopWorkers(self);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001556 }
1557
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001558 size_t NextIndex() {
Ian Rogers3e5cf302014-05-20 16:40:37 -07001559 return index_.FetchAndAddSequentiallyConsistent(1);
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001560 }
1561
Brian Carlstrom7940e442013-07-12 13:46:57 -07001562 private:
Brian Carlstrom7940e442013-07-12 13:46:57 -07001563 class ForAllClosure : public Task {
1564 public:
Mathieu Chartier90443472015-07-16 20:32:27 -07001565 ForAllClosure(ParallelCompilationManager* manager, size_t end, CompilationVisitor* visitor)
Brian Carlstrom7940e442013-07-12 13:46:57 -07001566 : manager_(manager),
Brian Carlstrom7940e442013-07-12 13:46:57 -07001567 end_(end),
Mathieu Chartier90443472015-07-16 20:32:27 -07001568 visitor_(visitor) {}
Brian Carlstrom7940e442013-07-12 13:46:57 -07001569
1570 virtual void Run(Thread* self) {
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001571 while (true) {
1572 const size_t index = manager_->NextIndex();
1573 if (UNLIKELY(index >= end_)) {
1574 break;
1575 }
Mathieu Chartier90443472015-07-16 20:32:27 -07001576 visitor_->Visit(index);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001577 self->AssertNoPendingException();
1578 }
1579 }
1580
1581 virtual void Finalize() {
1582 delete this;
1583 }
Brian Carlstrom0cd7ec22013-07-17 23:40:20 -07001584
Brian Carlstrom7940e442013-07-12 13:46:57 -07001585 private:
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001586 ParallelCompilationManager* const manager_;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001587 const size_t end_;
Mathieu Chartier90443472015-07-16 20:32:27 -07001588 CompilationVisitor* const visitor_;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001589 };
1590
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001591 AtomicInteger index_;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001592 ClassLinker* const class_linker_;
1593 const jobject class_loader_;
1594 CompilerDriver* const compiler_;
1595 const DexFile* const dex_file_;
Andreas Gampede7b4362014-07-28 18:38:57 -07001596 const std::vector<const DexFile*>& dex_files_;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001597 ThreadPool* const thread_pool_;
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001598
1599 DISALLOW_COPY_AND_ASSIGN(ParallelCompilationManager);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001600};
1601
Jeff Hao0e49b422013-11-08 12:16:56 -08001602// A fast version of SkipClass above if the class pointer is available
1603// that avoids the expensive FindInClassPath search.
Vladimir Marko28e012a2017-12-07 11:22:59 +00001604static bool SkipClass(jobject class_loader, const DexFile& dex_file, ObjPtr<mirror::Class> klass)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001605 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001606 DCHECK(klass != nullptr);
Jeff Hao0e49b422013-11-08 12:16:56 -08001607 const DexFile& original_dex_file = *klass->GetDexCache()->GetDexFile();
1608 if (&dex_file != &original_dex_file) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001609 if (class_loader == nullptr) {
David Sehr709b0702016-10-13 09:12:37 -07001610 LOG(WARNING) << "Skipping class " << klass->PrettyDescriptor() << " from "
Jeff Hao0e49b422013-11-08 12:16:56 -08001611 << dex_file.GetLocation() << " previously found in "
1612 << original_dex_file.GetLocation();
1613 }
1614 return true;
1615 }
1616 return false;
1617}
1618
Mathieu Chartier70b63482014-06-27 17:19:04 -07001619static void CheckAndClearResolveException(Thread* self)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001620 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier70b63482014-06-27 17:19:04 -07001621 CHECK(self->IsExceptionPending());
Nicolas Geoffray14691c52015-03-05 10:40:17 +00001622 mirror::Throwable* exception = self->GetException();
Ian Rogers1ff3c982014-08-12 02:30:58 -07001623 std::string temp;
1624 const char* descriptor = exception->GetClass()->GetDescriptor(&temp);
1625 const char* expected_exceptions[] = {
1626 "Ljava/lang/IllegalAccessError;",
1627 "Ljava/lang/IncompatibleClassChangeError;",
1628 "Ljava/lang/InstantiationError;",
Brian Carlstrom898fcb52014-08-25 23:07:30 -07001629 "Ljava/lang/LinkageError;",
Ian Rogers1ff3c982014-08-12 02:30:58 -07001630 "Ljava/lang/NoClassDefFoundError;",
1631 "Ljava/lang/NoSuchFieldError;",
1632 "Ljava/lang/NoSuchMethodError;"
1633 };
1634 bool found = false;
1635 for (size_t i = 0; (found == false) && (i < arraysize(expected_exceptions)); ++i) {
1636 if (strcmp(descriptor, expected_exceptions[i]) == 0) {
1637 found = true;
1638 }
1639 }
1640 if (!found) {
Brian Carlstrom898fcb52014-08-25 23:07:30 -07001641 LOG(FATAL) << "Unexpected exception " << exception->Dump();
Mathieu Chartier70b63482014-06-27 17:19:04 -07001642 }
1643 self->ClearException();
1644}
1645
Mathieu Chartierb5d38612016-04-07 10:52:52 -07001646bool CompilerDriver::RequiresConstructorBarrier(const DexFile& dex_file,
1647 uint16_t class_def_idx) const {
1648 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_idx);
1649 const uint8_t* class_data = dex_file.GetClassData(class_def);
1650 if (class_data == nullptr) {
1651 // Empty class such as a marker interface.
1652 return false;
1653 }
1654 ClassDataItemIterator it(dex_file, class_data);
Mathieu Chartiere17cf242017-06-19 11:05:51 -07001655 it.SkipStaticFields();
Mathieu Chartierb5d38612016-04-07 10:52:52 -07001656 // We require a constructor barrier if there are final instance fields.
1657 while (it.HasNextInstanceField()) {
1658 if (it.MemberIsFinal()) {
1659 return true;
1660 }
1661 it.Next();
1662 }
1663 return false;
1664}
1665
Mathieu Chartier90443472015-07-16 20:32:27 -07001666class ResolveClassFieldsAndMethodsVisitor : public CompilationVisitor {
1667 public:
1668 explicit ResolveClassFieldsAndMethodsVisitor(const ParallelCompilationManager* manager)
1669 : manager_(manager) {}
Brian Carlstrom7940e442013-07-12 13:46:57 -07001670
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001671 void Visit(size_t class_def_index) OVERRIDE REQUIRES(!Locks::mutator_lock_) {
Andreas Gampe9b827ab2017-12-07 19:32:48 -08001672 ScopedTrace trace(__FUNCTION__);
Mathieu Chartier90443472015-07-16 20:32:27 -07001673 Thread* const self = Thread::Current();
1674 jobject jclass_loader = manager_->GetClassLoader();
1675 const DexFile& dex_file = *manager_->GetDexFile();
1676 ClassLinker* class_linker = manager_->GetClassLinker();
Ian Rogerse6bb3b22013-08-19 21:51:45 -07001677
Mathieu Chartier90443472015-07-16 20:32:27 -07001678 // If an instance field is final then we need to have a barrier on the return, static final
1679 // fields are assigned within the lock held for class initialization. Conservatively assume
1680 // constructor barriers are always required.
1681 bool requires_constructor_barrier = true;
1682
1683 // Method and Field are the worst. We can't resolve without either
1684 // context from the code use (to disambiguate virtual vs direct
1685 // method and instance vs static field) or from class
1686 // definitions. While the compiler will resolve what it can as it
1687 // needs it, here we try to resolve fields and methods used in class
1688 // definitions, since many of them many never be referenced by
1689 // generated code.
1690 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
1691 ScopedObjectAccess soa(self);
1692 StackHandleScope<2> hs(soa.Self());
1693 Handle<mirror::ClassLoader> class_loader(
Mathieu Chartier0795f232016-09-27 18:43:30 -07001694 hs.NewHandle(soa.Decode<mirror::ClassLoader>(jclass_loader)));
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001695 Handle<mirror::DexCache> dex_cache(hs.NewHandle(class_linker->FindDexCache(
Vladimir Markocd556b02017-02-03 11:47:34 +00001696 soa.Self(), dex_file)));
Mathieu Chartier90443472015-07-16 20:32:27 -07001697 // Resolve the class.
Vladimir Marko28e012a2017-12-07 11:22:59 +00001698 ObjPtr<mirror::Class> klass =
Vladimir Marko666ee3d2017-12-11 18:37:36 +00001699 class_linker->ResolveType(class_def.class_idx_, dex_cache, class_loader);
Mathieu Chartier90443472015-07-16 20:32:27 -07001700 bool resolve_fields_and_methods;
1701 if (klass == nullptr) {
1702 // Class couldn't be resolved, for example, super-class is in a different dex file. Don't
1703 // attempt to resolve methods and fields when there is no declaring class.
1704 CheckAndClearResolveException(soa.Self());
1705 resolve_fields_and_methods = false;
1706 } else {
1707 // We successfully resolved a class, should we skip it?
1708 if (SkipClass(jclass_loader, dex_file, klass)) {
1709 return;
Ian Rogerse6bb3b22013-08-19 21:51:45 -07001710 }
Mathieu Chartier90443472015-07-16 20:32:27 -07001711 // We want to resolve the methods and fields eagerly.
1712 resolve_fields_and_methods = true;
Ian Rogers68b56852014-08-29 20:19:11 -07001713 }
Mathieu Chartier90443472015-07-16 20:32:27 -07001714 // Note the class_data pointer advances through the headers,
1715 // static fields, instance fields, direct methods, and virtual
1716 // methods.
1717 const uint8_t* class_data = dex_file.GetClassData(class_def);
1718 if (class_data == nullptr) {
1719 // Empty class such as a marker interface.
1720 requires_constructor_barrier = false;
1721 } else {
1722 ClassDataItemIterator it(dex_file, class_data);
1723 while (it.HasNextStaticField()) {
1724 if (resolve_fields_and_methods) {
Vladimir Markoe11dd502017-12-08 14:09:45 +00001725 ArtField* field = class_linker->ResolveField(
1726 it.GetMemberIndex(), dex_cache, class_loader, /* is_static */ true);
Mathieu Chartier90443472015-07-16 20:32:27 -07001727 if (field == nullptr) {
1728 CheckAndClearResolveException(soa.Self());
1729 }
Ian Rogers68b56852014-08-29 20:19:11 -07001730 }
1731 it.Next();
1732 }
Mathieu Chartier90443472015-07-16 20:32:27 -07001733 // We require a constructor barrier if there are final instance fields.
1734 requires_constructor_barrier = false;
1735 while (it.HasNextInstanceField()) {
1736 if (it.MemberIsFinal()) {
1737 requires_constructor_barrier = true;
1738 }
1739 if (resolve_fields_and_methods) {
Vladimir Markoe11dd502017-12-08 14:09:45 +00001740 ArtField* field = class_linker->ResolveField(
1741 it.GetMemberIndex(), dex_cache, class_loader, /* is_static */ false);
Mathieu Chartier90443472015-07-16 20:32:27 -07001742 if (field == nullptr) {
1743 CheckAndClearResolveException(soa.Self());
1744 }
Ian Rogers68b56852014-08-29 20:19:11 -07001745 }
1746 it.Next();
1747 }
Mathieu Chartier90443472015-07-16 20:32:27 -07001748 if (resolve_fields_and_methods) {
Mathieu Chartierb7c273c2017-11-10 18:07:56 -08001749 while (it.HasNextMethod()) {
Vladimir Markoba118822017-06-12 15:41:56 +01001750 ArtMethod* method = class_linker->ResolveMethod<ClassLinker::ResolveMode::kNoChecks>(
Vladimir Marko89011192017-12-11 13:45:05 +00001751 it.GetMemberIndex(),
1752 dex_cache,
1753 class_loader,
1754 /* referrer */ nullptr,
Mathieu Chartier90443472015-07-16 20:32:27 -07001755 it.GetMethodInvokeType(class_def));
1756 if (method == nullptr) {
1757 CheckAndClearResolveException(soa.Self());
1758 }
1759 it.Next();
1760 }
1761 DCHECK(!it.HasNext());
1762 }
1763 }
Mathieu Chartierc4ae9162016-04-07 13:19:19 -07001764 manager_->GetCompiler()->SetRequiresConstructorBarrier(self,
1765 &dex_file,
1766 class_def_index,
1767 requires_constructor_barrier);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001768 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001769
Mathieu Chartier90443472015-07-16 20:32:27 -07001770 private:
1771 const ParallelCompilationManager* const manager_;
1772};
1773
1774class ResolveTypeVisitor : public CompilationVisitor {
1775 public:
1776 explicit ResolveTypeVisitor(const ParallelCompilationManager* manager) : manager_(manager) {
1777 }
Andreas Gampea5b09a62016-11-17 15:21:22 -08001778 void Visit(size_t type_idx) OVERRIDE REQUIRES(!Locks::mutator_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001779 // Class derived values are more complicated, they require the linker and loader.
Mathieu Chartier90443472015-07-16 20:32:27 -07001780 ScopedObjectAccess soa(Thread::Current());
1781 ClassLinker* class_linker = manager_->GetClassLinker();
1782 const DexFile& dex_file = *manager_->GetDexFile();
1783 StackHandleScope<2> hs(soa.Self());
Mathieu Chartier90443472015-07-16 20:32:27 -07001784 Handle<mirror::ClassLoader> class_loader(
Mathieu Chartier0795f232016-09-27 18:43:30 -07001785 hs.NewHandle(soa.Decode<mirror::ClassLoader>(manager_->GetClassLoader())));
Mathieu Chartierd57d4542015-10-14 10:55:30 -07001786 Handle<mirror::DexCache> dex_cache(hs.NewHandle(class_linker->RegisterDexFile(
1787 dex_file,
Mathieu Chartierf284d442016-06-02 11:48:30 -07001788 class_loader.Get())));
Andreas Gampefa4333d2017-02-14 11:10:34 -08001789 ObjPtr<mirror::Class> klass = (dex_cache != nullptr)
Vladimir Marko666ee3d2017-12-11 18:37:36 +00001790 ? class_linker->ResolveType(dex::TypeIndex(type_idx), dex_cache, class_loader)
Vladimir Markocd556b02017-02-03 11:47:34 +00001791 : nullptr;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001792
Mathieu Chartier90443472015-07-16 20:32:27 -07001793 if (klass == nullptr) {
1794 soa.Self()->AssertPendingException();
1795 mirror::Throwable* exception = soa.Self()->GetException();
1796 VLOG(compiler) << "Exception during type resolution: " << exception->Dump();
1797 if (exception->GetClass()->DescriptorEquals("Ljava/lang/OutOfMemoryError;")) {
1798 // There's little point continuing compilation if the heap is exhausted.
1799 LOG(FATAL) << "Out of memory during type resolution for compilation";
1800 }
1801 soa.Self()->ClearException();
Ian Rogersa436fde2013-08-27 23:34:06 -07001802 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001803 }
Mathieu Chartier90443472015-07-16 20:32:27 -07001804
1805 private:
1806 const ParallelCompilationManager* const manager_;
1807};
Brian Carlstrom7940e442013-07-12 13:46:57 -07001808
Andreas Gampeace0dc12016-01-20 13:33:13 -08001809void CompilerDriver::ResolveDexFile(jobject class_loader,
1810 const DexFile& dex_file,
Andreas Gampede7b4362014-07-28 18:38:57 -07001811 const std::vector<const DexFile*>& dex_files,
Andreas Gampeace0dc12016-01-20 13:33:13 -08001812 ThreadPool* thread_pool,
1813 size_t thread_count,
1814 TimingLogger* timings) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001815 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1816
1817 // TODO: we could resolve strings here, although the string table is largely filled with class
1818 // and method names.
1819
Andreas Gampede7b4362014-07-28 18:38:57 -07001820 ParallelCompilationManager context(class_linker, class_loader, this, &dex_file, dex_files,
1821 thread_pool);
Vladimir Markoaad75c62016-10-03 08:46:48 +00001822 if (GetCompilerOptions().IsBootImage()) {
Ian Rogerse6bb3b22013-08-19 21:51:45 -07001823 // For images we resolve all types, such as array, whereas for applications just those with
1824 // classdefs are resolved by ResolveClassFieldsAndMethods.
Mathieu Chartierf5997b42014-06-20 10:37:54 -07001825 TimingLogger::ScopedTiming t("Resolve Types", timings);
Mathieu Chartier90443472015-07-16 20:32:27 -07001826 ResolveTypeVisitor visitor(&context);
Andreas Gampeace0dc12016-01-20 13:33:13 -08001827 context.ForAll(0, dex_file.NumTypeIds(), &visitor, thread_count);
Ian Rogerse6bb3b22013-08-19 21:51:45 -07001828 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001829
Mathieu Chartierf5997b42014-06-20 10:37:54 -07001830 TimingLogger::ScopedTiming t("Resolve MethodsAndFields", timings);
Mathieu Chartier90443472015-07-16 20:32:27 -07001831 ResolveClassFieldsAndMethodsVisitor visitor(&context);
Andreas Gampeace0dc12016-01-20 13:33:13 -08001832 context.ForAll(0, dex_file.NumClassDefs(), &visitor, thread_count);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001833}
1834
Andreas Gampeace0dc12016-01-20 13:33:13 -08001835void CompilerDriver::SetVerified(jobject class_loader,
1836 const std::vector<const DexFile*>& dex_files,
1837 TimingLogger* timings) {
1838 // This can be run in parallel.
Mathieu Chartier90443472015-07-16 20:32:27 -07001839 for (const DexFile* dex_file : dex_files) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001840 CHECK(dex_file != nullptr);
Andreas Gampeace0dc12016-01-20 13:33:13 -08001841 SetVerifiedDexFile(class_loader,
1842 *dex_file,
1843 dex_files,
1844 parallel_thread_pool_.get(),
1845 parallel_thread_count_,
1846 timings);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001847 }
1848}
1849
Nicolas Geoffray51c17fa2016-11-25 15:56:12 +00001850static void PopulateVerifiedMethods(const DexFile& dex_file,
1851 uint32_t class_def_index,
1852 VerificationResults* verification_results) {
1853 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
1854 const uint8_t* class_data = dex_file.GetClassData(class_def);
1855 if (class_data == nullptr) {
1856 return;
1857 }
1858 ClassDataItemIterator it(dex_file, class_data);
Mathieu Chartiere17cf242017-06-19 11:05:51 -07001859 it.SkipAllFields();
Nicolas Geoffray51c17fa2016-11-25 15:56:12 +00001860
Mathieu Chartierb7c273c2017-11-10 18:07:56 -08001861 while (it.HasNextMethod()) {
Nicolas Geoffray51c17fa2016-11-25 15:56:12 +00001862 verification_results->CreateVerifiedMethodFor(MethodReference(&dex_file, it.GetMemberIndex()));
1863 it.Next();
1864 }
1865 DCHECK(!it.HasNext());
1866}
1867
Nicolas Geoffray0a27fd02017-01-25 16:18:54 +00001868static void LoadAndUpdateStatus(const DexFile& dex_file,
1869 const DexFile::ClassDef& class_def,
Vladimir Marko2c64a832018-01-04 11:31:56 +00001870 ClassStatus status,
Nicolas Geoffray0a27fd02017-01-25 16:18:54 +00001871 Handle<mirror::ClassLoader> class_loader,
1872 Thread* self)
1873 REQUIRES_SHARED(Locks::mutator_lock_) {
1874 StackHandleScope<1> hs(self);
1875 const char* descriptor = dex_file.GetClassDescriptor(class_def);
1876 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1877 Handle<mirror::Class> cls(hs.NewHandle<mirror::Class>(
1878 class_linker->FindClass(self, descriptor, class_loader)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08001879 if (cls != nullptr) {
Nicolas Geoffray0a27fd02017-01-25 16:18:54 +00001880 // Check that the class is resolved with the current dex file. We might get
1881 // a boot image class, or a class in a different dex file for multidex, and
1882 // we should not update the status in that case.
1883 if (&cls->GetDexFile() == &dex_file) {
1884 ObjectLock<mirror::Class> lock(self, cls);
1885 mirror::Class::SetStatus(cls, status, self);
1886 }
1887 } else {
1888 DCHECK(self->IsExceptionPending());
1889 self->ClearException();
1890 }
1891}
1892
Nicolas Geoffray74981052017-01-16 17:54:09 +00001893bool CompilerDriver::FastVerify(jobject jclass_loader,
1894 const std::vector<const DexFile*>& dex_files,
1895 TimingLogger* timings) {
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +00001896 verifier::VerifierDeps* verifier_deps =
1897 Runtime::Current()->GetCompilerCallbacks()->GetVerifierDeps();
Mathieu Chartier72041a02017-07-14 18:23:25 -07001898 // If there exist VerifierDeps that aren't the ones we just created to output, use them to verify.
1899 if (verifier_deps == nullptr || verifier_deps->OutputOnly()) {
Nicolas Geoffray74981052017-01-16 17:54:09 +00001900 return false;
1901 }
1902 TimingLogger::ScopedTiming t("Fast Verify", timings);
1903 ScopedObjectAccess soa(Thread::Current());
1904 StackHandleScope<2> hs(soa.Self());
1905 Handle<mirror::ClassLoader> class_loader(
1906 hs.NewHandle(soa.Decode<mirror::ClassLoader>(jclass_loader)));
Nicolas Geoffray74981052017-01-16 17:54:09 +00001907 if (!verifier_deps->ValidateDependencies(class_loader, soa.Self())) {
1908 return false;
1909 }
1910
Nicolas Geoffray49cda062017-04-21 13:08:25 +01001911 bool compiler_only_verifies = !GetCompilerOptions().IsAnyCompilationEnabled();
Nicolas Geoffray0a27fd02017-01-25 16:18:54 +00001912
Nicolas Geoffray74981052017-01-16 17:54:09 +00001913 // We successfully validated the dependencies, now update class status
1914 // of verified classes. Note that the dependencies also record which classes
1915 // could not be fully verified; we could try again, but that would hurt verification
1916 // time. So instead we assume these classes still need to be verified at
1917 // runtime.
1918 for (const DexFile* dex_file : dex_files) {
Mathieu Chartierbf755fe2017-08-01 13:42:56 -07001919 // Fetch the list of unverified classes.
1920 const std::set<dex::TypeIndex>& unverified_classes =
Nicolas Geoffray74981052017-01-16 17:54:09 +00001921 verifier_deps->GetUnverifiedClasses(*dex_file);
Nicolas Geoffray74981052017-01-16 17:54:09 +00001922 for (uint32_t i = 0; i < dex_file->NumClassDefs(); ++i) {
1923 const DexFile::ClassDef& class_def = dex_file->GetClassDef(i);
Mathieu Chartierbf755fe2017-08-01 13:42:56 -07001924 if (unverified_classes.find(class_def.class_idx_) == unverified_classes.end()) {
Nicolas Geoffray0a27fd02017-01-25 16:18:54 +00001925 if (compiler_only_verifies) {
Nicolas Geoffray74981052017-01-16 17:54:09 +00001926 // Just update the compiled_classes_ map. The compiler doesn't need to resolve
1927 // the type.
Mathieu Chartierfc8b4222017-09-17 13:44:24 -07001928 ClassReference ref(dex_file, i);
Vladimir Marko2c64a832018-01-04 11:31:56 +00001929 ClassStatus existing = ClassStatus::kNotReady;
Mathieu Chartier1a088d42017-07-18 11:43:57 -07001930 DCHECK(compiled_classes_.Get(ref, &existing)) << ref.dex_file->GetLocation();
1931 ClassStateTable::InsertResult result =
Vladimir Marko2c64a832018-01-04 11:31:56 +00001932 compiled_classes_.Insert(ref, existing, ClassStatus::kVerified);
Mathieu Chartier1a088d42017-07-18 11:43:57 -07001933 CHECK_EQ(result, ClassStateTable::kInsertResultSuccess);
Nicolas Geoffray74981052017-01-16 17:54:09 +00001934 } else {
Nicolas Geoffray0a27fd02017-01-25 16:18:54 +00001935 // Update the class status, so later compilation stages know they don't need to verify
Nicolas Geoffray74981052017-01-16 17:54:09 +00001936 // the class.
Nicolas Geoffray0a27fd02017-01-25 16:18:54 +00001937 LoadAndUpdateStatus(
Vladimir Marko2c64a832018-01-04 11:31:56 +00001938 *dex_file, class_def, ClassStatus::kVerified, class_loader, soa.Self());
Nicolas Geoffray74981052017-01-16 17:54:09 +00001939 // Create `VerifiedMethod`s for each methods, the compiler expects one for
1940 // quickening or compiling.
1941 // Note that this means:
1942 // - We're only going to compile methods that did verify.
1943 // - Quickening will not do checkcast ellision.
1944 // TODO(ngeoffray): Reconsider this once we refactor compiler filters.
1945 PopulateVerifiedMethods(*dex_file, i, verification_results_);
Nicolas Geoffray6bb7f1b2016-11-03 10:52:49 +00001946 }
Nicolas Geoffray0a27fd02017-01-25 16:18:54 +00001947 } else if (!compiler_only_verifies) {
1948 // Make sure later compilation stages know they should not try to verify
1949 // this class again.
1950 LoadAndUpdateStatus(*dex_file,
1951 class_def,
Vladimir Marko2c64a832018-01-04 11:31:56 +00001952 ClassStatus::kRetryVerificationAtRuntime,
Nicolas Geoffray0a27fd02017-01-25 16:18:54 +00001953 class_loader,
1954 soa.Self());
Nicolas Geoffray6bb7f1b2016-11-03 10:52:49 +00001955 }
Nicolas Geoffray6bb7f1b2016-11-03 10:52:49 +00001956 }
1957 }
Nicolas Geoffray74981052017-01-16 17:54:09 +00001958 return true;
1959}
1960
1961void CompilerDriver::Verify(jobject jclass_loader,
1962 const std::vector<const DexFile*>& dex_files,
1963 TimingLogger* timings) {
1964 if (FastVerify(jclass_loader, dex_files, timings)) {
1965 return;
1966 }
Nicolas Geoffray6bb7f1b2016-11-03 10:52:49 +00001967
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +00001968 // If there is no existing `verifier_deps` (because of non-existing vdex), or
1969 // the existing `verifier_deps` is not valid anymore, create a new one for
Nicolas Geoffray6bb7f1b2016-11-03 10:52:49 +00001970 // non boot image compilation. The verifier will need it to record the new dependencies.
1971 // Then dex2oat can update the vdex file with these new dependencies.
1972 if (!GetCompilerOptions().IsBootImage()) {
Mathieu Chartier72041a02017-07-14 18:23:25 -07001973 // Dex2oat creates the verifier deps.
Nicolas Geoffray340dafa2016-11-18 16:03:10 +00001974 // Create the main VerifierDeps, and set it to this thread.
Mathieu Chartier72041a02017-07-14 18:23:25 -07001975 verifier::VerifierDeps* verifier_deps =
1976 Runtime::Current()->GetCompilerCallbacks()->GetVerifierDeps();
1977 CHECK(verifier_deps != nullptr);
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +00001978 Thread::Current()->SetVerifierDeps(verifier_deps);
Nicolas Geoffray340dafa2016-11-18 16:03:10 +00001979 // Create per-thread VerifierDeps to avoid contention on the main one.
1980 // We will merge them after verification.
1981 for (ThreadPoolWorker* worker : parallel_thread_pool_->GetWorkers()) {
Mathieu Chartier72041a02017-07-14 18:23:25 -07001982 worker->GetThread()->SetVerifierDeps(new verifier::VerifierDeps(dex_files_for_oat_file_));
Nicolas Geoffray340dafa2016-11-18 16:03:10 +00001983 }
Nicolas Geoffray6bb7f1b2016-11-03 10:52:49 +00001984 }
Nicolas Geoffray74981052017-01-16 17:54:09 +00001985
Nicolas Geoffray46847392017-04-28 14:56:39 +01001986 // Verification updates VerifierDeps and needs to run single-threaded to be deterministic.
1987 bool force_determinism = GetCompilerOptions().IsForceDeterminism();
1988 ThreadPool* verify_thread_pool =
1989 force_determinism ? single_thread_pool_.get() : parallel_thread_pool_.get();
1990 size_t verify_thread_count = force_determinism ? 1U : parallel_thread_count_;
Mathieu Chartier90443472015-07-16 20:32:27 -07001991 for (const DexFile* dex_file : dex_files) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001992 CHECK(dex_file != nullptr);
Nicolas Geoffray6bb7f1b2016-11-03 10:52:49 +00001993 VerifyDexFile(jclass_loader,
Andreas Gampeace0dc12016-01-20 13:33:13 -08001994 *dex_file,
1995 dex_files,
Nicolas Geoffray46847392017-04-28 14:56:39 +01001996 verify_thread_pool,
1997 verify_thread_count,
Andreas Gampeace0dc12016-01-20 13:33:13 -08001998 timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001999 }
Nicolas Geoffray340dafa2016-11-18 16:03:10 +00002000
2001 if (!GetCompilerOptions().IsBootImage()) {
Nicolas Geoffray340dafa2016-11-18 16:03:10 +00002002 // Merge all VerifierDeps into the main one.
Nicolas Geoffray74981052017-01-16 17:54:09 +00002003 verifier::VerifierDeps* verifier_deps = Thread::Current()->GetVerifierDeps();
Nicolas Geoffray340dafa2016-11-18 16:03:10 +00002004 for (ThreadPoolWorker* worker : parallel_thread_pool_->GetWorkers()) {
2005 verifier::VerifierDeps* thread_deps = worker->GetThread()->GetVerifierDeps();
2006 worker->GetThread()->SetVerifierDeps(nullptr);
Mathieu Chartier72041a02017-07-14 18:23:25 -07002007 verifier_deps->MergeWith(*thread_deps, dex_files_for_oat_file_);
Nicolas Geoffray340dafa2016-11-18 16:03:10 +00002008 delete thread_deps;
2009 }
2010 Thread::Current()->SetVerifierDeps(nullptr);
2011 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002012}
2013
Mathieu Chartier90443472015-07-16 20:32:27 -07002014class VerifyClassVisitor : public CompilationVisitor {
2015 public:
Andreas Gampe5fd66d02016-09-12 20:22:19 -07002016 VerifyClassVisitor(const ParallelCompilationManager* manager, verifier::HardFailLogMode log_level)
Andreas Gampe7fe30232016-03-25 16:58:00 -07002017 : manager_(manager), log_level_(log_level) {}
Brian Carlstrom7940e442013-07-12 13:46:57 -07002018
Mathieu Chartier90443472015-07-16 20:32:27 -07002019 virtual void Visit(size_t class_def_index) REQUIRES(!Locks::mutator_lock_) OVERRIDE {
Andreas Gampe9b827ab2017-12-07 19:32:48 -08002020 ScopedTrace trace(__FUNCTION__);
Mathieu Chartier90443472015-07-16 20:32:27 -07002021 ScopedObjectAccess soa(Thread::Current());
2022 const DexFile& dex_file = *manager_->GetDexFile();
2023 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
2024 const char* descriptor = dex_file.GetClassDescriptor(class_def);
2025 ClassLinker* class_linker = manager_->GetClassLinker();
2026 jobject jclass_loader = manager_->GetClassLoader();
2027 StackHandleScope<3> hs(soa.Self());
2028 Handle<mirror::ClassLoader> class_loader(
Mathieu Chartier0795f232016-09-27 18:43:30 -07002029 hs.NewHandle(soa.Decode<mirror::ClassLoader>(jclass_loader)));
Mathieu Chartier90443472015-07-16 20:32:27 -07002030 Handle<mirror::Class> klass(
2031 hs.NewHandle(class_linker->FindClass(soa.Self(), descriptor, class_loader)));
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07002032 verifier::FailureKind failure_kind;
Andreas Gampefa4333d2017-02-14 11:10:34 -08002033 if (klass == nullptr) {
Ian Rogerse6bb3b22013-08-19 21:51:45 -07002034 CHECK(soa.Self()->IsExceptionPending());
2035 soa.Self()->ClearException();
Mathieu Chartier90443472015-07-16 20:32:27 -07002036
2037 /*
2038 * At compile time, we can still structurally verify the class even if FindClass fails.
2039 * This is to ensure the class is structurally sound for compilation. An unsound class
2040 * will be rejected by the verifier and later skipped during compilation in the compiler.
2041 */
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002042 Handle<mirror::DexCache> dex_cache(hs.NewHandle(class_linker->FindDexCache(
Vladimir Markocd556b02017-02-03 11:47:34 +00002043 soa.Self(), dex_file)));
Mathieu Chartier90443472015-07-16 20:32:27 -07002044 std::string error_msg;
Nicolas Geoffray08025182016-10-25 17:20:18 +01002045 failure_kind =
2046 verifier::MethodVerifier::VerifyClass(soa.Self(),
Andreas Gampeec6e6c12015-11-05 20:39:56 -08002047 &dex_file,
2048 dex_cache,
2049 class_loader,
David Brazdil15fc7292016-09-02 14:13:18 +01002050 class_def,
Andreas Gampe53e32d12015-12-09 21:03:23 -08002051 Runtime::Current()->GetCompilerCallbacks(),
Andreas Gampeec6e6c12015-11-05 20:39:56 -08002052 true /* allow soft failures */,
Andreas Gampe7fe30232016-03-25 16:58:00 -07002053 log_level_,
Nicolas Geoffray08025182016-10-25 17:20:18 +01002054 &error_msg);
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07002055 if (failure_kind == verifier::FailureKind::kHardFailure) {
Mathieu Chartier90443472015-07-16 20:32:27 -07002056 LOG(ERROR) << "Verification failed on class " << PrettyDescriptor(descriptor)
2057 << " because: " << error_msg;
2058 manager_->GetCompiler()->SetHadHardVerifierFailure();
Andreas Gampef39208f2017-10-19 15:06:59 -07002059 } else if (failure_kind == verifier::FailureKind::kSoftFailure) {
2060 manager_->GetCompiler()->AddSoftVerifierFailure();
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00002061 } else {
2062 // Force a soft failure for the VerifierDeps. This is a sanity measure, as
2063 // the vdex file already records that the class hasn't been resolved. It avoids
2064 // trying to do future verification optimizations when processing the vdex file.
Andreas Gampef39208f2017-10-19 15:06:59 -07002065 DCHECK(failure_kind == verifier::FailureKind::kNoFailure) << failure_kind;
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07002066 failure_kind = verifier::FailureKind::kSoftFailure;
Mathieu Chartier90443472015-07-16 20:32:27 -07002067 }
2068 } else if (!SkipClass(jclass_loader, dex_file, klass.Get())) {
David Sehr709b0702016-10-13 09:12:37 -07002069 CHECK(klass->IsResolved()) << klass->PrettyClass();
Nicolas Geoffray08025182016-10-25 17:20:18 +01002070 failure_kind = class_linker->VerifyClass(soa.Self(), klass, log_level_);
Mathieu Chartier90443472015-07-16 20:32:27 -07002071
2072 if (klass->IsErroneous()) {
2073 // ClassLinker::VerifyClass throws, which isn't useful in the compiler.
2074 CHECK(soa.Self()->IsExceptionPending());
2075 soa.Self()->ClearException();
2076 manager_->GetCompiler()->SetHadHardVerifierFailure();
Andreas Gampef39208f2017-10-19 15:06:59 -07002077 } else if (failure_kind == verifier::FailureKind::kSoftFailure) {
2078 manager_->GetCompiler()->AddSoftVerifierFailure();
Mathieu Chartier90443472015-07-16 20:32:27 -07002079 }
2080
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00002081 CHECK(klass->ShouldVerifyAtRuntime() || klass->IsVerified() || klass->IsErroneous())
David Sehr709b0702016-10-13 09:12:37 -07002082 << klass->PrettyDescriptor() << ": state=" << klass->GetStatus();
Mathieu Chartier90443472015-07-16 20:32:27 -07002083
Nicolas Geoffrayc7da1d62017-04-19 09:36:24 +01002084 // Class has a meaningful status for the compiler now, record it.
2085 ClassReference ref(manager_->GetDexFile(), class_def_index);
2086 manager_->GetCompiler()->RecordClassStatus(ref, klass->GetStatus());
2087
Andreas Gamped278cb42017-11-22 14:13:00 -08002088 // It is *very* problematic if there are resolution errors in the boot classpath.
2089 //
2090 // It is also bad if classes fail verification. For example, we rely on things working
2091 // OK without verification when the decryption dialog is brought up. It is thus highly
2092 // recommended to compile the boot classpath with
2093 // --abort-on-hard-verifier-error --abort-on-soft-verifier-error
2094 // which is the default build system configuration.
Narayan Kamathe3eae5e2016-10-27 11:47:30 +01002095 if (kIsDebugBuild) {
Orion Hodsonc5e0d3f2017-08-22 19:00:04 +01002096 if (manager_->GetCompiler()->GetCompilerOptions().IsBootImage()) {
Andreas Gamped278cb42017-11-22 14:13:00 -08002097 if (!klass->IsResolved() || klass->IsErroneous()) {
Andreas Gampe12fadcd2017-08-03 05:06:28 -07002098 LOG(FATAL) << "Boot classpath class " << klass->PrettyClass()
Andreas Gamped278cb42017-11-22 14:13:00 -08002099 << " failed to resolve/is erroneous: state= " << klass->GetStatus();
2100 UNREACHABLE();
Andreas Gampe12fadcd2017-08-03 05:06:28 -07002101 }
Narayan Kamathe3eae5e2016-10-27 11:47:30 +01002102 }
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00002103 if (klass->IsVerified()) {
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07002104 DCHECK_EQ(failure_kind, verifier::FailureKind::kNoFailure);
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00002105 } else if (klass->ShouldVerifyAtRuntime()) {
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07002106 DCHECK_EQ(failure_kind, verifier::FailureKind::kSoftFailure);
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00002107 } else {
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07002108 DCHECK_EQ(failure_kind, verifier::FailureKind::kHardFailure);
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00002109 }
Narayan Kamathe3eae5e2016-10-27 11:47:30 +01002110 }
Nicolas Geoffray08025182016-10-25 17:20:18 +01002111 } else {
2112 // Make the skip a soft failure, essentially being considered as verify at runtime.
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07002113 failure_kind = verifier::FailureKind::kSoftFailure;
Ian Rogerse6bb3b22013-08-19 21:51:45 -07002114 }
Nicolas Geoffray08025182016-10-25 17:20:18 +01002115 verifier::VerifierDeps::MaybeRecordVerificationStatus(
2116 dex_file, class_def.class_idx_, failure_kind);
Mathieu Chartier90443472015-07-16 20:32:27 -07002117 soa.Self()->AssertNoPendingException();
Brian Carlstrom7940e442013-07-12 13:46:57 -07002118 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002119
2120 private:
2121 const ParallelCompilationManager* const manager_;
Andreas Gampe5fd66d02016-09-12 20:22:19 -07002122 const verifier::HardFailLogMode log_level_;
Mathieu Chartier90443472015-07-16 20:32:27 -07002123};
Brian Carlstrom7940e442013-07-12 13:46:57 -07002124
Andreas Gampeace0dc12016-01-20 13:33:13 -08002125void CompilerDriver::VerifyDexFile(jobject class_loader,
2126 const DexFile& dex_file,
Andreas Gampede7b4362014-07-28 18:38:57 -07002127 const std::vector<const DexFile*>& dex_files,
Andreas Gampeace0dc12016-01-20 13:33:13 -08002128 ThreadPool* thread_pool,
2129 size_t thread_count,
2130 TimingLogger* timings) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07002131 TimingLogger::ScopedTiming t("Verify Dex File", timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002132 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Andreas Gampede7b4362014-07-28 18:38:57 -07002133 ParallelCompilationManager context(class_linker, class_loader, this, &dex_file, dex_files,
2134 thread_pool);
Andreas Gampef39208f2017-10-19 15:06:59 -07002135 bool abort_on_verifier_failures = GetCompilerOptions().AbortOnHardVerifierFailure()
2136 || GetCompilerOptions().AbortOnSoftVerifierFailure();
2137 verifier::HardFailLogMode log_level = abort_on_verifier_failures
Andreas Gampe5fd66d02016-09-12 20:22:19 -07002138 ? verifier::HardFailLogMode::kLogInternalFatal
2139 : verifier::HardFailLogMode::kLogWarning;
Andreas Gampe7fe30232016-03-25 16:58:00 -07002140 VerifyClassVisitor visitor(&context, log_level);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002141 context.ForAll(0, dex_file.NumClassDefs(), &visitor, thread_count);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002142}
2143
Mathieu Chartier90443472015-07-16 20:32:27 -07002144class SetVerifiedClassVisitor : public CompilationVisitor {
2145 public:
2146 explicit SetVerifiedClassVisitor(const ParallelCompilationManager* manager) : manager_(manager) {}
2147
2148 virtual void Visit(size_t class_def_index) REQUIRES(!Locks::mutator_lock_) OVERRIDE {
Andreas Gampe9b827ab2017-12-07 19:32:48 -08002149 ScopedTrace trace(__FUNCTION__);
Mathieu Chartier90443472015-07-16 20:32:27 -07002150 ScopedObjectAccess soa(Thread::Current());
2151 const DexFile& dex_file = *manager_->GetDexFile();
2152 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
2153 const char* descriptor = dex_file.GetClassDescriptor(class_def);
2154 ClassLinker* class_linker = manager_->GetClassLinker();
2155 jobject jclass_loader = manager_->GetClassLoader();
2156 StackHandleScope<3> hs(soa.Self());
2157 Handle<mirror::ClassLoader> class_loader(
Mathieu Chartier0795f232016-09-27 18:43:30 -07002158 hs.NewHandle(soa.Decode<mirror::ClassLoader>(jclass_loader)));
Mathieu Chartier90443472015-07-16 20:32:27 -07002159 Handle<mirror::Class> klass(
2160 hs.NewHandle(class_linker->FindClass(soa.Self(), descriptor, class_loader)));
2161 // Class might have failed resolution. Then don't set it to verified.
Andreas Gampefa4333d2017-02-14 11:10:34 -08002162 if (klass != nullptr) {
Mathieu Chartier90443472015-07-16 20:32:27 -07002163 // Only do this if the class is resolved. If even resolution fails, quickening will go very,
2164 // very wrong.
Vladimir Marko72ab6842017-01-20 19:32:50 +00002165 if (klass->IsResolved() && !klass->IsErroneousResolved()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00002166 if (klass->GetStatus() < ClassStatus::kVerified) {
Mathieu Chartier90443472015-07-16 20:32:27 -07002167 ObjectLock<mirror::Class> lock(soa.Self(), klass);
2168 // Set class status to verified.
Vladimir Marko2c64a832018-01-04 11:31:56 +00002169 mirror::Class::SetStatus(klass, ClassStatus::kVerified, soa.Self());
Mathieu Chartier90443472015-07-16 20:32:27 -07002170 // Mark methods as pre-verified. If we don't do this, the interpreter will run with
2171 // access checks.
Igor Murashkindf707e42016-02-02 16:56:50 -08002172 klass->SetSkipAccessChecksFlagOnAllMethods(
Mathieu Chartier90443472015-07-16 20:32:27 -07002173 GetInstructionSetPointerSize(manager_->GetCompiler()->GetInstructionSet()));
Igor Murashkindf707e42016-02-02 16:56:50 -08002174 klass->SetVerificationAttempted();
Mathieu Chartier90443472015-07-16 20:32:27 -07002175 }
2176 // Record the final class status if necessary.
2177 ClassReference ref(manager_->GetDexFile(), class_def_index);
2178 manager_->GetCompiler()->RecordClassStatus(ref, klass->GetStatus());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002179 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002180 } else {
2181 Thread* self = soa.Self();
2182 DCHECK(self->IsExceptionPending());
2183 self->ClearException();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002184 }
2185 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002186
2187 private:
2188 const ParallelCompilationManager* const manager_;
2189};
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002190
Andreas Gampeace0dc12016-01-20 13:33:13 -08002191void CompilerDriver::SetVerifiedDexFile(jobject class_loader,
2192 const DexFile& dex_file,
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002193 const std::vector<const DexFile*>& dex_files,
Andreas Gampeace0dc12016-01-20 13:33:13 -08002194 ThreadPool* thread_pool,
2195 size_t thread_count,
2196 TimingLogger* timings) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002197 TimingLogger::ScopedTiming t("Verify Dex File", timings);
Mathieu Chartier1a088d42017-07-18 11:43:57 -07002198 if (!compiled_classes_.HaveDexFile(&dex_file)) {
Mathieu Chartierfc8b4222017-09-17 13:44:24 -07002199 compiled_classes_.AddDexFile(&dex_file);
Mathieu Chartier1a088d42017-07-18 11:43:57 -07002200 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002201 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
2202 ParallelCompilationManager context(class_linker, class_loader, this, &dex_file, dex_files,
2203 thread_pool);
Mathieu Chartier90443472015-07-16 20:32:27 -07002204 SetVerifiedClassVisitor visitor(&context);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002205 context.ForAll(0, dex_file.NumClassDefs(), &visitor, thread_count);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002206}
2207
Mathieu Chartier90443472015-07-16 20:32:27 -07002208class InitializeClassVisitor : public CompilationVisitor {
2209 public:
2210 explicit InitializeClassVisitor(const ParallelCompilationManager* manager) : manager_(manager) {}
Ian Rogersfc0e94b2013-09-23 23:51:32 -07002211
Mathieu Chartierf1dd69a2017-06-08 23:30:15 +00002212 void Visit(size_t class_def_index) OVERRIDE {
Andreas Gampe9b827ab2017-12-07 19:32:48 -08002213 ScopedTrace trace(__FUNCTION__);
Mathieu Chartier90443472015-07-16 20:32:27 -07002214 jobject jclass_loader = manager_->GetClassLoader();
2215 const DexFile& dex_file = *manager_->GetDexFile();
2216 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
2217 const DexFile::TypeId& class_type_id = dex_file.GetTypeId(class_def.class_idx_);
2218 const char* descriptor = dex_file.StringDataByIdx(class_type_id.descriptor_idx_);
Jeff Hao0e49b422013-11-08 12:16:56 -08002219
Mathieu Chartier90443472015-07-16 20:32:27 -07002220 ScopedObjectAccess soa(Thread::Current());
2221 StackHandleScope<3> hs(soa.Self());
2222 Handle<mirror::ClassLoader> class_loader(
Mathieu Chartier0795f232016-09-27 18:43:30 -07002223 hs.NewHandle(soa.Decode<mirror::ClassLoader>(jclass_loader)));
Mathieu Chartier90443472015-07-16 20:32:27 -07002224 Handle<mirror::Class> klass(
2225 hs.NewHandle(manager_->GetClassLinker()->FindClass(soa.Self(), descriptor, class_loader)));
2226
Mathieu Chartierf1dd69a2017-06-08 23:30:15 +00002227 if (klass != nullptr && !SkipClass(manager_->GetClassLoader(), dex_file, klass.Get())) {
2228 TryInitializeClass(klass, class_loader);
2229 }
2230 // Clear any class not found or verification exceptions.
2231 soa.Self()->ClearException();
2232 }
2233
2234 // A helper function for initializing klass.
2235 void TryInitializeClass(Handle<mirror::Class> klass, Handle<mirror::ClassLoader>& class_loader)
2236 REQUIRES_SHARED(Locks::mutator_lock_) {
2237 const DexFile& dex_file = klass->GetDexFile();
2238 const DexFile::ClassDef* class_def = klass->GetClassDef();
2239 const DexFile::TypeId& class_type_id = dex_file.GetTypeId(class_def->class_idx_);
2240 const char* descriptor = dex_file.StringDataByIdx(class_type_id.descriptor_idx_);
2241 ScopedObjectAccessUnchecked soa(Thread::Current());
2242 StackHandleScope<3> hs(soa.Self());
Mathieu Chartierdabeb3a2017-06-12 17:10:07 -07002243 const bool is_boot_image = manager_->GetCompiler()->GetCompilerOptions().IsBootImage();
Mathieu Chartier17498e52017-06-13 11:35:04 -07002244 const bool is_app_image = manager_->GetCompiler()->GetCompilerOptions().IsAppImage();
Mathieu Chartierf1dd69a2017-06-08 23:30:15 +00002245
Vladimir Marko2c64a832018-01-04 11:31:56 +00002246 ClassStatus old_status = klass->GetStatus();
Mathieu Chartier1a088d42017-07-18 11:43:57 -07002247 // Don't initialize classes in boot space when compiling app image
2248 if (is_app_image && klass->IsBootStrapClassLoaded()) {
2249 // Also return early and don't store the class status in the recorded class status.
2250 return;
2251 }
Mathieu Chartierf1dd69a2017-06-08 23:30:15 +00002252 // Only try to initialize classes that were successfully verified.
2253 if (klass->IsVerified()) {
2254 // Attempt to initialize the class but bail if we either need to initialize the super-class
2255 // or static fields.
Nicolas Geoffrayabadf022017-08-03 08:25:41 +00002256 manager_->GetClassLinker()->EnsureInitialized(soa.Self(), klass, false, false);
Mathieu Chartierf1dd69a2017-06-08 23:30:15 +00002257 old_status = klass->GetStatus();
2258 if (!klass->IsInitialized()) {
2259 // We don't want non-trivial class initialization occurring on multiple threads due to
2260 // deadlock problems. For example, a parent class is initialized (holding its lock) that
2261 // refers to a sub-class in its static/class initializer causing it to try to acquire the
2262 // sub-class' lock. While on a second thread the sub-class is initialized (holding its lock)
2263 // after first initializing its parents, whose locks are acquired. This leads to a
2264 // parent-to-child and a child-to-parent lock ordering and consequent potential deadlock.
2265 // We need to use an ObjectLock due to potential suspension in the interpreting code. Rather
2266 // than use a special Object for the purpose we use the Class of java.lang.Class.
2267 Handle<mirror::Class> h_klass(hs.NewHandle(klass->GetClass()));
2268 ObjectLock<mirror::Class> lock(soa.Self(), h_klass);
2269 // Attempt to initialize allowing initialization of parent classes but still not static
2270 // fields.
Chang Xinge602b1c2017-06-30 11:55:01 -07002271 // Initialize dependencies first only for app image, to make TryInitialize recursive.
2272 bool is_superclass_initialized = !is_app_image ? true :
2273 InitializeDependencies(klass, class_loader, soa.Self());
2274 if (!is_app_image || (is_app_image && is_superclass_initialized)) {
Nicolas Geoffrayabadf022017-08-03 08:25:41 +00002275 manager_->GetClassLinker()->EnsureInitialized(soa.Self(), klass, false, true);
Chang Xinge602b1c2017-06-30 11:55:01 -07002276 }
2277 // Otherwise it's in app image but superclasses can't be initialized, no need to proceed.
Mathieu Chartierf1dd69a2017-06-08 23:30:15 +00002278 old_status = klass->GetStatus();
Chang Xing70f689d2017-06-08 17:16:12 -07002279
2280 bool too_many_encoded_fields = false;
2281 if (!is_boot_image && klass->NumStaticFields() > kMaxEncodedFields) {
2282 too_many_encoded_fields = true;
2283 }
Mathieu Chartierdabeb3a2017-06-12 17:10:07 -07002284 // If the class was not initialized, we can proceed to see if we can initialize static
Chang Xing70f689d2017-06-08 17:16:12 -07002285 // fields. Limit the max number of encoded fields.
Mathieu Chartierf1dd69a2017-06-08 23:30:15 +00002286 if (!klass->IsInitialized() &&
Mathieu Chartier17498e52017-06-13 11:35:04 -07002287 (is_app_image || is_boot_image) &&
Chang Xinge602b1c2017-06-30 11:55:01 -07002288 is_superclass_initialized &&
Chang Xing70f689d2017-06-08 17:16:12 -07002289 !too_many_encoded_fields &&
Mathieu Chartierf1dd69a2017-06-08 23:30:15 +00002290 manager_->GetCompiler()->IsImageClass(descriptor)) {
2291 bool can_init_static_fields = false;
Mathieu Chartierdabeb3a2017-06-12 17:10:07 -07002292 if (is_boot_image) {
Mathieu Chartier90443472015-07-16 20:32:27 -07002293 // We need to initialize static fields, we only do this for image classes that aren't
Mathieu Chartierdabeb3a2017-06-12 17:10:07 -07002294 // marked with the $NoPreloadHolder (which implies this should not be initialized
2295 // early).
Mathieu Chartierf1dd69a2017-06-08 23:30:15 +00002296 can_init_static_fields = !StringPiece(descriptor).ends_with("$NoPreloadHolder;");
2297 } else {
Mathieu Chartier17498e52017-06-13 11:35:04 -07002298 CHECK(is_app_image);
Mathieu Chartierdabeb3a2017-06-12 17:10:07 -07002299 // The boot image case doesn't need to recursively initialize the dependencies with
2300 // special logic since the class linker already does this.
Mathieu Chartierdabeb3a2017-06-12 17:10:07 -07002301 can_init_static_fields =
Mathieu Chartierf1dd69a2017-06-08 23:30:15 +00002302 !soa.Self()->IsExceptionPending() &&
Nicolas Geoffrayabadf022017-08-03 08:25:41 +00002303 is_superclass_initialized &&
2304 NoClinitInDependency(klass, soa.Self(), &class_loader);
Mathieu Chartierf1dd69a2017-06-08 23:30:15 +00002305 // TODO The checking for clinit can be removed since it's already
2306 // checked when init superclass. Currently keep it because it contains
2307 // processing of intern strings. Will be removed later when intern strings
2308 // and clinit are both initialized.
2309 }
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002310
Mathieu Chartierf1dd69a2017-06-08 23:30:15 +00002311 if (can_init_static_fields) {
2312 VLOG(compiler) << "Initializing: " << descriptor;
2313 // TODO multithreading support. We should ensure the current compilation thread has
2314 // exclusive access to the runtime and the transaction. To achieve this, we could use
2315 // a ReaderWriterMutex but we're holding the mutator lock so we fail mutex sanity
2316 // checks in Thread::AssertThreadSuspensionIsAllowable.
2317 Runtime* const runtime = Runtime::Current();
Mathieu Chartierf1dd69a2017-06-08 23:30:15 +00002318 // Run the class initializer in transaction mode.
Chang Xing5a906fc2017-07-26 15:01:16 -07002319 runtime->EnterTransactionMode(is_app_image, klass.Get());
Mathieu Chartierf1dd69a2017-06-08 23:30:15 +00002320 bool success = manager_->GetClassLinker()->EnsureInitialized(soa.Self(), klass, true,
2321 true);
2322 // TODO we detach transaction from runtime to indicate we quit the transactional
2323 // mode which prevents the GC from visiting objects modified during the transaction.
2324 // Ensure GC is not run so don't access freed objects when aborting transaction.
Andreas Gampe9e7078b2017-03-02 13:50:36 -08002325
Mathieu Chartierf1dd69a2017-06-08 23:30:15 +00002326 {
2327 ScopedAssertNoThreadSuspension ants("Transaction end");
Chang Xing16d1dd82017-07-20 17:56:26 -07002328
2329 if (success) {
2330 runtime->ExitTransactionMode();
2331 DCHECK(!runtime->IsActiveTransaction());
2332 }
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002333
Mathieu Chartier90443472015-07-16 20:32:27 -07002334 if (!success) {
Mathieu Chartierf1dd69a2017-06-08 23:30:15 +00002335 CHECK(soa.Self()->IsExceptionPending());
2336 mirror::Throwable* exception = soa.Self()->GetException();
2337 VLOG(compiler) << "Initialization of " << descriptor << " aborted because of "
2338 << exception->Dump();
2339 std::ostream* file_log = manager_->GetCompiler()->
2340 GetCompilerOptions().GetInitFailureOutput();
2341 if (file_log != nullptr) {
2342 *file_log << descriptor << "\n";
2343 *file_log << exception->Dump() << "\n";
2344 }
2345 soa.Self()->ClearException();
Chang Xing605fe242017-07-20 15:57:21 -07002346 runtime->RollbackAllTransactions();
Mathieu Chartierf1dd69a2017-06-08 23:30:15 +00002347 CHECK_EQ(old_status, klass->GetStatus()) << "Previous class status not restored";
Mathieu Chartierdabeb3a2017-06-12 17:10:07 -07002348 } else if (is_boot_image) {
2349 // For boot image, we want to put the updated status in the oat class since we can't
2350 // reject the image anyways.
2351 old_status = klass->GetStatus();
Mathieu Chartierf1dd69a2017-06-08 23:30:15 +00002352 }
2353 }
2354
Nicolas Geoffrayabadf022017-08-03 08:25:41 +00002355 if (!success) {
Mathieu Chartierf1dd69a2017-06-08 23:30:15 +00002356 // On failure, still intern strings of static fields and seen in <clinit>, as these
2357 // will be created in the zygote. This is separated from the transaction code just
2358 // above as we will allocate strings, so must be allowed to suspend.
2359 if (&klass->GetDexFile() == manager_->GetDexFile()) {
Andreas Gampe9e7078b2017-03-02 13:50:36 -08002360 InternStrings(klass, class_loader);
Mathieu Chartierdabeb3a2017-06-12 17:10:07 -07002361 } else {
2362 DCHECK(!is_boot_image) << "Boot image must have equal dex files";
Andreas Gampedbfe2542014-11-25 22:21:42 -08002363 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002364 }
2365 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002366 }
Jeff Hao0cb17282017-07-12 14:51:49 -07002367 // If the class still isn't initialized, at least try some checks that initialization
2368 // would do so they can be skipped at runtime.
2369 if (!klass->IsInitialized() &&
2370 manager_->GetClassLinker()->ValidateSuperClassDescriptors(klass)) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00002371 old_status = ClassStatus::kSuperclassValidated;
Jeff Hao0cb17282017-07-12 14:51:49 -07002372 } else {
2373 soa.Self()->ClearException();
2374 }
Mathieu Chartierf1dd69a2017-06-08 23:30:15 +00002375 soa.Self()->AssertNoPendingException();
Brian Carlstrom7940e442013-07-12 13:46:57 -07002376 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002377 }
Mathieu Chartierf1dd69a2017-06-08 23:30:15 +00002378 // Record the final class status if necessary.
2379 ClassReference ref(&dex_file, klass->GetDexClassDefIndex());
2380 // Back up the status before doing initialization for static encoded fields,
2381 // because the static encoded branch wants to keep the status to uninitialized.
2382 manager_->GetCompiler()->RecordClassStatus(ref, old_status);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002383 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002384
2385 private:
Andreas Gampe9e7078b2017-03-02 13:50:36 -08002386 void InternStrings(Handle<mirror::Class> klass, Handle<mirror::ClassLoader> class_loader)
2387 REQUIRES_SHARED(Locks::mutator_lock_) {
2388 DCHECK(manager_->GetCompiler()->GetCompilerOptions().IsBootImage());
2389 DCHECK(klass->IsVerified());
2390 DCHECK(!klass->IsInitialized());
2391
2392 StackHandleScope<1> hs(Thread::Current());
Vladimir Markoe11dd502017-12-08 14:09:45 +00002393 Handle<mirror::DexCache> dex_cache = hs.NewHandle(klass->GetDexCache());
Andreas Gampe9e7078b2017-03-02 13:50:36 -08002394 const DexFile::ClassDef* class_def = klass->GetClassDef();
2395 ClassLinker* class_linker = manager_->GetClassLinker();
2396
Andreas Gampe7bf90482017-03-02 16:41:35 -08002397 // Check encoded final field values for strings and intern.
Vladimir Markoe11dd502017-12-08 14:09:45 +00002398 annotations::RuntimeEncodedStaticFieldValueIterator value_it(dex_cache,
2399 class_loader,
Andreas Gampe9e7078b2017-03-02 13:50:36 -08002400 manager_->GetClassLinker(),
2401 *class_def);
2402 for ( ; value_it.HasNext(); value_it.Next()) {
2403 if (value_it.GetValueType() == annotations::RuntimeEncodedStaticFieldValueIterator::kString) {
2404 // Resolve the string. This will intern the string.
2405 art::ObjPtr<mirror::String> resolved = class_linker->ResolveString(
Vladimir Markoa64b52d2017-12-08 16:27:49 +00002406 dex::StringIndex(value_it.GetJavaValue().i), dex_cache);
Andreas Gampe9e7078b2017-03-02 13:50:36 -08002407 CHECK(resolved != nullptr);
2408 }
2409 }
Andreas Gampe7bf90482017-03-02 16:41:35 -08002410
2411 // Intern strings seen in <clinit>.
2412 ArtMethod* clinit = klass->FindClassInitializer(class_linker->GetImagePointerSize());
2413 if (clinit != nullptr) {
Mathieu Chartier73f21d42018-01-02 14:26:50 -08002414 for (const DexInstructionPcPair& inst : clinit->DexInstructions()) {
Mathieu Chartier2b2bef22017-10-26 17:10:19 -07002415 if (inst->Opcode() == Instruction::CONST_STRING) {
Andreas Gampe7bf90482017-03-02 16:41:35 -08002416 ObjPtr<mirror::String> s = class_linker->ResolveString(
Vladimir Markoa64b52d2017-12-08 16:27:49 +00002417 dex::StringIndex(inst->VRegB_21c()), dex_cache);
Andreas Gampe7bf90482017-03-02 16:41:35 -08002418 CHECK(s != nullptr);
Mathieu Chartier2b2bef22017-10-26 17:10:19 -07002419 } else if (inst->Opcode() == Instruction::CONST_STRING_JUMBO) {
Andreas Gampe7bf90482017-03-02 16:41:35 -08002420 ObjPtr<mirror::String> s = class_linker->ResolveString(
Vladimir Markoa64b52d2017-12-08 16:27:49 +00002421 dex::StringIndex(inst->VRegB_31c()), dex_cache);
Andreas Gampe7bf90482017-03-02 16:41:35 -08002422 CHECK(s != nullptr);
2423 }
Andreas Gampe7bf90482017-03-02 16:41:35 -08002424 }
2425 }
Andreas Gampe9e7078b2017-03-02 13:50:36 -08002426 }
2427
Mathieu Chartierf1dd69a2017-06-08 23:30:15 +00002428 bool ResolveTypesOfMethods(Thread* self, ArtMethod* m)
2429 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markob45528c2017-07-27 14:14:28 +01002430 // Return value of ResolveReturnType() is discarded because resolve will be done internally.
2431 ObjPtr<mirror::Class> rtn_type = m->ResolveReturnType();
Mathieu Chartier7a8bcfd2017-06-13 13:40:43 -07002432 if (rtn_type == nullptr) {
2433 self->ClearException();
2434 return false;
2435 }
2436 const DexFile::TypeList* types = m->GetParameterTypeList();
2437 if (types != nullptr) {
2438 for (uint32_t i = 0; i < types->Size(); ++i) {
2439 dex::TypeIndex param_type_idx = types->GetTypeItem(i).type_idx_;
Vladimir Markob45528c2017-07-27 14:14:28 +01002440 ObjPtr<mirror::Class> param_type = m->ResolveClassFromTypeIndex(param_type_idx);
Mathieu Chartier7a8bcfd2017-06-13 13:40:43 -07002441 if (param_type == nullptr) {
2442 self->ClearException();
2443 return false;
Mathieu Chartierf1dd69a2017-06-08 23:30:15 +00002444 }
2445 }
Mathieu Chartier7a8bcfd2017-06-13 13:40:43 -07002446 }
2447 return true;
Mathieu Chartierf1dd69a2017-06-08 23:30:15 +00002448 }
2449
2450 // Pre resolve types mentioned in all method signatures before start a transaction
2451 // since ResolveType doesn't work in transaction mode.
2452 bool PreResolveTypes(Thread* self, const Handle<mirror::Class>& klass)
2453 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier7a8bcfd2017-06-13 13:40:43 -07002454 PointerSize pointer_size = manager_->GetClassLinker()->GetImagePointerSize();
2455 for (ArtMethod& m : klass->GetMethods(pointer_size)) {
2456 if (!ResolveTypesOfMethods(self, &m)) {
2457 return false;
2458 }
2459 }
2460 if (klass->IsInterface()) {
2461 return true;
2462 } else if (klass->HasSuperClass()) {
2463 StackHandleScope<1> hs(self);
2464 MutableHandle<mirror::Class> super_klass(hs.NewHandle<mirror::Class>(klass->GetSuperClass()));
2465 for (int i = super_klass->GetVTableLength() - 1; i >= 0; --i) {
2466 ArtMethod* m = klass->GetVTableEntry(i, pointer_size);
2467 ArtMethod* super_m = super_klass->GetVTableEntry(i, pointer_size);
2468 if (!ResolveTypesOfMethods(self, m) || !ResolveTypesOfMethods(self, super_m)) {
Mathieu Chartierf1dd69a2017-06-08 23:30:15 +00002469 return false;
2470 }
2471 }
Mathieu Chartier7a8bcfd2017-06-13 13:40:43 -07002472 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
2473 super_klass.Assign(klass->GetIfTable()->GetInterface(i));
2474 if (klass->GetClassLoader() != super_klass->GetClassLoader()) {
2475 uint32_t num_methods = super_klass->NumVirtualMethods();
2476 for (uint32_t j = 0; j < num_methods; ++j) {
2477 ArtMethod* m = klass->GetIfTable()->GetMethodArray(i)->GetElementPtrSize<ArtMethod*>(
2478 j, pointer_size);
2479 ArtMethod* super_m = super_klass->GetVirtualMethod(j, pointer_size);
2480 if (!ResolveTypesOfMethods(self, m) || !ResolveTypesOfMethods(self, super_m)) {
2481 return false;
Mathieu Chartierf1dd69a2017-06-08 23:30:15 +00002482 }
2483 }
2484 }
2485 }
Mathieu Chartier7a8bcfd2017-06-13 13:40:43 -07002486 }
2487 return true;
Mathieu Chartierf1dd69a2017-06-08 23:30:15 +00002488 }
2489
2490 // Initialize the klass's dependencies recursively before initializing itself.
2491 // Checking for interfaces is also necessary since interfaces can contain
2492 // both default methods and static encoded fields.
2493 bool InitializeDependencies(const Handle<mirror::Class>& klass,
2494 Handle<mirror::ClassLoader> class_loader,
2495 Thread* self)
2496 REQUIRES_SHARED(Locks::mutator_lock_) {
2497 if (klass->HasSuperClass()) {
2498 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
2499 StackHandleScope<1> hs(self);
2500 Handle<mirror::Class> handle_scope_super(hs.NewHandle(super_class));
2501 if (!handle_scope_super->IsInitialized()) {
2502 this->TryInitializeClass(handle_scope_super, class_loader);
2503 if (!handle_scope_super->IsInitialized()) {
2504 return false;
2505 }
2506 }
2507 }
2508
2509 uint32_t num_if = klass->NumDirectInterfaces();
2510 for (size_t i = 0; i < num_if; i++) {
2511 ObjPtr<mirror::Class>
2512 interface = mirror::Class::GetDirectInterface(self, klass.Get(), i);
2513 StackHandleScope<1> hs(self);
2514 Handle<mirror::Class> handle_interface(hs.NewHandle(interface));
2515
2516 TryInitializeClass(handle_interface, class_loader);
2517
2518 if (!handle_interface->IsInitialized()) {
2519 return false;
2520 }
2521 }
2522
2523 return PreResolveTypes(self, klass);
2524 }
2525
2526 // In this phase the classes containing class initializers are ignored. Make sure no
2527 // clinit appears in kalss's super class chain and interfaces.
2528 bool NoClinitInDependency(const Handle<mirror::Class>& klass,
2529 Thread* self,
2530 Handle<mirror::ClassLoader>* class_loader)
2531 REQUIRES_SHARED(Locks::mutator_lock_) {
2532 ArtMethod* clinit =
2533 klass->FindClassInitializer(manager_->GetClassLinker()->GetImagePointerSize());
2534 if (clinit != nullptr) {
2535 VLOG(compiler) << klass->PrettyClass() << ' ' << clinit->PrettyMethod(true);
2536 return false;
2537 }
2538 if (klass->HasSuperClass()) {
2539 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
2540 StackHandleScope<1> hs(self);
2541 Handle<mirror::Class> handle_scope_super(hs.NewHandle(super_class));
2542 if (!NoClinitInDependency(handle_scope_super, self, class_loader)) {
2543 return false;
2544 }
2545 }
2546
2547 uint32_t num_if = klass->NumDirectInterfaces();
2548 for (size_t i = 0; i < num_if; i++) {
2549 ObjPtr<mirror::Class>
2550 interface = mirror::Class::GetDirectInterface(self, klass.Get(), i);
2551 StackHandleScope<1> hs(self);
2552 Handle<mirror::Class> handle_interface(hs.NewHandle(interface));
2553 if (!NoClinitInDependency(handle_interface, self, class_loader)) {
2554 return false;
2555 }
2556 }
2557
Chang Xingba17dbd2017-06-28 21:27:56 +00002558 return true;
Mathieu Chartierf1dd69a2017-06-08 23:30:15 +00002559 }
2560
Mathieu Chartier90443472015-07-16 20:32:27 -07002561 const ParallelCompilationManager* const manager_;
2562};
Brian Carlstrom7940e442013-07-12 13:46:57 -07002563
Andreas Gampeace0dc12016-01-20 13:33:13 -08002564void CompilerDriver::InitializeClasses(jobject jni_class_loader,
2565 const DexFile& dex_file,
Andreas Gampede7b4362014-07-28 18:38:57 -07002566 const std::vector<const DexFile*>& dex_files,
Andreas Gampeace0dc12016-01-20 13:33:13 -08002567 TimingLogger* timings) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07002568 TimingLogger::ScopedTiming t("InitializeNoClinit", timings);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002569
2570 // Initialization allocates objects and needs to run single-threaded to be deterministic.
2571 bool force_determinism = GetCompilerOptions().IsForceDeterminism();
2572 ThreadPool* init_thread_pool = force_determinism
2573 ? single_thread_pool_.get()
2574 : parallel_thread_pool_.get();
2575 size_t init_thread_count = force_determinism ? 1U : parallel_thread_count_;
2576
Brian Carlstrom7940e442013-07-12 13:46:57 -07002577 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Andreas Gampede7b4362014-07-28 18:38:57 -07002578 ParallelCompilationManager context(class_linker, jni_class_loader, this, &dex_file, dex_files,
Andreas Gampeace0dc12016-01-20 13:33:13 -08002579 init_thread_pool);
Mathieu Chartierf1dd69a2017-06-08 23:30:15 +00002580
2581 if (GetCompilerOptions().IsBootImage() || GetCompilerOptions().IsAppImage()) {
2582 // Set the concurrency thread to 1 to support initialization for App Images since transaction
2583 // doesn't support multithreading now.
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002584 // TODO: remove this when transactional mode supports multithreading.
Andreas Gampeace0dc12016-01-20 13:33:13 -08002585 init_thread_count = 1U;
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002586 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002587 InitializeClassVisitor visitor(&context);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002588 context.ForAll(0, dex_file.NumClassDefs(), &visitor, init_thread_count);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002589}
2590
Mathieu Chartier91288d82016-04-28 09:44:54 -07002591class InitializeArrayClassesAndCreateConflictTablesVisitor : public ClassVisitor {
Mathieu Chartier085a0722016-04-01 17:33:31 -07002592 public:
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002593 explicit InitializeArrayClassesAndCreateConflictTablesVisitor(VariableSizedHandleScope& hs)
2594 : hs_(hs) {}
2595
2596 virtual bool operator()(ObjPtr<mirror::Class> klass) OVERRIDE
2597 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier91288d82016-04-28 09:44:54 -07002598 if (Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(klass)) {
2599 return true;
2600 }
Mathieu Chartier085a0722016-04-01 17:33:31 -07002601 if (klass->IsArrayClass()) {
2602 StackHandleScope<1> hs(Thread::Current());
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002603 auto h_klass = hs.NewHandleWrapper(&klass);
2604 Runtime::Current()->GetClassLinker()->EnsureInitialized(hs.Self(), h_klass, true, true);
Mathieu Chartier085a0722016-04-01 17:33:31 -07002605 }
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002606 // Collect handles since there may be thread suspension in future EnsureInitialized.
2607 to_visit_.push_back(hs_.NewHandle(klass));
Nicolas Geoffray88f288e2016-06-29 08:17:52 +00002608 return true;
Nelli Kimbadee982016-05-13 13:08:53 +03002609 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00002610
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002611 void FillAllIMTAndConflictTables() REQUIRES_SHARED(Locks::mutator_lock_) {
2612 for (Handle<mirror::Class> c : to_visit_) {
2613 // Create the conflict tables.
2614 FillIMTAndConflictTables(c.Get());
2615 }
2616 }
2617
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00002618 private:
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002619 void FillIMTAndConflictTables(ObjPtr<mirror::Class> klass)
2620 REQUIRES_SHARED(Locks::mutator_lock_) {
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00002621 if (!klass->ShouldHaveImt()) {
2622 return;
2623 }
2624 if (visited_classes_.find(klass) != visited_classes_.end()) {
2625 return;
2626 }
2627 if (klass->HasSuperClass()) {
2628 FillIMTAndConflictTables(klass->GetSuperClass());
2629 }
2630 if (!klass->IsTemp()) {
2631 Runtime::Current()->GetClassLinker()->FillIMTAndConflictTables(klass);
2632 }
2633 visited_classes_.insert(klass);
2634 }
2635
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002636 VariableSizedHandleScope& hs_;
2637 std::vector<Handle<mirror::Class>> to_visit_;
2638 std::unordered_set<ObjPtr<mirror::Class>, HashObjPtr> visited_classes_;
Mathieu Chartier085a0722016-04-01 17:33:31 -07002639};
2640
Brian Carlstrom7940e442013-07-12 13:46:57 -07002641void CompilerDriver::InitializeClasses(jobject class_loader,
2642 const std::vector<const DexFile*>& dex_files,
Andreas Gampeace0dc12016-01-20 13:33:13 -08002643 TimingLogger* timings) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07002644 for (size_t i = 0; i != dex_files.size(); ++i) {
2645 const DexFile* dex_file = dex_files[i];
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002646 CHECK(dex_file != nullptr);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002647 InitializeClasses(class_loader, *dex_file, dex_files, timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002648 }
Vladimir Markoaad75c62016-10-03 08:46:48 +00002649 if (GetCompilerOptions().IsBootImage() || GetCompilerOptions().IsAppImage()) {
Mathieu Chartier085a0722016-04-01 17:33:31 -07002650 // Make sure that we call EnsureIntiailized on all the array classes to call
2651 // SetVerificationAttempted so that the access flags are set. If we do not do this they get
2652 // changed at runtime resulting in more dirty image pages.
Mathieu Chartier91288d82016-04-28 09:44:54 -07002653 // Also create conflict tables.
2654 // Only useful if we are compiling an image (image_classes_ is not null).
Mathieu Chartier085a0722016-04-01 17:33:31 -07002655 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002656 VariableSizedHandleScope hs(soa.Self());
2657 InitializeArrayClassesAndCreateConflictTablesVisitor visitor(hs);
Mathieu Chartier91288d82016-04-28 09:44:54 -07002658 Runtime::Current()->GetClassLinker()->VisitClassesWithoutClassesLock(&visitor);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002659 visitor.FillAllIMTAndConflictTables();
Mathieu Chartier085a0722016-04-01 17:33:31 -07002660 }
Vladimir Markoaad75c62016-10-03 08:46:48 +00002661 if (GetCompilerOptions().IsBootImage()) {
Mathieu Chartier093ef212014-08-11 13:52:12 -07002662 // Prune garbage objects created during aborted transactions.
2663 Runtime::Current()->GetHeap()->CollectGarbage(true);
2664 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002665}
2666
Andreas Gampeace0dc12016-01-20 13:33:13 -08002667void CompilerDriver::Compile(jobject class_loader,
2668 const std::vector<const DexFile*>& dex_files,
2669 TimingLogger* timings) {
Calin Juravle998c2162015-12-21 15:39:33 +02002670 if (kDebugProfileGuidedCompilation) {
2671 LOG(INFO) << "[ProfileGuidedCompilation] " <<
2672 ((profile_compilation_info_ == nullptr)
2673 ? "null"
2674 : profile_compilation_info_->DumpInfo(&dex_files));
Calin Juravle226501b2015-12-11 14:41:31 +00002675 }
Vladimir Marko492a7fa2016-06-01 18:38:43 +01002676
Mathieu Chartiera79efdb2018-01-18 16:31:01 -08002677 dex_to_dex_compiler_.ClearState();
2678 compiling_dex_to_dex_ = false;
Vladimir Marko492a7fa2016-06-01 18:38:43 +01002679 for (const DexFile* dex_file : dex_files) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002680 CHECK(dex_file != nullptr);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002681 CompileDexFile(class_loader,
2682 *dex_file,
2683 dex_files,
2684 parallel_thread_pool_.get(),
2685 parallel_thread_count_,
2686 timings);
Calin Juravle69158982016-03-16 11:53:41 +00002687 const ArenaPool* const arena_pool = Runtime::Current()->GetArenaPool();
2688 const size_t arena_alloc = arena_pool->GetBytesAllocated();
2689 max_arena_alloc_ = std::max(arena_alloc, max_arena_alloc_);
Jean-Philippe Halimica76a1a2016-02-02 19:48:52 +01002690 Runtime::Current()->ReclaimArenaPoolMemory();
Brian Carlstrom7940e442013-07-12 13:46:57 -07002691 }
Vladimir Marko492a7fa2016-06-01 18:38:43 +01002692
Mathieu Chartiera79efdb2018-01-18 16:31:01 -08002693 if (dex_to_dex_compiler_.NumUniqueCodeItems(Thread::Current()) > 0u) {
2694 compiling_dex_to_dex_ = true;
2695 // TODO: Not visit all of the dex files, its probably rare that only one would have quickened
2696 // methods though.
2697 for (const DexFile* dex_file : dex_files) {
2698 CompileDexFile(class_loader,
2699 *dex_file,
2700 dex_files,
2701 parallel_thread_pool_.get(),
2702 parallel_thread_count_,
2703 timings);
2704 }
2705 dex_to_dex_compiler_.ClearState();
2706 compiling_dex_to_dex_ = false;
Vladimir Marko492a7fa2016-06-01 18:38:43 +01002707 }
Vladimir Marko492a7fa2016-06-01 18:38:43 +01002708
Andreas Gampe8d295f82015-01-20 14:50:21 -08002709 VLOG(compiler) << "Compile: " << GetMemoryUsageString(false);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002710}
2711
Mathieu Chartier90443472015-07-16 20:32:27 -07002712class CompileClassVisitor : public CompilationVisitor {
2713 public:
2714 explicit CompileClassVisitor(const ParallelCompilationManager* manager) : manager_(manager) {}
2715
2716 virtual void Visit(size_t class_def_index) REQUIRES(!Locks::mutator_lock_) OVERRIDE {
Andreas Gampe9b827ab2017-12-07 19:32:48 -08002717 ScopedTrace trace(__FUNCTION__);
Mathieu Chartier90443472015-07-16 20:32:27 -07002718 const DexFile& dex_file = *manager_->GetDexFile();
2719 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
2720 ClassLinker* class_linker = manager_->GetClassLinker();
2721 jobject jclass_loader = manager_->GetClassLoader();
Mathieu Chartier90443472015-07-16 20:32:27 -07002722 ClassReference ref(&dex_file, class_def_index);
2723 // Skip compiling classes with generic verifier failures since they will still fail at runtime
2724 if (manager_->GetCompiler()->verification_results_->IsClassRejected(ref)) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07002725 return;
2726 }
Mathieu Chartier736b5602015-09-02 14:54:11 -07002727 // Use a scoped object access to perform to the quick SkipClass check.
2728 const char* descriptor = dex_file.GetClassDescriptor(class_def);
2729 ScopedObjectAccess soa(Thread::Current());
2730 StackHandleScope<3> hs(soa.Self());
2731 Handle<mirror::ClassLoader> class_loader(
Mathieu Chartier0795f232016-09-27 18:43:30 -07002732 hs.NewHandle(soa.Decode<mirror::ClassLoader>(jclass_loader)));
Mathieu Chartier736b5602015-09-02 14:54:11 -07002733 Handle<mirror::Class> klass(
2734 hs.NewHandle(class_linker->FindClass(soa.Self(), descriptor, class_loader)));
2735 Handle<mirror::DexCache> dex_cache;
Andreas Gampefa4333d2017-02-14 11:10:34 -08002736 if (klass == nullptr) {
Mathieu Chartier736b5602015-09-02 14:54:11 -07002737 soa.Self()->AssertPendingException();
2738 soa.Self()->ClearException();
2739 dex_cache = hs.NewHandle(class_linker->FindDexCache(soa.Self(), dex_file));
2740 } else if (SkipClass(jclass_loader, dex_file, klass.Get())) {
2741 return;
2742 } else {
2743 dex_cache = hs.NewHandle(klass->GetDexCache());
2744 }
2745
Mathieu Chartier90443472015-07-16 20:32:27 -07002746 const uint8_t* class_data = dex_file.GetClassData(class_def);
2747 if (class_data == nullptr) {
2748 // empty class, probably a marker interface
2749 return;
Brian Carlstrom7940e442013-07-12 13:46:57 -07002750 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002751
Mathieu Chartier736b5602015-09-02 14:54:11 -07002752 // Go to native so that we don't block GC during compilation.
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07002753 ScopedThreadSuspension sts(soa.Self(), kNative);
Mathieu Chartier736b5602015-09-02 14:54:11 -07002754
Mathieu Chartier90443472015-07-16 20:32:27 -07002755 CompilerDriver* const driver = manager_->GetCompiler();
2756
2757 // Can we run DEX-to-DEX compiler on this class ?
Mathieu Chartiera79efdb2018-01-18 16:31:01 -08002758 optimizer::DexToDexCompiler::CompilationLevel dex_to_dex_compilation_level =
Mathieu Chartier736b5602015-09-02 14:54:11 -07002759 GetDexToDexCompilationLevel(soa.Self(), *driver, jclass_loader, dex_file, class_def);
Andreas Gampe5eb0d382015-07-23 01:19:26 -07002760
Mathieu Chartier90443472015-07-16 20:32:27 -07002761 ClassDataItemIterator it(dex_file, class_data);
Mathieu Chartiere17cf242017-06-19 11:05:51 -07002762 it.SkipAllFields();
Mathieu Chartier90443472015-07-16 20:32:27 -07002763
2764 bool compilation_enabled = driver->IsClassToCompile(
2765 dex_file.StringByTypeIdx(class_def.class_idx_));
2766
Mathieu Chartierb7c273c2017-11-10 18:07:56 -08002767 // Compile direct and virtual methods.
2768 int64_t previous_method_idx = -1;
2769 while (it.HasNextMethod()) {
Mathieu Chartier90443472015-07-16 20:32:27 -07002770 uint32_t method_idx = it.GetMemberIndex();
Mathieu Chartierb7c273c2017-11-10 18:07:56 -08002771 if (method_idx == previous_method_idx) {
Mathieu Chartier90443472015-07-16 20:32:27 -07002772 // smali can create dex files with two encoded_methods sharing the same method_idx
2773 // http://code.google.com/p/smali/issues/detail?id=119
2774 it.Next();
2775 continue;
2776 }
Mathieu Chartierb7c273c2017-11-10 18:07:56 -08002777 previous_method_idx = method_idx;
Vladimir Marko8d6768d2017-03-14 10:13:21 +00002778 CompileMethod(soa.Self(),
2779 driver,
2780 it.GetMethodCodeItem(),
2781 it.GetMethodAccessFlags(),
2782 it.GetMethodInvokeType(class_def),
2783 class_def_index,
2784 method_idx,
2785 class_loader,
2786 dex_file,
2787 dex_to_dex_compilation_level,
2788 compilation_enabled,
2789 dex_cache);
Mathieu Chartier90443472015-07-16 20:32:27 -07002790 it.Next();
2791 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002792 DCHECK(!it.HasNext());
Brian Carlstrom7940e442013-07-12 13:46:57 -07002793 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002794
2795 private:
2796 const ParallelCompilationManager* const manager_;
2797};
Brian Carlstrom7940e442013-07-12 13:46:57 -07002798
Andreas Gampeace0dc12016-01-20 13:33:13 -08002799void CompilerDriver::CompileDexFile(jobject class_loader,
2800 const DexFile& dex_file,
Andreas Gampede7b4362014-07-28 18:38:57 -07002801 const std::vector<const DexFile*>& dex_files,
Andreas Gampeace0dc12016-01-20 13:33:13 -08002802 ThreadPool* thread_pool,
2803 size_t thread_count,
2804 TimingLogger* timings) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07002805 TimingLogger::ScopedTiming t("Compile Dex File", timings);
Ian Rogersbe7149f2013-08-20 09:29:39 -07002806 ParallelCompilationManager context(Runtime::Current()->GetClassLinker(), class_loader, this,
Andreas Gampede7b4362014-07-28 18:38:57 -07002807 &dex_file, dex_files, thread_pool);
Mathieu Chartier90443472015-07-16 20:32:27 -07002808 CompileClassVisitor visitor(&context);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002809 context.ForAll(0, dex_file.NumClassDefs(), &visitor, thread_count);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002810}
2811
Andreas Gampe5eb0d382015-07-23 01:19:26 -07002812void CompilerDriver::AddCompiledMethod(const MethodReference& method_ref,
2813 CompiledMethod* const compiled_method,
2814 size_t non_relative_linker_patch_count) {
Mathieu Chartierfc8b4222017-09-17 13:44:24 -07002815 DCHECK(GetCompiledMethod(method_ref) == nullptr) << method_ref.PrettyMethod();
2816 MethodTable::InsertResult result = compiled_methods_.Insert(method_ref,
2817 /*expected*/ nullptr,
2818 compiled_method);
Mathieu Chartieracab8d42016-11-23 13:45:58 -08002819 CHECK(result == MethodTable::kInsertResultSuccess);
2820 non_relative_linker_patch_count_.FetchAndAddRelaxed(non_relative_linker_patch_count);
Mathieu Chartierfc8b4222017-09-17 13:44:24 -07002821 DCHECK(GetCompiledMethod(method_ref) != nullptr) << method_ref.PrettyMethod();
Brian Carlstrom7940e442013-07-12 13:46:57 -07002822}
2823
Vladimir Marko2c64a832018-01-04 11:31:56 +00002824bool CompilerDriver::GetCompiledClass(const ClassReference& ref, ClassStatus* status) const {
Andreas Gampebb846102017-05-11 21:03:35 -07002825 DCHECK(status != nullptr);
Mathieu Chartier1a088d42017-07-18 11:43:57 -07002826 // The table doesn't know if something wasn't inserted. For this case it will return
Vladimir Marko2c64a832018-01-04 11:31:56 +00002827 // ClassStatus::kNotReady. To handle this, just assume anything we didn't try to verify
2828 // is not compiled.
Mathieu Chartierfc8b4222017-09-17 13:44:24 -07002829 if (!compiled_classes_.Get(ref, status) ||
Vladimir Marko2c64a832018-01-04 11:31:56 +00002830 *status < ClassStatus::kRetryVerificationAtRuntime) {
Andreas Gampebb846102017-05-11 21:03:35 -07002831 return false;
Brian Carlstrom7940e442013-07-12 13:46:57 -07002832 }
Andreas Gampebb846102017-05-11 21:03:35 -07002833 return true;
Brian Carlstrom7940e442013-07-12 13:46:57 -07002834}
2835
Vladimir Marko2c64a832018-01-04 11:31:56 +00002836ClassStatus CompilerDriver::GetClassStatus(const ClassReference& ref) const {
2837 ClassStatus status = ClassStatus::kNotReady;
Nicolas Geoffray486dda02017-09-11 14:15:52 +01002838 if (!GetCompiledClass(ref, &status)) {
Mathieu Chartierfc8b4222017-09-17 13:44:24 -07002839 classpath_classes_.Get(ref, &status);
Nicolas Geoffray486dda02017-09-11 14:15:52 +01002840 }
2841 return status;
2842}
2843
Vladimir Marko2c64a832018-01-04 11:31:56 +00002844void CompilerDriver::RecordClassStatus(const ClassReference& ref, ClassStatus status) {
Nicolas Geoffrayade72d62016-12-15 13:20:02 +00002845 switch (status) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00002846 case ClassStatus::kErrorResolved:
2847 case ClassStatus::kErrorUnresolved:
2848 case ClassStatus::kNotReady:
2849 case ClassStatus::kResolved:
2850 case ClassStatus::kRetryVerificationAtRuntime:
2851 case ClassStatus::kVerified:
2852 case ClassStatus::kSuperclassValidated:
2853 case ClassStatus::kInitialized:
Nicolas Geoffrayade72d62016-12-15 13:20:02 +00002854 break; // Expected states.
2855 default:
2856 LOG(FATAL) << "Unexpected class status for class "
Mathieu Chartierfc8b4222017-09-17 13:44:24 -07002857 << PrettyDescriptor(
2858 ref.dex_file->GetClassDescriptor(ref.dex_file->GetClassDef(ref.index)))
Nicolas Geoffrayade72d62016-12-15 13:20:02 +00002859 << " of " << status;
2860 }
2861
Mathieu Chartier1a088d42017-07-18 11:43:57 -07002862 ClassStateTable::InsertResult result;
Nicolas Geoffray486dda02017-09-11 14:15:52 +01002863 ClassStateTable* table = &compiled_classes_;
Mathieu Chartier1a088d42017-07-18 11:43:57 -07002864 do {
Vladimir Marko2c64a832018-01-04 11:31:56 +00002865 ClassStatus existing = ClassStatus::kNotReady;
Mathieu Chartierfc8b4222017-09-17 13:44:24 -07002866 if (!table->Get(ref, &existing)) {
Nicolas Geoffray486dda02017-09-11 14:15:52 +01002867 // A classpath class.
Mathieu Chartier010f5cc2017-07-24 15:53:46 -07002868 if (kIsDebugBuild) {
2869 // Check to make sure it's not a dex file for an oat file we are compiling since these
2870 // should always succeed. These do not include classes in for used libraries.
Mathieu Chartier72041a02017-07-14 18:23:25 -07002871 for (const DexFile* dex_file : GetDexFilesForOatFile()) {
Mathieu Chartierfc8b4222017-09-17 13:44:24 -07002872 CHECK_NE(ref.dex_file, dex_file) << ref.dex_file->GetLocation();
Mathieu Chartier010f5cc2017-07-24 15:53:46 -07002873 }
2874 }
Mathieu Chartierfc8b4222017-09-17 13:44:24 -07002875 if (!classpath_classes_.HaveDexFile(ref.dex_file)) {
Nicolas Geoffray486dda02017-09-11 14:15:52 +01002876 // Boot classpath dex file.
2877 return;
2878 }
2879 table = &classpath_classes_;
Mathieu Chartierfc8b4222017-09-17 13:44:24 -07002880 table->Get(ref, &existing);
Mathieu Chartier010f5cc2017-07-24 15:53:46 -07002881 }
Mathieu Chartier1a088d42017-07-18 11:43:57 -07002882 if (existing >= status) {
2883 // Existing status is already better than we expect, break.
2884 break;
2885 }
Nicolas Geoffrayade72d62016-12-15 13:20:02 +00002886 // Update the status if we now have a greater one. This happens with vdex,
2887 // which records a class is verified, but does not resolve it.
Mathieu Chartierfc8b4222017-09-17 13:44:24 -07002888 result = table->Insert(ref, existing, status);
2889 CHECK(result != ClassStateTable::kInsertResultInvalidDexFile) << ref.dex_file->GetLocation();
Mathieu Chartier1a088d42017-07-18 11:43:57 -07002890 } while (result != ClassStateTable::kInsertResultSuccess);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07002891}
2892
Brian Carlstrom7940e442013-07-12 13:46:57 -07002893CompiledMethod* CompilerDriver::GetCompiledMethod(MethodReference ref) const {
Mathieu Chartieracab8d42016-11-23 13:45:58 -08002894 CompiledMethod* compiled_method = nullptr;
Mathieu Chartierfc8b4222017-09-17 13:44:24 -07002895 compiled_methods_.Get(ref, &compiled_method);
Mathieu Chartieracab8d42016-11-23 13:45:58 -08002896 return compiled_method;
Brian Carlstrom7940e442013-07-12 13:46:57 -07002897}
2898
Calin Juravlef1c6d9e2015-04-13 18:42:21 +01002899bool CompilerDriver::IsMethodVerifiedWithoutFailures(uint32_t method_idx,
2900 uint16_t class_def_idx,
2901 const DexFile& dex_file) const {
2902 const VerifiedMethod* verified_method = GetVerifiedMethod(&dex_file, method_idx);
2903 if (verified_method != nullptr) {
2904 return !verified_method->HasVerificationFailures();
2905 }
2906
2907 // If we can't find verification metadata, check if this is a system class (we trust that system
2908 // classes have their methods verified). If it's not, be conservative and assume the method
2909 // has not been verified successfully.
2910
2911 // TODO: When compiling the boot image it should be safe to assume that everything is verified,
2912 // even if methods are not found in the verification cache.
2913 const char* descriptor = dex_file.GetClassDescriptor(dex_file.GetClassDef(class_def_idx));
2914 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
2915 Thread* self = Thread::Current();
2916 ScopedObjectAccess soa(self);
2917 bool is_system_class = class_linker->FindSystemClass(self, descriptor) != nullptr;
2918 if (!is_system_class) {
2919 self->ClearException();
2920 }
2921 return is_system_class;
2922}
2923
Vladimir Markof4da6752014-08-01 19:04:18 +01002924size_t CompilerDriver::GetNonRelativeLinkerPatchCount() const {
Mathieu Chartieracab8d42016-11-23 13:45:58 -08002925 return non_relative_linker_patch_count_.LoadRelaxed();
Vladimir Markof4da6752014-08-01 19:04:18 +01002926}
2927
Mathieu Chartierc4ae9162016-04-07 13:19:19 -07002928void CompilerDriver::SetRequiresConstructorBarrier(Thread* self,
2929 const DexFile* dex_file,
2930 uint16_t class_def_index,
2931 bool requires) {
2932 WriterMutexLock mu(self, requires_constructor_barrier_lock_);
2933 requires_constructor_barrier_.emplace(ClassReference(dex_file, class_def_index), requires);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002934}
2935
Mathieu Chartier371bd832016-04-07 10:19:48 -07002936bool CompilerDriver::RequiresConstructorBarrier(Thread* self,
2937 const DexFile* dex_file,
Mathieu Chartierc4ae9162016-04-07 13:19:19 -07002938 uint16_t class_def_index) {
2939 ClassReference class_ref(dex_file, class_def_index);
2940 {
2941 ReaderMutexLock mu(self, requires_constructor_barrier_lock_);
2942 auto it = requires_constructor_barrier_.find(class_ref);
2943 if (it != requires_constructor_barrier_.end()) {
2944 return it->second;
2945 }
Mathieu Chartierb5d38612016-04-07 10:52:52 -07002946 }
Mathieu Chartierc4ae9162016-04-07 13:19:19 -07002947 WriterMutexLock mu(self, requires_constructor_barrier_lock_);
2948 const bool requires = RequiresConstructorBarrier(*dex_file, class_def_index);
2949 requires_constructor_barrier_.emplace(class_ref, requires);
2950 return requires;
Brian Carlstrom7940e442013-07-12 13:46:57 -07002951}
2952
Andreas Gampe8d295f82015-01-20 14:50:21 -08002953std::string CompilerDriver::GetMemoryUsageString(bool extended) const {
Mathieu Chartierab972ef2014-12-03 17:38:22 -08002954 std::ostringstream oss;
Calin Juravle69158982016-03-16 11:53:41 +00002955 const gc::Heap* const heap = Runtime::Current()->GetHeap();
Anton Kirilovdd9473b2016-01-28 15:08:01 +00002956 const size_t java_alloc = heap->GetBytesAllocated();
Calin Juravle69158982016-03-16 11:53:41 +00002957 oss << "arena alloc=" << PrettySize(max_arena_alloc_) << " (" << max_arena_alloc_ << "B)";
Anton Kirilovdd9473b2016-01-28 15:08:01 +00002958 oss << " java alloc=" << PrettySize(java_alloc) << " (" << java_alloc << "B)";
Elliott Hughes7bf5a262015-04-02 20:55:07 -07002959#if defined(__BIONIC__) || defined(__GLIBC__)
Anton Kirilovdd9473b2016-01-28 15:08:01 +00002960 const struct mallinfo info = mallinfo();
Mathieu Chartierab972ef2014-12-03 17:38:22 -08002961 const size_t allocated_space = static_cast<size_t>(info.uordblks);
2962 const size_t free_space = static_cast<size_t>(info.fordblks);
Anton Kirilovdd9473b2016-01-28 15:08:01 +00002963 oss << " native alloc=" << PrettySize(allocated_space) << " (" << allocated_space << "B)"
2964 << " free=" << PrettySize(free_space) << " (" << free_space << "B)";
Mathieu Chartierab972ef2014-12-03 17:38:22 -08002965#endif
Vladimir Marko35831e82015-09-11 11:59:18 +01002966 compiled_method_storage_.DumpMemoryUsage(oss, extended);
Mathieu Chartierab972ef2014-12-03 17:38:22 -08002967 return oss.str();
2968}
2969
Jeff Haodcdc85b2015-12-04 14:06:18 -08002970bool CompilerDriver::MayInlineInternal(const DexFile* inlined_from,
2971 const DexFile* inlined_into) const {
2972 // We're not allowed to inline across dex files if we're the no-inline-from dex file.
2973 if (inlined_from != inlined_into &&
Vladimir Marko47496c22016-01-27 16:15:08 +00002974 compiler_options_->GetNoInlineFromDexFile() != nullptr &&
2975 ContainsElement(*compiler_options_->GetNoInlineFromDexFile(), inlined_from)) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002976 return false;
2977 }
2978
2979 return true;
2980}
2981
Andreas Gampeace0dc12016-01-20 13:33:13 -08002982void CompilerDriver::InitializeThreadPools() {
2983 size_t parallel_count = parallel_thread_count_ > 0 ? parallel_thread_count_ - 1 : 0;
2984 parallel_thread_pool_.reset(
2985 new ThreadPool("Compiler driver thread pool", parallel_count));
2986 single_thread_pool_.reset(new ThreadPool("Single-threaded Compiler driver thread pool", 0));
2987}
2988
2989void CompilerDriver::FreeThreadPools() {
2990 parallel_thread_pool_.reset();
2991 single_thread_pool_.reset();
2992}
2993
Mathieu Chartier72041a02017-07-14 18:23:25 -07002994void CompilerDriver::SetDexFilesForOatFile(const std::vector<const DexFile*>& dex_files) {
2995 dex_files_for_oat_file_ = dex_files;
Nicolas Geoffray486dda02017-09-11 14:15:52 +01002996 compiled_classes_.AddDexFiles(dex_files);
2997}
2998
2999void CompilerDriver::SetClasspathDexFiles(const std::vector<const DexFile*>& dex_files) {
3000 classpath_classes_.AddDexFiles(dex_files);
Mathieu Chartier72041a02017-07-14 18:23:25 -07003001}
3002
Brian Carlstrom7940e442013-07-12 13:46:57 -07003003} // namespace art