blob: fd7ae9f570f310e968fbad8f043201135c79b9c7 [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"
Brian Carlstrom7940e442013-07-12 13:46:57 -070035#include "base/stl_util.h"
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -080036#include "base/systrace.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010037#include "base/time_utils.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070038#include "base/timing_logger.h"
Vladimir Marko3481ba22015-04-13 12:22:36 +010039#include "class_linker-inl.h"
Vladimir Markod8dbc8d2017-09-20 13:37:47 +010040#include "compiled_method-inl.h"
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +000041#include "compiler.h"
Nicolas Geoffray6bb7f1b2016-11-03 10:52:49 +000042#include "compiler_callbacks.h"
Vladimir Markobe0e5462014-02-26 11:24:15 +000043#include "compiler_driver-inl.h"
Andreas Gampe5eb0d382015-07-23 01:19:26 -070044#include "dex/dex_to_dex_compiler.h"
Vladimir Markoc7f83202014-01-24 17:55:18 +000045#include "dex/verification_results.h"
Vladimir Marko2730db02014-01-27 11:15:17 +000046#include "dex/verified_method.h"
Steven Morelande431e272017-07-18 16:53:49 -070047#include "dex_compilation_unit.h"
48#include "dex_file-inl.h"
Vladimir Markob0a6aee2017-10-27 10:34:04 +010049#include "dex_file_annotations.h"
Steven Morelande431e272017-07-18 16:53:49 -070050#include "dex_instruction-inl.h"
Mark Mendellae9fd932014-02-10 16:14:35 -080051#include "driver/compiler_options.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070052#include "gc/accounting/card_table-inl.h"
53#include "gc/accounting/heap_bitmap.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070054#include "gc/space/image_space.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070055#include "gc/space/space.h"
Steven Morelande431e272017-07-18 16:53:49 -070056#include "handle_scope-inl.h"
57#include "intrinsics_enum.h"
58#include "jni_internal.h"
Vladimir Markod8dbc8d2017-09-20 13:37:47 +010059#include "linker/linker_patch.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070060#include "mirror/class-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -070061#include "mirror/class_loader.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070062#include "mirror/dex_cache-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070063#include "mirror/object-inl.h"
Andreas Gampec6ea7d02017-02-01 16:46:28 -080064#include "mirror/object-refvisitor-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070065#include "mirror/object_array-inl.h"
66#include "mirror/throwable.h"
Steven Morelande431e272017-07-18 16:53:49 -070067#include "nativehelper/ScopedLocalRef.h"
68#include "object_lock.h"
69#include "runtime.h"
Orion Hodson26ef34c2017-11-01 13:32:41 +000070#include "runtime_intrinsics.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070071#include "scoped_thread_state_change-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070072#include "thread.h"
Andreas Gampeb0f370e2014-09-25 22:51:40 -070073#include "thread_list.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070074#include "thread_pool.h"
Ian Rogers848871b2013-08-05 10:56:33 -070075#include "trampolines/trampoline_compiler.h"
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +010076#include "transaction.h"
Mathieu Chartier93764b82017-07-17 14:51:53 -070077#include "utils/atomic_dex_ref_map-inl.h"
Vladimir Marko20f85592015-03-19 10:07:02 +000078#include "utils/dex_cache_arrays_layout-inl.h"
Andreas Gampee21dc3d2014-12-08 16:59:43 -080079#include "utils/swap_space.h"
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +000080#include "vdex_file.h"
Vladimir Marko2bc47802014-02-10 09:43:07 +000081#include "verifier/method_verifier-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -070082#include "verifier/method_verifier.h"
Nicolas Geoffray08025182016-10-25 17:20:18 +010083#include "verifier/verifier_deps.h"
Andreas Gampe6d7abbd2017-04-24 13:19:09 -070084#include "verifier/verifier_enums.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070085
Brian Carlstrom7940e442013-07-12 13:46:57 -070086namespace art {
87
Mathieu Chartier8e219ae2014-08-19 14:29:46 -070088static constexpr bool kTimeCompileMethod = !kIsDebugBuild;
89
Calin Juravle226501b2015-12-11 14:41:31 +000090// Print additional info during profile guided compilation.
91static constexpr bool kDebugProfileGuidedCompilation = false;
92
Chang Xing70f689d2017-06-08 17:16:12 -070093// Max encoded fields allowed for initializing app image. Hardcode the number for now
94// because 5000 should be large enough.
95static constexpr uint32_t kMaxEncodedFields = 5000;
96
Brian Carlstrom7940e442013-07-12 13:46:57 -070097static double Percentage(size_t x, size_t y) {
98 return 100.0 * (static_cast<double>(x)) / (static_cast<double>(x + y));
99}
100
101static void DumpStat(size_t x, size_t y, const char* str) {
102 if (x == 0 && y == 0) {
103 return;
104 }
Ian Rogerse732ef12013-10-09 15:22:24 -0700105 LOG(INFO) << Percentage(x, y) << "% of " << str << " for " << (x + y) << " cases";
Brian Carlstrom7940e442013-07-12 13:46:57 -0700106}
107
Vladimir Markof096aad2014-01-23 15:51:58 +0000108class CompilerDriver::AOTCompilationStats {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700109 public:
110 AOTCompilationStats()
111 : stats_lock_("AOT compilation statistics lock"),
Brian Carlstrom7940e442013-07-12 13:46:57 -0700112 resolved_types_(0), unresolved_types_(0),
113 resolved_instance_fields_(0), unresolved_instance_fields_(0),
114 resolved_local_static_fields_(0), resolved_static_fields_(0), unresolved_static_fields_(0),
115 type_based_devirtualization_(0),
116 safe_casts_(0), not_safe_casts_(0) {
117 for (size_t i = 0; i <= kMaxInvokeType; i++) {
118 resolved_methods_[i] = 0;
119 unresolved_methods_[i] = 0;
120 virtual_made_direct_[i] = 0;
121 direct_calls_to_boot_[i] = 0;
122 direct_methods_to_boot_[i] = 0;
123 }
124 }
125
126 void Dump() {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700127 DumpStat(resolved_types_, unresolved_types_, "types resolved");
128 DumpStat(resolved_instance_fields_, unresolved_instance_fields_, "instance fields resolved");
129 DumpStat(resolved_local_static_fields_ + resolved_static_fields_, unresolved_static_fields_,
130 "static fields resolved");
131 DumpStat(resolved_local_static_fields_, resolved_static_fields_ + unresolved_static_fields_,
132 "static fields local to a class");
133 DumpStat(safe_casts_, not_safe_casts_, "check-casts removed based on type information");
134 // Note, the code below subtracts the stat value so that when added to the stat value we have
135 // 100% of samples. TODO: clean this up.
136 DumpStat(type_based_devirtualization_,
137 resolved_methods_[kVirtual] + unresolved_methods_[kVirtual] +
138 resolved_methods_[kInterface] + unresolved_methods_[kInterface] -
139 type_based_devirtualization_,
140 "virtual/interface calls made direct based on type information");
141
142 for (size_t i = 0; i <= kMaxInvokeType; i++) {
143 std::ostringstream oss;
144 oss << static_cast<InvokeType>(i) << " methods were AOT resolved";
145 DumpStat(resolved_methods_[i], unresolved_methods_[i], oss.str().c_str());
146 if (virtual_made_direct_[i] > 0) {
147 std::ostringstream oss2;
148 oss2 << static_cast<InvokeType>(i) << " methods made direct";
149 DumpStat(virtual_made_direct_[i],
150 resolved_methods_[i] + unresolved_methods_[i] - virtual_made_direct_[i],
151 oss2.str().c_str());
152 }
153 if (direct_calls_to_boot_[i] > 0) {
154 std::ostringstream oss2;
155 oss2 << static_cast<InvokeType>(i) << " method calls are direct into boot";
156 DumpStat(direct_calls_to_boot_[i],
157 resolved_methods_[i] + unresolved_methods_[i] - direct_calls_to_boot_[i],
158 oss2.str().c_str());
159 }
160 if (direct_methods_to_boot_[i] > 0) {
161 std::ostringstream oss2;
162 oss2 << static_cast<InvokeType>(i) << " method calls have methods in boot";
163 DumpStat(direct_methods_to_boot_[i],
164 resolved_methods_[i] + unresolved_methods_[i] - direct_methods_to_boot_[i],
165 oss2.str().c_str());
166 }
167 }
168 }
169
170// Allow lossy statistics in non-debug builds.
171#ifndef NDEBUG
172#define STATS_LOCK() MutexLock mu(Thread::Current(), stats_lock_)
173#else
174#define STATS_LOCK()
175#endif
176
Mathieu Chartier90443472015-07-16 20:32:27 -0700177 void TypeDoesntNeedAccessCheck() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700178 STATS_LOCK();
179 resolved_types_++;
180 }
181
Mathieu Chartier90443472015-07-16 20:32:27 -0700182 void TypeNeedsAccessCheck() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700183 STATS_LOCK();
184 unresolved_types_++;
185 }
186
Mathieu Chartier90443472015-07-16 20:32:27 -0700187 void ResolvedInstanceField() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700188 STATS_LOCK();
189 resolved_instance_fields_++;
190 }
191
Mathieu Chartier90443472015-07-16 20:32:27 -0700192 void UnresolvedInstanceField() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700193 STATS_LOCK();
194 unresolved_instance_fields_++;
195 }
196
Mathieu Chartier90443472015-07-16 20:32:27 -0700197 void ResolvedLocalStaticField() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700198 STATS_LOCK();
199 resolved_local_static_fields_++;
200 }
201
Mathieu Chartier90443472015-07-16 20:32:27 -0700202 void ResolvedStaticField() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700203 STATS_LOCK();
204 resolved_static_fields_++;
205 }
206
Mathieu Chartier90443472015-07-16 20:32:27 -0700207 void UnresolvedStaticField() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700208 STATS_LOCK();
209 unresolved_static_fields_++;
210 }
211
212 // Indicate that type information from the verifier led to devirtualization.
Mathieu Chartier90443472015-07-16 20:32:27 -0700213 void PreciseTypeDevirtualization() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700214 STATS_LOCK();
215 type_based_devirtualization_++;
216 }
217
Brian Carlstrom7940e442013-07-12 13:46:57 -0700218 // A check-cast could be eliminated due to verifier type analysis.
Mathieu Chartier90443472015-07-16 20:32:27 -0700219 void SafeCast() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700220 STATS_LOCK();
221 safe_casts_++;
222 }
223
224 // A check-cast couldn't be eliminated due to verifier type analysis.
Mathieu Chartier90443472015-07-16 20:32:27 -0700225 void NotASafeCast() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700226 STATS_LOCK();
227 not_safe_casts_++;
228 }
229
230 private:
231 Mutex stats_lock_;
232
Brian Carlstrom7940e442013-07-12 13:46:57 -0700233 size_t resolved_types_;
234 size_t unresolved_types_;
235
236 size_t resolved_instance_fields_;
237 size_t unresolved_instance_fields_;
238
239 size_t resolved_local_static_fields_;
240 size_t resolved_static_fields_;
241 size_t unresolved_static_fields_;
242 // Type based devirtualization for invoke interface and virtual.
243 size_t type_based_devirtualization_;
244
245 size_t resolved_methods_[kMaxInvokeType + 1];
246 size_t unresolved_methods_[kMaxInvokeType + 1];
247 size_t virtual_made_direct_[kMaxInvokeType + 1];
248 size_t direct_calls_to_boot_[kMaxInvokeType + 1];
249 size_t direct_methods_to_boot_[kMaxInvokeType + 1];
250
251 size_t safe_casts_;
252 size_t not_safe_casts_;
253
254 DISALLOW_COPY_AND_ASSIGN(AOTCompilationStats);
255};
256
Vladimir Marko492a7fa2016-06-01 18:38:43 +0100257class CompilerDriver::DexFileMethodSet {
258 public:
259 explicit DexFileMethodSet(const DexFile& dex_file)
260 : dex_file_(dex_file),
261 method_indexes_(dex_file.NumMethodIds(), false, Allocator::GetMallocAllocator()) {
262 }
263 DexFileMethodSet(DexFileMethodSet&& other) = default;
264
265 const DexFile& GetDexFile() const { return dex_file_; }
266
267 BitVector& GetMethodIndexes() { return method_indexes_; }
268 const BitVector& GetMethodIndexes() const { return method_indexes_; }
269
270 private:
271 const DexFile& dex_file_;
272 BitVector method_indexes_;
273};
274
Jeff Haodcdc85b2015-12-04 14:06:18 -0800275CompilerDriver::CompilerDriver(
276 const CompilerOptions* compiler_options,
277 VerificationResults* verification_results,
Jeff Haodcdc85b2015-12-04 14:06:18 -0800278 Compiler::Kind compiler_kind,
279 InstructionSet instruction_set,
280 const InstructionSetFeatures* instruction_set_features,
Vladimir Marko944da602016-02-19 12:27:55 +0000281 std::unordered_set<std::string>* image_classes,
Jeff Haodcdc85b2015-12-04 14:06:18 -0800282 std::unordered_set<std::string>* compiled_classes,
283 std::unordered_set<std::string>* compiled_methods,
Vladimir Marko944da602016-02-19 12:27:55 +0000284 size_t thread_count,
285 bool dump_stats,
286 bool dump_passes,
287 CumulativeLogger* timer,
288 int swap_fd,
Calin Juravle998c2162015-12-21 15:39:33 +0200289 const ProfileCompilationInfo* profile_compilation_info)
Calin Juravle226501b2015-12-11 14:41:31 +0000290 : compiler_options_(compiler_options),
Brian Carlstrom6449c622014-02-10 23:48:36 -0800291 verification_results_(verification_results),
Ian Rogers72d32622014-05-06 16:20:11 -0700292 compiler_(Compiler::Create(this, compiler_kind)),
Jeff Hao48699fb2015-04-06 14:21:37 -0700293 compiler_kind_(compiler_kind),
Vladimir Marko33bff252017-11-01 14:35:42 +0000294 instruction_set_(
295 instruction_set == InstructionSet::kArm ? InstructionSet::kThumb2 : instruction_set),
Dave Allison70202782013-10-22 17:52:19 -0700296 instruction_set_features_(instruction_set_features),
Mathieu Chartierc4ae9162016-04-07 13:19:19 -0700297 requires_constructor_barrier_lock_("constructor barrier lock"),
Vladimir Markof4da6752014-08-01 19:04:18 +0100298 non_relative_linker_patch_count_(0u),
Brian Carlstrom7940e442013-07-12 13:46:57 -0700299 image_classes_(image_classes),
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800300 classes_to_compile_(compiled_classes),
Andreas Gampe70bef0d2015-04-15 02:37:28 -0700301 methods_to_compile_(compiled_methods),
Andreas Gampef39208f2017-10-19 15:06:59 -0700302 number_of_soft_verifier_failures_(0),
Andreas Gampe6cf49e52015-03-05 13:08:45 -0800303 had_hard_verifier_failure_(false),
Andreas Gampeace0dc12016-01-20 13:33:13 -0800304 parallel_thread_count_(thread_count),
Brian Carlstrom7940e442013-07-12 13:46:57 -0700305 stats_(new AOTCompilationStats),
306 dump_stats_(dump_stats),
Nicolas Geoffrayea3fa0b2014-02-10 11:59:41 +0000307 dump_passes_(dump_passes),
308 timings_logger_(timer),
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700309 compiler_context_(nullptr),
Alexey Frunze19f6c692016-11-30 19:19:55 -0800310 support_boot_image_fixup_(true),
Calin Juravle998c2162015-12-21 15:39:33 +0200311 compiled_method_storage_(swap_fd),
Calin Juravle69158982016-03-16 11:53:41 +0000312 profile_compilation_info_(profile_compilation_info),
Vladimir Marko492a7fa2016-06-01 18:38:43 +0100313 max_arena_alloc_(0),
314 dex_to_dex_references_lock_("dex-to-dex references lock"),
315 dex_to_dex_references_(),
316 current_dex_to_dex_methods_(nullptr) {
Brian Carlstrom6449c622014-02-10 23:48:36 -0800317 DCHECK(compiler_options_ != nullptr);
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700318
Ian Rogers72d32622014-05-06 16:20:11 -0700319 compiler_->Init();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700320
Vladimir Markoaad75c62016-10-03 08:46:48 +0000321 if (GetCompilerOptions().IsBootImage()) {
Mathieu Chartierc5dd3192015-12-09 16:38:30 -0800322 CHECK(image_classes_.get() != nullptr) << "Expected image classes for boot image";
323 }
Andreas Gampecac31ad2017-11-06 20:01:17 -0800324
325 compiled_method_storage_.SetDedupeEnabled(compiler_options_->DeduplicateCode());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700326}
327
328CompilerDriver::~CompilerDriver() {
Mathieu Chartier93764b82017-07-17 14:51:53 -0700329 compiled_methods_.Visit([this](const DexFileReference& ref ATTRIBUTE_UNUSED,
Mathieu Chartieracab8d42016-11-23 13:45:58 -0800330 CompiledMethod* method) {
331 if (method != nullptr) {
332 CompiledMethod::ReleaseSwapAllocatedCompiledMethod(this, method);
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800333 }
Mathieu Chartieracab8d42016-11-23 13:45:58 -0800334 });
Ian Rogers72d32622014-05-06 16:20:11 -0700335 compiler_->UnInit();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700336}
337
Vladimir Marko35831e82015-09-11 11:59:18 +0100338
Ian Rogersdd7624d2014-03-14 17:43:00 -0700339#define CREATE_TRAMPOLINE(type, abi, offset) \
Andreas Gampeaf13ad92014-04-11 12:07:48 -0700340 if (Is64BitInstructionSet(instruction_set_)) { \
Ian Rogersdd7624d2014-03-14 17:43:00 -0700341 return CreateTrampoline64(instruction_set_, abi, \
Andreas Gampe542451c2016-07-26 09:02:02 -0700342 type ## _ENTRYPOINT_OFFSET(PointerSize::k64, offset)); \
Ian Rogersdd7624d2014-03-14 17:43:00 -0700343 } else { \
344 return CreateTrampoline32(instruction_set_, abi, \
Andreas Gampe542451c2016-07-26 09:02:02 -0700345 type ## _ENTRYPOINT_OFFSET(PointerSize::k32, offset)); \
Ian Rogersdd7624d2014-03-14 17:43:00 -0700346 }
347
Vladimir Marko93205e32016-04-13 11:59:46 +0100348std::unique_ptr<const std::vector<uint8_t>> CompilerDriver::CreateJniDlsymLookup() const {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700349 CREATE_TRAMPOLINE(JNI, kJniAbi, pDlsymLookup)
Ian Rogers848871b2013-08-05 10:56:33 -0700350}
351
Vladimir Marko93205e32016-04-13 11:59:46 +0100352std::unique_ptr<const std::vector<uint8_t>> CompilerDriver::CreateQuickGenericJniTrampoline()
353 const {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700354 CREATE_TRAMPOLINE(QUICK, kQuickAbi, pQuickGenericJniTrampoline)
Andreas Gampe2da88232014-02-27 12:26:20 -0800355}
356
Vladimir Marko93205e32016-04-13 11:59:46 +0100357std::unique_ptr<const std::vector<uint8_t>> CompilerDriver::CreateQuickImtConflictTrampoline()
358 const {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700359 CREATE_TRAMPOLINE(QUICK, kQuickAbi, pQuickImtConflictTrampoline)
Jeff Hao88474b42013-10-23 16:24:40 -0700360}
361
Vladimir Marko93205e32016-04-13 11:59:46 +0100362std::unique_ptr<const std::vector<uint8_t>> CompilerDriver::CreateQuickResolutionTrampoline()
363 const {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700364 CREATE_TRAMPOLINE(QUICK, kQuickAbi, pQuickResolutionTrampoline)
Brian Carlstrom7940e442013-07-12 13:46:57 -0700365}
366
Vladimir Marko93205e32016-04-13 11:59:46 +0100367std::unique_ptr<const std::vector<uint8_t>> CompilerDriver::CreateQuickToInterpreterBridge()
368 const {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700369 CREATE_TRAMPOLINE(QUICK, kQuickAbi, pQuickToInterpreterBridge)
Brian Carlstrom7940e442013-07-12 13:46:57 -0700370}
Ian Rogersdd7624d2014-03-14 17:43:00 -0700371#undef CREATE_TRAMPOLINE
Brian Carlstrom7940e442013-07-12 13:46:57 -0700372
373void CompilerDriver::CompileAll(jobject class_loader,
Brian Carlstrom45602482013-07-21 22:07:55 -0700374 const std::vector<const DexFile*>& dex_files,
Ian Rogers3d504072014-03-01 09:16:49 -0800375 TimingLogger* timings) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700376 DCHECK(!Runtime::Current()->IsStarted());
Andreas Gampeace0dc12016-01-20 13:33:13 -0800377
378 InitializeThreadPools();
379
Andreas Gampe8d295f82015-01-20 14:50:21 -0800380 VLOG(compiler) << "Before precompile " << GetMemoryUsageString(false);
Andreas Gampe740667a2015-09-15 17:55:06 -0700381 // Precompile:
382 // 1) Load image classes
383 // 2) Resolve all classes
384 // 3) Attempt to verify all classes
385 // 4) Attempt to initialize image classes, and trivially initialized classes
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000386 PreCompile(class_loader, dex_files, timings);
Vladimir Markoaad75c62016-10-03 08:46:48 +0000387 if (GetCompilerOptions().IsBootImage()) {
Nicolas Geoffray762869d2016-07-15 15:28:35 +0100388 // We don't need to setup the intrinsics for non boot image compilation, as
389 // those compilations will pick up a boot image that have the ArtMethod already
390 // set with the intrinsics flag.
Orion Hodson26ef34c2017-11-01 13:32:41 +0000391 InitializeIntrinsics();
Nicolas Geoffray762869d2016-07-15 15:28:35 +0100392 }
Andreas Gampe740667a2015-09-15 17:55:06 -0700393 // Compile:
394 // 1) Compile all classes and methods enabled for compilation. May fall back to dex-to-dex
395 // compilation.
Nicolas Geoffray49cda062017-04-21 13:08:25 +0100396 if (GetCompilerOptions().IsAnyCompilationEnabled()) {
Andreas Gampeace0dc12016-01-20 13:33:13 -0800397 Compile(class_loader, dex_files, timings);
Andreas Gampe740667a2015-09-15 17:55:06 -0700398 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700399 if (dump_stats_) {
400 stats_->Dump();
401 }
Andreas Gampeace0dc12016-01-20 13:33:13 -0800402
403 FreeThreadPools();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700404}
405
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700406static optimizer::DexToDexCompilationLevel GetDexToDexCompilationLevel(
407 Thread* self, const CompilerDriver& driver, Handle<mirror::ClassLoader> class_loader,
408 const DexFile& dex_file, const DexFile::ClassDef& class_def)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700409 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800410 auto* const runtime = Runtime::Current();
Nicolas Geoffray49cda062017-04-21 13:08:25 +0100411 DCHECK(driver.GetCompilerOptions().IsQuickeningCompilationEnabled());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700412 const char* descriptor = dex_file.GetClassDescriptor(class_def);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800413 ClassLinker* class_linker = runtime->GetClassLinker();
Ian Rogers98379392014-02-24 16:53:16 -0800414 mirror::Class* klass = class_linker->FindClass(self, descriptor, class_loader);
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700415 if (klass == nullptr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700416 CHECK(self->IsExceptionPending());
417 self->ClearException();
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700418 return optimizer::DexToDexCompilationLevel::kDontDexToDexCompile;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700419 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700420 // DexToDex at the kOptimize level may introduce quickened opcodes, which replace symbolic
421 // references with actual offsets. We cannot re-verify such instructions.
422 //
423 // We store the verification information in the class status in the oat file, which the linker
424 // can validate (checksums) and use to skip load-time verification. It is thus safe to
425 // optimize when a class has been fully verified before.
Alex Lighte40dd382017-01-25 17:44:53 -0800426 optimizer::DexToDexCompilationLevel max_level = optimizer::DexToDexCompilationLevel::kOptimize;
427 if (driver.GetCompilerOptions().GetDebuggable()) {
428 // We are debuggable so definitions of classes might be changed. We don't want to do any
429 // optimizations that could break that.
Andreas Gampe1a4bc7f2017-03-27 14:57:30 -0700430 max_level = optimizer::DexToDexCompilationLevel::kDontDexToDexCompile;
Alex Lighte40dd382017-01-25 17:44:53 -0800431 }
Nicolas Geoffrayb4c6acb2017-11-10 12:48:14 +0000432 if (!VdexFile::CanEncodeQuickenedData(dex_file)) {
433 // Don't do any dex level optimizations if we cannot encode the quickening.
434 return optimizer::DexToDexCompilationLevel::kDontDexToDexCompile;
435 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700436 if (klass->IsVerified()) {
Sebastien Hertz75021222013-07-16 18:34:50 +0200437 // Class is verified so we can enable DEX-to-DEX compilation for performance.
Alex Lighte40dd382017-01-25 17:44:53 -0800438 return max_level;
Sebastien Hertz75021222013-07-16 18:34:50 +0200439 } else {
Andreas Gampe1a4bc7f2017-03-27 14:57:30 -0700440 // Class verification has failed: do not run DEX-to-DEX optimizations.
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700441 return optimizer::DexToDexCompilationLevel::kDontDexToDexCompile;
442 }
443}
444
445static optimizer::DexToDexCompilationLevel GetDexToDexCompilationLevel(
446 Thread* self,
447 const CompilerDriver& driver,
448 jobject jclass_loader,
449 const DexFile& dex_file,
450 const DexFile::ClassDef& class_def) {
451 ScopedObjectAccess soa(self);
452 StackHandleScope<1> hs(soa.Self());
453 Handle<mirror::ClassLoader> class_loader(
Mathieu Chartier0795f232016-09-27 18:43:30 -0700454 hs.NewHandle(soa.Decode<mirror::ClassLoader>(jclass_loader)));
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700455 return GetDexToDexCompilationLevel(self, driver, class_loader, dex_file, class_def);
456}
457
458// Does the runtime for the InstructionSet provide an implementation returned by
459// GetQuickGenericJniStub allowing down calls that aren't compiled using a JNI compiler?
460static bool InstructionSetHasGenericJniStub(InstructionSet isa) {
461 switch (isa) {
Vladimir Marko33bff252017-11-01 14:35:42 +0000462 case InstructionSet::kArm:
463 case InstructionSet::kArm64:
464 case InstructionSet::kThumb2:
465 case InstructionSet::kMips:
466 case InstructionSet::kMips64:
467 case InstructionSet::kX86:
468 case InstructionSet::kX86_64: return true;
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700469 default: return false;
470 }
471}
472
473static void CompileMethod(Thread* self,
474 CompilerDriver* driver,
475 const DexFile::CodeItem* code_item,
476 uint32_t access_flags,
477 InvokeType invoke_type,
478 uint16_t class_def_idx,
479 uint32_t method_idx,
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000480 Handle<mirror::ClassLoader> class_loader,
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700481 const DexFile& dex_file,
482 optimizer::DexToDexCompilationLevel dex_to_dex_compilation_level,
Mathieu Chartier736b5602015-09-02 14:54:11 -0700483 bool compilation_enabled,
Mathieu Chartieracab8d42016-11-23 13:45:58 -0800484 Handle<mirror::DexCache> dex_cache) {
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700485 DCHECK(driver != nullptr);
486 CompiledMethod* compiled_method = nullptr;
487 uint64_t start_ns = kTimeCompileMethod ? NanoTime() : 0;
488 MethodReference method_ref(&dex_file, method_idx);
489
Vladimir Marko492a7fa2016-06-01 18:38:43 +0100490 if (driver->GetCurrentDexToDexMethods() != nullptr) {
491 // This is the second pass when we dex-to-dex compile previously marked methods.
492 // TODO: Refactor the compilation to avoid having to distinguish the two passes
493 // here. That should be done on a higher level. http://b/29089975
494 if (driver->GetCurrentDexToDexMethods()->IsBitSet(method_idx)) {
Mathieu Chartier0733dc82017-07-17 14:05:28 -0700495 VerificationResults* results = driver->GetVerificationResults();
496 DCHECK(results != nullptr);
497 const VerifiedMethod* verified_method = results->GetVerifiedMethod(method_ref);
Vladimir Marko492a7fa2016-06-01 18:38:43 +0100498 // Do not optimize if a VerifiedMethod is missing. SafeCast elision,
499 // for example, relies on it.
500 compiled_method = optimizer::ArtCompileDEX(
501 driver,
502 code_item,
503 access_flags,
504 invoke_type,
505 class_def_idx,
506 method_idx,
507 class_loader,
508 dex_file,
509 (verified_method != nullptr)
510 ? dex_to_dex_compilation_level
Andreas Gampe1a4bc7f2017-03-27 14:57:30 -0700511 : optimizer::DexToDexCompilationLevel::kDontDexToDexCompile);
Vladimir Marko492a7fa2016-06-01 18:38:43 +0100512 }
513 } else if ((access_flags & kAccNative) != 0) {
Goran Jakovljevic8d41c082016-09-28 08:49:46 +0000514 // Are we extracting only and have support for generic JNI down calls?
515 if (!driver->GetCompilerOptions().IsJniCompilationEnabled() &&
516 InstructionSetHasGenericJniStub(driver->GetInstructionSet())) {
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700517 // Leaving this empty will trigger the generic JNI version
518 } else {
Igor Murashkin367f3dd2016-09-01 17:00:24 -0700519 // Query any JNI optimization annotations such as @FastNative or @CriticalNative.
Vladimir Markob0a6aee2017-10-27 10:34:04 +0100520 access_flags |= annotations::GetNativeMethodAnnotationAccessFlags(
521 dex_file, dex_file.GetClassDef(class_def_idx), method_idx);
Igor Murashkin9d4b6da2016-07-29 09:51:58 -0700522
Vladimir Marko92f7f3c2017-10-31 11:38:30 +0000523 compiled_method = driver->GetCompiler()->JniCompile(
524 access_flags, method_idx, dex_file, dex_cache);
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700525 CHECK(compiled_method != nullptr);
526 }
527 } else if ((access_flags & kAccAbstract) != 0) {
528 // Abstract methods don't have code.
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000529 } else {
Mathieu Chartier0733dc82017-07-17 14:05:28 -0700530 VerificationResults* results = driver->GetVerificationResults();
531 DCHECK(results != nullptr);
532 const VerifiedMethod* verified_method = results->GetVerifiedMethod(method_ref);
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700533 bool compile = compilation_enabled &&
534 // Basic checks, e.g., not <clinit>.
Mathieu Chartier0733dc82017-07-17 14:05:28 -0700535 results->IsCandidateForCompilation(method_ref, access_flags) &&
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700536 // Did not fail to create VerifiedMethod metadata.
Andreas Gampe0760a812015-08-26 17:12:51 -0700537 verified_method != nullptr &&
538 // Do not have failures that should punt to the interpreter.
539 !verified_method->HasRuntimeThrow() &&
540 (verified_method->GetEncounteredVerificationFailures() &
Andreas Gampea727e372015-08-25 09:22:37 -0700541 (verifier::VERIFY_ERROR_FORCE_INTERPRETER | verifier::VERIFY_ERROR_LOCKING)) == 0 &&
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700542 // Is eligable for compilation by methods-to-compile filter.
Calin Juravle226501b2015-12-11 14:41:31 +0000543 driver->IsMethodToCompile(method_ref) &&
544 driver->ShouldCompileBasedOnProfile(method_ref);
545
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700546 if (compile) {
547 // NOTE: if compiler declines to compile this method, it will return null.
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000548 compiled_method = driver->GetCompiler()->Compile(code_item,
549 access_flags,
550 invoke_type,
551 class_def_idx,
552 method_idx,
553 class_loader,
554 dex_file,
555 dex_cache);
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700556 }
557 if (compiled_method == nullptr &&
558 dex_to_dex_compilation_level != optimizer::DexToDexCompilationLevel::kDontDexToDexCompile) {
Vladimir Marko492a7fa2016-06-01 18:38:43 +0100559 DCHECK(!Runtime::Current()->UseJitCompilation());
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700560 // TODO: add a command-line option to disable DEX-to-DEX compilation ?
Vladimir Marko492a7fa2016-06-01 18:38:43 +0100561 driver->MarkForDexToDexCompilation(self, method_ref);
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700562 }
563 }
564 if (kTimeCompileMethod) {
565 uint64_t duration_ns = NanoTime() - start_ns;
566 if (duration_ns > MsToNs(driver->GetCompiler()->GetMaximumCompilationTimeBeforeWarning())) {
David Sehr709b0702016-10-13 09:12:37 -0700567 LOG(WARNING) << "Compilation of " << dex_file.PrettyMethod(method_idx)
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700568 << " took " << PrettyDuration(duration_ns);
569 }
570 }
571
572 if (compiled_method != nullptr) {
573 // Count non-relative linker patches.
574 size_t non_relative_linker_patch_count = 0u;
Vladimir Markod8dbc8d2017-09-20 13:37:47 +0100575 for (const linker::LinkerPatch& patch : compiled_method->GetPatches()) {
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700576 if (!patch.IsPcRelative()) {
577 ++non_relative_linker_patch_count;
578 }
579 }
580 bool compile_pic = driver->GetCompilerOptions().GetCompilePic(); // Off by default
581 // When compiling with PIC, there should be zero non-relative linker patches
582 CHECK(!compile_pic || non_relative_linker_patch_count == 0u);
583
584 driver->AddCompiledMethod(method_ref, compiled_method, non_relative_linker_patch_count);
585 }
586
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700587 if (self->IsExceptionPending()) {
588 ScopedObjectAccess soa(self);
David Sehr709b0702016-10-13 09:12:37 -0700589 LOG(FATAL) << "Unexpected exception compiling: " << dex_file.PrettyMethod(method_idx) << "\n"
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700590 << self->GetException()->Dump();
Sebastien Hertz75021222013-07-16 18:34:50 +0200591 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700592}
593
Mathieu Chartiere401d142015-04-22 13:56:20 -0700594void CompilerDriver::CompileOne(Thread* self, ArtMethod* method, TimingLogger* timings) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700595 DCHECK(!Runtime::Current()->IsStarted());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700596 jobject jclass_loader;
597 const DexFile* dex_file;
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700598 uint16_t class_def_idx;
Ian Rogersef7d42f2014-01-06 12:55:46 -0800599 uint32_t method_idx = method->GetDexMethodIndex();
600 uint32_t access_flags = method->GetAccessFlags();
601 InvokeType invoke_type = method->GetInvokeType();
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000602 StackHandleScope<2> hs(self);
Mathieu Chartier736b5602015-09-02 14:54:11 -0700603 Handle<mirror::DexCache> dex_cache(hs.NewHandle(method->GetDexCache()));
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000604 Handle<mirror::ClassLoader> class_loader(
605 hs.NewHandle(method->GetDeclaringClass()->GetClassLoader()));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700606 {
607 ScopedObjectAccessUnchecked soa(self);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800608 ScopedLocalRef<jobject> local_class_loader(
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000609 soa.Env(), soa.AddLocalReference<jobject>(class_loader.Get()));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700610 jclass_loader = soa.Env()->NewGlobalRef(local_class_loader.get());
611 // Find the dex_file
Mathieu Chartierbfd9a432014-05-21 17:43:44 -0700612 dex_file = method->GetDexFile();
613 class_def_idx = method->GetClassDefIndex();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700614 }
Ian Rogersef7d42f2014-01-06 12:55:46 -0800615 const DexFile::CodeItem* code_item = dex_file->GetCodeItem(method->GetCodeItemOffset());
Mathieu Chartier736b5602015-09-02 14:54:11 -0700616
617 // Go to native so that we don't block GC during compilation.
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700618 ScopedThreadSuspension sts(self, kNative);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700619
620 std::vector<const DexFile*> dex_files;
621 dex_files.push_back(dex_file);
622
Andreas Gampeace0dc12016-01-20 13:33:13 -0800623 InitializeThreadPools();
624
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000625 PreCompile(jclass_loader, dex_files, timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700626
Brian Carlstrom7940e442013-07-12 13:46:57 -0700627 // Can we run DEX-to-DEX compiler on this class ?
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700628 optimizer::DexToDexCompilationLevel dex_to_dex_compilation_level =
629 GetDexToDexCompilationLevel(self,
630 *this,
631 jclass_loader,
632 *dex_file,
633 dex_file->GetClassDef(class_def_idx));
634
Vladimir Marko492a7fa2016-06-01 18:38:43 +0100635 DCHECK(current_dex_to_dex_methods_ == nullptr);
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700636 CompileMethod(self,
637 this,
638 code_item,
639 access_flags,
640 invoke_type,
641 class_def_idx,
642 method_idx,
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000643 class_loader,
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700644 *dex_file,
645 dex_to_dex_compilation_level,
Mathieu Chartier736b5602015-09-02 14:54:11 -0700646 true,
647 dex_cache);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700648
Vladimir Marko492a7fa2016-06-01 18:38:43 +0100649 ArrayRef<DexFileMethodSet> dex_to_dex_references;
650 {
651 // From this point on, we shall not modify dex_to_dex_references_, so
652 // just grab a reference to it that we use without holding the mutex.
653 MutexLock lock(Thread::Current(), dex_to_dex_references_lock_);
654 dex_to_dex_references = ArrayRef<DexFileMethodSet>(dex_to_dex_references_);
655 }
656 if (!dex_to_dex_references.empty()) {
657 DCHECK_EQ(dex_to_dex_references.size(), 1u);
658 DCHECK(&dex_to_dex_references[0].GetDexFile() == dex_file);
659 current_dex_to_dex_methods_ = &dex_to_dex_references.front().GetMethodIndexes();
660 DCHECK(current_dex_to_dex_methods_->IsBitSet(method_idx));
661 DCHECK_EQ(current_dex_to_dex_methods_->NumSetBits(), 1u);
662 CompileMethod(self,
663 this,
664 code_item,
665 access_flags,
666 invoke_type,
667 class_def_idx,
668 method_idx,
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000669 class_loader,
Vladimir Marko492a7fa2016-06-01 18:38:43 +0100670 *dex_file,
671 dex_to_dex_compilation_level,
672 true,
673 dex_cache);
674 current_dex_to_dex_methods_ = nullptr;
675 }
676
Andreas Gampeace0dc12016-01-20 13:33:13 -0800677 FreeThreadPools();
678
Brian Carlstrom7940e442013-07-12 13:46:57 -0700679 self->GetJniEnv()->DeleteGlobalRef(jclass_loader);
Mathieu Chartier2535abe2015-02-17 10:38:49 -0800680}
681
Andreas Gampeace0dc12016-01-20 13:33:13 -0800682void CompilerDriver::Resolve(jobject class_loader,
683 const std::vector<const DexFile*>& dex_files,
684 TimingLogger* timings) {
685 // Resolution allocates classes and needs to run single-threaded to be deterministic.
686 bool force_determinism = GetCompilerOptions().IsForceDeterminism();
687 ThreadPool* resolve_thread_pool = force_determinism
688 ? single_thread_pool_.get()
689 : parallel_thread_pool_.get();
690 size_t resolve_thread_count = force_determinism ? 1U : parallel_thread_count_;
691
Brian Carlstrom7940e442013-07-12 13:46:57 -0700692 for (size_t i = 0; i != dex_files.size(); ++i) {
693 const DexFile* dex_file = dex_files[i];
Kenny Rootd5185342014-05-13 14:47:05 -0700694 CHECK(dex_file != nullptr);
Andreas Gampeace0dc12016-01-20 13:33:13 -0800695 ResolveDexFile(class_loader,
696 *dex_file,
697 dex_files,
698 resolve_thread_pool,
699 resolve_thread_count,
700 timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700701 }
702}
703
Andreas Gampeace0dc12016-01-20 13:33:13 -0800704// Resolve const-strings in the code. Done to have deterministic allocation behavior. Right now
705// this is single-threaded for simplicity.
706// TODO: Collect the relevant string indices in parallel, then allocate them sequentially in a
707// stable order.
708
Nicolas Geoffray571d2342016-10-12 13:03:15 +0000709static void ResolveConstStrings(Handle<mirror::DexCache> dex_cache,
Andreas Gampeace0dc12016-01-20 13:33:13 -0800710 const DexFile& dex_file,
Nicolas Geoffray571d2342016-10-12 13:03:15 +0000711 const DexFile::CodeItem* code_item)
712 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampeace0dc12016-01-20 13:33:13 -0800713 if (code_item == nullptr) {
714 // Abstract or native method.
715 return;
716 }
717
Nicolas Geoffray571d2342016-10-12 13:03:15 +0000718 ClassLinker* const class_linker = Runtime::Current()->GetClassLinker();
Mathieu Chartier2b2bef22017-10-26 17:10:19 -0700719 for (const DexInstructionPcPair& inst : code_item->Instructions()) {
720 switch (inst->Opcode()) {
Nicolas Geoffray571d2342016-10-12 13:03:15 +0000721 case Instruction::CONST_STRING:
Andreas Gampeace0dc12016-01-20 13:33:13 -0800722 case Instruction::CONST_STRING_JUMBO: {
Mathieu Chartier2b2bef22017-10-26 17:10:19 -0700723 dex::StringIndex string_index((inst->Opcode() == Instruction::CONST_STRING)
724 ? inst->VRegB_21c()
725 : inst->VRegB_31c());
Nicolas Geoffray571d2342016-10-12 13:03:15 +0000726 mirror::String* string = class_linker->ResolveString(dex_file, string_index, dex_cache);
727 CHECK(string != nullptr) << "Could not allocate a string when forcing determinism";
Andreas Gampeace0dc12016-01-20 13:33:13 -0800728 break;
729 }
730
731 default:
732 break;
733 }
Andreas Gampeace0dc12016-01-20 13:33:13 -0800734 }
735}
736
737static void ResolveConstStrings(CompilerDriver* driver,
738 const std::vector<const DexFile*>& dex_files,
739 TimingLogger* timings) {
Nicolas Geoffray571d2342016-10-12 13:03:15 +0000740 ScopedObjectAccess soa(Thread::Current());
741 StackHandleScope<1> hs(soa.Self());
742 ClassLinker* const class_linker = Runtime::Current()->GetClassLinker();
743 MutableHandle<mirror::DexCache> dex_cache(hs.NewHandle<mirror::DexCache>(nullptr));
744
Andreas Gampeace0dc12016-01-20 13:33:13 -0800745 for (const DexFile* dex_file : dex_files) {
Vladimir Markocd556b02017-02-03 11:47:34 +0000746 dex_cache.Assign(class_linker->FindDexCache(soa.Self(), *dex_file));
Andreas Gampeace0dc12016-01-20 13:33:13 -0800747 TimingLogger::ScopedTiming t("Resolve const-string Strings", timings);
748
749 size_t class_def_count = dex_file->NumClassDefs();
750 for (size_t class_def_index = 0; class_def_index < class_def_count; ++class_def_index) {
751 const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_index);
752
753 const uint8_t* class_data = dex_file->GetClassData(class_def);
754 if (class_data == nullptr) {
755 // empty class, probably a marker interface
756 continue;
757 }
758
759 ClassDataItemIterator it(*dex_file, class_data);
Mathieu Chartiere17cf242017-06-19 11:05:51 -0700760 it.SkipAllFields();
Andreas Gampeace0dc12016-01-20 13:33:13 -0800761
762 bool compilation_enabled = driver->IsClassToCompile(
763 dex_file->StringByTypeIdx(class_def.class_idx_));
764 if (!compilation_enabled) {
765 // Compilation is skipped, do not resolve const-string in code of this class.
766 // TODO: Make sure that inlining honors this.
767 continue;
768 }
769
Mathieu Chartierb7c273c2017-11-10 18:07:56 -0800770 // Direct and virtual methods.
771 int64_t previous_method_idx = -1;
772 while (it.HasNextMethod()) {
Andreas Gampeace0dc12016-01-20 13:33:13 -0800773 uint32_t method_idx = it.GetMemberIndex();
Mathieu Chartierb7c273c2017-11-10 18:07:56 -0800774 if (method_idx == previous_method_idx) {
Andreas Gampeace0dc12016-01-20 13:33:13 -0800775 // smali can create dex files with two encoded_methods sharing the same method_idx
776 // http://code.google.com/p/smali/issues/detail?id=119
777 it.Next();
778 continue;
779 }
Mathieu Chartierb7c273c2017-11-10 18:07:56 -0800780 previous_method_idx = method_idx;
Nicolas Geoffray571d2342016-10-12 13:03:15 +0000781 ResolveConstStrings(dex_cache, *dex_file, it.GetMethodCodeItem());
Andreas Gampeace0dc12016-01-20 13:33:13 -0800782 it.Next();
783 }
784 DCHECK(!it.HasNext());
785 }
786 }
787}
788
789inline void CompilerDriver::CheckThreadPools() {
790 DCHECK(parallel_thread_pool_ != nullptr);
791 DCHECK(single_thread_pool_ != nullptr);
792}
793
Nicolas Geoffray0a27fd02017-01-25 16:18:54 +0000794static void EnsureVerifiedOrVerifyAtRuntime(jobject jclass_loader,
795 const std::vector<const DexFile*>& dex_files) {
796 ScopedObjectAccess soa(Thread::Current());
797 StackHandleScope<2> hs(soa.Self());
798 Handle<mirror::ClassLoader> class_loader(
799 hs.NewHandle(soa.Decode<mirror::ClassLoader>(jclass_loader)));
800 MutableHandle<mirror::Class> cls(hs.NewHandle<mirror::Class>(nullptr));
801 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
802
803 for (const DexFile* dex_file : dex_files) {
804 for (uint32_t i = 0; i < dex_file->NumClassDefs(); ++i) {
805 const DexFile::ClassDef& class_def = dex_file->GetClassDef(i);
806 const char* descriptor = dex_file->GetClassDescriptor(class_def);
807 cls.Assign(class_linker->FindClass(soa.Self(), descriptor, class_loader));
Andreas Gampefa4333d2017-02-14 11:10:34 -0800808 if (cls == nullptr) {
Nicolas Geoffray0a27fd02017-01-25 16:18:54 +0000809 soa.Self()->ClearException();
810 } else if (&cls->GetDexFile() == dex_file) {
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +0000811 DCHECK(cls->IsErroneous() || cls->IsVerified() || cls->ShouldVerifyAtRuntime())
Nicolas Geoffray0a27fd02017-01-25 16:18:54 +0000812 << cls->PrettyClass()
813 << " " << cls->GetStatus();
814 }
815 }
816 }
817}
818
Andreas Gampeace0dc12016-01-20 13:33:13 -0800819void CompilerDriver::PreCompile(jobject class_loader,
820 const std::vector<const DexFile*>& dex_files,
821 TimingLogger* timings) {
822 CheckThreadPools();
823
Brian Carlstrom7940e442013-07-12 13:46:57 -0700824 LoadImageClasses(timings);
Andreas Gampe8d295f82015-01-20 14:50:21 -0800825 VLOG(compiler) << "LoadImageClasses: " << GetMemoryUsageString(false);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700826
Nicolas Geoffray49cda062017-04-21 13:08:25 +0100827 if (compiler_options_->IsAnyCompilationEnabled()) {
Mathieu Chartier88b74b62017-07-16 17:08:19 -0700828 // Avoid adding the dex files in the case where we aren't going to add compiled methods.
829 // This reduces RAM usage for this case.
830 for (const DexFile* dex_file : dex_files) {
831 // Can be already inserted if the caller is CompileOne. This happens for gtests.
832 if (!compiled_methods_.HaveDexFile(dex_file)) {
Mathieu Chartierfc8b4222017-09-17 13:44:24 -0700833 compiled_methods_.AddDexFile(dex_file);
Mathieu Chartier88b74b62017-07-16 17:08:19 -0700834 }
835 }
Nicolas Geoffray49cda062017-04-21 13:08:25 +0100836 // Resolve eagerly to prepare for compilation.
Andreas Gampeace0dc12016-01-20 13:33:13 -0800837 Resolve(class_loader, dex_files, timings);
Mathieu Chartiere86deef2015-03-19 13:43:37 -0700838 VLOG(compiler) << "Resolve: " << GetMemoryUsageString(false);
839 }
840
Nicolas Geoffray60ca9492016-12-20 21:15:00 +0000841 if (compiler_options_->AssumeClassesAreVerified()) {
Mathieu Chartierab972ef2014-12-03 17:38:22 -0800842 VLOG(compiler) << "Verify none mode specified, skipping verification.";
Andreas Gampeace0dc12016-01-20 13:33:13 -0800843 SetVerified(class_loader, dex_files, timings);
Mathieu Chartiere86deef2015-03-19 13:43:37 -0700844 }
845
Nicolas Geoffray60ca9492016-12-20 21:15:00 +0000846 if (!compiler_options_->IsVerificationEnabled()) {
Jeff Hao4a200f52014-04-01 14:58:49 -0700847 return;
848 }
849
Vladimir Markoaad75c62016-10-03 08:46:48 +0000850 if (GetCompilerOptions().IsForceDeterminism() && GetCompilerOptions().IsBootImage()) {
Andreas Gampeace0dc12016-01-20 13:33:13 -0800851 // Resolve strings from const-string. Do this now to have a deterministic image.
852 ResolveConstStrings(this, dex_files, timings);
853 VLOG(compiler) << "Resolve const-strings: " << GetMemoryUsageString(false);
854 }
855
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000856 Verify(class_loader, dex_files, timings);
Andreas Gampe8d295f82015-01-20 14:50:21 -0800857 VLOG(compiler) << "Verify: " << GetMemoryUsageString(false);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700858
Andreas Gampe6cf49e52015-03-05 13:08:45 -0800859 if (had_hard_verifier_failure_ && GetCompilerOptions().AbortOnHardVerifierFailure()) {
Andreas Gampefdfb4d42017-07-27 12:12:22 -0700860 // Avoid dumping threads. Even if we shut down the thread pools, there will still be three
861 // instances of this thread's stack.
862 LOG(FATAL_WITHOUT_ABORT) << "Had a hard failure verifying all classes, and was asked to abort "
863 << "in such situations. Please check the log.";
864 abort();
Andreas Gampef39208f2017-10-19 15:06:59 -0700865 } else if (number_of_soft_verifier_failures_ > 0 &&
866 GetCompilerOptions().AbortOnSoftVerifierFailure()) {
867 LOG(FATAL_WITHOUT_ABORT) << "Had " << number_of_soft_verifier_failures_ << " soft failure(s) "
868 << "verifying all classes, and was asked to abort in such situations. "
869 << "Please check the log.";
870 abort();
Andreas Gampe6cf49e52015-03-05 13:08:45 -0800871 }
872
Nicolas Geoffray49cda062017-04-21 13:08:25 +0100873 if (compiler_options_->IsAnyCompilationEnabled()) {
Nicolas Geoffray0a27fd02017-01-25 16:18:54 +0000874 if (kIsDebugBuild) {
875 EnsureVerifiedOrVerifyAtRuntime(class_loader, dex_files);
876 }
Nicolas Geoffrayade72d62016-12-15 13:20:02 +0000877 InitializeClasses(class_loader, dex_files, timings);
878 VLOG(compiler) << "InitializeClasses: " << GetMemoryUsageString(false);
879 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700880
881 UpdateImageClasses(timings);
Andreas Gampe8d295f82015-01-20 14:50:21 -0800882 VLOG(compiler) << "UpdateImageClasses: " << GetMemoryUsageString(false);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700883}
884
Ian Rogersdfb325e2013-10-30 01:00:44 -0700885bool CompilerDriver::IsImageClass(const char* descriptor) const {
Mathieu Chartierc5dd3192015-12-09 16:38:30 -0800886 if (image_classes_ != nullptr) {
887 // If we have a set of image classes, use those.
Ian Rogersdfb325e2013-10-30 01:00:44 -0700888 return image_classes_->find(descriptor) != image_classes_->end();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700889 }
Mathieu Chartierc5dd3192015-12-09 16:38:30 -0800890 // No set of image classes, assume we include all the classes.
891 // NOTE: Currently only reachable from InitImageMethodVisitor for the app image case.
Vladimir Markoaad75c62016-10-03 08:46:48 +0000892 return !GetCompilerOptions().IsBootImage();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700893}
894
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800895bool CompilerDriver::IsClassToCompile(const char* descriptor) const {
Andreas Gampeb1fcead2015-04-20 18:53:51 -0700896 if (classes_to_compile_ == nullptr) {
897 return true;
898 }
899 return classes_to_compile_->find(descriptor) != classes_to_compile_->end();
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800900}
901
Andreas Gampe70bef0d2015-04-15 02:37:28 -0700902bool CompilerDriver::IsMethodToCompile(const MethodReference& method_ref) const {
Andreas Gampe70bef0d2015-04-15 02:37:28 -0700903 if (methods_to_compile_ == nullptr) {
904 return true;
905 }
906
Mathieu Chartierfc8b4222017-09-17 13:44:24 -0700907 std::string tmp = method_ref.PrettyMethod();
Andreas Gampe70bef0d2015-04-15 02:37:28 -0700908 return methods_to_compile_->find(tmp.c_str()) != methods_to_compile_->end();
909}
910
Calin Juravle226501b2015-12-11 14:41:31 +0000911bool CompilerDriver::ShouldCompileBasedOnProfile(const MethodReference& method_ref) const {
Mathieu Chartier97ab5e32017-02-22 13:35:44 -0800912 // Profile compilation info may be null if no profile is passed.
Mathieu Chartierd0af56c2017-02-17 12:56:25 -0800913 if (!CompilerFilter::DependsOnProfile(compiler_options_->GetCompilerFilter())) {
914 // Use the compiler filter instead of the presence of profile_compilation_info_ since
915 // we may want to have full speed compilation along with profile based layout optimizations.
Calin Juravle226501b2015-12-11 14:41:31 +0000916 return true;
917 }
Mathieu Chartier97ab5e32017-02-22 13:35:44 -0800918 // If we are using a profile filter but do not have a profile compilation info, compile nothing.
919 if (profile_compilation_info_ == nullptr) {
920 return false;
921 }
Mathieu Chartier7b135c82017-06-05 12:54:01 -0700922 // Compile only hot methods, it is the profile saver's job to decide what startup methods to mark
923 // as hot.
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -0700924 bool result = profile_compilation_info_->GetMethodHotness(method_ref).IsHot();
Calin Juravle226501b2015-12-11 14:41:31 +0000925
926 if (kDebugProfileGuidedCompilation) {
927 LOG(INFO) << "[ProfileGuidedCompilation] "
Mathieu Chartierfc8b4222017-09-17 13:44:24 -0700928 << (result ? "Compiled" : "Skipped") << " method:" << method_ref.PrettyMethod(true);
Calin Juravle226501b2015-12-11 14:41:31 +0000929 }
930 return result;
931}
932
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700933class ResolveCatchBlockExceptionsClassVisitor : public ClassVisitor {
934 public:
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000935 ResolveCatchBlockExceptionsClassVisitor() : classes_() {}
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700936
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700937 virtual bool operator()(ObjPtr<mirror::Class> c) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000938 classes_.push_back(c);
Mathieu Chartiere4275c02015-08-06 15:34:15 -0700939 return true;
940 }
941
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000942 void FindExceptionTypesToResolve(
943 std::set<std::pair<dex::TypeIndex, const DexFile*>>* exceptions_to_resolve)
Vladimir Markobfb80d22017-02-14 14:08:12 +0000944 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000945 const auto pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
946 for (ObjPtr<mirror::Class> klass : classes_) {
947 for (ArtMethod& method : klass->GetMethods(pointer_size)) {
948 FindExceptionTypesToResolveForMethod(&method, exceptions_to_resolve);
949 }
950 }
951 }
952
953 private:
954 void FindExceptionTypesToResolveForMethod(
955 ArtMethod* method,
956 std::set<std::pair<dex::TypeIndex, const DexFile*>>* exceptions_to_resolve)
957 REQUIRES_SHARED(Locks::mutator_lock_) {
958 const DexFile::CodeItem* code_item = method->GetCodeItem();
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700959 if (code_item == nullptr) {
960 return; // native or abstract method
Brian Carlstrom7940e442013-07-12 13:46:57 -0700961 }
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700962 if (code_item->tries_size_ == 0) {
963 return; // nothing to process
964 }
965 const uint8_t* encoded_catch_handler_list = DexFile::GetCatchHandlerData(*code_item, 0);
966 size_t num_encoded_catch_handlers = DecodeUnsignedLeb128(&encoded_catch_handler_list);
967 for (size_t i = 0; i < num_encoded_catch_handlers; i++) {
968 int32_t encoded_catch_handler_size = DecodeSignedLeb128(&encoded_catch_handler_list);
969 bool has_catch_all = false;
970 if (encoded_catch_handler_size <= 0) {
971 encoded_catch_handler_size = -encoded_catch_handler_size;
972 has_catch_all = true;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700973 }
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700974 for (int32_t j = 0; j < encoded_catch_handler_size; j++) {
Andreas Gampea5b09a62016-11-17 15:21:22 -0800975 dex::TypeIndex encoded_catch_handler_handlers_type_idx =
976 dex::TypeIndex(DecodeUnsignedLeb128(&encoded_catch_handler_list));
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700977 // Add to set of types to resolve if not already in the dex cache resolved types
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000978 if (!method->IsResolvedTypeIdx(encoded_catch_handler_handlers_type_idx)) {
979 exceptions_to_resolve->emplace(encoded_catch_handler_handlers_type_idx,
980 method->GetDexFile());
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700981 }
982 // ignore address associated with catch handler
983 DecodeUnsignedLeb128(&encoded_catch_handler_list);
984 }
985 if (has_catch_all) {
986 // ignore catch all address
987 DecodeUnsignedLeb128(&encoded_catch_handler_list);
988 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700989 }
990 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700991
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000992 std::vector<ObjPtr<mirror::Class>> classes_;
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700993};
994
995class RecordImageClassesVisitor : public ClassVisitor {
996 public:
997 explicit RecordImageClassesVisitor(std::unordered_set<std::string>* image_classes)
998 : image_classes_(image_classes) {}
999
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001000 bool operator()(ObjPtr<mirror::Class> klass) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001001 std::string temp;
1002 image_classes_->insert(klass->GetDescriptor(&temp));
1003 return true;
1004 }
1005
1006 private:
1007 std::unordered_set<std::string>* const image_classes_;
1008};
Brian Carlstrom7940e442013-07-12 13:46:57 -07001009
1010// Make a list of descriptors for classes to include in the image
Mathieu Chartier90443472015-07-16 20:32:27 -07001011void CompilerDriver::LoadImageClasses(TimingLogger* timings) {
Kenny Rootd5185342014-05-13 14:47:05 -07001012 CHECK(timings != nullptr);
Vladimir Markoaad75c62016-10-03 08:46:48 +00001013 if (!GetCompilerOptions().IsBootImage()) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001014 return;
1015 }
1016
Mathieu Chartierf5997b42014-06-20 10:37:54 -07001017 TimingLogger::ScopedTiming t("LoadImageClasses", timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001018 // Make a first class to load all classes explicitly listed in the file
1019 Thread* self = Thread::Current();
1020 ScopedObjectAccess soa(self);
1021 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Kenny Rootd5185342014-05-13 14:47:05 -07001022 CHECK(image_classes_.get() != nullptr);
Mathieu Chartier02e25112013-08-14 16:14:24 -07001023 for (auto it = image_classes_->begin(), end = image_classes_->end(); it != end;) {
Vladimir Markoe9c36b32013-11-21 15:49:16 +00001024 const std::string& descriptor(*it);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001025 StackHandleScope<1> hs(self);
1026 Handle<mirror::Class> klass(
1027 hs.NewHandle(class_linker->FindSystemClass(self, descriptor.c_str())));
Andreas Gampefa4333d2017-02-14 11:10:34 -08001028 if (klass == nullptr) {
Ian Rogerse6bb3b22013-08-19 21:51:45 -07001029 VLOG(compiler) << "Failed to find class " << descriptor;
Vladimir Markoe9c36b32013-11-21 15:49:16 +00001030 image_classes_->erase(it++);
Ian Rogersa436fde2013-08-27 23:34:06 -07001031 self->ClearException();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001032 } else {
1033 ++it;
1034 }
1035 }
1036
1037 // Resolve exception classes referenced by the loaded classes. The catch logic assumes
1038 // exceptions are resolved by the verifier when there is a catch block in an interested method.
1039 // Do this here so that exception classes appear to have been specified image classes.
Andreas Gampea5b09a62016-11-17 15:21:22 -08001040 std::set<std::pair<dex::TypeIndex, const DexFile*>> unresolved_exception_types;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001041 StackHandleScope<1> hs(self);
1042 Handle<mirror::Class> java_lang_Throwable(
1043 hs.NewHandle(class_linker->FindSystemClass(self, "Ljava/lang/Throwable;")));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001044 do {
1045 unresolved_exception_types.clear();
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001046 {
1047 // Thread suspension is not allowed while ResolveCatchBlockExceptionsClassVisitor
1048 // is using a std::vector<ObjPtr<mirror::Class>>.
1049 ScopedAssertNoThreadSuspension ants(__FUNCTION__);
1050 ResolveCatchBlockExceptionsClassVisitor visitor;
1051 class_linker->VisitClasses(&visitor);
1052 visitor.FindExceptionTypesToResolve(&unresolved_exception_types);
1053 }
Andreas Gampea5b09a62016-11-17 15:21:22 -08001054 for (const auto& exception_type : unresolved_exception_types) {
1055 dex::TypeIndex exception_type_idx = exception_type.first;
Mathieu Chartier02e25112013-08-14 16:14:24 -07001056 const DexFile* dex_file = exception_type.second;
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001057 StackHandleScope<2> hs2(self);
Mathieu Chartierf284d442016-06-02 11:48:30 -07001058 Handle<mirror::DexCache> dex_cache(hs2.NewHandle(class_linker->RegisterDexFile(*dex_file,
1059 nullptr)));
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001060 Handle<mirror::Class> klass(hs2.NewHandle(
Andreas Gampefa4333d2017-02-14 11:10:34 -08001061 (dex_cache != nullptr)
Vladimir Markocd556b02017-02-03 11:47:34 +00001062 ? class_linker->ResolveType(*dex_file,
1063 exception_type_idx,
1064 dex_cache,
1065 ScopedNullHandle<mirror::ClassLoader>())
1066 : nullptr));
Andreas Gampefa4333d2017-02-14 11:10:34 -08001067 if (klass == nullptr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001068 const DexFile::TypeId& type_id = dex_file->GetTypeId(exception_type_idx);
1069 const char* descriptor = dex_file->GetTypeDescriptor(type_id);
1070 LOG(FATAL) << "Failed to resolve class " << descriptor;
1071 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001072 DCHECK(java_lang_Throwable->IsAssignableFrom(klass.Get()));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001073 }
1074 // Resolving exceptions may load classes that reference more exceptions, iterate until no
1075 // more are found
1076 } while (!unresolved_exception_types.empty());
1077
1078 // We walk the roots looking for classes so that we'll pick up the
1079 // above classes plus any classes them depend on such super
1080 // classes, interfaces, and the required ClassLinker roots.
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001081 RecordImageClassesVisitor visitor(image_classes_.get());
1082 class_linker->VisitClasses(&visitor);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001083
1084 CHECK_NE(image_classes_->size(), 0U);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001085}
1086
Vladimir Marko19a4d372016-12-08 14:41:46 +00001087static void MaybeAddToImageClasses(Thread* self,
1088 ObjPtr<mirror::Class> klass,
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001089 std::unordered_set<std::string>* image_classes)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001090 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko19a4d372016-12-08 14:41:46 +00001091 DCHECK_EQ(self, Thread::Current());
Mathieu Chartierf8322842014-05-16 10:59:25 -07001092 StackHandleScope<1> hs(self);
Ian Rogers1ff3c982014-08-12 02:30:58 -07001093 std::string temp;
Andreas Gampe542451c2016-07-26 09:02:02 -07001094 const PointerSize pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001095 while (!klass->IsObjectClass()) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07001096 const char* descriptor = klass->GetDescriptor(&temp);
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001097 std::pair<std::unordered_set<std::string>::iterator, bool> result =
1098 image_classes->insert(descriptor);
Ian Rogers1ff3c982014-08-12 02:30:58 -07001099 if (!result.second) { // Previously inserted.
1100 break;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001101 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07001102 VLOG(compiler) << "Adding " << descriptor << " to image classes";
Vladimir Marko19a4d372016-12-08 14:41:46 +00001103 for (size_t i = 0, num_interfaces = klass->NumDirectInterfaces(); i != num_interfaces; ++i) {
1104 ObjPtr<mirror::Class> interface = mirror::Class::GetDirectInterface(self, klass, i);
1105 DCHECK(interface != nullptr);
1106 MaybeAddToImageClasses(self, interface, image_classes);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001107 }
Vladimir Marko19a4d372016-12-08 14:41:46 +00001108 for (auto& m : klass->GetVirtualMethods(pointer_size)) {
1109 MaybeAddToImageClasses(self, m.GetDeclaringClass(), image_classes);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001110 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001111 if (klass->IsArrayClass()) {
Vladimir Marko19a4d372016-12-08 14:41:46 +00001112 MaybeAddToImageClasses(self, klass->GetComponentType(), image_classes);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001113 }
Mathieu Chartierf8322842014-05-16 10:59:25 -07001114 klass.Assign(klass->GetSuperClass());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001115 }
1116}
1117
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001118// Keeps all the data for the update together. Also doubles as the reference visitor.
1119// Note: we can use object pointers because we suspend all threads.
1120class ClinitImageUpdate {
1121 public:
Mathieu Chartier31e88222016-10-14 18:43:19 -07001122 static ClinitImageUpdate* Create(VariableSizedHandleScope& hs,
1123 std::unordered_set<std::string>* image_class_descriptors,
1124 Thread* self,
1125 ClassLinker* linker) {
1126 std::unique_ptr<ClinitImageUpdate> res(new ClinitImageUpdate(hs,
1127 image_class_descriptors,
1128 self,
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001129 linker));
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001130 return res.release();
1131 }
1132
1133 ~ClinitImageUpdate() {
1134 // Allow others to suspend again.
1135 self_->EndAssertNoThreadSuspension(old_cause_);
1136 }
1137
1138 // Visitor for VisitReferences.
Mathieu Chartier31e88222016-10-14 18:43:19 -07001139 void operator()(ObjPtr<mirror::Object> object,
1140 MemberOffset field_offset,
1141 bool /* is_static */) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001142 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001143 mirror::Object* ref = object->GetFieldObject<mirror::Object>(field_offset);
1144 if (ref != nullptr) {
1145 VisitClinitClassesObject(ref);
1146 }
1147 }
1148
Roland Levillain5e8d5f02016-10-18 18:03:43 +01001149 // java.lang.ref.Reference visitor for VisitReferences.
Mathieu Chartier31e88222016-10-14 18:43:19 -07001150 void operator()(ObjPtr<mirror::Class> klass ATTRIBUTE_UNUSED,
1151 ObjPtr<mirror::Reference> ref ATTRIBUTE_UNUSED) const {}
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001152
1153 // Ignore class native roots.
1154 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED)
1155 const {}
1156 void VisitRoot(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED) const {}
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001157
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001158 void Walk() REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001159 // Use the initial classes as roots for a search.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001160 for (Handle<mirror::Class> klass_root : image_classes_) {
1161 VisitClinitClassesObject(klass_root.Get());
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001162 }
Vladimir Marko19a4d372016-12-08 14:41:46 +00001163 Thread* self = Thread::Current();
1164 ScopedAssertNoThreadSuspension ants(__FUNCTION__);
Mathieu Chartier31e88222016-10-14 18:43:19 -07001165 for (Handle<mirror::Class> h_klass : to_insert_) {
Vladimir Marko19a4d372016-12-08 14:41:46 +00001166 MaybeAddToImageClasses(self, h_klass.Get(), image_class_descriptors_);
Mathieu Chartier31e88222016-10-14 18:43:19 -07001167 }
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001168 }
1169
1170 private:
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001171 class FindImageClassesVisitor : public ClassVisitor {
1172 public:
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001173 explicit FindImageClassesVisitor(VariableSizedHandleScope& hs,
1174 ClinitImageUpdate* data)
1175 : data_(data),
1176 hs_(hs) {}
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001177
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001178 bool operator()(ObjPtr<mirror::Class> klass) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001179 std::string temp;
1180 const char* name = klass->GetDescriptor(&temp);
1181 if (data_->image_class_descriptors_->find(name) != data_->image_class_descriptors_->end()) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001182 data_->image_classes_.push_back(hs_.NewHandle(klass));
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001183 } else {
1184 // Check whether it is initialized and has a clinit. They must be kept, too.
1185 if (klass->IsInitialized() && klass->FindClassInitializer(
1186 Runtime::Current()->GetClassLinker()->GetImagePointerSize()) != nullptr) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001187 data_->image_classes_.push_back(hs_.NewHandle(klass));
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001188 }
1189 }
1190 return true;
1191 }
1192
1193 private:
1194 ClinitImageUpdate* const data_;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001195 VariableSizedHandleScope& hs_;
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001196 };
1197
Mathieu Chartier31e88222016-10-14 18:43:19 -07001198 ClinitImageUpdate(VariableSizedHandleScope& hs,
1199 std::unordered_set<std::string>* image_class_descriptors,
1200 Thread* self,
1201 ClassLinker* linker) REQUIRES_SHARED(Locks::mutator_lock_)
1202 : hs_(hs),
1203 image_class_descriptors_(image_class_descriptors),
1204 self_(self) {
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001205 CHECK(linker != nullptr);
1206 CHECK(image_class_descriptors != nullptr);
1207
1208 // Make sure nobody interferes with us.
1209 old_cause_ = self->StartAssertNoThreadSuspension("Boot image closure");
1210
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001211 // Find all the already-marked classes.
1212 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001213 FindImageClassesVisitor visitor(hs_, this);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001214 linker->VisitClasses(&visitor);
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001215 }
1216
1217 void VisitClinitClassesObject(mirror::Object* object) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001218 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001219 DCHECK(object != nullptr);
1220 if (marked_objects_.find(object) != marked_objects_.end()) {
1221 // Already processed.
1222 return;
1223 }
1224
1225 // Mark it.
1226 marked_objects_.insert(object);
1227
1228 if (object->IsClass()) {
Mathieu Chartier31e88222016-10-14 18:43:19 -07001229 // Add to the TODO list since MaybeAddToImageClasses may cause thread suspension. Thread
1230 // suspensionb is not safe to do in VisitObjects or VisitReferences.
1231 to_insert_.push_back(hs_.NewHandle(object->AsClass()));
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001232 } else {
1233 // Else visit the object's class.
1234 VisitClinitClassesObject(object->GetClass());
1235 }
1236
Mathieu Chartiere401d142015-04-22 13:56:20 -07001237 // If it is not a DexCache, visit all references.
Mathieu Chartier31e88222016-10-14 18:43:19 -07001238 if (!object->IsDexCache()) {
Mathieu Chartier059ef3d2015-08-18 13:54:21 -07001239 object->VisitReferences(*this, *this);
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001240 }
1241 }
1242
Mathieu Chartier31e88222016-10-14 18:43:19 -07001243 VariableSizedHandleScope& hs_;
1244 mutable std::vector<Handle<mirror::Class>> to_insert_;
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001245 mutable std::unordered_set<mirror::Object*> marked_objects_;
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001246 std::unordered_set<std::string>* const image_class_descriptors_;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001247 std::vector<Handle<mirror::Class>> image_classes_;
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001248 Thread* const self_;
1249 const char* old_cause_;
1250
1251 DISALLOW_COPY_AND_ASSIGN(ClinitImageUpdate);
1252};
Brian Carlstrom7940e442013-07-12 13:46:57 -07001253
Ian Rogers3d504072014-03-01 09:16:49 -08001254void CompilerDriver::UpdateImageClasses(TimingLogger* timings) {
Vladimir Markoaad75c62016-10-03 08:46:48 +00001255 if (GetCompilerOptions().IsBootImage()) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07001256 TimingLogger::ScopedTiming t("UpdateImageClasses", timings);
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001257
Mathieu Chartier4f55e222015-09-04 13:26:21 -07001258 Runtime* runtime = Runtime::Current();
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001259
1260 // Suspend all threads.
Mathieu Chartier4f55e222015-09-04 13:26:21 -07001261 ScopedSuspendAll ssa(__FUNCTION__);
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001262
Mathieu Chartier31e88222016-10-14 18:43:19 -07001263 VariableSizedHandleScope hs(Thread::Current());
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001264 std::string error_msg;
Mathieu Chartier31e88222016-10-14 18:43:19 -07001265 std::unique_ptr<ClinitImageUpdate> update(ClinitImageUpdate::Create(hs,
1266 image_classes_.get(),
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001267 Thread::Current(),
Mathieu Chartier31e88222016-10-14 18:43:19 -07001268 runtime->GetClassLinker()));
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001269
1270 // Do the marking.
1271 update->Walk();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001272 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001273}
1274
Vladimir Marko07785bb2015-06-15 18:52:54 +01001275bool CompilerDriver::CanAssumeClassIsLoaded(mirror::Class* klass) {
1276 Runtime* runtime = Runtime::Current();
1277 if (!runtime->IsAotCompiler()) {
Calin Juravleffc87072016-04-20 14:22:09 +01001278 DCHECK(runtime->UseJitCompilation());
Vladimir Marko07785bb2015-06-15 18:52:54 +01001279 // Having the klass reference here implies that the klass is already loaded.
1280 return true;
1281 }
Vladimir Markoaad75c62016-10-03 08:46:48 +00001282 if (!GetCompilerOptions().IsBootImage()) {
Vladimir Marko07785bb2015-06-15 18:52:54 +01001283 // Assume loaded only if klass is in the boot image. App classes cannot be assumed
1284 // loaded because we don't even know what class loader will be used to load them.
1285 bool class_in_image = runtime->GetHeap()->FindSpaceFromObject(klass, false)->IsImageSpace();
1286 return class_in_image;
1287 }
1288 std::string temp;
1289 const char* descriptor = klass->GetDescriptor(&temp);
1290 return IsImageClass(descriptor);
1291}
1292
Vladimir Marko492a7fa2016-06-01 18:38:43 +01001293void CompilerDriver::MarkForDexToDexCompilation(Thread* self, const MethodReference& method_ref) {
1294 MutexLock lock(self, dex_to_dex_references_lock_);
1295 // Since we're compiling one dex file at a time, we need to look for the
1296 // current dex file entry only at the end of dex_to_dex_references_.
1297 if (dex_to_dex_references_.empty() ||
1298 &dex_to_dex_references_.back().GetDexFile() != method_ref.dex_file) {
1299 dex_to_dex_references_.emplace_back(*method_ref.dex_file);
1300 }
Mathieu Chartierfc8b4222017-09-17 13:44:24 -07001301 dex_to_dex_references_.back().GetMethodIndexes().SetBit(method_ref.index);
Vladimir Marko492a7fa2016-06-01 18:38:43 +01001302}
1303
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001304bool CompilerDriver::CanAccessTypeWithoutChecks(ObjPtr<mirror::Class> referrer_class,
1305 ObjPtr<mirror::Class> resolved_class) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001306 if (resolved_class == nullptr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001307 stats_->TypeNeedsAccessCheck();
1308 return false; // Unknown class needs access checks.
1309 }
David Brazdil38f64d32016-01-18 17:13:41 +00001310 bool is_accessible = resolved_class->IsPublic(); // Public classes are always accessible.
1311 if (!is_accessible) {
David Brazdil38f64d32016-01-18 17:13:41 +00001312 if (referrer_class == nullptr) {
1313 stats_->TypeNeedsAccessCheck();
1314 return false; // Incomplete referrer knowledge needs access check.
1315 }
1316 // Perform access check, will return true if access is ok or false if we're going to have to
1317 // check this at runtime (for example for class loaders).
1318 is_accessible = referrer_class->CanAccess(resolved_class);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001319 }
David Brazdil38f64d32016-01-18 17:13:41 +00001320 if (is_accessible) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001321 stats_->TypeDoesntNeedAccessCheck();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001322 } else {
1323 stats_->TypeNeedsAccessCheck();
1324 }
David Brazdil38f64d32016-01-18 17:13:41 +00001325 return is_accessible;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001326}
1327
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001328bool CompilerDriver::CanAccessInstantiableTypeWithoutChecks(ObjPtr<mirror::Class> referrer_class,
1329 ObjPtr<mirror::Class> resolved_class,
Mingyao Yangfb8464a2015-11-02 10:56:59 -08001330 bool* finalizable) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001331 if (resolved_class == nullptr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001332 stats_->TypeNeedsAccessCheck();
Mingyao Yangfb8464a2015-11-02 10:56:59 -08001333 // Be conservative.
1334 *finalizable = true;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001335 return false; // Unknown class needs access checks.
1336 }
Mingyao Yangfb8464a2015-11-02 10:56:59 -08001337 *finalizable = resolved_class->IsFinalizable();
David Brazdil38f64d32016-01-18 17:13:41 +00001338 bool is_accessible = resolved_class->IsPublic(); // Public classes are always accessible.
1339 if (!is_accessible) {
David Brazdil38f64d32016-01-18 17:13:41 +00001340 if (referrer_class == nullptr) {
1341 stats_->TypeNeedsAccessCheck();
1342 return false; // Incomplete referrer knowledge needs access check.
1343 }
1344 // Perform access and instantiable checks, will return true if access is ok or false if we're
1345 // going to have to check this at runtime (for example for class loaders).
1346 is_accessible = referrer_class->CanAccess(resolved_class);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001347 }
David Brazdil38f64d32016-01-18 17:13:41 +00001348 bool result = is_accessible && resolved_class->IsInstantiable();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001349 if (result) {
1350 stats_->TypeDoesntNeedAccessCheck();
1351 } else {
1352 stats_->TypeNeedsAccessCheck();
1353 }
1354 return result;
1355}
1356
Vladimir Markobe0e5462014-02-26 11:24:15 +00001357void CompilerDriver::ProcessedInstanceField(bool resolved) {
1358 if (!resolved) {
1359 stats_->UnresolvedInstanceField();
1360 } else {
1361 stats_->ResolvedInstanceField();
1362 }
1363}
1364
1365void CompilerDriver::ProcessedStaticField(bool resolved, bool local) {
1366 if (!resolved) {
1367 stats_->UnresolvedStaticField();
1368 } else if (local) {
1369 stats_->ResolvedLocalStaticField();
1370 } else {
1371 stats_->ResolvedStaticField();
1372 }
1373}
1374
Mathieu Chartierc7853442015-03-27 14:35:38 -07001375ArtField* CompilerDriver::ComputeInstanceFieldInfo(uint32_t field_idx,
1376 const DexCompilationUnit* mUnit, bool is_put,
1377 const ScopedObjectAccess& soa) {
Vladimir Markobe0e5462014-02-26 11:24:15 +00001378 // Try to resolve the field and compiling method's class.
Mathieu Chartierc7853442015-03-27 14:35:38 -07001379 ArtField* resolved_field;
Vladimir Markobe0e5462014-02-26 11:24:15 +00001380 mirror::Class* referrer_class;
Mathieu Chartier736b5602015-09-02 14:54:11 -07001381 Handle<mirror::DexCache> dex_cache(mUnit->GetDexCache());
Vladimir Markobe0e5462014-02-26 11:24:15 +00001382 {
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001383 Handle<mirror::ClassLoader> class_loader_handle = mUnit->GetClassLoader();
Mathieu Chartier736b5602015-09-02 14:54:11 -07001384 resolved_field = ResolveField(soa, dex_cache, class_loader_handle, mUnit, field_idx, false);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001385 referrer_class = resolved_field != nullptr
Mathieu Chartier736b5602015-09-02 14:54:11 -07001386 ? ResolveCompilingMethodsClass(soa, dex_cache, class_loader_handle, mUnit) : nullptr;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001387 }
Nicolas Geoffraye5038322014-07-04 09:41:32 +01001388 bool can_link = false;
Vladimir Markobe0e5462014-02-26 11:24:15 +00001389 if (resolved_field != nullptr && referrer_class != nullptr) {
Vladimir Markobe0e5462014-02-26 11:24:15 +00001390 std::pair<bool, bool> fast_path = IsFastInstanceField(
Mathieu Chartier736b5602015-09-02 14:54:11 -07001391 dex_cache.Get(), referrer_class, resolved_field, field_idx);
Nicolas Geoffraye5038322014-07-04 09:41:32 +01001392 can_link = is_put ? fast_path.second : fast_path.first;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001393 }
Nicolas Geoffraye5038322014-07-04 09:41:32 +01001394 ProcessedInstanceField(can_link);
1395 return can_link ? resolved_field : nullptr;
1396}
1397
1398bool CompilerDriver::ComputeInstanceFieldInfo(uint32_t field_idx, const DexCompilationUnit* mUnit,
1399 bool is_put, MemberOffset* field_offset,
1400 bool* is_volatile) {
1401 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartierc7853442015-03-27 14:35:38 -07001402 ArtField* resolved_field = ComputeInstanceFieldInfo(field_idx, mUnit, is_put, soa);
Nicolas Geoffraye5038322014-07-04 09:41:32 +01001403
Mathieu Chartierc7853442015-03-27 14:35:38 -07001404 if (resolved_field == nullptr) {
Vladimir Markobe0e5462014-02-26 11:24:15 +00001405 // Conservative defaults.
1406 *is_volatile = true;
1407 *field_offset = MemberOffset(static_cast<size_t>(-1));
Nicolas Geoffraye5038322014-07-04 09:41:32 +01001408 return false;
1409 } else {
1410 *is_volatile = resolved_field->IsVolatile();
1411 *field_offset = resolved_field->GetOffset();
1412 return true;
Vladimir Markobe0e5462014-02-26 11:24:15 +00001413 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001414}
1415
Vladimir Marko2730db02014-01-27 11:15:17 +00001416const VerifiedMethod* CompilerDriver::GetVerifiedMethod(const DexFile* dex_file,
1417 uint32_t method_idx) const {
1418 MethodReference ref(dex_file, method_idx);
1419 return verification_results_->GetVerifiedMethod(ref);
1420}
1421
1422bool CompilerDriver::IsSafeCast(const DexCompilationUnit* mUnit, uint32_t dex_pc) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001423 if (!compiler_options_->IsVerificationEnabled()) {
1424 // If we didn't verify, every cast has to be treated as non-safe.
1425 return false;
1426 }
Vladimir Marko2730db02014-01-27 11:15:17 +00001427 DCHECK(mUnit->GetVerifiedMethod() != nullptr);
1428 bool result = mUnit->GetVerifiedMethod()->IsSafeCast(dex_pc);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001429 if (result) {
1430 stats_->SafeCast();
1431 } else {
1432 stats_->NotASafeCast();
1433 }
1434 return result;
1435}
1436
Mathieu Chartier90443472015-07-16 20:32:27 -07001437class CompilationVisitor {
1438 public:
1439 virtual ~CompilationVisitor() {}
1440 virtual void Visit(size_t index) = 0;
1441};
1442
Brian Carlstrom7940e442013-07-12 13:46:57 -07001443class ParallelCompilationManager {
1444 public:
Brian Carlstrom7940e442013-07-12 13:46:57 -07001445 ParallelCompilationManager(ClassLinker* class_linker,
1446 jobject class_loader,
1447 CompilerDriver* compiler,
1448 const DexFile* dex_file,
Andreas Gampede7b4362014-07-28 18:38:57 -07001449 const std::vector<const DexFile*>& dex_files,
Ian Rogers3d504072014-03-01 09:16:49 -08001450 ThreadPool* thread_pool)
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001451 : index_(0),
1452 class_linker_(class_linker),
Brian Carlstrom7940e442013-07-12 13:46:57 -07001453 class_loader_(class_loader),
1454 compiler_(compiler),
1455 dex_file_(dex_file),
Andreas Gampede7b4362014-07-28 18:38:57 -07001456 dex_files_(dex_files),
Ian Rogers3d504072014-03-01 09:16:49 -08001457 thread_pool_(thread_pool) {}
Brian Carlstrom7940e442013-07-12 13:46:57 -07001458
1459 ClassLinker* GetClassLinker() const {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001460 CHECK(class_linker_ != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001461 return class_linker_;
1462 }
1463
1464 jobject GetClassLoader() const {
1465 return class_loader_;
1466 }
1467
1468 CompilerDriver* GetCompiler() const {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001469 CHECK(compiler_ != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001470 return compiler_;
1471 }
1472
1473 const DexFile* GetDexFile() const {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001474 CHECK(dex_file_ != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001475 return dex_file_;
1476 }
1477
Andreas Gampede7b4362014-07-28 18:38:57 -07001478 const std::vector<const DexFile*>& GetDexFiles() const {
1479 return dex_files_;
1480 }
1481
Mathieu Chartier90443472015-07-16 20:32:27 -07001482 void ForAll(size_t begin, size_t end, CompilationVisitor* visitor, size_t work_units)
1483 REQUIRES(!*Locks::mutator_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001484 Thread* self = Thread::Current();
1485 self->AssertNoPendingException();
1486 CHECK_GT(work_units, 0U);
1487
Ian Rogers3e5cf302014-05-20 16:40:37 -07001488 index_.StoreRelaxed(begin);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001489 for (size_t i = 0; i < work_units; ++i) {
Mathieu Chartier90443472015-07-16 20:32:27 -07001490 thread_pool_->AddTask(self, new ForAllClosure(this, end, visitor));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001491 }
1492 thread_pool_->StartWorkers(self);
1493
1494 // Ensure we're suspended while we're blocked waiting for the other threads to finish (worker
1495 // thread destructor's called below perform join).
1496 CHECK_NE(self->GetState(), kRunnable);
1497
1498 // Wait for all the worker threads to finish.
1499 thread_pool_->Wait(self, true, false);
Andreas Gampeace0dc12016-01-20 13:33:13 -08001500
1501 // And stop the workers accepting jobs.
1502 thread_pool_->StopWorkers(self);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001503 }
1504
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001505 size_t NextIndex() {
Ian Rogers3e5cf302014-05-20 16:40:37 -07001506 return index_.FetchAndAddSequentiallyConsistent(1);
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001507 }
1508
Brian Carlstrom7940e442013-07-12 13:46:57 -07001509 private:
Brian Carlstrom7940e442013-07-12 13:46:57 -07001510 class ForAllClosure : public Task {
1511 public:
Mathieu Chartier90443472015-07-16 20:32:27 -07001512 ForAllClosure(ParallelCompilationManager* manager, size_t end, CompilationVisitor* visitor)
Brian Carlstrom7940e442013-07-12 13:46:57 -07001513 : manager_(manager),
Brian Carlstrom7940e442013-07-12 13:46:57 -07001514 end_(end),
Mathieu Chartier90443472015-07-16 20:32:27 -07001515 visitor_(visitor) {}
Brian Carlstrom7940e442013-07-12 13:46:57 -07001516
1517 virtual void Run(Thread* self) {
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001518 while (true) {
1519 const size_t index = manager_->NextIndex();
1520 if (UNLIKELY(index >= end_)) {
1521 break;
1522 }
Mathieu Chartier90443472015-07-16 20:32:27 -07001523 visitor_->Visit(index);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001524 self->AssertNoPendingException();
1525 }
1526 }
1527
1528 virtual void Finalize() {
1529 delete this;
1530 }
Brian Carlstrom0cd7ec22013-07-17 23:40:20 -07001531
Brian Carlstrom7940e442013-07-12 13:46:57 -07001532 private:
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001533 ParallelCompilationManager* const manager_;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001534 const size_t end_;
Mathieu Chartier90443472015-07-16 20:32:27 -07001535 CompilationVisitor* const visitor_;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001536 };
1537
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001538 AtomicInteger index_;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001539 ClassLinker* const class_linker_;
1540 const jobject class_loader_;
1541 CompilerDriver* const compiler_;
1542 const DexFile* const dex_file_;
Andreas Gampede7b4362014-07-28 18:38:57 -07001543 const std::vector<const DexFile*>& dex_files_;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001544 ThreadPool* const thread_pool_;
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001545
1546 DISALLOW_COPY_AND_ASSIGN(ParallelCompilationManager);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001547};
1548
Jeff Hao0e49b422013-11-08 12:16:56 -08001549// A fast version of SkipClass above if the class pointer is available
1550// that avoids the expensive FindInClassPath search.
1551static bool SkipClass(jobject class_loader, const DexFile& dex_file, mirror::Class* klass)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001552 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001553 DCHECK(klass != nullptr);
Jeff Hao0e49b422013-11-08 12:16:56 -08001554 const DexFile& original_dex_file = *klass->GetDexCache()->GetDexFile();
1555 if (&dex_file != &original_dex_file) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001556 if (class_loader == nullptr) {
David Sehr709b0702016-10-13 09:12:37 -07001557 LOG(WARNING) << "Skipping class " << klass->PrettyDescriptor() << " from "
Jeff Hao0e49b422013-11-08 12:16:56 -08001558 << dex_file.GetLocation() << " previously found in "
1559 << original_dex_file.GetLocation();
1560 }
1561 return true;
1562 }
1563 return false;
1564}
1565
Mathieu Chartier70b63482014-06-27 17:19:04 -07001566static void CheckAndClearResolveException(Thread* self)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001567 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier70b63482014-06-27 17:19:04 -07001568 CHECK(self->IsExceptionPending());
Nicolas Geoffray14691c52015-03-05 10:40:17 +00001569 mirror::Throwable* exception = self->GetException();
Ian Rogers1ff3c982014-08-12 02:30:58 -07001570 std::string temp;
1571 const char* descriptor = exception->GetClass()->GetDescriptor(&temp);
1572 const char* expected_exceptions[] = {
1573 "Ljava/lang/IllegalAccessError;",
1574 "Ljava/lang/IncompatibleClassChangeError;",
1575 "Ljava/lang/InstantiationError;",
Brian Carlstrom898fcb52014-08-25 23:07:30 -07001576 "Ljava/lang/LinkageError;",
Ian Rogers1ff3c982014-08-12 02:30:58 -07001577 "Ljava/lang/NoClassDefFoundError;",
1578 "Ljava/lang/NoSuchFieldError;",
1579 "Ljava/lang/NoSuchMethodError;"
1580 };
1581 bool found = false;
1582 for (size_t i = 0; (found == false) && (i < arraysize(expected_exceptions)); ++i) {
1583 if (strcmp(descriptor, expected_exceptions[i]) == 0) {
1584 found = true;
1585 }
1586 }
1587 if (!found) {
Brian Carlstrom898fcb52014-08-25 23:07:30 -07001588 LOG(FATAL) << "Unexpected exception " << exception->Dump();
Mathieu Chartier70b63482014-06-27 17:19:04 -07001589 }
1590 self->ClearException();
1591}
1592
Mathieu Chartierb5d38612016-04-07 10:52:52 -07001593bool CompilerDriver::RequiresConstructorBarrier(const DexFile& dex_file,
1594 uint16_t class_def_idx) const {
1595 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_idx);
1596 const uint8_t* class_data = dex_file.GetClassData(class_def);
1597 if (class_data == nullptr) {
1598 // Empty class such as a marker interface.
1599 return false;
1600 }
1601 ClassDataItemIterator it(dex_file, class_data);
Mathieu Chartiere17cf242017-06-19 11:05:51 -07001602 it.SkipStaticFields();
Mathieu Chartierb5d38612016-04-07 10:52:52 -07001603 // We require a constructor barrier if there are final instance fields.
1604 while (it.HasNextInstanceField()) {
1605 if (it.MemberIsFinal()) {
1606 return true;
1607 }
1608 it.Next();
1609 }
1610 return false;
1611}
1612
Mathieu Chartier90443472015-07-16 20:32:27 -07001613class ResolveClassFieldsAndMethodsVisitor : public CompilationVisitor {
1614 public:
1615 explicit ResolveClassFieldsAndMethodsVisitor(const ParallelCompilationManager* manager)
1616 : manager_(manager) {}
Brian Carlstrom7940e442013-07-12 13:46:57 -07001617
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001618 void Visit(size_t class_def_index) OVERRIDE REQUIRES(!Locks::mutator_lock_) {
Mathieu Chartier90443472015-07-16 20:32:27 -07001619 ATRACE_CALL();
1620 Thread* const self = Thread::Current();
1621 jobject jclass_loader = manager_->GetClassLoader();
1622 const DexFile& dex_file = *manager_->GetDexFile();
1623 ClassLinker* class_linker = manager_->GetClassLinker();
Ian Rogerse6bb3b22013-08-19 21:51:45 -07001624
Mathieu Chartier90443472015-07-16 20:32:27 -07001625 // If an instance field is final then we need to have a barrier on the return, static final
1626 // fields are assigned within the lock held for class initialization. Conservatively assume
1627 // constructor barriers are always required.
1628 bool requires_constructor_barrier = true;
1629
1630 // Method and Field are the worst. We can't resolve without either
1631 // context from the code use (to disambiguate virtual vs direct
1632 // method and instance vs static field) or from class
1633 // definitions. While the compiler will resolve what it can as it
1634 // needs it, here we try to resolve fields and methods used in class
1635 // definitions, since many of them many never be referenced by
1636 // generated code.
1637 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
1638 ScopedObjectAccess soa(self);
1639 StackHandleScope<2> hs(soa.Self());
1640 Handle<mirror::ClassLoader> class_loader(
Mathieu Chartier0795f232016-09-27 18:43:30 -07001641 hs.NewHandle(soa.Decode<mirror::ClassLoader>(jclass_loader)));
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001642 Handle<mirror::DexCache> dex_cache(hs.NewHandle(class_linker->FindDexCache(
Vladimir Markocd556b02017-02-03 11:47:34 +00001643 soa.Self(), dex_file)));
Mathieu Chartier90443472015-07-16 20:32:27 -07001644 // Resolve the class.
1645 mirror::Class* klass = class_linker->ResolveType(dex_file, class_def.class_idx_, dex_cache,
1646 class_loader);
1647 bool resolve_fields_and_methods;
1648 if (klass == nullptr) {
1649 // Class couldn't be resolved, for example, super-class is in a different dex file. Don't
1650 // attempt to resolve methods and fields when there is no declaring class.
1651 CheckAndClearResolveException(soa.Self());
1652 resolve_fields_and_methods = false;
1653 } else {
1654 // We successfully resolved a class, should we skip it?
1655 if (SkipClass(jclass_loader, dex_file, klass)) {
1656 return;
Ian Rogerse6bb3b22013-08-19 21:51:45 -07001657 }
Mathieu Chartier90443472015-07-16 20:32:27 -07001658 // We want to resolve the methods and fields eagerly.
1659 resolve_fields_and_methods = true;
Ian Rogers68b56852014-08-29 20:19:11 -07001660 }
Mathieu Chartier90443472015-07-16 20:32:27 -07001661 // Note the class_data pointer advances through the headers,
1662 // static fields, instance fields, direct methods, and virtual
1663 // methods.
1664 const uint8_t* class_data = dex_file.GetClassData(class_def);
1665 if (class_data == nullptr) {
1666 // Empty class such as a marker interface.
1667 requires_constructor_barrier = false;
1668 } else {
1669 ClassDataItemIterator it(dex_file, class_data);
1670 while (it.HasNextStaticField()) {
1671 if (resolve_fields_and_methods) {
1672 ArtField* field = class_linker->ResolveField(dex_file, it.GetMemberIndex(),
1673 dex_cache, class_loader, true);
1674 if (field == nullptr) {
1675 CheckAndClearResolveException(soa.Self());
1676 }
Ian Rogers68b56852014-08-29 20:19:11 -07001677 }
1678 it.Next();
1679 }
Mathieu Chartier90443472015-07-16 20:32:27 -07001680 // We require a constructor barrier if there are final instance fields.
1681 requires_constructor_barrier = false;
1682 while (it.HasNextInstanceField()) {
1683 if (it.MemberIsFinal()) {
1684 requires_constructor_barrier = true;
1685 }
1686 if (resolve_fields_and_methods) {
1687 ArtField* field = class_linker->ResolveField(dex_file, it.GetMemberIndex(),
1688 dex_cache, class_loader, false);
1689 if (field == nullptr) {
1690 CheckAndClearResolveException(soa.Self());
1691 }
Ian Rogers68b56852014-08-29 20:19:11 -07001692 }
1693 it.Next();
1694 }
Mathieu Chartier90443472015-07-16 20:32:27 -07001695 if (resolve_fields_and_methods) {
Mathieu Chartierb7c273c2017-11-10 18:07:56 -08001696 while (it.HasNextMethod()) {
Vladimir Markoba118822017-06-12 15:41:56 +01001697 ArtMethod* method = class_linker->ResolveMethod<ClassLinker::ResolveMode::kNoChecks>(
Mathieu Chartier90443472015-07-16 20:32:27 -07001698 dex_file, it.GetMemberIndex(), dex_cache, class_loader, nullptr,
1699 it.GetMethodInvokeType(class_def));
1700 if (method == nullptr) {
1701 CheckAndClearResolveException(soa.Self());
1702 }
1703 it.Next();
1704 }
1705 DCHECK(!it.HasNext());
1706 }
1707 }
Mathieu Chartierc4ae9162016-04-07 13:19:19 -07001708 manager_->GetCompiler()->SetRequiresConstructorBarrier(self,
1709 &dex_file,
1710 class_def_index,
1711 requires_constructor_barrier);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001712 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001713
Mathieu Chartier90443472015-07-16 20:32:27 -07001714 private:
1715 const ParallelCompilationManager* const manager_;
1716};
1717
1718class ResolveTypeVisitor : public CompilationVisitor {
1719 public:
1720 explicit ResolveTypeVisitor(const ParallelCompilationManager* manager) : manager_(manager) {
1721 }
Andreas Gampea5b09a62016-11-17 15:21:22 -08001722 void Visit(size_t type_idx) OVERRIDE REQUIRES(!Locks::mutator_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001723 // Class derived values are more complicated, they require the linker and loader.
Mathieu Chartier90443472015-07-16 20:32:27 -07001724 ScopedObjectAccess soa(Thread::Current());
1725 ClassLinker* class_linker = manager_->GetClassLinker();
1726 const DexFile& dex_file = *manager_->GetDexFile();
1727 StackHandleScope<2> hs(soa.Self());
Mathieu Chartier90443472015-07-16 20:32:27 -07001728 Handle<mirror::ClassLoader> class_loader(
Mathieu Chartier0795f232016-09-27 18:43:30 -07001729 hs.NewHandle(soa.Decode<mirror::ClassLoader>(manager_->GetClassLoader())));
Mathieu Chartierd57d4542015-10-14 10:55:30 -07001730 Handle<mirror::DexCache> dex_cache(hs.NewHandle(class_linker->RegisterDexFile(
1731 dex_file,
Mathieu Chartierf284d442016-06-02 11:48:30 -07001732 class_loader.Get())));
Andreas Gampefa4333d2017-02-14 11:10:34 -08001733 ObjPtr<mirror::Class> klass = (dex_cache != nullptr)
Vladimir Markocd556b02017-02-03 11:47:34 +00001734 ? class_linker->ResolveType(dex_file, dex::TypeIndex(type_idx), dex_cache, class_loader)
1735 : nullptr;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001736
Mathieu Chartier90443472015-07-16 20:32:27 -07001737 if (klass == nullptr) {
1738 soa.Self()->AssertPendingException();
1739 mirror::Throwable* exception = soa.Self()->GetException();
1740 VLOG(compiler) << "Exception during type resolution: " << exception->Dump();
1741 if (exception->GetClass()->DescriptorEquals("Ljava/lang/OutOfMemoryError;")) {
1742 // There's little point continuing compilation if the heap is exhausted.
1743 LOG(FATAL) << "Out of memory during type resolution for compilation";
1744 }
1745 soa.Self()->ClearException();
Ian Rogersa436fde2013-08-27 23:34:06 -07001746 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001747 }
Mathieu Chartier90443472015-07-16 20:32:27 -07001748
1749 private:
1750 const ParallelCompilationManager* const manager_;
1751};
Brian Carlstrom7940e442013-07-12 13:46:57 -07001752
Andreas Gampeace0dc12016-01-20 13:33:13 -08001753void CompilerDriver::ResolveDexFile(jobject class_loader,
1754 const DexFile& dex_file,
Andreas Gampede7b4362014-07-28 18:38:57 -07001755 const std::vector<const DexFile*>& dex_files,
Andreas Gampeace0dc12016-01-20 13:33:13 -08001756 ThreadPool* thread_pool,
1757 size_t thread_count,
1758 TimingLogger* timings) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001759 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1760
1761 // TODO: we could resolve strings here, although the string table is largely filled with class
1762 // and method names.
1763
Andreas Gampede7b4362014-07-28 18:38:57 -07001764 ParallelCompilationManager context(class_linker, class_loader, this, &dex_file, dex_files,
1765 thread_pool);
Vladimir Markoaad75c62016-10-03 08:46:48 +00001766 if (GetCompilerOptions().IsBootImage()) {
Ian Rogerse6bb3b22013-08-19 21:51:45 -07001767 // For images we resolve all types, such as array, whereas for applications just those with
1768 // classdefs are resolved by ResolveClassFieldsAndMethods.
Mathieu Chartierf5997b42014-06-20 10:37:54 -07001769 TimingLogger::ScopedTiming t("Resolve Types", timings);
Mathieu Chartier90443472015-07-16 20:32:27 -07001770 ResolveTypeVisitor visitor(&context);
Andreas Gampeace0dc12016-01-20 13:33:13 -08001771 context.ForAll(0, dex_file.NumTypeIds(), &visitor, thread_count);
Ian Rogerse6bb3b22013-08-19 21:51:45 -07001772 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001773
Mathieu Chartierf5997b42014-06-20 10:37:54 -07001774 TimingLogger::ScopedTiming t("Resolve MethodsAndFields", timings);
Mathieu Chartier90443472015-07-16 20:32:27 -07001775 ResolveClassFieldsAndMethodsVisitor visitor(&context);
Andreas Gampeace0dc12016-01-20 13:33:13 -08001776 context.ForAll(0, dex_file.NumClassDefs(), &visitor, thread_count);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001777}
1778
Andreas Gampeace0dc12016-01-20 13:33:13 -08001779void CompilerDriver::SetVerified(jobject class_loader,
1780 const std::vector<const DexFile*>& dex_files,
1781 TimingLogger* timings) {
1782 // This can be run in parallel.
Mathieu Chartier90443472015-07-16 20:32:27 -07001783 for (const DexFile* dex_file : dex_files) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001784 CHECK(dex_file != nullptr);
Andreas Gampeace0dc12016-01-20 13:33:13 -08001785 SetVerifiedDexFile(class_loader,
1786 *dex_file,
1787 dex_files,
1788 parallel_thread_pool_.get(),
1789 parallel_thread_count_,
1790 timings);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001791 }
1792}
1793
Nicolas Geoffray51c17fa2016-11-25 15:56:12 +00001794static void PopulateVerifiedMethods(const DexFile& dex_file,
1795 uint32_t class_def_index,
1796 VerificationResults* verification_results) {
1797 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
1798 const uint8_t* class_data = dex_file.GetClassData(class_def);
1799 if (class_data == nullptr) {
1800 return;
1801 }
1802 ClassDataItemIterator it(dex_file, class_data);
Mathieu Chartiere17cf242017-06-19 11:05:51 -07001803 it.SkipAllFields();
Nicolas Geoffray51c17fa2016-11-25 15:56:12 +00001804
Mathieu Chartierb7c273c2017-11-10 18:07:56 -08001805 while (it.HasNextMethod()) {
Nicolas Geoffray51c17fa2016-11-25 15:56:12 +00001806 verification_results->CreateVerifiedMethodFor(MethodReference(&dex_file, it.GetMemberIndex()));
1807 it.Next();
1808 }
1809 DCHECK(!it.HasNext());
1810}
1811
Nicolas Geoffray0a27fd02017-01-25 16:18:54 +00001812static void LoadAndUpdateStatus(const DexFile& dex_file,
1813 const DexFile::ClassDef& class_def,
1814 mirror::Class::Status status,
1815 Handle<mirror::ClassLoader> class_loader,
1816 Thread* self)
1817 REQUIRES_SHARED(Locks::mutator_lock_) {
1818 StackHandleScope<1> hs(self);
1819 const char* descriptor = dex_file.GetClassDescriptor(class_def);
1820 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1821 Handle<mirror::Class> cls(hs.NewHandle<mirror::Class>(
1822 class_linker->FindClass(self, descriptor, class_loader)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08001823 if (cls != nullptr) {
Nicolas Geoffray0a27fd02017-01-25 16:18:54 +00001824 // Check that the class is resolved with the current dex file. We might get
1825 // a boot image class, or a class in a different dex file for multidex, and
1826 // we should not update the status in that case.
1827 if (&cls->GetDexFile() == &dex_file) {
1828 ObjectLock<mirror::Class> lock(self, cls);
1829 mirror::Class::SetStatus(cls, status, self);
1830 }
1831 } else {
1832 DCHECK(self->IsExceptionPending());
1833 self->ClearException();
1834 }
1835}
1836
Nicolas Geoffray74981052017-01-16 17:54:09 +00001837bool CompilerDriver::FastVerify(jobject jclass_loader,
1838 const std::vector<const DexFile*>& dex_files,
1839 TimingLogger* timings) {
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +00001840 verifier::VerifierDeps* verifier_deps =
1841 Runtime::Current()->GetCompilerCallbacks()->GetVerifierDeps();
Mathieu Chartier72041a02017-07-14 18:23:25 -07001842 // If there exist VerifierDeps that aren't the ones we just created to output, use them to verify.
1843 if (verifier_deps == nullptr || verifier_deps->OutputOnly()) {
Nicolas Geoffray74981052017-01-16 17:54:09 +00001844 return false;
1845 }
1846 TimingLogger::ScopedTiming t("Fast Verify", timings);
1847 ScopedObjectAccess soa(Thread::Current());
1848 StackHandleScope<2> hs(soa.Self());
1849 Handle<mirror::ClassLoader> class_loader(
1850 hs.NewHandle(soa.Decode<mirror::ClassLoader>(jclass_loader)));
Nicolas Geoffray74981052017-01-16 17:54:09 +00001851 if (!verifier_deps->ValidateDependencies(class_loader, soa.Self())) {
1852 return false;
1853 }
1854
Nicolas Geoffray49cda062017-04-21 13:08:25 +01001855 bool compiler_only_verifies = !GetCompilerOptions().IsAnyCompilationEnabled();
Nicolas Geoffray0a27fd02017-01-25 16:18:54 +00001856
Nicolas Geoffray74981052017-01-16 17:54:09 +00001857 // We successfully validated the dependencies, now update class status
1858 // of verified classes. Note that the dependencies also record which classes
1859 // could not be fully verified; we could try again, but that would hurt verification
1860 // time. So instead we assume these classes still need to be verified at
1861 // runtime.
1862 for (const DexFile* dex_file : dex_files) {
Mathieu Chartierbf755fe2017-08-01 13:42:56 -07001863 // Fetch the list of unverified classes.
1864 const std::set<dex::TypeIndex>& unverified_classes =
Nicolas Geoffray74981052017-01-16 17:54:09 +00001865 verifier_deps->GetUnverifiedClasses(*dex_file);
Nicolas Geoffray74981052017-01-16 17:54:09 +00001866 for (uint32_t i = 0; i < dex_file->NumClassDefs(); ++i) {
1867 const DexFile::ClassDef& class_def = dex_file->GetClassDef(i);
Mathieu Chartierbf755fe2017-08-01 13:42:56 -07001868 if (unverified_classes.find(class_def.class_idx_) == unverified_classes.end()) {
Nicolas Geoffray0a27fd02017-01-25 16:18:54 +00001869 if (compiler_only_verifies) {
Nicolas Geoffray74981052017-01-16 17:54:09 +00001870 // Just update the compiled_classes_ map. The compiler doesn't need to resolve
1871 // the type.
Mathieu Chartierfc8b4222017-09-17 13:44:24 -07001872 ClassReference ref(dex_file, i);
Mathieu Chartier1a088d42017-07-18 11:43:57 -07001873 mirror::Class::Status existing = mirror::Class::kStatusNotReady;
1874 DCHECK(compiled_classes_.Get(ref, &existing)) << ref.dex_file->GetLocation();
1875 ClassStateTable::InsertResult result =
1876 compiled_classes_.Insert(ref, existing, mirror::Class::kStatusVerified);
1877 CHECK_EQ(result, ClassStateTable::kInsertResultSuccess);
Nicolas Geoffray74981052017-01-16 17:54:09 +00001878 } else {
Nicolas Geoffray0a27fd02017-01-25 16:18:54 +00001879 // Update the class status, so later compilation stages know they don't need to verify
Nicolas Geoffray74981052017-01-16 17:54:09 +00001880 // the class.
Nicolas Geoffray0a27fd02017-01-25 16:18:54 +00001881 LoadAndUpdateStatus(
1882 *dex_file, class_def, mirror::Class::kStatusVerified, class_loader, soa.Self());
Nicolas Geoffray74981052017-01-16 17:54:09 +00001883 // Create `VerifiedMethod`s for each methods, the compiler expects one for
1884 // quickening or compiling.
1885 // Note that this means:
1886 // - We're only going to compile methods that did verify.
1887 // - Quickening will not do checkcast ellision.
1888 // TODO(ngeoffray): Reconsider this once we refactor compiler filters.
1889 PopulateVerifiedMethods(*dex_file, i, verification_results_);
Nicolas Geoffray6bb7f1b2016-11-03 10:52:49 +00001890 }
Nicolas Geoffray0a27fd02017-01-25 16:18:54 +00001891 } else if (!compiler_only_verifies) {
1892 // Make sure later compilation stages know they should not try to verify
1893 // this class again.
1894 LoadAndUpdateStatus(*dex_file,
1895 class_def,
1896 mirror::Class::kStatusRetryVerificationAtRuntime,
1897 class_loader,
1898 soa.Self());
Nicolas Geoffray6bb7f1b2016-11-03 10:52:49 +00001899 }
Nicolas Geoffray6bb7f1b2016-11-03 10:52:49 +00001900 }
1901 }
Nicolas Geoffray74981052017-01-16 17:54:09 +00001902 return true;
1903}
1904
1905void CompilerDriver::Verify(jobject jclass_loader,
1906 const std::vector<const DexFile*>& dex_files,
1907 TimingLogger* timings) {
1908 if (FastVerify(jclass_loader, dex_files, timings)) {
1909 return;
1910 }
Nicolas Geoffray6bb7f1b2016-11-03 10:52:49 +00001911
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +00001912 // If there is no existing `verifier_deps` (because of non-existing vdex), or
1913 // the existing `verifier_deps` is not valid anymore, create a new one for
Nicolas Geoffray6bb7f1b2016-11-03 10:52:49 +00001914 // non boot image compilation. The verifier will need it to record the new dependencies.
1915 // Then dex2oat can update the vdex file with these new dependencies.
1916 if (!GetCompilerOptions().IsBootImage()) {
Mathieu Chartier72041a02017-07-14 18:23:25 -07001917 // Dex2oat creates the verifier deps.
Nicolas Geoffray340dafa2016-11-18 16:03:10 +00001918 // Create the main VerifierDeps, and set it to this thread.
Mathieu Chartier72041a02017-07-14 18:23:25 -07001919 verifier::VerifierDeps* verifier_deps =
1920 Runtime::Current()->GetCompilerCallbacks()->GetVerifierDeps();
1921 CHECK(verifier_deps != nullptr);
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +00001922 Thread::Current()->SetVerifierDeps(verifier_deps);
Nicolas Geoffray340dafa2016-11-18 16:03:10 +00001923 // Create per-thread VerifierDeps to avoid contention on the main one.
1924 // We will merge them after verification.
1925 for (ThreadPoolWorker* worker : parallel_thread_pool_->GetWorkers()) {
Mathieu Chartier72041a02017-07-14 18:23:25 -07001926 worker->GetThread()->SetVerifierDeps(new verifier::VerifierDeps(dex_files_for_oat_file_));
Nicolas Geoffray340dafa2016-11-18 16:03:10 +00001927 }
Nicolas Geoffray6bb7f1b2016-11-03 10:52:49 +00001928 }
Nicolas Geoffray74981052017-01-16 17:54:09 +00001929
Nicolas Geoffray46847392017-04-28 14:56:39 +01001930 // Verification updates VerifierDeps and needs to run single-threaded to be deterministic.
1931 bool force_determinism = GetCompilerOptions().IsForceDeterminism();
1932 ThreadPool* verify_thread_pool =
1933 force_determinism ? single_thread_pool_.get() : parallel_thread_pool_.get();
1934 size_t verify_thread_count = force_determinism ? 1U : parallel_thread_count_;
Mathieu Chartier90443472015-07-16 20:32:27 -07001935 for (const DexFile* dex_file : dex_files) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001936 CHECK(dex_file != nullptr);
Nicolas Geoffray6bb7f1b2016-11-03 10:52:49 +00001937 VerifyDexFile(jclass_loader,
Andreas Gampeace0dc12016-01-20 13:33:13 -08001938 *dex_file,
1939 dex_files,
Nicolas Geoffray46847392017-04-28 14:56:39 +01001940 verify_thread_pool,
1941 verify_thread_count,
Andreas Gampeace0dc12016-01-20 13:33:13 -08001942 timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001943 }
Nicolas Geoffray340dafa2016-11-18 16:03:10 +00001944
1945 if (!GetCompilerOptions().IsBootImage()) {
Nicolas Geoffray340dafa2016-11-18 16:03:10 +00001946 // Merge all VerifierDeps into the main one.
Nicolas Geoffray74981052017-01-16 17:54:09 +00001947 verifier::VerifierDeps* verifier_deps = Thread::Current()->GetVerifierDeps();
Nicolas Geoffray340dafa2016-11-18 16:03:10 +00001948 for (ThreadPoolWorker* worker : parallel_thread_pool_->GetWorkers()) {
1949 verifier::VerifierDeps* thread_deps = worker->GetThread()->GetVerifierDeps();
1950 worker->GetThread()->SetVerifierDeps(nullptr);
Mathieu Chartier72041a02017-07-14 18:23:25 -07001951 verifier_deps->MergeWith(*thread_deps, dex_files_for_oat_file_);
Nicolas Geoffray340dafa2016-11-18 16:03:10 +00001952 delete thread_deps;
1953 }
1954 Thread::Current()->SetVerifierDeps(nullptr);
1955 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001956}
1957
Mathieu Chartier90443472015-07-16 20:32:27 -07001958class VerifyClassVisitor : public CompilationVisitor {
1959 public:
Andreas Gampe5fd66d02016-09-12 20:22:19 -07001960 VerifyClassVisitor(const ParallelCompilationManager* manager, verifier::HardFailLogMode log_level)
Andreas Gampe7fe30232016-03-25 16:58:00 -07001961 : manager_(manager), log_level_(log_level) {}
Brian Carlstrom7940e442013-07-12 13:46:57 -07001962
Mathieu Chartier90443472015-07-16 20:32:27 -07001963 virtual void Visit(size_t class_def_index) REQUIRES(!Locks::mutator_lock_) OVERRIDE {
1964 ATRACE_CALL();
1965 ScopedObjectAccess soa(Thread::Current());
1966 const DexFile& dex_file = *manager_->GetDexFile();
1967 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
1968 const char* descriptor = dex_file.GetClassDescriptor(class_def);
1969 ClassLinker* class_linker = manager_->GetClassLinker();
1970 jobject jclass_loader = manager_->GetClassLoader();
1971 StackHandleScope<3> hs(soa.Self());
1972 Handle<mirror::ClassLoader> class_loader(
Mathieu Chartier0795f232016-09-27 18:43:30 -07001973 hs.NewHandle(soa.Decode<mirror::ClassLoader>(jclass_loader)));
Mathieu Chartier90443472015-07-16 20:32:27 -07001974 Handle<mirror::Class> klass(
1975 hs.NewHandle(class_linker->FindClass(soa.Self(), descriptor, class_loader)));
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07001976 verifier::FailureKind failure_kind;
Andreas Gampefa4333d2017-02-14 11:10:34 -08001977 if (klass == nullptr) {
Ian Rogerse6bb3b22013-08-19 21:51:45 -07001978 CHECK(soa.Self()->IsExceptionPending());
1979 soa.Self()->ClearException();
Mathieu Chartier90443472015-07-16 20:32:27 -07001980
1981 /*
1982 * At compile time, we can still structurally verify the class even if FindClass fails.
1983 * This is to ensure the class is structurally sound for compilation. An unsound class
1984 * will be rejected by the verifier and later skipped during compilation in the compiler.
1985 */
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001986 Handle<mirror::DexCache> dex_cache(hs.NewHandle(class_linker->FindDexCache(
Vladimir Markocd556b02017-02-03 11:47:34 +00001987 soa.Self(), dex_file)));
Mathieu Chartier90443472015-07-16 20:32:27 -07001988 std::string error_msg;
Nicolas Geoffray08025182016-10-25 17:20:18 +01001989 failure_kind =
1990 verifier::MethodVerifier::VerifyClass(soa.Self(),
Andreas Gampeec6e6c12015-11-05 20:39:56 -08001991 &dex_file,
1992 dex_cache,
1993 class_loader,
David Brazdil15fc7292016-09-02 14:13:18 +01001994 class_def,
Andreas Gampe53e32d12015-12-09 21:03:23 -08001995 Runtime::Current()->GetCompilerCallbacks(),
Andreas Gampeec6e6c12015-11-05 20:39:56 -08001996 true /* allow soft failures */,
Andreas Gampe7fe30232016-03-25 16:58:00 -07001997 log_level_,
Nicolas Geoffray08025182016-10-25 17:20:18 +01001998 &error_msg);
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07001999 if (failure_kind == verifier::FailureKind::kHardFailure) {
Mathieu Chartier90443472015-07-16 20:32:27 -07002000 LOG(ERROR) << "Verification failed on class " << PrettyDescriptor(descriptor)
2001 << " because: " << error_msg;
2002 manager_->GetCompiler()->SetHadHardVerifierFailure();
Andreas Gampef39208f2017-10-19 15:06:59 -07002003 } else if (failure_kind == verifier::FailureKind::kSoftFailure) {
2004 manager_->GetCompiler()->AddSoftVerifierFailure();
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00002005 } else {
2006 // Force a soft failure for the VerifierDeps. This is a sanity measure, as
2007 // the vdex file already records that the class hasn't been resolved. It avoids
2008 // trying to do future verification optimizations when processing the vdex file.
Andreas Gampef39208f2017-10-19 15:06:59 -07002009 DCHECK(failure_kind == verifier::FailureKind::kNoFailure) << failure_kind;
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07002010 failure_kind = verifier::FailureKind::kSoftFailure;
Mathieu Chartier90443472015-07-16 20:32:27 -07002011 }
2012 } else if (!SkipClass(jclass_loader, dex_file, klass.Get())) {
David Sehr709b0702016-10-13 09:12:37 -07002013 CHECK(klass->IsResolved()) << klass->PrettyClass();
Nicolas Geoffray08025182016-10-25 17:20:18 +01002014 failure_kind = class_linker->VerifyClass(soa.Self(), klass, log_level_);
Mathieu Chartier90443472015-07-16 20:32:27 -07002015
2016 if (klass->IsErroneous()) {
2017 // ClassLinker::VerifyClass throws, which isn't useful in the compiler.
2018 CHECK(soa.Self()->IsExceptionPending());
2019 soa.Self()->ClearException();
2020 manager_->GetCompiler()->SetHadHardVerifierFailure();
Andreas Gampef39208f2017-10-19 15:06:59 -07002021 } else if (failure_kind == verifier::FailureKind::kSoftFailure) {
2022 manager_->GetCompiler()->AddSoftVerifierFailure();
Mathieu Chartier90443472015-07-16 20:32:27 -07002023 }
2024
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00002025 CHECK(klass->ShouldVerifyAtRuntime() || klass->IsVerified() || klass->IsErroneous())
David Sehr709b0702016-10-13 09:12:37 -07002026 << klass->PrettyDescriptor() << ": state=" << klass->GetStatus();
Mathieu Chartier90443472015-07-16 20:32:27 -07002027
Nicolas Geoffrayc7da1d62017-04-19 09:36:24 +01002028 // Class has a meaningful status for the compiler now, record it.
2029 ClassReference ref(manager_->GetDexFile(), class_def_index);
2030 manager_->GetCompiler()->RecordClassStatus(ref, klass->GetStatus());
2031
Andreas Gamped278cb42017-11-22 14:13:00 -08002032 // It is *very* problematic if there are resolution errors in the boot classpath.
2033 //
2034 // It is also bad if classes fail verification. For example, we rely on things working
2035 // OK without verification when the decryption dialog is brought up. It is thus highly
2036 // recommended to compile the boot classpath with
2037 // --abort-on-hard-verifier-error --abort-on-soft-verifier-error
2038 // which is the default build system configuration.
Narayan Kamathe3eae5e2016-10-27 11:47:30 +01002039 if (kIsDebugBuild) {
Orion Hodsonc5e0d3f2017-08-22 19:00:04 +01002040 if (manager_->GetCompiler()->GetCompilerOptions().IsBootImage()) {
Andreas Gamped278cb42017-11-22 14:13:00 -08002041 if (!klass->IsResolved() || klass->IsErroneous()) {
Andreas Gampe12fadcd2017-08-03 05:06:28 -07002042 LOG(FATAL) << "Boot classpath class " << klass->PrettyClass()
Andreas Gamped278cb42017-11-22 14:13:00 -08002043 << " failed to resolve/is erroneous: state= " << klass->GetStatus();
2044 UNREACHABLE();
Andreas Gampe12fadcd2017-08-03 05:06:28 -07002045 }
Narayan Kamathe3eae5e2016-10-27 11:47:30 +01002046 }
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00002047 if (klass->IsVerified()) {
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07002048 DCHECK_EQ(failure_kind, verifier::FailureKind::kNoFailure);
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00002049 } else if (klass->ShouldVerifyAtRuntime()) {
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07002050 DCHECK_EQ(failure_kind, verifier::FailureKind::kSoftFailure);
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00002051 } else {
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07002052 DCHECK_EQ(failure_kind, verifier::FailureKind::kHardFailure);
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00002053 }
Narayan Kamathe3eae5e2016-10-27 11:47:30 +01002054 }
Nicolas Geoffray08025182016-10-25 17:20:18 +01002055 } else {
2056 // Make the skip a soft failure, essentially being considered as verify at runtime.
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07002057 failure_kind = verifier::FailureKind::kSoftFailure;
Ian Rogerse6bb3b22013-08-19 21:51:45 -07002058 }
Nicolas Geoffray08025182016-10-25 17:20:18 +01002059 verifier::VerifierDeps::MaybeRecordVerificationStatus(
2060 dex_file, class_def.class_idx_, failure_kind);
Mathieu Chartier90443472015-07-16 20:32:27 -07002061 soa.Self()->AssertNoPendingException();
Brian Carlstrom7940e442013-07-12 13:46:57 -07002062 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002063
2064 private:
2065 const ParallelCompilationManager* const manager_;
Andreas Gampe5fd66d02016-09-12 20:22:19 -07002066 const verifier::HardFailLogMode log_level_;
Mathieu Chartier90443472015-07-16 20:32:27 -07002067};
Brian Carlstrom7940e442013-07-12 13:46:57 -07002068
Andreas Gampeace0dc12016-01-20 13:33:13 -08002069void CompilerDriver::VerifyDexFile(jobject class_loader,
2070 const DexFile& dex_file,
Andreas Gampede7b4362014-07-28 18:38:57 -07002071 const std::vector<const DexFile*>& dex_files,
Andreas Gampeace0dc12016-01-20 13:33:13 -08002072 ThreadPool* thread_pool,
2073 size_t thread_count,
2074 TimingLogger* timings) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07002075 TimingLogger::ScopedTiming t("Verify Dex File", timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002076 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Andreas Gampede7b4362014-07-28 18:38:57 -07002077 ParallelCompilationManager context(class_linker, class_loader, this, &dex_file, dex_files,
2078 thread_pool);
Andreas Gampef39208f2017-10-19 15:06:59 -07002079 bool abort_on_verifier_failures = GetCompilerOptions().AbortOnHardVerifierFailure()
2080 || GetCompilerOptions().AbortOnSoftVerifierFailure();
2081 verifier::HardFailLogMode log_level = abort_on_verifier_failures
Andreas Gampe5fd66d02016-09-12 20:22:19 -07002082 ? verifier::HardFailLogMode::kLogInternalFatal
2083 : verifier::HardFailLogMode::kLogWarning;
Andreas Gampe7fe30232016-03-25 16:58:00 -07002084 VerifyClassVisitor visitor(&context, log_level);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002085 context.ForAll(0, dex_file.NumClassDefs(), &visitor, thread_count);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002086}
2087
Mathieu Chartier90443472015-07-16 20:32:27 -07002088class SetVerifiedClassVisitor : public CompilationVisitor {
2089 public:
2090 explicit SetVerifiedClassVisitor(const ParallelCompilationManager* manager) : manager_(manager) {}
2091
2092 virtual void Visit(size_t class_def_index) REQUIRES(!Locks::mutator_lock_) OVERRIDE {
2093 ATRACE_CALL();
2094 ScopedObjectAccess soa(Thread::Current());
2095 const DexFile& dex_file = *manager_->GetDexFile();
2096 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
2097 const char* descriptor = dex_file.GetClassDescriptor(class_def);
2098 ClassLinker* class_linker = manager_->GetClassLinker();
2099 jobject jclass_loader = manager_->GetClassLoader();
2100 StackHandleScope<3> hs(soa.Self());
2101 Handle<mirror::ClassLoader> class_loader(
Mathieu Chartier0795f232016-09-27 18:43:30 -07002102 hs.NewHandle(soa.Decode<mirror::ClassLoader>(jclass_loader)));
Mathieu Chartier90443472015-07-16 20:32:27 -07002103 Handle<mirror::Class> klass(
2104 hs.NewHandle(class_linker->FindClass(soa.Self(), descriptor, class_loader)));
2105 // Class might have failed resolution. Then don't set it to verified.
Andreas Gampefa4333d2017-02-14 11:10:34 -08002106 if (klass != nullptr) {
Mathieu Chartier90443472015-07-16 20:32:27 -07002107 // Only do this if the class is resolved. If even resolution fails, quickening will go very,
2108 // very wrong.
Vladimir Marko72ab6842017-01-20 19:32:50 +00002109 if (klass->IsResolved() && !klass->IsErroneousResolved()) {
Mathieu Chartier90443472015-07-16 20:32:27 -07002110 if (klass->GetStatus() < mirror::Class::kStatusVerified) {
2111 ObjectLock<mirror::Class> lock(soa.Self(), klass);
2112 // Set class status to verified.
2113 mirror::Class::SetStatus(klass, mirror::Class::kStatusVerified, soa.Self());
2114 // Mark methods as pre-verified. If we don't do this, the interpreter will run with
2115 // access checks.
Igor Murashkindf707e42016-02-02 16:56:50 -08002116 klass->SetSkipAccessChecksFlagOnAllMethods(
Mathieu Chartier90443472015-07-16 20:32:27 -07002117 GetInstructionSetPointerSize(manager_->GetCompiler()->GetInstructionSet()));
Igor Murashkindf707e42016-02-02 16:56:50 -08002118 klass->SetVerificationAttempted();
Mathieu Chartier90443472015-07-16 20:32:27 -07002119 }
2120 // Record the final class status if necessary.
2121 ClassReference ref(manager_->GetDexFile(), class_def_index);
2122 manager_->GetCompiler()->RecordClassStatus(ref, klass->GetStatus());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002123 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002124 } else {
2125 Thread* self = soa.Self();
2126 DCHECK(self->IsExceptionPending());
2127 self->ClearException();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002128 }
2129 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002130
2131 private:
2132 const ParallelCompilationManager* const manager_;
2133};
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002134
Andreas Gampeace0dc12016-01-20 13:33:13 -08002135void CompilerDriver::SetVerifiedDexFile(jobject class_loader,
2136 const DexFile& dex_file,
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002137 const std::vector<const DexFile*>& dex_files,
Andreas Gampeace0dc12016-01-20 13:33:13 -08002138 ThreadPool* thread_pool,
2139 size_t thread_count,
2140 TimingLogger* timings) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002141 TimingLogger::ScopedTiming t("Verify Dex File", timings);
Mathieu Chartier1a088d42017-07-18 11:43:57 -07002142 if (!compiled_classes_.HaveDexFile(&dex_file)) {
Mathieu Chartierfc8b4222017-09-17 13:44:24 -07002143 compiled_classes_.AddDexFile(&dex_file);
Mathieu Chartier1a088d42017-07-18 11:43:57 -07002144 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002145 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
2146 ParallelCompilationManager context(class_linker, class_loader, this, &dex_file, dex_files,
2147 thread_pool);
Mathieu Chartier90443472015-07-16 20:32:27 -07002148 SetVerifiedClassVisitor visitor(&context);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002149 context.ForAll(0, dex_file.NumClassDefs(), &visitor, thread_count);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002150}
2151
Mathieu Chartier90443472015-07-16 20:32:27 -07002152class InitializeClassVisitor : public CompilationVisitor {
2153 public:
2154 explicit InitializeClassVisitor(const ParallelCompilationManager* manager) : manager_(manager) {}
Ian Rogersfc0e94b2013-09-23 23:51:32 -07002155
Mathieu Chartierf1dd69a2017-06-08 23:30:15 +00002156 void Visit(size_t class_def_index) OVERRIDE {
Mathieu Chartier90443472015-07-16 20:32:27 -07002157 ATRACE_CALL();
2158 jobject jclass_loader = manager_->GetClassLoader();
2159 const DexFile& dex_file = *manager_->GetDexFile();
2160 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
2161 const DexFile::TypeId& class_type_id = dex_file.GetTypeId(class_def.class_idx_);
2162 const char* descriptor = dex_file.StringDataByIdx(class_type_id.descriptor_idx_);
Jeff Hao0e49b422013-11-08 12:16:56 -08002163
Mathieu Chartier90443472015-07-16 20:32:27 -07002164 ScopedObjectAccess soa(Thread::Current());
2165 StackHandleScope<3> hs(soa.Self());
2166 Handle<mirror::ClassLoader> class_loader(
Mathieu Chartier0795f232016-09-27 18:43:30 -07002167 hs.NewHandle(soa.Decode<mirror::ClassLoader>(jclass_loader)));
Mathieu Chartier90443472015-07-16 20:32:27 -07002168 Handle<mirror::Class> klass(
2169 hs.NewHandle(manager_->GetClassLinker()->FindClass(soa.Self(), descriptor, class_loader)));
2170
Mathieu Chartierf1dd69a2017-06-08 23:30:15 +00002171 if (klass != nullptr && !SkipClass(manager_->GetClassLoader(), dex_file, klass.Get())) {
2172 TryInitializeClass(klass, class_loader);
2173 }
2174 // Clear any class not found or verification exceptions.
2175 soa.Self()->ClearException();
2176 }
2177
2178 // A helper function for initializing klass.
2179 void TryInitializeClass(Handle<mirror::Class> klass, Handle<mirror::ClassLoader>& class_loader)
2180 REQUIRES_SHARED(Locks::mutator_lock_) {
2181 const DexFile& dex_file = klass->GetDexFile();
2182 const DexFile::ClassDef* class_def = klass->GetClassDef();
2183 const DexFile::TypeId& class_type_id = dex_file.GetTypeId(class_def->class_idx_);
2184 const char* descriptor = dex_file.StringDataByIdx(class_type_id.descriptor_idx_);
2185 ScopedObjectAccessUnchecked soa(Thread::Current());
2186 StackHandleScope<3> hs(soa.Self());
Mathieu Chartierdabeb3a2017-06-12 17:10:07 -07002187 const bool is_boot_image = manager_->GetCompiler()->GetCompilerOptions().IsBootImage();
Mathieu Chartier17498e52017-06-13 11:35:04 -07002188 const bool is_app_image = manager_->GetCompiler()->GetCompilerOptions().IsAppImage();
Mathieu Chartierf1dd69a2017-06-08 23:30:15 +00002189
Jeff Hao0cb17282017-07-12 14:51:49 -07002190 mirror::Class::Status old_status = klass->GetStatus();
Mathieu Chartier1a088d42017-07-18 11:43:57 -07002191 // Don't initialize classes in boot space when compiling app image
2192 if (is_app_image && klass->IsBootStrapClassLoaded()) {
2193 // Also return early and don't store the class status in the recorded class status.
2194 return;
2195 }
Mathieu Chartierf1dd69a2017-06-08 23:30:15 +00002196 // Only try to initialize classes that were successfully verified.
2197 if (klass->IsVerified()) {
2198 // Attempt to initialize the class but bail if we either need to initialize the super-class
2199 // or static fields.
Nicolas Geoffrayabadf022017-08-03 08:25:41 +00002200 manager_->GetClassLinker()->EnsureInitialized(soa.Self(), klass, false, false);
Mathieu Chartierf1dd69a2017-06-08 23:30:15 +00002201 old_status = klass->GetStatus();
2202 if (!klass->IsInitialized()) {
2203 // We don't want non-trivial class initialization occurring on multiple threads due to
2204 // deadlock problems. For example, a parent class is initialized (holding its lock) that
2205 // refers to a sub-class in its static/class initializer causing it to try to acquire the
2206 // sub-class' lock. While on a second thread the sub-class is initialized (holding its lock)
2207 // after first initializing its parents, whose locks are acquired. This leads to a
2208 // parent-to-child and a child-to-parent lock ordering and consequent potential deadlock.
2209 // We need to use an ObjectLock due to potential suspension in the interpreting code. Rather
2210 // than use a special Object for the purpose we use the Class of java.lang.Class.
2211 Handle<mirror::Class> h_klass(hs.NewHandle(klass->GetClass()));
2212 ObjectLock<mirror::Class> lock(soa.Self(), h_klass);
2213 // Attempt to initialize allowing initialization of parent classes but still not static
2214 // fields.
Chang Xinge602b1c2017-06-30 11:55:01 -07002215 // Initialize dependencies first only for app image, to make TryInitialize recursive.
2216 bool is_superclass_initialized = !is_app_image ? true :
2217 InitializeDependencies(klass, class_loader, soa.Self());
2218 if (!is_app_image || (is_app_image && is_superclass_initialized)) {
Nicolas Geoffrayabadf022017-08-03 08:25:41 +00002219 manager_->GetClassLinker()->EnsureInitialized(soa.Self(), klass, false, true);
Chang Xinge602b1c2017-06-30 11:55:01 -07002220 }
2221 // Otherwise it's in app image but superclasses can't be initialized, no need to proceed.
Mathieu Chartierf1dd69a2017-06-08 23:30:15 +00002222 old_status = klass->GetStatus();
Chang Xing70f689d2017-06-08 17:16:12 -07002223
2224 bool too_many_encoded_fields = false;
2225 if (!is_boot_image && klass->NumStaticFields() > kMaxEncodedFields) {
2226 too_many_encoded_fields = true;
2227 }
Mathieu Chartierdabeb3a2017-06-12 17:10:07 -07002228 // If the class was not initialized, we can proceed to see if we can initialize static
Chang Xing70f689d2017-06-08 17:16:12 -07002229 // fields. Limit the max number of encoded fields.
Mathieu Chartierf1dd69a2017-06-08 23:30:15 +00002230 if (!klass->IsInitialized() &&
Mathieu Chartier17498e52017-06-13 11:35:04 -07002231 (is_app_image || is_boot_image) &&
Chang Xinge602b1c2017-06-30 11:55:01 -07002232 is_superclass_initialized &&
Chang Xing70f689d2017-06-08 17:16:12 -07002233 !too_many_encoded_fields &&
Mathieu Chartierf1dd69a2017-06-08 23:30:15 +00002234 manager_->GetCompiler()->IsImageClass(descriptor)) {
2235 bool can_init_static_fields = false;
Mathieu Chartierdabeb3a2017-06-12 17:10:07 -07002236 if (is_boot_image) {
Mathieu Chartier90443472015-07-16 20:32:27 -07002237 // We need to initialize static fields, we only do this for image classes that aren't
Mathieu Chartierdabeb3a2017-06-12 17:10:07 -07002238 // marked with the $NoPreloadHolder (which implies this should not be initialized
2239 // early).
Mathieu Chartierf1dd69a2017-06-08 23:30:15 +00002240 can_init_static_fields = !StringPiece(descriptor).ends_with("$NoPreloadHolder;");
2241 } else {
Mathieu Chartier17498e52017-06-13 11:35:04 -07002242 CHECK(is_app_image);
Mathieu Chartierdabeb3a2017-06-12 17:10:07 -07002243 // The boot image case doesn't need to recursively initialize the dependencies with
2244 // special logic since the class linker already does this.
Mathieu Chartierdabeb3a2017-06-12 17:10:07 -07002245 can_init_static_fields =
Mathieu Chartierf1dd69a2017-06-08 23:30:15 +00002246 !soa.Self()->IsExceptionPending() &&
Nicolas Geoffrayabadf022017-08-03 08:25:41 +00002247 is_superclass_initialized &&
2248 NoClinitInDependency(klass, soa.Self(), &class_loader);
Mathieu Chartierf1dd69a2017-06-08 23:30:15 +00002249 // TODO The checking for clinit can be removed since it's already
2250 // checked when init superclass. Currently keep it because it contains
2251 // processing of intern strings. Will be removed later when intern strings
2252 // and clinit are both initialized.
2253 }
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002254
Mathieu Chartierf1dd69a2017-06-08 23:30:15 +00002255 if (can_init_static_fields) {
2256 VLOG(compiler) << "Initializing: " << descriptor;
2257 // TODO multithreading support. We should ensure the current compilation thread has
2258 // exclusive access to the runtime and the transaction. To achieve this, we could use
2259 // a ReaderWriterMutex but we're holding the mutator lock so we fail mutex sanity
2260 // checks in Thread::AssertThreadSuspensionIsAllowable.
2261 Runtime* const runtime = Runtime::Current();
Mathieu Chartierf1dd69a2017-06-08 23:30:15 +00002262 // Run the class initializer in transaction mode.
Chang Xing5a906fc2017-07-26 15:01:16 -07002263 runtime->EnterTransactionMode(is_app_image, klass.Get());
Mathieu Chartierf1dd69a2017-06-08 23:30:15 +00002264 bool success = manager_->GetClassLinker()->EnsureInitialized(soa.Self(), klass, true,
2265 true);
2266 // TODO we detach transaction from runtime to indicate we quit the transactional
2267 // mode which prevents the GC from visiting objects modified during the transaction.
2268 // Ensure GC is not run so don't access freed objects when aborting transaction.
Andreas Gampe9e7078b2017-03-02 13:50:36 -08002269
Mathieu Chartierf1dd69a2017-06-08 23:30:15 +00002270 {
2271 ScopedAssertNoThreadSuspension ants("Transaction end");
Chang Xing16d1dd82017-07-20 17:56:26 -07002272
2273 if (success) {
2274 runtime->ExitTransactionMode();
2275 DCHECK(!runtime->IsActiveTransaction());
2276 }
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002277
Mathieu Chartier90443472015-07-16 20:32:27 -07002278 if (!success) {
Mathieu Chartierf1dd69a2017-06-08 23:30:15 +00002279 CHECK(soa.Self()->IsExceptionPending());
2280 mirror::Throwable* exception = soa.Self()->GetException();
2281 VLOG(compiler) << "Initialization of " << descriptor << " aborted because of "
2282 << exception->Dump();
2283 std::ostream* file_log = manager_->GetCompiler()->
2284 GetCompilerOptions().GetInitFailureOutput();
2285 if (file_log != nullptr) {
2286 *file_log << descriptor << "\n";
2287 *file_log << exception->Dump() << "\n";
2288 }
2289 soa.Self()->ClearException();
Chang Xing605fe242017-07-20 15:57:21 -07002290 runtime->RollbackAllTransactions();
Mathieu Chartierf1dd69a2017-06-08 23:30:15 +00002291 CHECK_EQ(old_status, klass->GetStatus()) << "Previous class status not restored";
Mathieu Chartierdabeb3a2017-06-12 17:10:07 -07002292 } else if (is_boot_image) {
2293 // For boot image, we want to put the updated status in the oat class since we can't
2294 // reject the image anyways.
2295 old_status = klass->GetStatus();
Mathieu Chartierf1dd69a2017-06-08 23:30:15 +00002296 }
2297 }
2298
Nicolas Geoffrayabadf022017-08-03 08:25:41 +00002299 if (!success) {
Mathieu Chartierf1dd69a2017-06-08 23:30:15 +00002300 // On failure, still intern strings of static fields and seen in <clinit>, as these
2301 // will be created in the zygote. This is separated from the transaction code just
2302 // above as we will allocate strings, so must be allowed to suspend.
2303 if (&klass->GetDexFile() == manager_->GetDexFile()) {
Andreas Gampe9e7078b2017-03-02 13:50:36 -08002304 InternStrings(klass, class_loader);
Mathieu Chartierdabeb3a2017-06-12 17:10:07 -07002305 } else {
2306 DCHECK(!is_boot_image) << "Boot image must have equal dex files";
Andreas Gampedbfe2542014-11-25 22:21:42 -08002307 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002308 }
2309 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002310 }
Jeff Hao0cb17282017-07-12 14:51:49 -07002311 // If the class still isn't initialized, at least try some checks that initialization
2312 // would do so they can be skipped at runtime.
2313 if (!klass->IsInitialized() &&
2314 manager_->GetClassLinker()->ValidateSuperClassDescriptors(klass)) {
2315 old_status = mirror::Class::kStatusSuperclassValidated;
2316 } else {
2317 soa.Self()->ClearException();
2318 }
Mathieu Chartierf1dd69a2017-06-08 23:30:15 +00002319 soa.Self()->AssertNoPendingException();
Brian Carlstrom7940e442013-07-12 13:46:57 -07002320 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002321 }
Mathieu Chartierf1dd69a2017-06-08 23:30:15 +00002322 // Record the final class status if necessary.
2323 ClassReference ref(&dex_file, klass->GetDexClassDefIndex());
2324 // Back up the status before doing initialization for static encoded fields,
2325 // because the static encoded branch wants to keep the status to uninitialized.
2326 manager_->GetCompiler()->RecordClassStatus(ref, old_status);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002327 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002328
2329 private:
Andreas Gampe9e7078b2017-03-02 13:50:36 -08002330 void InternStrings(Handle<mirror::Class> klass, Handle<mirror::ClassLoader> class_loader)
2331 REQUIRES_SHARED(Locks::mutator_lock_) {
2332 DCHECK(manager_->GetCompiler()->GetCompilerOptions().IsBootImage());
2333 DCHECK(klass->IsVerified());
2334 DCHECK(!klass->IsInitialized());
2335
2336 StackHandleScope<1> hs(Thread::Current());
2337 Handle<mirror::DexCache> h_dex_cache = hs.NewHandle(klass->GetDexCache());
2338 const DexFile* dex_file = manager_->GetDexFile();
2339 const DexFile::ClassDef* class_def = klass->GetClassDef();
2340 ClassLinker* class_linker = manager_->GetClassLinker();
2341
Andreas Gampe7bf90482017-03-02 16:41:35 -08002342 // Check encoded final field values for strings and intern.
Andreas Gampe9e7078b2017-03-02 13:50:36 -08002343 annotations::RuntimeEncodedStaticFieldValueIterator value_it(*dex_file,
2344 &h_dex_cache,
2345 &class_loader,
2346 manager_->GetClassLinker(),
2347 *class_def);
2348 for ( ; value_it.HasNext(); value_it.Next()) {
2349 if (value_it.GetValueType() == annotations::RuntimeEncodedStaticFieldValueIterator::kString) {
2350 // Resolve the string. This will intern the string.
2351 art::ObjPtr<mirror::String> resolved = class_linker->ResolveString(
2352 *dex_file, dex::StringIndex(value_it.GetJavaValue().i), h_dex_cache);
2353 CHECK(resolved != nullptr);
2354 }
2355 }
Andreas Gampe7bf90482017-03-02 16:41:35 -08002356
2357 // Intern strings seen in <clinit>.
2358 ArtMethod* clinit = klass->FindClassInitializer(class_linker->GetImagePointerSize());
2359 if (clinit != nullptr) {
2360 const DexFile::CodeItem* code_item = clinit->GetCodeItem();
2361 DCHECK(code_item != nullptr);
Mathieu Chartier2b2bef22017-10-26 17:10:19 -07002362 for (const DexInstructionPcPair& inst : code_item->Instructions()) {
2363 if (inst->Opcode() == Instruction::CONST_STRING) {
Andreas Gampe7bf90482017-03-02 16:41:35 -08002364 ObjPtr<mirror::String> s = class_linker->ResolveString(
Mathieu Chartier2b2bef22017-10-26 17:10:19 -07002365 *dex_file, dex::StringIndex(inst->VRegB_21c()), h_dex_cache);
Andreas Gampe7bf90482017-03-02 16:41:35 -08002366 CHECK(s != nullptr);
Mathieu Chartier2b2bef22017-10-26 17:10:19 -07002367 } else if (inst->Opcode() == Instruction::CONST_STRING_JUMBO) {
Andreas Gampe7bf90482017-03-02 16:41:35 -08002368 ObjPtr<mirror::String> s = class_linker->ResolveString(
Mathieu Chartier2b2bef22017-10-26 17:10:19 -07002369 *dex_file, dex::StringIndex(inst->VRegB_31c()), h_dex_cache);
Andreas Gampe7bf90482017-03-02 16:41:35 -08002370 CHECK(s != nullptr);
2371 }
Andreas Gampe7bf90482017-03-02 16:41:35 -08002372 }
2373 }
Andreas Gampe9e7078b2017-03-02 13:50:36 -08002374 }
2375
Mathieu Chartierf1dd69a2017-06-08 23:30:15 +00002376 bool ResolveTypesOfMethods(Thread* self, ArtMethod* m)
2377 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markob45528c2017-07-27 14:14:28 +01002378 // Return value of ResolveReturnType() is discarded because resolve will be done internally.
2379 ObjPtr<mirror::Class> rtn_type = m->ResolveReturnType();
Mathieu Chartier7a8bcfd2017-06-13 13:40:43 -07002380 if (rtn_type == nullptr) {
2381 self->ClearException();
2382 return false;
2383 }
2384 const DexFile::TypeList* types = m->GetParameterTypeList();
2385 if (types != nullptr) {
2386 for (uint32_t i = 0; i < types->Size(); ++i) {
2387 dex::TypeIndex param_type_idx = types->GetTypeItem(i).type_idx_;
Vladimir Markob45528c2017-07-27 14:14:28 +01002388 ObjPtr<mirror::Class> param_type = m->ResolveClassFromTypeIndex(param_type_idx);
Mathieu Chartier7a8bcfd2017-06-13 13:40:43 -07002389 if (param_type == nullptr) {
2390 self->ClearException();
2391 return false;
Mathieu Chartierf1dd69a2017-06-08 23:30:15 +00002392 }
2393 }
Mathieu Chartier7a8bcfd2017-06-13 13:40:43 -07002394 }
2395 return true;
Mathieu Chartierf1dd69a2017-06-08 23:30:15 +00002396 }
2397
2398 // Pre resolve types mentioned in all method signatures before start a transaction
2399 // since ResolveType doesn't work in transaction mode.
2400 bool PreResolveTypes(Thread* self, const Handle<mirror::Class>& klass)
2401 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier7a8bcfd2017-06-13 13:40:43 -07002402 PointerSize pointer_size = manager_->GetClassLinker()->GetImagePointerSize();
2403 for (ArtMethod& m : klass->GetMethods(pointer_size)) {
2404 if (!ResolveTypesOfMethods(self, &m)) {
2405 return false;
2406 }
2407 }
2408 if (klass->IsInterface()) {
2409 return true;
2410 } else if (klass->HasSuperClass()) {
2411 StackHandleScope<1> hs(self);
2412 MutableHandle<mirror::Class> super_klass(hs.NewHandle<mirror::Class>(klass->GetSuperClass()));
2413 for (int i = super_klass->GetVTableLength() - 1; i >= 0; --i) {
2414 ArtMethod* m = klass->GetVTableEntry(i, pointer_size);
2415 ArtMethod* super_m = super_klass->GetVTableEntry(i, pointer_size);
2416 if (!ResolveTypesOfMethods(self, m) || !ResolveTypesOfMethods(self, super_m)) {
Mathieu Chartierf1dd69a2017-06-08 23:30:15 +00002417 return false;
2418 }
2419 }
Mathieu Chartier7a8bcfd2017-06-13 13:40:43 -07002420 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
2421 super_klass.Assign(klass->GetIfTable()->GetInterface(i));
2422 if (klass->GetClassLoader() != super_klass->GetClassLoader()) {
2423 uint32_t num_methods = super_klass->NumVirtualMethods();
2424 for (uint32_t j = 0; j < num_methods; ++j) {
2425 ArtMethod* m = klass->GetIfTable()->GetMethodArray(i)->GetElementPtrSize<ArtMethod*>(
2426 j, pointer_size);
2427 ArtMethod* super_m = super_klass->GetVirtualMethod(j, pointer_size);
2428 if (!ResolveTypesOfMethods(self, m) || !ResolveTypesOfMethods(self, super_m)) {
2429 return false;
Mathieu Chartierf1dd69a2017-06-08 23:30:15 +00002430 }
2431 }
2432 }
2433 }
Mathieu Chartier7a8bcfd2017-06-13 13:40:43 -07002434 }
2435 return true;
Mathieu Chartierf1dd69a2017-06-08 23:30:15 +00002436 }
2437
2438 // Initialize the klass's dependencies recursively before initializing itself.
2439 // Checking for interfaces is also necessary since interfaces can contain
2440 // both default methods and static encoded fields.
2441 bool InitializeDependencies(const Handle<mirror::Class>& klass,
2442 Handle<mirror::ClassLoader> class_loader,
2443 Thread* self)
2444 REQUIRES_SHARED(Locks::mutator_lock_) {
2445 if (klass->HasSuperClass()) {
2446 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
2447 StackHandleScope<1> hs(self);
2448 Handle<mirror::Class> handle_scope_super(hs.NewHandle(super_class));
2449 if (!handle_scope_super->IsInitialized()) {
2450 this->TryInitializeClass(handle_scope_super, class_loader);
2451 if (!handle_scope_super->IsInitialized()) {
2452 return false;
2453 }
2454 }
2455 }
2456
2457 uint32_t num_if = klass->NumDirectInterfaces();
2458 for (size_t i = 0; i < num_if; i++) {
2459 ObjPtr<mirror::Class>
2460 interface = mirror::Class::GetDirectInterface(self, klass.Get(), i);
2461 StackHandleScope<1> hs(self);
2462 Handle<mirror::Class> handle_interface(hs.NewHandle(interface));
2463
2464 TryInitializeClass(handle_interface, class_loader);
2465
2466 if (!handle_interface->IsInitialized()) {
2467 return false;
2468 }
2469 }
2470
2471 return PreResolveTypes(self, klass);
2472 }
2473
2474 // In this phase the classes containing class initializers are ignored. Make sure no
2475 // clinit appears in kalss's super class chain and interfaces.
2476 bool NoClinitInDependency(const Handle<mirror::Class>& klass,
2477 Thread* self,
2478 Handle<mirror::ClassLoader>* class_loader)
2479 REQUIRES_SHARED(Locks::mutator_lock_) {
2480 ArtMethod* clinit =
2481 klass->FindClassInitializer(manager_->GetClassLinker()->GetImagePointerSize());
2482 if (clinit != nullptr) {
2483 VLOG(compiler) << klass->PrettyClass() << ' ' << clinit->PrettyMethod(true);
2484 return false;
2485 }
2486 if (klass->HasSuperClass()) {
2487 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
2488 StackHandleScope<1> hs(self);
2489 Handle<mirror::Class> handle_scope_super(hs.NewHandle(super_class));
2490 if (!NoClinitInDependency(handle_scope_super, self, class_loader)) {
2491 return false;
2492 }
2493 }
2494
2495 uint32_t num_if = klass->NumDirectInterfaces();
2496 for (size_t i = 0; i < num_if; i++) {
2497 ObjPtr<mirror::Class>
2498 interface = mirror::Class::GetDirectInterface(self, klass.Get(), i);
2499 StackHandleScope<1> hs(self);
2500 Handle<mirror::Class> handle_interface(hs.NewHandle(interface));
2501 if (!NoClinitInDependency(handle_interface, self, class_loader)) {
2502 return false;
2503 }
2504 }
2505
Chang Xingba17dbd2017-06-28 21:27:56 +00002506 return true;
Mathieu Chartierf1dd69a2017-06-08 23:30:15 +00002507 }
2508
Mathieu Chartier90443472015-07-16 20:32:27 -07002509 const ParallelCompilationManager* const manager_;
2510};
Brian Carlstrom7940e442013-07-12 13:46:57 -07002511
Andreas Gampeace0dc12016-01-20 13:33:13 -08002512void CompilerDriver::InitializeClasses(jobject jni_class_loader,
2513 const DexFile& dex_file,
Andreas Gampede7b4362014-07-28 18:38:57 -07002514 const std::vector<const DexFile*>& dex_files,
Andreas Gampeace0dc12016-01-20 13:33:13 -08002515 TimingLogger* timings) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07002516 TimingLogger::ScopedTiming t("InitializeNoClinit", timings);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002517
2518 // Initialization allocates objects and needs to run single-threaded to be deterministic.
2519 bool force_determinism = GetCompilerOptions().IsForceDeterminism();
2520 ThreadPool* init_thread_pool = force_determinism
2521 ? single_thread_pool_.get()
2522 : parallel_thread_pool_.get();
2523 size_t init_thread_count = force_determinism ? 1U : parallel_thread_count_;
2524
Brian Carlstrom7940e442013-07-12 13:46:57 -07002525 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Andreas Gampede7b4362014-07-28 18:38:57 -07002526 ParallelCompilationManager context(class_linker, jni_class_loader, this, &dex_file, dex_files,
Andreas Gampeace0dc12016-01-20 13:33:13 -08002527 init_thread_pool);
Mathieu Chartierf1dd69a2017-06-08 23:30:15 +00002528
2529 if (GetCompilerOptions().IsBootImage() || GetCompilerOptions().IsAppImage()) {
2530 // Set the concurrency thread to 1 to support initialization for App Images since transaction
2531 // doesn't support multithreading now.
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002532 // TODO: remove this when transactional mode supports multithreading.
Andreas Gampeace0dc12016-01-20 13:33:13 -08002533 init_thread_count = 1U;
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002534 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002535 InitializeClassVisitor visitor(&context);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002536 context.ForAll(0, dex_file.NumClassDefs(), &visitor, init_thread_count);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002537}
2538
Mathieu Chartier91288d82016-04-28 09:44:54 -07002539class InitializeArrayClassesAndCreateConflictTablesVisitor : public ClassVisitor {
Mathieu Chartier085a0722016-04-01 17:33:31 -07002540 public:
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002541 explicit InitializeArrayClassesAndCreateConflictTablesVisitor(VariableSizedHandleScope& hs)
2542 : hs_(hs) {}
2543
2544 virtual bool operator()(ObjPtr<mirror::Class> klass) OVERRIDE
2545 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier91288d82016-04-28 09:44:54 -07002546 if (Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(klass)) {
2547 return true;
2548 }
Mathieu Chartier085a0722016-04-01 17:33:31 -07002549 if (klass->IsArrayClass()) {
2550 StackHandleScope<1> hs(Thread::Current());
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002551 auto h_klass = hs.NewHandleWrapper(&klass);
2552 Runtime::Current()->GetClassLinker()->EnsureInitialized(hs.Self(), h_klass, true, true);
Mathieu Chartier085a0722016-04-01 17:33:31 -07002553 }
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002554 // Collect handles since there may be thread suspension in future EnsureInitialized.
2555 to_visit_.push_back(hs_.NewHandle(klass));
Nicolas Geoffray88f288e2016-06-29 08:17:52 +00002556 return true;
Nelli Kimbadee982016-05-13 13:08:53 +03002557 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00002558
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002559 void FillAllIMTAndConflictTables() REQUIRES_SHARED(Locks::mutator_lock_) {
2560 for (Handle<mirror::Class> c : to_visit_) {
2561 // Create the conflict tables.
2562 FillIMTAndConflictTables(c.Get());
2563 }
2564 }
2565
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00002566 private:
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002567 void FillIMTAndConflictTables(ObjPtr<mirror::Class> klass)
2568 REQUIRES_SHARED(Locks::mutator_lock_) {
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00002569 if (!klass->ShouldHaveImt()) {
2570 return;
2571 }
2572 if (visited_classes_.find(klass) != visited_classes_.end()) {
2573 return;
2574 }
2575 if (klass->HasSuperClass()) {
2576 FillIMTAndConflictTables(klass->GetSuperClass());
2577 }
2578 if (!klass->IsTemp()) {
2579 Runtime::Current()->GetClassLinker()->FillIMTAndConflictTables(klass);
2580 }
2581 visited_classes_.insert(klass);
2582 }
2583
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002584 VariableSizedHandleScope& hs_;
2585 std::vector<Handle<mirror::Class>> to_visit_;
2586 std::unordered_set<ObjPtr<mirror::Class>, HashObjPtr> visited_classes_;
Mathieu Chartier085a0722016-04-01 17:33:31 -07002587};
2588
Brian Carlstrom7940e442013-07-12 13:46:57 -07002589void CompilerDriver::InitializeClasses(jobject class_loader,
2590 const std::vector<const DexFile*>& dex_files,
Andreas Gampeace0dc12016-01-20 13:33:13 -08002591 TimingLogger* timings) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07002592 for (size_t i = 0; i != dex_files.size(); ++i) {
2593 const DexFile* dex_file = dex_files[i];
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002594 CHECK(dex_file != nullptr);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002595 InitializeClasses(class_loader, *dex_file, dex_files, timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002596 }
Vladimir Markoaad75c62016-10-03 08:46:48 +00002597 if (GetCompilerOptions().IsBootImage() || GetCompilerOptions().IsAppImage()) {
Mathieu Chartier085a0722016-04-01 17:33:31 -07002598 // Make sure that we call EnsureIntiailized on all the array classes to call
2599 // SetVerificationAttempted so that the access flags are set. If we do not do this they get
2600 // changed at runtime resulting in more dirty image pages.
Mathieu Chartier91288d82016-04-28 09:44:54 -07002601 // Also create conflict tables.
2602 // Only useful if we are compiling an image (image_classes_ is not null).
Mathieu Chartier085a0722016-04-01 17:33:31 -07002603 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002604 VariableSizedHandleScope hs(soa.Self());
2605 InitializeArrayClassesAndCreateConflictTablesVisitor visitor(hs);
Mathieu Chartier91288d82016-04-28 09:44:54 -07002606 Runtime::Current()->GetClassLinker()->VisitClassesWithoutClassesLock(&visitor);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002607 visitor.FillAllIMTAndConflictTables();
Mathieu Chartier085a0722016-04-01 17:33:31 -07002608 }
Vladimir Markoaad75c62016-10-03 08:46:48 +00002609 if (GetCompilerOptions().IsBootImage()) {
Mathieu Chartier093ef212014-08-11 13:52:12 -07002610 // Prune garbage objects created during aborted transactions.
2611 Runtime::Current()->GetHeap()->CollectGarbage(true);
2612 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002613}
2614
Andreas Gampeace0dc12016-01-20 13:33:13 -08002615void CompilerDriver::Compile(jobject class_loader,
2616 const std::vector<const DexFile*>& dex_files,
2617 TimingLogger* timings) {
Calin Juravle998c2162015-12-21 15:39:33 +02002618 if (kDebugProfileGuidedCompilation) {
2619 LOG(INFO) << "[ProfileGuidedCompilation] " <<
2620 ((profile_compilation_info_ == nullptr)
2621 ? "null"
2622 : profile_compilation_info_->DumpInfo(&dex_files));
Calin Juravle226501b2015-12-11 14:41:31 +00002623 }
Vladimir Marko492a7fa2016-06-01 18:38:43 +01002624
Mathieu Chartier72041a02017-07-14 18:23:25 -07002625 current_dex_to_dex_methods_ = nullptr;
2626 Thread* const self = Thread::Current();
2627 {
2628 // Clear in case we aren't the first call to Compile.
2629 MutexLock mu(self, dex_to_dex_references_lock_);
2630 dex_to_dex_references_.clear();
2631 }
2632
Vladimir Marko492a7fa2016-06-01 18:38:43 +01002633 for (const DexFile* dex_file : dex_files) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002634 CHECK(dex_file != nullptr);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002635 CompileDexFile(class_loader,
2636 *dex_file,
2637 dex_files,
2638 parallel_thread_pool_.get(),
2639 parallel_thread_count_,
2640 timings);
Calin Juravle69158982016-03-16 11:53:41 +00002641 const ArenaPool* const arena_pool = Runtime::Current()->GetArenaPool();
2642 const size_t arena_alloc = arena_pool->GetBytesAllocated();
2643 max_arena_alloc_ = std::max(arena_alloc, max_arena_alloc_);
Jean-Philippe Halimica76a1a2016-02-02 19:48:52 +01002644 Runtime::Current()->ReclaimArenaPoolMemory();
Brian Carlstrom7940e442013-07-12 13:46:57 -07002645 }
Vladimir Marko492a7fa2016-06-01 18:38:43 +01002646
2647 ArrayRef<DexFileMethodSet> dex_to_dex_references;
2648 {
2649 // From this point on, we shall not modify dex_to_dex_references_, so
2650 // just grab a reference to it that we use without holding the mutex.
Mathieu Chartier72041a02017-07-14 18:23:25 -07002651 MutexLock lock(self, dex_to_dex_references_lock_);
Vladimir Marko492a7fa2016-06-01 18:38:43 +01002652 dex_to_dex_references = ArrayRef<DexFileMethodSet>(dex_to_dex_references_);
2653 }
2654 for (const auto& method_set : dex_to_dex_references) {
2655 current_dex_to_dex_methods_ = &method_set.GetMethodIndexes();
2656 CompileDexFile(class_loader,
2657 method_set.GetDexFile(),
2658 dex_files,
2659 parallel_thread_pool_.get(),
2660 parallel_thread_count_,
2661 timings);
2662 }
2663 current_dex_to_dex_methods_ = nullptr;
2664
Andreas Gampe8d295f82015-01-20 14:50:21 -08002665 VLOG(compiler) << "Compile: " << GetMemoryUsageString(false);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002666}
2667
Mathieu Chartier90443472015-07-16 20:32:27 -07002668class CompileClassVisitor : public CompilationVisitor {
2669 public:
2670 explicit CompileClassVisitor(const ParallelCompilationManager* manager) : manager_(manager) {}
2671
2672 virtual void Visit(size_t class_def_index) REQUIRES(!Locks::mutator_lock_) OVERRIDE {
2673 ATRACE_CALL();
2674 const DexFile& dex_file = *manager_->GetDexFile();
2675 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
2676 ClassLinker* class_linker = manager_->GetClassLinker();
2677 jobject jclass_loader = manager_->GetClassLoader();
Mathieu Chartier90443472015-07-16 20:32:27 -07002678 ClassReference ref(&dex_file, class_def_index);
2679 // Skip compiling classes with generic verifier failures since they will still fail at runtime
2680 if (manager_->GetCompiler()->verification_results_->IsClassRejected(ref)) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07002681 return;
2682 }
Mathieu Chartier736b5602015-09-02 14:54:11 -07002683 // Use a scoped object access to perform to the quick SkipClass check.
2684 const char* descriptor = dex_file.GetClassDescriptor(class_def);
2685 ScopedObjectAccess soa(Thread::Current());
2686 StackHandleScope<3> hs(soa.Self());
2687 Handle<mirror::ClassLoader> class_loader(
Mathieu Chartier0795f232016-09-27 18:43:30 -07002688 hs.NewHandle(soa.Decode<mirror::ClassLoader>(jclass_loader)));
Mathieu Chartier736b5602015-09-02 14:54:11 -07002689 Handle<mirror::Class> klass(
2690 hs.NewHandle(class_linker->FindClass(soa.Self(), descriptor, class_loader)));
2691 Handle<mirror::DexCache> dex_cache;
Andreas Gampefa4333d2017-02-14 11:10:34 -08002692 if (klass == nullptr) {
Mathieu Chartier736b5602015-09-02 14:54:11 -07002693 soa.Self()->AssertPendingException();
2694 soa.Self()->ClearException();
2695 dex_cache = hs.NewHandle(class_linker->FindDexCache(soa.Self(), dex_file));
2696 } else if (SkipClass(jclass_loader, dex_file, klass.Get())) {
2697 return;
2698 } else {
2699 dex_cache = hs.NewHandle(klass->GetDexCache());
2700 }
2701
Mathieu Chartier90443472015-07-16 20:32:27 -07002702 const uint8_t* class_data = dex_file.GetClassData(class_def);
2703 if (class_data == nullptr) {
2704 // empty class, probably a marker interface
2705 return;
Brian Carlstrom7940e442013-07-12 13:46:57 -07002706 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002707
Mathieu Chartier736b5602015-09-02 14:54:11 -07002708 // Go to native so that we don't block GC during compilation.
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07002709 ScopedThreadSuspension sts(soa.Self(), kNative);
Mathieu Chartier736b5602015-09-02 14:54:11 -07002710
Mathieu Chartier90443472015-07-16 20:32:27 -07002711 CompilerDriver* const driver = manager_->GetCompiler();
2712
2713 // Can we run DEX-to-DEX compiler on this class ?
Andreas Gampe5eb0d382015-07-23 01:19:26 -07002714 optimizer::DexToDexCompilationLevel dex_to_dex_compilation_level =
Mathieu Chartier736b5602015-09-02 14:54:11 -07002715 GetDexToDexCompilationLevel(soa.Self(), *driver, jclass_loader, dex_file, class_def);
Andreas Gampe5eb0d382015-07-23 01:19:26 -07002716
Mathieu Chartier90443472015-07-16 20:32:27 -07002717 ClassDataItemIterator it(dex_file, class_data);
Mathieu Chartiere17cf242017-06-19 11:05:51 -07002718 it.SkipAllFields();
Mathieu Chartier90443472015-07-16 20:32:27 -07002719
2720 bool compilation_enabled = driver->IsClassToCompile(
2721 dex_file.StringByTypeIdx(class_def.class_idx_));
2722
Mathieu Chartierb7c273c2017-11-10 18:07:56 -08002723 // Compile direct and virtual methods.
2724 int64_t previous_method_idx = -1;
2725 while (it.HasNextMethod()) {
Mathieu Chartier90443472015-07-16 20:32:27 -07002726 uint32_t method_idx = it.GetMemberIndex();
Mathieu Chartierb7c273c2017-11-10 18:07:56 -08002727 if (method_idx == previous_method_idx) {
Mathieu Chartier90443472015-07-16 20:32:27 -07002728 // smali can create dex files with two encoded_methods sharing the same method_idx
2729 // http://code.google.com/p/smali/issues/detail?id=119
2730 it.Next();
2731 continue;
2732 }
Mathieu Chartierb7c273c2017-11-10 18:07:56 -08002733 previous_method_idx = method_idx;
Vladimir Marko8d6768d2017-03-14 10:13:21 +00002734 CompileMethod(soa.Self(),
2735 driver,
2736 it.GetMethodCodeItem(),
2737 it.GetMethodAccessFlags(),
2738 it.GetMethodInvokeType(class_def),
2739 class_def_index,
2740 method_idx,
2741 class_loader,
2742 dex_file,
2743 dex_to_dex_compilation_level,
2744 compilation_enabled,
2745 dex_cache);
Mathieu Chartier90443472015-07-16 20:32:27 -07002746 it.Next();
2747 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002748 DCHECK(!it.HasNext());
Brian Carlstrom7940e442013-07-12 13:46:57 -07002749 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002750
2751 private:
2752 const ParallelCompilationManager* const manager_;
2753};
Brian Carlstrom7940e442013-07-12 13:46:57 -07002754
Andreas Gampeace0dc12016-01-20 13:33:13 -08002755void CompilerDriver::CompileDexFile(jobject class_loader,
2756 const DexFile& dex_file,
Andreas Gampede7b4362014-07-28 18:38:57 -07002757 const std::vector<const DexFile*>& dex_files,
Andreas Gampeace0dc12016-01-20 13:33:13 -08002758 ThreadPool* thread_pool,
2759 size_t thread_count,
2760 TimingLogger* timings) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07002761 TimingLogger::ScopedTiming t("Compile Dex File", timings);
Ian Rogersbe7149f2013-08-20 09:29:39 -07002762 ParallelCompilationManager context(Runtime::Current()->GetClassLinker(), class_loader, this,
Andreas Gampede7b4362014-07-28 18:38:57 -07002763 &dex_file, dex_files, thread_pool);
Mathieu Chartier90443472015-07-16 20:32:27 -07002764 CompileClassVisitor visitor(&context);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002765 context.ForAll(0, dex_file.NumClassDefs(), &visitor, thread_count);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002766}
2767
Andreas Gampe5eb0d382015-07-23 01:19:26 -07002768void CompilerDriver::AddCompiledMethod(const MethodReference& method_ref,
2769 CompiledMethod* const compiled_method,
2770 size_t non_relative_linker_patch_count) {
Mathieu Chartierfc8b4222017-09-17 13:44:24 -07002771 DCHECK(GetCompiledMethod(method_ref) == nullptr) << method_ref.PrettyMethod();
2772 MethodTable::InsertResult result = compiled_methods_.Insert(method_ref,
2773 /*expected*/ nullptr,
2774 compiled_method);
Mathieu Chartieracab8d42016-11-23 13:45:58 -08002775 CHECK(result == MethodTable::kInsertResultSuccess);
2776 non_relative_linker_patch_count_.FetchAndAddRelaxed(non_relative_linker_patch_count);
Mathieu Chartierfc8b4222017-09-17 13:44:24 -07002777 DCHECK(GetCompiledMethod(method_ref) != nullptr) << method_ref.PrettyMethod();
Brian Carlstrom7940e442013-07-12 13:46:57 -07002778}
2779
Mathieu Chartierfc8b4222017-09-17 13:44:24 -07002780bool CompilerDriver::GetCompiledClass(const ClassReference& ref,
2781 mirror::Class::Status* status) const {
Andreas Gampebb846102017-05-11 21:03:35 -07002782 DCHECK(status != nullptr);
Mathieu Chartier1a088d42017-07-18 11:43:57 -07002783 // The table doesn't know if something wasn't inserted. For this case it will return
Jeff Haof1aa2652017-08-03 17:09:33 -07002784 // kStatusNotReady. To handle this, just assume anything we didn't try to verify is not compiled.
Mathieu Chartierfc8b4222017-09-17 13:44:24 -07002785 if (!compiled_classes_.Get(ref, status) ||
Jeff Haof1aa2652017-08-03 17:09:33 -07002786 *status < mirror::Class::kStatusRetryVerificationAtRuntime) {
Andreas Gampebb846102017-05-11 21:03:35 -07002787 return false;
Brian Carlstrom7940e442013-07-12 13:46:57 -07002788 }
Andreas Gampebb846102017-05-11 21:03:35 -07002789 return true;
Brian Carlstrom7940e442013-07-12 13:46:57 -07002790}
2791
Mathieu Chartierfc8b4222017-09-17 13:44:24 -07002792mirror::Class::Status CompilerDriver::GetClassStatus(const ClassReference& ref) const {
Nicolas Geoffray486dda02017-09-11 14:15:52 +01002793 mirror::Class::Status status = ClassStatus::kStatusNotReady;
2794 if (!GetCompiledClass(ref, &status)) {
Mathieu Chartierfc8b4222017-09-17 13:44:24 -07002795 classpath_classes_.Get(ref, &status);
Nicolas Geoffray486dda02017-09-11 14:15:52 +01002796 }
2797 return status;
2798}
2799
Mathieu Chartierfc8b4222017-09-17 13:44:24 -07002800void CompilerDriver::RecordClassStatus(const ClassReference& ref, mirror::Class::Status status) {
Nicolas Geoffrayade72d62016-12-15 13:20:02 +00002801 switch (status) {
Vladimir Marko72ab6842017-01-20 19:32:50 +00002802 case mirror::Class::kStatusErrorResolved:
2803 case mirror::Class::kStatusErrorUnresolved:
Jeff Hao0cb17282017-07-12 14:51:49 -07002804 case mirror::Class::kStatusNotReady:
2805 case mirror::Class::kStatusResolved:
Nicolas Geoffrayade72d62016-12-15 13:20:02 +00002806 case mirror::Class::kStatusRetryVerificationAtRuntime:
2807 case mirror::Class::kStatusVerified:
Jeff Hao0cb17282017-07-12 14:51:49 -07002808 case mirror::Class::kStatusSuperclassValidated:
Nicolas Geoffrayade72d62016-12-15 13:20:02 +00002809 case mirror::Class::kStatusInitialized:
Nicolas Geoffrayade72d62016-12-15 13:20:02 +00002810 break; // Expected states.
2811 default:
2812 LOG(FATAL) << "Unexpected class status for class "
Mathieu Chartierfc8b4222017-09-17 13:44:24 -07002813 << PrettyDescriptor(
2814 ref.dex_file->GetClassDescriptor(ref.dex_file->GetClassDef(ref.index)))
Nicolas Geoffrayade72d62016-12-15 13:20:02 +00002815 << " of " << status;
2816 }
2817
Mathieu Chartier1a088d42017-07-18 11:43:57 -07002818 ClassStateTable::InsertResult result;
Nicolas Geoffray486dda02017-09-11 14:15:52 +01002819 ClassStateTable* table = &compiled_classes_;
Mathieu Chartier1a088d42017-07-18 11:43:57 -07002820 do {
Mathieu Chartier1a088d42017-07-18 11:43:57 -07002821 mirror::Class::Status existing = mirror::Class::kStatusNotReady;
Mathieu Chartierfc8b4222017-09-17 13:44:24 -07002822 if (!table->Get(ref, &existing)) {
Nicolas Geoffray486dda02017-09-11 14:15:52 +01002823 // A classpath class.
Mathieu Chartier010f5cc2017-07-24 15:53:46 -07002824 if (kIsDebugBuild) {
2825 // Check to make sure it's not a dex file for an oat file we are compiling since these
2826 // should always succeed. These do not include classes in for used libraries.
Mathieu Chartier72041a02017-07-14 18:23:25 -07002827 for (const DexFile* dex_file : GetDexFilesForOatFile()) {
Mathieu Chartierfc8b4222017-09-17 13:44:24 -07002828 CHECK_NE(ref.dex_file, dex_file) << ref.dex_file->GetLocation();
Mathieu Chartier010f5cc2017-07-24 15:53:46 -07002829 }
2830 }
Mathieu Chartierfc8b4222017-09-17 13:44:24 -07002831 if (!classpath_classes_.HaveDexFile(ref.dex_file)) {
Nicolas Geoffray486dda02017-09-11 14:15:52 +01002832 // Boot classpath dex file.
2833 return;
2834 }
2835 table = &classpath_classes_;
Mathieu Chartierfc8b4222017-09-17 13:44:24 -07002836 table->Get(ref, &existing);
Mathieu Chartier010f5cc2017-07-24 15:53:46 -07002837 }
Mathieu Chartier1a088d42017-07-18 11:43:57 -07002838 if (existing >= status) {
2839 // Existing status is already better than we expect, break.
2840 break;
2841 }
Nicolas Geoffrayade72d62016-12-15 13:20:02 +00002842 // Update the status if we now have a greater one. This happens with vdex,
2843 // which records a class is verified, but does not resolve it.
Mathieu Chartierfc8b4222017-09-17 13:44:24 -07002844 result = table->Insert(ref, existing, status);
2845 CHECK(result != ClassStateTable::kInsertResultInvalidDexFile) << ref.dex_file->GetLocation();
Mathieu Chartier1a088d42017-07-18 11:43:57 -07002846 } while (result != ClassStateTable::kInsertResultSuccess);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07002847}
2848
Brian Carlstrom7940e442013-07-12 13:46:57 -07002849CompiledMethod* CompilerDriver::GetCompiledMethod(MethodReference ref) const {
Mathieu Chartieracab8d42016-11-23 13:45:58 -08002850 CompiledMethod* compiled_method = nullptr;
Mathieu Chartierfc8b4222017-09-17 13:44:24 -07002851 compiled_methods_.Get(ref, &compiled_method);
Mathieu Chartieracab8d42016-11-23 13:45:58 -08002852 return compiled_method;
Brian Carlstrom7940e442013-07-12 13:46:57 -07002853}
2854
Calin Juravlef1c6d9e2015-04-13 18:42:21 +01002855bool CompilerDriver::IsMethodVerifiedWithoutFailures(uint32_t method_idx,
2856 uint16_t class_def_idx,
2857 const DexFile& dex_file) const {
2858 const VerifiedMethod* verified_method = GetVerifiedMethod(&dex_file, method_idx);
2859 if (verified_method != nullptr) {
2860 return !verified_method->HasVerificationFailures();
2861 }
2862
2863 // If we can't find verification metadata, check if this is a system class (we trust that system
2864 // classes have their methods verified). If it's not, be conservative and assume the method
2865 // has not been verified successfully.
2866
2867 // TODO: When compiling the boot image it should be safe to assume that everything is verified,
2868 // even if methods are not found in the verification cache.
2869 const char* descriptor = dex_file.GetClassDescriptor(dex_file.GetClassDef(class_def_idx));
2870 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
2871 Thread* self = Thread::Current();
2872 ScopedObjectAccess soa(self);
2873 bool is_system_class = class_linker->FindSystemClass(self, descriptor) != nullptr;
2874 if (!is_system_class) {
2875 self->ClearException();
2876 }
2877 return is_system_class;
2878}
2879
Vladimir Markof4da6752014-08-01 19:04:18 +01002880size_t CompilerDriver::GetNonRelativeLinkerPatchCount() const {
Mathieu Chartieracab8d42016-11-23 13:45:58 -08002881 return non_relative_linker_patch_count_.LoadRelaxed();
Vladimir Markof4da6752014-08-01 19:04:18 +01002882}
2883
Mathieu Chartierc4ae9162016-04-07 13:19:19 -07002884void CompilerDriver::SetRequiresConstructorBarrier(Thread* self,
2885 const DexFile* dex_file,
2886 uint16_t class_def_index,
2887 bool requires) {
2888 WriterMutexLock mu(self, requires_constructor_barrier_lock_);
2889 requires_constructor_barrier_.emplace(ClassReference(dex_file, class_def_index), requires);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002890}
2891
Mathieu Chartier371bd832016-04-07 10:19:48 -07002892bool CompilerDriver::RequiresConstructorBarrier(Thread* self,
2893 const DexFile* dex_file,
Mathieu Chartierc4ae9162016-04-07 13:19:19 -07002894 uint16_t class_def_index) {
2895 ClassReference class_ref(dex_file, class_def_index);
2896 {
2897 ReaderMutexLock mu(self, requires_constructor_barrier_lock_);
2898 auto it = requires_constructor_barrier_.find(class_ref);
2899 if (it != requires_constructor_barrier_.end()) {
2900 return it->second;
2901 }
Mathieu Chartierb5d38612016-04-07 10:52:52 -07002902 }
Mathieu Chartierc4ae9162016-04-07 13:19:19 -07002903 WriterMutexLock mu(self, requires_constructor_barrier_lock_);
2904 const bool requires = RequiresConstructorBarrier(*dex_file, class_def_index);
2905 requires_constructor_barrier_.emplace(class_ref, requires);
2906 return requires;
Brian Carlstrom7940e442013-07-12 13:46:57 -07002907}
2908
Andreas Gampe8d295f82015-01-20 14:50:21 -08002909std::string CompilerDriver::GetMemoryUsageString(bool extended) const {
Mathieu Chartierab972ef2014-12-03 17:38:22 -08002910 std::ostringstream oss;
Calin Juravle69158982016-03-16 11:53:41 +00002911 const gc::Heap* const heap = Runtime::Current()->GetHeap();
Anton Kirilovdd9473b2016-01-28 15:08:01 +00002912 const size_t java_alloc = heap->GetBytesAllocated();
Calin Juravle69158982016-03-16 11:53:41 +00002913 oss << "arena alloc=" << PrettySize(max_arena_alloc_) << " (" << max_arena_alloc_ << "B)";
Anton Kirilovdd9473b2016-01-28 15:08:01 +00002914 oss << " java alloc=" << PrettySize(java_alloc) << " (" << java_alloc << "B)";
Elliott Hughes7bf5a262015-04-02 20:55:07 -07002915#if defined(__BIONIC__) || defined(__GLIBC__)
Anton Kirilovdd9473b2016-01-28 15:08:01 +00002916 const struct mallinfo info = mallinfo();
Mathieu Chartierab972ef2014-12-03 17:38:22 -08002917 const size_t allocated_space = static_cast<size_t>(info.uordblks);
2918 const size_t free_space = static_cast<size_t>(info.fordblks);
Anton Kirilovdd9473b2016-01-28 15:08:01 +00002919 oss << " native alloc=" << PrettySize(allocated_space) << " (" << allocated_space << "B)"
2920 << " free=" << PrettySize(free_space) << " (" << free_space << "B)";
Mathieu Chartierab972ef2014-12-03 17:38:22 -08002921#endif
Vladimir Marko35831e82015-09-11 11:59:18 +01002922 compiled_method_storage_.DumpMemoryUsage(oss, extended);
Mathieu Chartierab972ef2014-12-03 17:38:22 -08002923 return oss.str();
2924}
2925
Jeff Haodcdc85b2015-12-04 14:06:18 -08002926bool CompilerDriver::MayInlineInternal(const DexFile* inlined_from,
2927 const DexFile* inlined_into) const {
2928 // We're not allowed to inline across dex files if we're the no-inline-from dex file.
2929 if (inlined_from != inlined_into &&
Vladimir Marko47496c22016-01-27 16:15:08 +00002930 compiler_options_->GetNoInlineFromDexFile() != nullptr &&
2931 ContainsElement(*compiler_options_->GetNoInlineFromDexFile(), inlined_from)) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002932 return false;
2933 }
2934
2935 return true;
2936}
2937
Andreas Gampeace0dc12016-01-20 13:33:13 -08002938void CompilerDriver::InitializeThreadPools() {
2939 size_t parallel_count = parallel_thread_count_ > 0 ? parallel_thread_count_ - 1 : 0;
2940 parallel_thread_pool_.reset(
2941 new ThreadPool("Compiler driver thread pool", parallel_count));
2942 single_thread_pool_.reset(new ThreadPool("Single-threaded Compiler driver thread pool", 0));
2943}
2944
2945void CompilerDriver::FreeThreadPools() {
2946 parallel_thread_pool_.reset();
2947 single_thread_pool_.reset();
2948}
2949
Mathieu Chartier72041a02017-07-14 18:23:25 -07002950void CompilerDriver::SetDexFilesForOatFile(const std::vector<const DexFile*>& dex_files) {
2951 dex_files_for_oat_file_ = dex_files;
Nicolas Geoffray486dda02017-09-11 14:15:52 +01002952 compiled_classes_.AddDexFiles(dex_files);
2953}
2954
2955void CompilerDriver::SetClasspathDexFiles(const std::vector<const DexFile*>& dex_files) {
2956 classpath_classes_.AddDexFiles(dex_files);
Mathieu Chartier72041a02017-07-14 18:23:25 -07002957}
2958
Brian Carlstrom7940e442013-07-12 13:46:57 -07002959} // namespace art