blob: 8c276bb706e285c65556c82f2847763a20334c41 [file] [log] [blame]
Brian Carlstrom7940e442013-07-12 13:46:57 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "compiler_driver.h"
18
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070019#include <unistd.h>
Andreas Gampeb0f370e2014-09-25 22:51:40 -070020#include <unordered_set>
Anwar Ghuloum67f99412013-08-12 14:19:48 -070021#include <vector>
Brian Carlstrom7940e442013-07-12 13:46:57 -070022
Mathieu Chartierab972ef2014-12-03 17:38:22 -080023#ifndef __APPLE__
24#include <malloc.h> // For mallinfo
25#endif
26
Narayan Kamathe3eae5e2016-10-27 11:47:30 +010027#include "android-base/strings.h"
28
Mathieu Chartierc7853442015-03-27 14:35:38 -070029#include "art_field-inl.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070030#include "art_method-inl.h"
Andreas Gampef0446e92017-05-16 13:51:57 -070031#include "base/arena_allocator.h"
David Brazdild9c90372016-09-14 16:53:55 +010032#include "base/array_ref.h"
Vladimir Marko492a7fa2016-06-01 18:38:43 +010033#include "base/bit_vector.h"
Andreas Gampe542451c2016-07-26 09:02:02 -070034#include "base/enums.h"
Andreas Gampe170331f2017-12-07 18:41:03 -080035#include "base/logging.h" // For VLOG
Brian Carlstrom7940e442013-07-12 13:46:57 -070036#include "base/stl_util.h"
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -080037#include "base/systrace.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010038#include "base/time_utils.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070039#include "base/timing_logger.h"
Vladimir Marko3481ba22015-04-13 12:22:36 +010040#include "class_linker-inl.h"
Vladimir Markod8dbc8d2017-09-20 13:37:47 +010041#include "compiled_method-inl.h"
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +000042#include "compiler.h"
Nicolas Geoffray6bb7f1b2016-11-03 10:52:49 +000043#include "compiler_callbacks.h"
Vladimir Markobe0e5462014-02-26 11:24:15 +000044#include "compiler_driver-inl.h"
Mathieu Chartierc8c8d5f2018-05-22 11:56:14 -070045#include "dex/class_accessor-inl.h"
David Sehrb2ec9f52018-02-21 13:20:31 -080046#include "dex/descriptors_names.h"
David Sehr9e734c72018-01-04 17:56:19 -080047#include "dex/dex_file-inl.h"
48#include "dex/dex_file_annotations.h"
49#include "dex/dex_instruction-inl.h"
Andreas Gampe5eb0d382015-07-23 01:19:26 -070050#include "dex/dex_to_dex_compiler.h"
Vladimir Markoc7f83202014-01-24 17:55:18 +000051#include "dex/verification_results.h"
Vladimir Marko2730db02014-01-27 11:15:17 +000052#include "dex/verified_method.h"
Steven Morelande431e272017-07-18 16:53:49 -070053#include "dex_compilation_unit.h"
Mark Mendellae9fd932014-02-10 16:14:35 -080054#include "driver/compiler_options.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070055#include "gc/accounting/card_table-inl.h"
56#include "gc/accounting/heap_bitmap.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070057#include "gc/space/image_space.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070058#include "gc/space/space.h"
Steven Morelande431e272017-07-18 16:53:49 -070059#include "handle_scope-inl.h"
60#include "intrinsics_enum.h"
Vladimir Markoa3ad0cd2018-05-04 10:06:38 +010061#include "jni/jni_internal.h"
Vladimir Markod8dbc8d2017-09-20 13:37:47 +010062#include "linker/linker_patch.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070063#include "mirror/class-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -070064#include "mirror/class_loader.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070065#include "mirror/dex_cache-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070066#include "mirror/object-inl.h"
Andreas Gampec6ea7d02017-02-01 16:46:28 -080067#include "mirror/object-refvisitor-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070068#include "mirror/object_array-inl.h"
69#include "mirror/throwable.h"
Steven Morelande431e272017-07-18 16:53:49 -070070#include "object_lock.h"
David Sehr82d046e2018-04-23 08:14:19 -070071#include "profile/profile_compilation_info.h"
Steven Morelande431e272017-07-18 16:53:49 -070072#include "runtime.h"
Orion Hodson26ef34c2017-11-01 13:32:41 +000073#include "runtime_intrinsics.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070074#include "scoped_thread_state_change-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070075#include "thread.h"
Andreas Gampeb0f370e2014-09-25 22:51:40 -070076#include "thread_list.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070077#include "thread_pool.h"
Ian Rogers848871b2013-08-05 10:56:33 -070078#include "trampolines/trampoline_compiler.h"
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +010079#include "transaction.h"
Mathieu Chartier93764b82017-07-17 14:51:53 -070080#include "utils/atomic_dex_ref_map-inl.h"
Vladimir Marko20f85592015-03-19 10:07:02 +000081#include "utils/dex_cache_arrays_layout-inl.h"
Andreas Gampee21dc3d2014-12-08 16:59:43 -080082#include "utils/swap_space.h"
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +000083#include "vdex_file.h"
Vladimir Marko2bc47802014-02-10 09:43:07 +000084#include "verifier/method_verifier-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -070085#include "verifier/method_verifier.h"
Nicolas Geoffray08025182016-10-25 17:20:18 +010086#include "verifier/verifier_deps.h"
Andreas Gampe6d7abbd2017-04-24 13:19:09 -070087#include "verifier/verifier_enums.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070088
Brian Carlstrom7940e442013-07-12 13:46:57 -070089namespace art {
90
Mathieu Chartier8e219ae2014-08-19 14:29:46 -070091static constexpr bool kTimeCompileMethod = !kIsDebugBuild;
92
Calin Juravle226501b2015-12-11 14:41:31 +000093// Print additional info during profile guided compilation.
94static constexpr bool kDebugProfileGuidedCompilation = false;
95
Chang Xing70f689d2017-06-08 17:16:12 -070096// Max encoded fields allowed for initializing app image. Hardcode the number for now
97// because 5000 should be large enough.
98static constexpr uint32_t kMaxEncodedFields = 5000;
99
Brian Carlstrom7940e442013-07-12 13:46:57 -0700100static double Percentage(size_t x, size_t y) {
101 return 100.0 * (static_cast<double>(x)) / (static_cast<double>(x + y));
102}
103
104static void DumpStat(size_t x, size_t y, const char* str) {
105 if (x == 0 && y == 0) {
106 return;
107 }
Ian Rogerse732ef12013-10-09 15:22:24 -0700108 LOG(INFO) << Percentage(x, y) << "% of " << str << " for " << (x + y) << " cases";
Brian Carlstrom7940e442013-07-12 13:46:57 -0700109}
110
Vladimir Markof096aad2014-01-23 15:51:58 +0000111class CompilerDriver::AOTCompilationStats {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700112 public:
113 AOTCompilationStats()
114 : stats_lock_("AOT compilation statistics lock"),
Brian Carlstrom7940e442013-07-12 13:46:57 -0700115 resolved_instance_fields_(0), unresolved_instance_fields_(0),
116 resolved_local_static_fields_(0), resolved_static_fields_(0), unresolved_static_fields_(0),
117 type_based_devirtualization_(0),
118 safe_casts_(0), not_safe_casts_(0) {
119 for (size_t i = 0; i <= kMaxInvokeType; i++) {
120 resolved_methods_[i] = 0;
121 unresolved_methods_[i] = 0;
122 virtual_made_direct_[i] = 0;
123 direct_calls_to_boot_[i] = 0;
124 direct_methods_to_boot_[i] = 0;
125 }
126 }
127
128 void Dump() {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700129 DumpStat(resolved_instance_fields_, unresolved_instance_fields_, "instance fields resolved");
130 DumpStat(resolved_local_static_fields_ + resolved_static_fields_, unresolved_static_fields_,
131 "static fields resolved");
132 DumpStat(resolved_local_static_fields_, resolved_static_fields_ + unresolved_static_fields_,
133 "static fields local to a class");
134 DumpStat(safe_casts_, not_safe_casts_, "check-casts removed based on type information");
135 // Note, the code below subtracts the stat value so that when added to the stat value we have
136 // 100% of samples. TODO: clean this up.
137 DumpStat(type_based_devirtualization_,
138 resolved_methods_[kVirtual] + unresolved_methods_[kVirtual] +
139 resolved_methods_[kInterface] + unresolved_methods_[kInterface] -
140 type_based_devirtualization_,
141 "virtual/interface calls made direct based on type information");
142
143 for (size_t i = 0; i <= kMaxInvokeType; i++) {
144 std::ostringstream oss;
145 oss << static_cast<InvokeType>(i) << " methods were AOT resolved";
146 DumpStat(resolved_methods_[i], unresolved_methods_[i], oss.str().c_str());
147 if (virtual_made_direct_[i] > 0) {
148 std::ostringstream oss2;
149 oss2 << static_cast<InvokeType>(i) << " methods made direct";
150 DumpStat(virtual_made_direct_[i],
151 resolved_methods_[i] + unresolved_methods_[i] - virtual_made_direct_[i],
152 oss2.str().c_str());
153 }
154 if (direct_calls_to_boot_[i] > 0) {
155 std::ostringstream oss2;
156 oss2 << static_cast<InvokeType>(i) << " method calls are direct into boot";
157 DumpStat(direct_calls_to_boot_[i],
158 resolved_methods_[i] + unresolved_methods_[i] - direct_calls_to_boot_[i],
159 oss2.str().c_str());
160 }
161 if (direct_methods_to_boot_[i] > 0) {
162 std::ostringstream oss2;
163 oss2 << static_cast<InvokeType>(i) << " method calls have methods in boot";
164 DumpStat(direct_methods_to_boot_[i],
165 resolved_methods_[i] + unresolved_methods_[i] - direct_methods_to_boot_[i],
166 oss2.str().c_str());
167 }
168 }
169 }
170
171// Allow lossy statistics in non-debug builds.
172#ifndef NDEBUG
173#define STATS_LOCK() MutexLock mu(Thread::Current(), stats_lock_)
174#else
175#define STATS_LOCK()
176#endif
177
Mathieu Chartier90443472015-07-16 20:32:27 -0700178 void ResolvedInstanceField() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700179 STATS_LOCK();
180 resolved_instance_fields_++;
181 }
182
Mathieu Chartier90443472015-07-16 20:32:27 -0700183 void UnresolvedInstanceField() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700184 STATS_LOCK();
185 unresolved_instance_fields_++;
186 }
187
Mathieu Chartier90443472015-07-16 20:32:27 -0700188 void ResolvedLocalStaticField() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700189 STATS_LOCK();
190 resolved_local_static_fields_++;
191 }
192
Mathieu Chartier90443472015-07-16 20:32:27 -0700193 void ResolvedStaticField() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700194 STATS_LOCK();
195 resolved_static_fields_++;
196 }
197
Mathieu Chartier90443472015-07-16 20:32:27 -0700198 void UnresolvedStaticField() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700199 STATS_LOCK();
200 unresolved_static_fields_++;
201 }
202
203 // Indicate that type information from the verifier led to devirtualization.
Mathieu Chartier90443472015-07-16 20:32:27 -0700204 void PreciseTypeDevirtualization() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700205 STATS_LOCK();
206 type_based_devirtualization_++;
207 }
208
Brian Carlstrom7940e442013-07-12 13:46:57 -0700209 // A check-cast could be eliminated due to verifier type analysis.
Mathieu Chartier90443472015-07-16 20:32:27 -0700210 void SafeCast() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700211 STATS_LOCK();
212 safe_casts_++;
213 }
214
215 // A check-cast couldn't be eliminated due to verifier type analysis.
Mathieu Chartier90443472015-07-16 20:32:27 -0700216 void NotASafeCast() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700217 STATS_LOCK();
218 not_safe_casts_++;
219 }
220
221 private:
222 Mutex stats_lock_;
223
Brian Carlstrom7940e442013-07-12 13:46:57 -0700224 size_t resolved_instance_fields_;
225 size_t unresolved_instance_fields_;
226
227 size_t resolved_local_static_fields_;
228 size_t resolved_static_fields_;
229 size_t unresolved_static_fields_;
230 // Type based devirtualization for invoke interface and virtual.
231 size_t type_based_devirtualization_;
232
233 size_t resolved_methods_[kMaxInvokeType + 1];
234 size_t unresolved_methods_[kMaxInvokeType + 1];
235 size_t virtual_made_direct_[kMaxInvokeType + 1];
236 size_t direct_calls_to_boot_[kMaxInvokeType + 1];
237 size_t direct_methods_to_boot_[kMaxInvokeType + 1];
238
239 size_t safe_casts_;
240 size_t not_safe_casts_;
241
242 DISALLOW_COPY_AND_ASSIGN(AOTCompilationStats);
243};
244
Jeff Haodcdc85b2015-12-04 14:06:18 -0800245CompilerDriver::CompilerDriver(
246 const CompilerOptions* compiler_options,
247 VerificationResults* verification_results,
Jeff Haodcdc85b2015-12-04 14:06:18 -0800248 Compiler::Kind compiler_kind,
Vladimir Markodc4bcce2018-06-21 16:15:42 +0100249 HashSet<std::string>* image_classes,
Vladimir Marko944da602016-02-19 12:27:55 +0000250 size_t thread_count,
Vladimir Marko944da602016-02-19 12:27:55 +0000251 int swap_fd,
Calin Juravle998c2162015-12-21 15:39:33 +0200252 const ProfileCompilationInfo* profile_compilation_info)
Calin Juravle226501b2015-12-11 14:41:31 +0000253 : compiler_options_(compiler_options),
Brian Carlstrom6449c622014-02-10 23:48:36 -0800254 verification_results_(verification_results),
Ian Rogers72d32622014-05-06 16:20:11 -0700255 compiler_(Compiler::Create(this, compiler_kind)),
Jeff Hao48699fb2015-04-06 14:21:37 -0700256 compiler_kind_(compiler_kind),
Vladimir Marko54159c62018-06-20 14:30:08 +0100257 image_classes_(std::move(image_classes)),
Andreas Gampef39208f2017-10-19 15:06:59 -0700258 number_of_soft_verifier_failures_(0),
Andreas Gampe6cf49e52015-03-05 13:08:45 -0800259 had_hard_verifier_failure_(false),
Andreas Gampeace0dc12016-01-20 13:33:13 -0800260 parallel_thread_count_(thread_count),
Brian Carlstrom7940e442013-07-12 13:46:57 -0700261 stats_(new AOTCompilationStats),
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700262 compiler_context_(nullptr),
Calin Juravle998c2162015-12-21 15:39:33 +0200263 compiled_method_storage_(swap_fd),
Calin Juravle69158982016-03-16 11:53:41 +0000264 profile_compilation_info_(profile_compilation_info),
Vladimir Marko492a7fa2016-06-01 18:38:43 +0100265 max_arena_alloc_(0),
Mathieu Chartiera79efdb2018-01-18 16:31:01 -0800266 dex_to_dex_compiler_(this) {
Brian Carlstrom6449c622014-02-10 23:48:36 -0800267 DCHECK(compiler_options_ != nullptr);
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700268
Ian Rogers72d32622014-05-06 16:20:11 -0700269 compiler_->Init();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700270
Vladimir Markoaad75c62016-10-03 08:46:48 +0000271 if (GetCompilerOptions().IsBootImage()) {
Vladimir Markodc4bcce2018-06-21 16:15:42 +0100272 CHECK(image_classes_ != nullptr) << "Expected image classes for boot image";
Mathieu Chartierc5dd3192015-12-09 16:38:30 -0800273 }
Andreas Gampecac31ad2017-11-06 20:01:17 -0800274
275 compiled_method_storage_.SetDedupeEnabled(compiler_options_->DeduplicateCode());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700276}
277
278CompilerDriver::~CompilerDriver() {
Mathieu Chartier93764b82017-07-17 14:51:53 -0700279 compiled_methods_.Visit([this](const DexFileReference& ref ATTRIBUTE_UNUSED,
Mathieu Chartieracab8d42016-11-23 13:45:58 -0800280 CompiledMethod* method) {
281 if (method != nullptr) {
282 CompiledMethod::ReleaseSwapAllocatedCompiledMethod(this, method);
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800283 }
Mathieu Chartieracab8d42016-11-23 13:45:58 -0800284 });
Ian Rogers72d32622014-05-06 16:20:11 -0700285 compiler_->UnInit();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700286}
287
Vladimir Marko35831e82015-09-11 11:59:18 +0100288
Vladimir Markoa0431112018-06-25 09:32:54 +0100289#define CREATE_TRAMPOLINE(type, abi, offset) \
290 if (Is64BitInstructionSet(GetCompilerOptions().GetInstructionSet())) { \
291 return CreateTrampoline64(GetCompilerOptions().GetInstructionSet(), \
292 abi, \
293 type ## _ENTRYPOINT_OFFSET(PointerSize::k64, offset)); \
294 } else { \
295 return CreateTrampoline32(GetCompilerOptions().GetInstructionSet(), \
296 abi, \
297 type ## _ENTRYPOINT_OFFSET(PointerSize::k32, offset)); \
Ian Rogersdd7624d2014-03-14 17:43:00 -0700298 }
299
Vladimir Marko93205e32016-04-13 11:59:46 +0100300std::unique_ptr<const std::vector<uint8_t>> CompilerDriver::CreateJniDlsymLookup() const {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700301 CREATE_TRAMPOLINE(JNI, kJniAbi, pDlsymLookup)
Ian Rogers848871b2013-08-05 10:56:33 -0700302}
303
Vladimir Marko93205e32016-04-13 11:59:46 +0100304std::unique_ptr<const std::vector<uint8_t>> CompilerDriver::CreateQuickGenericJniTrampoline()
305 const {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700306 CREATE_TRAMPOLINE(QUICK, kQuickAbi, pQuickGenericJniTrampoline)
Andreas Gampe2da88232014-02-27 12:26:20 -0800307}
308
Vladimir Marko93205e32016-04-13 11:59:46 +0100309std::unique_ptr<const std::vector<uint8_t>> CompilerDriver::CreateQuickImtConflictTrampoline()
310 const {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700311 CREATE_TRAMPOLINE(QUICK, kQuickAbi, pQuickImtConflictTrampoline)
Jeff Hao88474b42013-10-23 16:24:40 -0700312}
313
Vladimir Marko93205e32016-04-13 11:59:46 +0100314std::unique_ptr<const std::vector<uint8_t>> CompilerDriver::CreateQuickResolutionTrampoline()
315 const {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700316 CREATE_TRAMPOLINE(QUICK, kQuickAbi, pQuickResolutionTrampoline)
Brian Carlstrom7940e442013-07-12 13:46:57 -0700317}
318
Vladimir Marko93205e32016-04-13 11:59:46 +0100319std::unique_ptr<const std::vector<uint8_t>> CompilerDriver::CreateQuickToInterpreterBridge()
320 const {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700321 CREATE_TRAMPOLINE(QUICK, kQuickAbi, pQuickToInterpreterBridge)
Brian Carlstrom7940e442013-07-12 13:46:57 -0700322}
Ian Rogersdd7624d2014-03-14 17:43:00 -0700323#undef CREATE_TRAMPOLINE
Brian Carlstrom7940e442013-07-12 13:46:57 -0700324
325void CompilerDriver::CompileAll(jobject class_loader,
Brian Carlstrom45602482013-07-21 22:07:55 -0700326 const std::vector<const DexFile*>& dex_files,
Ian Rogers3d504072014-03-01 09:16:49 -0800327 TimingLogger* timings) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700328 DCHECK(!Runtime::Current()->IsStarted());
Andreas Gampeace0dc12016-01-20 13:33:13 -0800329
330 InitializeThreadPools();
331
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000332 PreCompile(class_loader, dex_files, timings);
Vladimir Markoaad75c62016-10-03 08:46:48 +0000333 if (GetCompilerOptions().IsBootImage()) {
Nicolas Geoffray762869d2016-07-15 15:28:35 +0100334 // We don't need to setup the intrinsics for non boot image compilation, as
335 // those compilations will pick up a boot image that have the ArtMethod already
336 // set with the intrinsics flag.
Orion Hodson26ef34c2017-11-01 13:32:41 +0000337 InitializeIntrinsics();
Nicolas Geoffray762869d2016-07-15 15:28:35 +0100338 }
Andreas Gampe740667a2015-09-15 17:55:06 -0700339 // Compile:
340 // 1) Compile all classes and methods enabled for compilation. May fall back to dex-to-dex
341 // compilation.
Nicolas Geoffray49cda062017-04-21 13:08:25 +0100342 if (GetCompilerOptions().IsAnyCompilationEnabled()) {
Andreas Gampeace0dc12016-01-20 13:33:13 -0800343 Compile(class_loader, dex_files, timings);
Andreas Gampe740667a2015-09-15 17:55:06 -0700344 }
Nicolas Geoffray2d8801f2017-11-28 15:50:07 +0000345 if (GetCompilerOptions().GetDumpStats()) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700346 stats_->Dump();
347 }
Andreas Gampeace0dc12016-01-20 13:33:13 -0800348
349 FreeThreadPools();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700350}
351
Mathieu Chartiera79efdb2018-01-18 16:31:01 -0800352static optimizer::DexToDexCompiler::CompilationLevel GetDexToDexCompilationLevel(
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700353 Thread* self, const CompilerDriver& driver, Handle<mirror::ClassLoader> class_loader,
354 const DexFile& dex_file, const DexFile::ClassDef& class_def)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700355 REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffrayf3075272018-01-08 12:41:19 +0000356 // When the dex file is uncompressed in the APK, we do not generate a copy in the .vdex
357 // file. As a result, dex2oat will map the dex file read-only, and we only need to check
358 // that to know if we can do quickening.
359 if (dex_file.GetContainer() != nullptr && dex_file.GetContainer()->IsReadOnly()) {
360 return optimizer::DexToDexCompiler::CompilationLevel::kDontDexToDexCompile;
361 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800362 auto* const runtime = Runtime::Current();
Nicolas Geoffray49cda062017-04-21 13:08:25 +0100363 DCHECK(driver.GetCompilerOptions().IsQuickeningCompilationEnabled());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700364 const char* descriptor = dex_file.GetClassDescriptor(class_def);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800365 ClassLinker* class_linker = runtime->GetClassLinker();
Vladimir Markoa8bba7d2018-05-30 15:18:48 +0100366 ObjPtr<mirror::Class> klass = class_linker->FindClass(self, descriptor, class_loader);
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700367 if (klass == nullptr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700368 CHECK(self->IsExceptionPending());
369 self->ClearException();
Mathieu Chartiera79efdb2018-01-18 16:31:01 -0800370 return optimizer::DexToDexCompiler::CompilationLevel::kDontDexToDexCompile;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700371 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700372 // DexToDex at the kOptimize level may introduce quickened opcodes, which replace symbolic
373 // references with actual offsets. We cannot re-verify such instructions.
374 //
375 // We store the verification information in the class status in the oat file, which the linker
376 // can validate (checksums) and use to skip load-time verification. It is thus safe to
377 // optimize when a class has been fully verified before.
Mathieu Chartiera79efdb2018-01-18 16:31:01 -0800378 optimizer::DexToDexCompiler::CompilationLevel max_level =
379 optimizer::DexToDexCompiler::CompilationLevel::kOptimize;
Alex Lighte40dd382017-01-25 17:44:53 -0800380 if (driver.GetCompilerOptions().GetDebuggable()) {
381 // We are debuggable so definitions of classes might be changed. We don't want to do any
382 // optimizations that could break that.
Mathieu Chartiera79efdb2018-01-18 16:31:01 -0800383 max_level = optimizer::DexToDexCompiler::CompilationLevel::kDontDexToDexCompile;
Alex Lighte40dd382017-01-25 17:44:53 -0800384 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700385 if (klass->IsVerified()) {
Sebastien Hertz75021222013-07-16 18:34:50 +0200386 // Class is verified so we can enable DEX-to-DEX compilation for performance.
Alex Lighte40dd382017-01-25 17:44:53 -0800387 return max_level;
Sebastien Hertz75021222013-07-16 18:34:50 +0200388 } else {
Andreas Gampe1a4bc7f2017-03-27 14:57:30 -0700389 // Class verification has failed: do not run DEX-to-DEX optimizations.
Mathieu Chartiera79efdb2018-01-18 16:31:01 -0800390 return optimizer::DexToDexCompiler::CompilationLevel::kDontDexToDexCompile;
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700391 }
392}
393
Mathieu Chartiera79efdb2018-01-18 16:31:01 -0800394static optimizer::DexToDexCompiler::CompilationLevel GetDexToDexCompilationLevel(
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700395 Thread* self,
396 const CompilerDriver& driver,
397 jobject jclass_loader,
398 const DexFile& dex_file,
399 const DexFile::ClassDef& class_def) {
400 ScopedObjectAccess soa(self);
401 StackHandleScope<1> hs(soa.Self());
402 Handle<mirror::ClassLoader> class_loader(
Mathieu Chartier0795f232016-09-27 18:43:30 -0700403 hs.NewHandle(soa.Decode<mirror::ClassLoader>(jclass_loader)));
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700404 return GetDexToDexCompilationLevel(self, driver, class_loader, dex_file, class_def);
405}
406
407// Does the runtime for the InstructionSet provide an implementation returned by
408// GetQuickGenericJniStub allowing down calls that aren't compiled using a JNI compiler?
409static bool InstructionSetHasGenericJniStub(InstructionSet isa) {
410 switch (isa) {
Vladimir Marko33bff252017-11-01 14:35:42 +0000411 case InstructionSet::kArm:
412 case InstructionSet::kArm64:
413 case InstructionSet::kThumb2:
414 case InstructionSet::kMips:
415 case InstructionSet::kMips64:
416 case InstructionSet::kX86:
417 case InstructionSet::kX86_64: return true;
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700418 default: return false;
419 }
420}
421
Andreas Gampe3c060ad2018-01-22 13:07:49 -0800422template <typename CompileFn>
423static void CompileMethodHarness(
424 Thread* self,
425 CompilerDriver* driver,
426 const DexFile::CodeItem* code_item,
427 uint32_t access_flags,
428 InvokeType invoke_type,
429 uint16_t class_def_idx,
430 uint32_t method_idx,
431 Handle<mirror::ClassLoader> class_loader,
432 const DexFile& dex_file,
433 optimizer::DexToDexCompiler::CompilationLevel dex_to_dex_compilation_level,
434 bool compilation_enabled,
435 Handle<mirror::DexCache> dex_cache,
436 CompileFn compile_fn) {
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700437 DCHECK(driver != nullptr);
Andreas Gampe3c060ad2018-01-22 13:07:49 -0800438 CompiledMethod* compiled_method;
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700439 uint64_t start_ns = kTimeCompileMethod ? NanoTime() : 0;
440 MethodReference method_ref(&dex_file, method_idx);
441
Andreas Gampe3c060ad2018-01-22 13:07:49 -0800442 compiled_method = compile_fn(self,
443 driver,
444 code_item,
445 access_flags,
446 invoke_type,
447 class_def_idx,
448 method_idx,
449 class_loader,
450 dex_file,
451 dex_to_dex_compilation_level,
452 compilation_enabled,
453 dex_cache);
Igor Murashkin9d4b6da2016-07-29 09:51:58 -0700454
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700455 if (kTimeCompileMethod) {
456 uint64_t duration_ns = NanoTime() - start_ns;
457 if (duration_ns > MsToNs(driver->GetCompiler()->GetMaximumCompilationTimeBeforeWarning())) {
David Sehr709b0702016-10-13 09:12:37 -0700458 LOG(WARNING) << "Compilation of " << dex_file.PrettyMethod(method_idx)
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700459 << " took " << PrettyDuration(duration_ns);
460 }
461 }
462
463 if (compiled_method != nullptr) {
Vladimir Marko8e524ad2018-07-13 10:27:43 +0100464 driver->AddCompiledMethod(method_ref, compiled_method);
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700465 }
466
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700467 if (self->IsExceptionPending()) {
468 ScopedObjectAccess soa(self);
David Sehr709b0702016-10-13 09:12:37 -0700469 LOG(FATAL) << "Unexpected exception compiling: " << dex_file.PrettyMethod(method_idx) << "\n"
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700470 << self->GetException()->Dump();
Sebastien Hertz75021222013-07-16 18:34:50 +0200471 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700472}
473
Andreas Gampe3c060ad2018-01-22 13:07:49 -0800474static void CompileMethodDex2Dex(
475 Thread* self,
476 CompilerDriver* driver,
477 const DexFile::CodeItem* code_item,
478 uint32_t access_flags,
479 InvokeType invoke_type,
480 uint16_t class_def_idx,
481 uint32_t method_idx,
482 Handle<mirror::ClassLoader> class_loader,
483 const DexFile& dex_file,
484 optimizer::DexToDexCompiler::CompilationLevel dex_to_dex_compilation_level,
485 bool compilation_enabled,
486 Handle<mirror::DexCache> dex_cache) {
487 auto dex_2_dex_fn = [](Thread* self ATTRIBUTE_UNUSED,
488 CompilerDriver* driver,
489 const DexFile::CodeItem* code_item,
490 uint32_t access_flags,
491 InvokeType invoke_type,
492 uint16_t class_def_idx,
493 uint32_t method_idx,
494 Handle<mirror::ClassLoader> class_loader,
495 const DexFile& dex_file,
496 optimizer::DexToDexCompiler::CompilationLevel dex_to_dex_compilation_level,
497 bool compilation_enabled ATTRIBUTE_UNUSED,
498 Handle<mirror::DexCache> dex_cache ATTRIBUTE_UNUSED) -> CompiledMethod* {
499 DCHECK(driver != nullptr);
500 MethodReference method_ref(&dex_file, method_idx);
501
502 optimizer::DexToDexCompiler* const compiler = &driver->GetDexToDexCompiler();
503
504 if (compiler->ShouldCompileMethod(method_ref)) {
505 VerificationResults* results = driver->GetVerificationResults();
506 DCHECK(results != nullptr);
507 const VerifiedMethod* verified_method = results->GetVerifiedMethod(method_ref);
508 // Do not optimize if a VerifiedMethod is missing. SafeCast elision,
509 // for example, relies on it.
510 return compiler->CompileMethod(
511 code_item,
512 access_flags,
513 invoke_type,
514 class_def_idx,
515 method_idx,
516 class_loader,
517 dex_file,
518 (verified_method != nullptr)
519 ? dex_to_dex_compilation_level
520 : optimizer::DexToDexCompiler::CompilationLevel::kDontDexToDexCompile);
521 }
522 return nullptr;
523 };
524 CompileMethodHarness(self,
525 driver,
526 code_item,
527 access_flags,
528 invoke_type,
529 class_def_idx,
530 method_idx,
531 class_loader,
532 dex_file,
533 dex_to_dex_compilation_level,
534 compilation_enabled,
535 dex_cache,
536 dex_2_dex_fn);
537}
538
539static void CompileMethodQuick(
540 Thread* self,
541 CompilerDriver* driver,
542 const DexFile::CodeItem* code_item,
543 uint32_t access_flags,
544 InvokeType invoke_type,
545 uint16_t class_def_idx,
546 uint32_t method_idx,
547 Handle<mirror::ClassLoader> class_loader,
548 const DexFile& dex_file,
549 optimizer::DexToDexCompiler::CompilationLevel dex_to_dex_compilation_level,
550 bool compilation_enabled,
551 Handle<mirror::DexCache> dex_cache) {
552 auto quick_fn = [](
553 Thread* self,
554 CompilerDriver* driver,
555 const DexFile::CodeItem* code_item,
556 uint32_t access_flags,
557 InvokeType invoke_type,
558 uint16_t class_def_idx,
559 uint32_t method_idx,
560 Handle<mirror::ClassLoader> class_loader,
561 const DexFile& dex_file,
562 optimizer::DexToDexCompiler::CompilationLevel dex_to_dex_compilation_level,
563 bool compilation_enabled,
564 Handle<mirror::DexCache> dex_cache) {
565 DCHECK(driver != nullptr);
566 CompiledMethod* compiled_method = nullptr;
567 MethodReference method_ref(&dex_file, method_idx);
568
569 if ((access_flags & kAccNative) != 0) {
570 // Are we extracting only and have support for generic JNI down calls?
571 if (!driver->GetCompilerOptions().IsJniCompilationEnabled() &&
Vladimir Markoa0431112018-06-25 09:32:54 +0100572 InstructionSetHasGenericJniStub(driver->GetCompilerOptions().GetInstructionSet())) {
Andreas Gampe3c060ad2018-01-22 13:07:49 -0800573 // Leaving this empty will trigger the generic JNI version
574 } else {
575 // Query any JNI optimization annotations such as @FastNative or @CriticalNative.
576 access_flags |= annotations::GetNativeMethodAnnotationAccessFlags(
577 dex_file, dex_file.GetClassDef(class_def_idx), method_idx);
578
579 compiled_method = driver->GetCompiler()->JniCompile(
580 access_flags, method_idx, dex_file, dex_cache);
581 CHECK(compiled_method != nullptr);
582 }
583 } else if ((access_flags & kAccAbstract) != 0) {
584 // Abstract methods don't have code.
585 } else {
586 VerificationResults* results = driver->GetVerificationResults();
587 DCHECK(results != nullptr);
588 const VerifiedMethod* verified_method = results->GetVerifiedMethod(method_ref);
589 bool compile = compilation_enabled &&
590 // Basic checks, e.g., not <clinit>.
591 results->IsCandidateForCompilation(method_ref, access_flags) &&
592 // Did not fail to create VerifiedMethod metadata.
593 verified_method != nullptr &&
594 // Do not have failures that should punt to the interpreter.
595 !verified_method->HasRuntimeThrow() &&
596 (verified_method->GetEncounteredVerificationFailures() &
597 (verifier::VERIFY_ERROR_FORCE_INTERPRETER | verifier::VERIFY_ERROR_LOCKING)) == 0 &&
598 // Is eligable for compilation by methods-to-compile filter.
Andreas Gampe3c060ad2018-01-22 13:07:49 -0800599 driver->ShouldCompileBasedOnProfile(method_ref);
600
601 if (compile) {
602 // NOTE: if compiler declines to compile this method, it will return null.
603 compiled_method = driver->GetCompiler()->Compile(code_item,
604 access_flags,
605 invoke_type,
606 class_def_idx,
607 method_idx,
608 class_loader,
609 dex_file,
610 dex_cache);
611 }
612 if (compiled_method == nullptr &&
613 dex_to_dex_compilation_level !=
614 optimizer::DexToDexCompiler::CompilationLevel::kDontDexToDexCompile) {
615 DCHECK(!Runtime::Current()->UseJitCompilation());
616 // TODO: add a command-line option to disable DEX-to-DEX compilation ?
Mathieu Chartier279e3a32018-01-24 18:17:55 -0800617 driver->GetDexToDexCompiler().MarkForCompilation(self, method_ref);
Andreas Gampe3c060ad2018-01-22 13:07:49 -0800618 }
619 }
620 return compiled_method;
621 };
622 CompileMethodHarness(self,
623 driver,
624 code_item,
625 access_flags,
626 invoke_type,
627 class_def_idx,
628 method_idx,
629 class_loader,
630 dex_file,
631 dex_to_dex_compilation_level,
632 compilation_enabled,
633 dex_cache,
634 quick_fn);
635}
636
Vladimir Markodc4bcce2018-06-21 16:15:42 +0100637// Compile a single Method. (For testing only.)
638void CompilerDriver::CompileOne(Thread* self,
639 jobject class_loader,
640 const DexFile& dex_file,
641 uint16_t class_def_idx,
642 uint32_t method_idx,
643 uint32_t access_flags,
644 InvokeType invoke_type,
645 const DexFile::CodeItem* code_item,
646 Handle<mirror::DexCache> dex_cache,
647 Handle<mirror::ClassLoader> h_class_loader) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700648 // Can we run DEX-to-DEX compiler on this class ?
Mathieu Chartiera79efdb2018-01-18 16:31:01 -0800649 optimizer::DexToDexCompiler::CompilationLevel dex_to_dex_compilation_level =
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700650 GetDexToDexCompilationLevel(self,
651 *this,
Vladimir Markodc4bcce2018-06-21 16:15:42 +0100652 class_loader,
653 dex_file,
654 dex_file.GetClassDef(class_def_idx));
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700655
Andreas Gampe3c060ad2018-01-22 13:07:49 -0800656 CompileMethodQuick(self,
657 this,
658 code_item,
659 access_flags,
660 invoke_type,
661 class_def_idx,
662 method_idx,
Vladimir Markodc4bcce2018-06-21 16:15:42 +0100663 h_class_loader,
664 dex_file,
Andreas Gampe3c060ad2018-01-22 13:07:49 -0800665 dex_to_dex_compilation_level,
666 true,
667 dex_cache);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700668
Mathieu Chartier279e3a32018-01-24 18:17:55 -0800669 const size_t num_methods = dex_to_dex_compiler_.NumCodeItemsToQuicken(self);
Mathieu Chartiera79efdb2018-01-18 16:31:01 -0800670 if (num_methods != 0) {
671 DCHECK_EQ(num_methods, 1u);
Andreas Gampe3c060ad2018-01-22 13:07:49 -0800672 CompileMethodDex2Dex(self,
673 this,
674 code_item,
675 access_flags,
676 invoke_type,
677 class_def_idx,
678 method_idx,
Vladimir Markodc4bcce2018-06-21 16:15:42 +0100679 h_class_loader,
680 dex_file,
Andreas Gampe3c060ad2018-01-22 13:07:49 -0800681 dex_to_dex_compilation_level,
682 true,
683 dex_cache);
Mathieu Chartiera79efdb2018-01-18 16:31:01 -0800684 dex_to_dex_compiler_.ClearState();
Vladimir Marko492a7fa2016-06-01 18:38:43 +0100685 }
Mathieu Chartier2535abe2015-02-17 10:38:49 -0800686}
687
Andreas Gampeace0dc12016-01-20 13:33:13 -0800688void CompilerDriver::Resolve(jobject class_loader,
689 const std::vector<const DexFile*>& dex_files,
690 TimingLogger* timings) {
691 // Resolution allocates classes and needs to run single-threaded to be deterministic.
692 bool force_determinism = GetCompilerOptions().IsForceDeterminism();
693 ThreadPool* resolve_thread_pool = force_determinism
694 ? single_thread_pool_.get()
695 : parallel_thread_pool_.get();
696 size_t resolve_thread_count = force_determinism ? 1U : parallel_thread_count_;
697
Brian Carlstrom7940e442013-07-12 13:46:57 -0700698 for (size_t i = 0; i != dex_files.size(); ++i) {
699 const DexFile* dex_file = dex_files[i];
Kenny Rootd5185342014-05-13 14:47:05 -0700700 CHECK(dex_file != nullptr);
Andreas Gampeace0dc12016-01-20 13:33:13 -0800701 ResolveDexFile(class_loader,
702 *dex_file,
703 dex_files,
704 resolve_thread_pool,
705 resolve_thread_count,
706 timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700707 }
708}
709
Mathieu Chartiercd0f38f2018-10-15 09:44:35 -0700710void CompilerDriver::ResolveConstStrings(const std::vector<const DexFile*>& dex_files,
711 bool only_startup_strings,
712 TimingLogger* timings) {
Nicolas Geoffray571d2342016-10-12 13:03:15 +0000713 ScopedObjectAccess soa(Thread::Current());
714 StackHandleScope<1> hs(soa.Self());
715 ClassLinker* const class_linker = Runtime::Current()->GetClassLinker();
716 MutableHandle<mirror::DexCache> dex_cache(hs.NewHandle<mirror::DexCache>(nullptr));
Mathieu Chartier22752772018-10-18 14:18:59 -0700717 size_t num_instructions = 0u;
Nicolas Geoffray571d2342016-10-12 13:03:15 +0000718
Andreas Gampeace0dc12016-01-20 13:33:13 -0800719 for (const DexFile* dex_file : dex_files) {
Vladimir Markocd556b02017-02-03 11:47:34 +0000720 dex_cache.Assign(class_linker->FindDexCache(soa.Self(), *dex_file));
Mathieu Chartier1ca718e2018-10-23 12:55:34 -0700721 if (only_startup_strings) {
722 // When resolving startup strings, create the preresolved strings array.
723 dex_cache->AddPreResolvedStringsArray();
724 }
Andreas Gampeace0dc12016-01-20 13:33:13 -0800725 TimingLogger::ScopedTiming t("Resolve const-string Strings", timings);
726
Mathieu Chartierc8c8d5f2018-05-22 11:56:14 -0700727 for (ClassAccessor accessor : dex_file->GetClasses()) {
Mathieu Chartiercd0f38f2018-10-15 09:44:35 -0700728 if (!IsClassToCompile(accessor.GetDescriptor())) {
Andreas Gampeace0dc12016-01-20 13:33:13 -0800729 // Compilation is skipped, do not resolve const-string in code of this class.
Vladimir Marko175e7862018-03-27 09:03:13 +0000730 // FIXME: Make sure that inlining honors this. b/26687569
Andreas Gampeace0dc12016-01-20 13:33:13 -0800731 continue;
732 }
Mathieu Chartier22752772018-10-18 14:18:59 -0700733
734 const bool is_startup_class =
735 profile_compilation_info_ != nullptr &&
736 profile_compilation_info_->ContainsClass(*dex_file, accessor.GetClassIdx());
737
Mathieu Chartier0d896bd2018-05-25 00:20:27 -0700738 for (const ClassAccessor::Method& method : accessor.GetMethods()) {
Mathieu Chartier22752772018-10-18 14:18:59 -0700739 const bool is_clinit = (method.GetAccessFlags() & kAccConstructor) != 0 &&
740 (method.GetAccessFlags() & kAccStatic) != 0;
741 const bool is_startup_clinit = is_startup_class && is_clinit;
742
Mathieu Chartiercd0f38f2018-10-15 09:44:35 -0700743 if (only_startup_strings &&
744 profile_compilation_info_ != nullptr &&
Mathieu Chartier22752772018-10-18 14:18:59 -0700745 (!profile_compilation_info_->GetMethodHotness(method.GetReference()).IsStartup() &&
746 !is_startup_clinit)) {
Mathieu Chartiercd0f38f2018-10-15 09:44:35 -0700747 continue;
748 }
749
Mathieu Chartierc8c8d5f2018-05-22 11:56:14 -0700750 // Resolve const-strings in the code. Done to have deterministic allocation behavior. Right
751 // now this is single-threaded for simplicity.
752 // TODO: Collect the relevant string indices in parallel, then allocate them sequentially
753 // in a stable order.
754 for (const DexInstructionPcPair& inst : method.GetInstructions()) {
755 switch (inst->Opcode()) {
756 case Instruction::CONST_STRING:
757 case Instruction::CONST_STRING_JUMBO: {
758 dex::StringIndex string_index((inst->Opcode() == Instruction::CONST_STRING)
759 ? inst->VRegB_21c()
760 : inst->VRegB_31c());
761 ObjPtr<mirror::String> string = class_linker->ResolveString(string_index, dex_cache);
762 CHECK(string != nullptr) << "Could not allocate a string when forcing determinism";
Mathieu Chartier1ca718e2018-10-23 12:55:34 -0700763 if (only_startup_strings) {
764 dex_cache->GetPreResolvedStrings()[string_index.index_] =
765 GcRoot<mirror::String>(string);
766 }
Mathieu Chartier22752772018-10-18 14:18:59 -0700767 ++num_instructions;
Mathieu Chartierc8c8d5f2018-05-22 11:56:14 -0700768 break;
769 }
Andreas Gampeace0dc12016-01-20 13:33:13 -0800770
Mathieu Chartierc8c8d5f2018-05-22 11:56:14 -0700771 default:
772 break;
773 }
774 }
Mathieu Chartier0d896bd2018-05-25 00:20:27 -0700775 }
Vladimir Marko175e7862018-03-27 09:03:13 +0000776 }
777 }
Mathieu Chartier22752772018-10-18 14:18:59 -0700778 VLOG(compiler) << "Resolved " << num_instructions << " const string instructions";
Vladimir Marko175e7862018-03-27 09:03:13 +0000779}
780
781// Initialize type check bit strings for check-cast and instance-of in the code. Done to have
782// deterministic allocation behavior. Right now this is single-threaded for simplicity.
783// TODO: Collect the relevant type indices in parallel, then process them sequentially in a
784// stable order.
785
786static void InitializeTypeCheckBitstrings(CompilerDriver* driver,
787 ClassLinker* class_linker,
788 Handle<mirror::DexCache> dex_cache,
789 const DexFile& dex_file,
Mathieu Chartierc8c8d5f2018-05-22 11:56:14 -0700790 const ClassAccessor::Method& method)
Vladimir Marko175e7862018-03-27 09:03:13 +0000791 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierc8c8d5f2018-05-22 11:56:14 -0700792 for (const DexInstructionPcPair& inst : method.GetInstructions()) {
Vladimir Marko175e7862018-03-27 09:03:13 +0000793 switch (inst->Opcode()) {
794 case Instruction::CHECK_CAST:
795 case Instruction::INSTANCE_OF: {
796 dex::TypeIndex type_index(
797 (inst->Opcode() == Instruction::CHECK_CAST) ? inst->VRegB_21c() : inst->VRegC_22c());
798 const char* descriptor = dex_file.StringByTypeIdx(type_index);
799 // We currently do not use the bitstring type check for array or final (including
800 // primitive) classes. We may reconsider this in future if it's deemed to be beneficial.
801 // And we cannot use it for classes outside the boot image as we do not know the runtime
802 // value of their bitstring when compiling (it may not even get assigned at runtime).
Vladimir Markodc4bcce2018-06-21 16:15:42 +0100803 if (descriptor[0] == 'L' && driver->GetCompilerOptions().IsImageClass(descriptor)) {
Vladimir Marko175e7862018-03-27 09:03:13 +0000804 ObjPtr<mirror::Class> klass =
805 class_linker->LookupResolvedType(type_index,
806 dex_cache.Get(),
807 /* class_loader */ nullptr);
808 CHECK(klass != nullptr) << descriptor << " should have been previously resolved.";
809 // Now assign the bitstring if the class is not final. Keep this in sync with sharpening.
810 if (!klass->IsFinal()) {
811 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
812 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureAssigned(klass);
813 }
Andreas Gampeace0dc12016-01-20 13:33:13 -0800814 }
Vladimir Marko175e7862018-03-27 09:03:13 +0000815 break;
816 }
817
818 default:
819 break;
820 }
821 }
822}
823
824static void InitializeTypeCheckBitstrings(CompilerDriver* driver,
825 const std::vector<const DexFile*>& dex_files,
826 TimingLogger* timings) {
827 ScopedObjectAccess soa(Thread::Current());
828 StackHandleScope<1> hs(soa.Self());
829 ClassLinker* const class_linker = Runtime::Current()->GetClassLinker();
830 MutableHandle<mirror::DexCache> dex_cache(hs.NewHandle<mirror::DexCache>(nullptr));
831
832 for (const DexFile* dex_file : dex_files) {
833 dex_cache.Assign(class_linker->FindDexCache(soa.Self(), *dex_file));
834 TimingLogger::ScopedTiming t("Initialize type check bitstrings", timings);
835
Mathieu Chartierc8c8d5f2018-05-22 11:56:14 -0700836 for (ClassAccessor accessor : dex_file->GetClasses()) {
837 if (!driver->IsClassToCompile(accessor.GetDescriptor())) {
Vladimir Marko175e7862018-03-27 09:03:13 +0000838 // Compilation is skipped, do not look for type checks in code of this class.
839 // FIXME: Make sure that inlining honors this. b/26687569
840 continue;
841 }
842
843 // Direct and virtual methods.
Mathieu Chartier0d896bd2018-05-25 00:20:27 -0700844 for (const ClassAccessor::Method& method : accessor.GetMethods()) {
Mathieu Chartierc8c8d5f2018-05-22 11:56:14 -0700845 InitializeTypeCheckBitstrings(driver, class_linker, dex_cache, *dex_file, method);
Mathieu Chartier0d896bd2018-05-25 00:20:27 -0700846 }
Andreas Gampeace0dc12016-01-20 13:33:13 -0800847 }
848 }
849}
850
851inline void CompilerDriver::CheckThreadPools() {
852 DCHECK(parallel_thread_pool_ != nullptr);
853 DCHECK(single_thread_pool_ != nullptr);
854}
855
Nicolas Geoffray0a27fd02017-01-25 16:18:54 +0000856static void EnsureVerifiedOrVerifyAtRuntime(jobject jclass_loader,
857 const std::vector<const DexFile*>& dex_files) {
858 ScopedObjectAccess soa(Thread::Current());
859 StackHandleScope<2> hs(soa.Self());
860 Handle<mirror::ClassLoader> class_loader(
861 hs.NewHandle(soa.Decode<mirror::ClassLoader>(jclass_loader)));
862 MutableHandle<mirror::Class> cls(hs.NewHandle<mirror::Class>(nullptr));
863 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
864
865 for (const DexFile* dex_file : dex_files) {
Mathieu Chartierc8c8d5f2018-05-22 11:56:14 -0700866 for (ClassAccessor accessor : dex_file->GetClasses()) {
867 cls.Assign(class_linker->FindClass(soa.Self(), accessor.GetDescriptor(), class_loader));
Andreas Gampefa4333d2017-02-14 11:10:34 -0800868 if (cls == nullptr) {
Nicolas Geoffray0a27fd02017-01-25 16:18:54 +0000869 soa.Self()->ClearException();
870 } else if (&cls->GetDexFile() == dex_file) {
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +0000871 DCHECK(cls->IsErroneous() || cls->IsVerified() || cls->ShouldVerifyAtRuntime())
Nicolas Geoffray0a27fd02017-01-25 16:18:54 +0000872 << cls->PrettyClass()
873 << " " << cls->GetStatus();
874 }
875 }
876 }
877}
878
Andreas Gampeace0dc12016-01-20 13:33:13 -0800879void CompilerDriver::PreCompile(jobject class_loader,
880 const std::vector<const DexFile*>& dex_files,
881 TimingLogger* timings) {
882 CheckThreadPools();
Vladimir Marko213ee2d2018-06-22 11:56:34 +0100883
Vladimir Markodc4bcce2018-06-21 16:15:42 +0100884 VLOG(compiler) << "Before precompile " << GetMemoryUsageString(false);
885
Vladimir Marko213ee2d2018-06-22 11:56:34 +0100886 compiled_classes_.AddDexFiles(GetCompilerOptions().GetDexFilesForOatFile());
887 dex_to_dex_compiler_.SetDexFiles(GetCompilerOptions().GetDexFilesForOatFile());
888
Vladimir Markodc4bcce2018-06-21 16:15:42 +0100889 // Precompile:
890 // 1) Load image classes.
891 // 2) Resolve all classes.
892 // 3) For deterministic boot image, resolve strings for const-string instructions.
893 // 4) Attempt to verify all classes.
894 // 5) Attempt to initialize image classes, and trivially initialized classes.
895 // 6) Update the set of image classes.
896 // 7) For deterministic boot image, initialize bitstrings for type checking.
Andreas Gampeace0dc12016-01-20 13:33:13 -0800897
Brian Carlstrom7940e442013-07-12 13:46:57 -0700898 LoadImageClasses(timings);
Andreas Gampe8d295f82015-01-20 14:50:21 -0800899 VLOG(compiler) << "LoadImageClasses: " << GetMemoryUsageString(false);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700900
Nicolas Geoffray49cda062017-04-21 13:08:25 +0100901 if (compiler_options_->IsAnyCompilationEnabled()) {
Mathieu Chartier88b74b62017-07-16 17:08:19 -0700902 // Avoid adding the dex files in the case where we aren't going to add compiled methods.
903 // This reduces RAM usage for this case.
904 for (const DexFile* dex_file : dex_files) {
905 // Can be already inserted if the caller is CompileOne. This happens for gtests.
906 if (!compiled_methods_.HaveDexFile(dex_file)) {
Mathieu Chartierfc8b4222017-09-17 13:44:24 -0700907 compiled_methods_.AddDexFile(dex_file);
Mathieu Chartier88b74b62017-07-16 17:08:19 -0700908 }
909 }
Nicolas Geoffray49cda062017-04-21 13:08:25 +0100910 // Resolve eagerly to prepare for compilation.
Andreas Gampeace0dc12016-01-20 13:33:13 -0800911 Resolve(class_loader, dex_files, timings);
Mathieu Chartiere86deef2015-03-19 13:43:37 -0700912 VLOG(compiler) << "Resolve: " << GetMemoryUsageString(false);
913 }
914
Nicolas Geoffray60ca9492016-12-20 21:15:00 +0000915 if (compiler_options_->AssumeClassesAreVerified()) {
Mathieu Chartierab972ef2014-12-03 17:38:22 -0800916 VLOG(compiler) << "Verify none mode specified, skipping verification.";
Andreas Gampeace0dc12016-01-20 13:33:13 -0800917 SetVerified(class_loader, dex_files, timings);
Mathieu Chartiere86deef2015-03-19 13:43:37 -0700918 }
919
Nicolas Geoffray60ca9492016-12-20 21:15:00 +0000920 if (!compiler_options_->IsVerificationEnabled()) {
Jeff Hao4a200f52014-04-01 14:58:49 -0700921 return;
922 }
923
Vladimir Markoaad75c62016-10-03 08:46:48 +0000924 if (GetCompilerOptions().IsForceDeterminism() && GetCompilerOptions().IsBootImage()) {
Andreas Gampeace0dc12016-01-20 13:33:13 -0800925 // Resolve strings from const-string. Do this now to have a deterministic image.
Mathieu Chartiercd0f38f2018-10-15 09:44:35 -0700926 ResolveConstStrings(dex_files, /*only_startup_strings=*/ false, timings);
Andreas Gampeace0dc12016-01-20 13:33:13 -0800927 VLOG(compiler) << "Resolve const-strings: " << GetMemoryUsageString(false);
Mathieu Chartiercd0f38f2018-10-15 09:44:35 -0700928 } else if (GetCompilerOptions().ResolveStartupConstStrings()) {
929 ResolveConstStrings(dex_files, /*only_startup_strings=*/ true, timings);
Andreas Gampeace0dc12016-01-20 13:33:13 -0800930 }
931
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000932 Verify(class_loader, dex_files, timings);
Andreas Gampe8d295f82015-01-20 14:50:21 -0800933 VLOG(compiler) << "Verify: " << GetMemoryUsageString(false);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700934
Andreas Gampe6cf49e52015-03-05 13:08:45 -0800935 if (had_hard_verifier_failure_ && GetCompilerOptions().AbortOnHardVerifierFailure()) {
Andreas Gampefdfb4d42017-07-27 12:12:22 -0700936 // Avoid dumping threads. Even if we shut down the thread pools, there will still be three
937 // instances of this thread's stack.
938 LOG(FATAL_WITHOUT_ABORT) << "Had a hard failure verifying all classes, and was asked to abort "
939 << "in such situations. Please check the log.";
Andreas Gampe56c9b7c2018-02-27 18:49:26 -0800940 _exit(1);
Andreas Gampef39208f2017-10-19 15:06:59 -0700941 } else if (number_of_soft_verifier_failures_ > 0 &&
942 GetCompilerOptions().AbortOnSoftVerifierFailure()) {
943 LOG(FATAL_WITHOUT_ABORT) << "Had " << number_of_soft_verifier_failures_ << " soft failure(s) "
944 << "verifying all classes, and was asked to abort in such situations. "
945 << "Please check the log.";
Andreas Gampe56c9b7c2018-02-27 18:49:26 -0800946 _exit(1);
Andreas Gampe6cf49e52015-03-05 13:08:45 -0800947 }
948
Nicolas Geoffray49cda062017-04-21 13:08:25 +0100949 if (compiler_options_->IsAnyCompilationEnabled()) {
Nicolas Geoffray0a27fd02017-01-25 16:18:54 +0000950 if (kIsDebugBuild) {
951 EnsureVerifiedOrVerifyAtRuntime(class_loader, dex_files);
952 }
Nicolas Geoffrayade72d62016-12-15 13:20:02 +0000953 InitializeClasses(class_loader, dex_files, timings);
954 VLOG(compiler) << "InitializeClasses: " << GetMemoryUsageString(false);
955 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700956
957 UpdateImageClasses(timings);
Andreas Gampe8d295f82015-01-20 14:50:21 -0800958 VLOG(compiler) << "UpdateImageClasses: " << GetMemoryUsageString(false);
Vladimir Marko175e7862018-03-27 09:03:13 +0000959
960 if (kBitstringSubtypeCheckEnabled &&
961 GetCompilerOptions().IsForceDeterminism() && GetCompilerOptions().IsBootImage()) {
962 // Initialize type check bit string used by check-cast and instanceof.
963 // Do this now to have a deterministic image.
964 // Note: This is done after UpdateImageClasses() at it relies on the image classes to be final.
965 InitializeTypeCheckBitstrings(this, dex_files, timings);
966 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700967}
968
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800969bool CompilerDriver::IsClassToCompile(const char* descriptor) const {
Andreas Gampeb1fcead2015-04-20 18:53:51 -0700970 if (classes_to_compile_ == nullptr) {
971 return true;
972 }
Vladimir Marko54159c62018-06-20 14:30:08 +0100973 return classes_to_compile_->find(StringPiece(descriptor)) != classes_to_compile_->end();
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800974}
975
Calin Juravle226501b2015-12-11 14:41:31 +0000976bool CompilerDriver::ShouldCompileBasedOnProfile(const MethodReference& method_ref) const {
Mathieu Chartier97ab5e32017-02-22 13:35:44 -0800977 // Profile compilation info may be null if no profile is passed.
Mathieu Chartierd0af56c2017-02-17 12:56:25 -0800978 if (!CompilerFilter::DependsOnProfile(compiler_options_->GetCompilerFilter())) {
979 // Use the compiler filter instead of the presence of profile_compilation_info_ since
980 // we may want to have full speed compilation along with profile based layout optimizations.
Calin Juravle226501b2015-12-11 14:41:31 +0000981 return true;
982 }
Mathieu Chartier97ab5e32017-02-22 13:35:44 -0800983 // If we are using a profile filter but do not have a profile compilation info, compile nothing.
984 if (profile_compilation_info_ == nullptr) {
985 return false;
986 }
Mathieu Chartier7b135c82017-06-05 12:54:01 -0700987 // Compile only hot methods, it is the profile saver's job to decide what startup methods to mark
988 // as hot.
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -0700989 bool result = profile_compilation_info_->GetMethodHotness(method_ref).IsHot();
Calin Juravle226501b2015-12-11 14:41:31 +0000990
991 if (kDebugProfileGuidedCompilation) {
992 LOG(INFO) << "[ProfileGuidedCompilation] "
Mathieu Chartierfc8b4222017-09-17 13:44:24 -0700993 << (result ? "Compiled" : "Skipped") << " method:" << method_ref.PrettyMethod(true);
Calin Juravle226501b2015-12-11 14:41:31 +0000994 }
995 return result;
996}
997
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700998class ResolveCatchBlockExceptionsClassVisitor : public ClassVisitor {
999 public:
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001000 ResolveCatchBlockExceptionsClassVisitor() : classes_() {}
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001001
Roland Levillainf73caca2018-08-24 17:19:07 +01001002 bool operator()(ObjPtr<mirror::Class> c) override REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001003 classes_.push_back(c);
Mathieu Chartiere4275c02015-08-06 15:34:15 -07001004 return true;
1005 }
1006
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001007 void FindExceptionTypesToResolve(
1008 std::set<std::pair<dex::TypeIndex, const DexFile*>>* exceptions_to_resolve)
Vladimir Markobfb80d22017-02-14 14:08:12 +00001009 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001010 const auto pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
1011 for (ObjPtr<mirror::Class> klass : classes_) {
1012 for (ArtMethod& method : klass->GetMethods(pointer_size)) {
1013 FindExceptionTypesToResolveForMethod(&method, exceptions_to_resolve);
1014 }
1015 }
1016 }
1017
1018 private:
1019 void FindExceptionTypesToResolveForMethod(
1020 ArtMethod* method,
1021 std::set<std::pair<dex::TypeIndex, const DexFile*>>* exceptions_to_resolve)
1022 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier808c7a52017-12-15 11:19:33 -08001023 if (method->GetCodeItem() == nullptr) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001024 return; // native or abstract method
Brian Carlstrom7940e442013-07-12 13:46:57 -07001025 }
David Sehr0225f8e2018-01-31 08:52:24 +00001026 CodeItemDataAccessor accessor(method->DexInstructionData());
Mathieu Chartier808c7a52017-12-15 11:19:33 -08001027 if (accessor.TriesSize() == 0) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001028 return; // nothing to process
1029 }
Mathieu Chartier808c7a52017-12-15 11:19:33 -08001030 const uint8_t* encoded_catch_handler_list = accessor.GetCatchHandlerData();
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001031 size_t num_encoded_catch_handlers = DecodeUnsignedLeb128(&encoded_catch_handler_list);
1032 for (size_t i = 0; i < num_encoded_catch_handlers; i++) {
1033 int32_t encoded_catch_handler_size = DecodeSignedLeb128(&encoded_catch_handler_list);
1034 bool has_catch_all = false;
1035 if (encoded_catch_handler_size <= 0) {
1036 encoded_catch_handler_size = -encoded_catch_handler_size;
1037 has_catch_all = true;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001038 }
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001039 for (int32_t j = 0; j < encoded_catch_handler_size; j++) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08001040 dex::TypeIndex encoded_catch_handler_handlers_type_idx =
1041 dex::TypeIndex(DecodeUnsignedLeb128(&encoded_catch_handler_list));
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001042 // Add to set of types to resolve if not already in the dex cache resolved types
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001043 if (!method->IsResolvedTypeIdx(encoded_catch_handler_handlers_type_idx)) {
1044 exceptions_to_resolve->emplace(encoded_catch_handler_handlers_type_idx,
1045 method->GetDexFile());
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001046 }
1047 // ignore address associated with catch handler
1048 DecodeUnsignedLeb128(&encoded_catch_handler_list);
1049 }
1050 if (has_catch_all) {
1051 // ignore catch all address
1052 DecodeUnsignedLeb128(&encoded_catch_handler_list);
1053 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001054 }
1055 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001056
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001057 std::vector<ObjPtr<mirror::Class>> classes_;
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001058};
1059
1060class RecordImageClassesVisitor : public ClassVisitor {
1061 public:
Vladimir Marko54159c62018-06-20 14:30:08 +01001062 explicit RecordImageClassesVisitor(HashSet<std::string>* image_classes)
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001063 : image_classes_(image_classes) {}
1064
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01001065 bool operator()(ObjPtr<mirror::Class> klass) override REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001066 std::string temp;
1067 image_classes_->insert(klass->GetDescriptor(&temp));
1068 return true;
1069 }
1070
1071 private:
Vladimir Marko54159c62018-06-20 14:30:08 +01001072 HashSet<std::string>* const image_classes_;
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001073};
Brian Carlstrom7940e442013-07-12 13:46:57 -07001074
1075// Make a list of descriptors for classes to include in the image
Mathieu Chartier90443472015-07-16 20:32:27 -07001076void CompilerDriver::LoadImageClasses(TimingLogger* timings) {
Kenny Rootd5185342014-05-13 14:47:05 -07001077 CHECK(timings != nullptr);
Vladimir Markoaad75c62016-10-03 08:46:48 +00001078 if (!GetCompilerOptions().IsBootImage()) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001079 return;
1080 }
1081
Mathieu Chartierf5997b42014-06-20 10:37:54 -07001082 TimingLogger::ScopedTiming t("LoadImageClasses", timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001083 // Make a first class to load all classes explicitly listed in the file
1084 Thread* self = Thread::Current();
1085 ScopedObjectAccess soa(self);
1086 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Vladimir Markodc4bcce2018-06-21 16:15:42 +01001087 CHECK(image_classes_ != nullptr);
Mathieu Chartier02e25112013-08-14 16:14:24 -07001088 for (auto it = image_classes_->begin(), end = image_classes_->end(); it != end;) {
Vladimir Markoe9c36b32013-11-21 15:49:16 +00001089 const std::string& descriptor(*it);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001090 StackHandleScope<1> hs(self);
1091 Handle<mirror::Class> klass(
1092 hs.NewHandle(class_linker->FindSystemClass(self, descriptor.c_str())));
Andreas Gampefa4333d2017-02-14 11:10:34 -08001093 if (klass == nullptr) {
Ian Rogerse6bb3b22013-08-19 21:51:45 -07001094 VLOG(compiler) << "Failed to find class " << descriptor;
Vladimir Marko54159c62018-06-20 14:30:08 +01001095 it = image_classes_->erase(it);
Ian Rogersa436fde2013-08-27 23:34:06 -07001096 self->ClearException();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001097 } else {
1098 ++it;
1099 }
1100 }
1101
1102 // Resolve exception classes referenced by the loaded classes. The catch logic assumes
1103 // exceptions are resolved by the verifier when there is a catch block in an interested method.
1104 // Do this here so that exception classes appear to have been specified image classes.
Andreas Gampea5b09a62016-11-17 15:21:22 -08001105 std::set<std::pair<dex::TypeIndex, const DexFile*>> unresolved_exception_types;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001106 StackHandleScope<1> hs(self);
1107 Handle<mirror::Class> java_lang_Throwable(
1108 hs.NewHandle(class_linker->FindSystemClass(self, "Ljava/lang/Throwable;")));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001109 do {
1110 unresolved_exception_types.clear();
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001111 {
1112 // Thread suspension is not allowed while ResolveCatchBlockExceptionsClassVisitor
1113 // is using a std::vector<ObjPtr<mirror::Class>>.
1114 ScopedAssertNoThreadSuspension ants(__FUNCTION__);
1115 ResolveCatchBlockExceptionsClassVisitor visitor;
1116 class_linker->VisitClasses(&visitor);
1117 visitor.FindExceptionTypesToResolve(&unresolved_exception_types);
1118 }
Andreas Gampea5b09a62016-11-17 15:21:22 -08001119 for (const auto& exception_type : unresolved_exception_types) {
1120 dex::TypeIndex exception_type_idx = exception_type.first;
Mathieu Chartier02e25112013-08-14 16:14:24 -07001121 const DexFile* dex_file = exception_type.second;
Vladimir Marko666ee3d2017-12-11 18:37:36 +00001122 StackHandleScope<1> hs2(self);
Mathieu Chartierf284d442016-06-02 11:48:30 -07001123 Handle<mirror::DexCache> dex_cache(hs2.NewHandle(class_linker->RegisterDexFile(*dex_file,
1124 nullptr)));
Vladimir Marko666ee3d2017-12-11 18:37:36 +00001125 ObjPtr<mirror::Class> klass =
Andreas Gampefa4333d2017-02-14 11:10:34 -08001126 (dex_cache != nullptr)
Vladimir Marko666ee3d2017-12-11 18:37:36 +00001127 ? class_linker->ResolveType(exception_type_idx,
Vladimir Markocd556b02017-02-03 11:47:34 +00001128 dex_cache,
1129 ScopedNullHandle<mirror::ClassLoader>())
Vladimir Marko666ee3d2017-12-11 18:37:36 +00001130 : nullptr;
Andreas Gampefa4333d2017-02-14 11:10:34 -08001131 if (klass == nullptr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001132 const DexFile::TypeId& type_id = dex_file->GetTypeId(exception_type_idx);
1133 const char* descriptor = dex_file->GetTypeDescriptor(type_id);
1134 LOG(FATAL) << "Failed to resolve class " << descriptor;
1135 }
Vladimir Marko666ee3d2017-12-11 18:37:36 +00001136 DCHECK(java_lang_Throwable->IsAssignableFrom(klass));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001137 }
1138 // Resolving exceptions may load classes that reference more exceptions, iterate until no
1139 // more are found
1140 } while (!unresolved_exception_types.empty());
1141
1142 // We walk the roots looking for classes so that we'll pick up the
1143 // above classes plus any classes them depend on such super
1144 // classes, interfaces, and the required ClassLinker roots.
Vladimir Markodc4bcce2018-06-21 16:15:42 +01001145 RecordImageClassesVisitor visitor(image_classes_);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001146 class_linker->VisitClasses(&visitor);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001147
Vladimir Marko54159c62018-06-20 14:30:08 +01001148 CHECK(!image_classes_->empty());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001149}
1150
Vladimir Marko19a4d372016-12-08 14:41:46 +00001151static void MaybeAddToImageClasses(Thread* self,
1152 ObjPtr<mirror::Class> klass,
Vladimir Marko54159c62018-06-20 14:30:08 +01001153 HashSet<std::string>* image_classes)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001154 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko19a4d372016-12-08 14:41:46 +00001155 DCHECK_EQ(self, Thread::Current());
Mathieu Chartierf8322842014-05-16 10:59:25 -07001156 StackHandleScope<1> hs(self);
Ian Rogers1ff3c982014-08-12 02:30:58 -07001157 std::string temp;
Andreas Gampe542451c2016-07-26 09:02:02 -07001158 const PointerSize pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001159 while (!klass->IsObjectClass()) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07001160 const char* descriptor = klass->GetDescriptor(&temp);
Vladimir Marko54159c62018-06-20 14:30:08 +01001161 if (image_classes->find(StringPiece(descriptor)) != image_classes->end()) {
1162 break; // Previously inserted.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001163 }
Vladimir Marko54159c62018-06-20 14:30:08 +01001164 image_classes->insert(descriptor);
Ian Rogers1ff3c982014-08-12 02:30:58 -07001165 VLOG(compiler) << "Adding " << descriptor << " to image classes";
Vladimir Marko19a4d372016-12-08 14:41:46 +00001166 for (size_t i = 0, num_interfaces = klass->NumDirectInterfaces(); i != num_interfaces; ++i) {
1167 ObjPtr<mirror::Class> interface = mirror::Class::GetDirectInterface(self, klass, i);
1168 DCHECK(interface != nullptr);
1169 MaybeAddToImageClasses(self, interface, image_classes);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001170 }
Vladimir Marko19a4d372016-12-08 14:41:46 +00001171 for (auto& m : klass->GetVirtualMethods(pointer_size)) {
1172 MaybeAddToImageClasses(self, m.GetDeclaringClass(), image_classes);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001173 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001174 if (klass->IsArrayClass()) {
Vladimir Marko19a4d372016-12-08 14:41:46 +00001175 MaybeAddToImageClasses(self, klass->GetComponentType(), image_classes);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001176 }
Andreas Gampe98104992018-10-16 12:49:47 -07001177 klass = klass->GetSuperClass();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001178 }
1179}
1180
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001181// Keeps all the data for the update together. Also doubles as the reference visitor.
1182// Note: we can use object pointers because we suspend all threads.
1183class ClinitImageUpdate {
1184 public:
Mathieu Chartier31e88222016-10-14 18:43:19 -07001185 static ClinitImageUpdate* Create(VariableSizedHandleScope& hs,
Vladimir Marko54159c62018-06-20 14:30:08 +01001186 HashSet<std::string>* image_class_descriptors,
Mathieu Chartier31e88222016-10-14 18:43:19 -07001187 Thread* self,
1188 ClassLinker* linker) {
1189 std::unique_ptr<ClinitImageUpdate> res(new ClinitImageUpdate(hs,
1190 image_class_descriptors,
1191 self,
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001192 linker));
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001193 return res.release();
1194 }
1195
1196 ~ClinitImageUpdate() {
1197 // Allow others to suspend again.
1198 self_->EndAssertNoThreadSuspension(old_cause_);
1199 }
1200
1201 // Visitor for VisitReferences.
Mathieu Chartier31e88222016-10-14 18:43:19 -07001202 void operator()(ObjPtr<mirror::Object> object,
1203 MemberOffset field_offset,
1204 bool /* is_static */) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001205 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001206 mirror::Object* ref = object->GetFieldObject<mirror::Object>(field_offset);
1207 if (ref != nullptr) {
1208 VisitClinitClassesObject(ref);
1209 }
1210 }
1211
Roland Levillain5e8d5f02016-10-18 18:03:43 +01001212 // java.lang.ref.Reference visitor for VisitReferences.
Mathieu Chartier31e88222016-10-14 18:43:19 -07001213 void operator()(ObjPtr<mirror::Class> klass ATTRIBUTE_UNUSED,
1214 ObjPtr<mirror::Reference> ref ATTRIBUTE_UNUSED) const {}
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001215
1216 // Ignore class native roots.
1217 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED)
1218 const {}
1219 void VisitRoot(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED) const {}
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001220
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001221 void Walk() REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001222 // Use the initial classes as roots for a search.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001223 for (Handle<mirror::Class> klass_root : image_classes_) {
1224 VisitClinitClassesObject(klass_root.Get());
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001225 }
Vladimir Marko19a4d372016-12-08 14:41:46 +00001226 Thread* self = Thread::Current();
1227 ScopedAssertNoThreadSuspension ants(__FUNCTION__);
Mathieu Chartier31e88222016-10-14 18:43:19 -07001228 for (Handle<mirror::Class> h_klass : to_insert_) {
Vladimir Marko19a4d372016-12-08 14:41:46 +00001229 MaybeAddToImageClasses(self, h_klass.Get(), image_class_descriptors_);
Mathieu Chartier31e88222016-10-14 18:43:19 -07001230 }
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001231 }
1232
1233 private:
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001234 class FindImageClassesVisitor : public ClassVisitor {
1235 public:
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001236 explicit FindImageClassesVisitor(VariableSizedHandleScope& hs,
1237 ClinitImageUpdate* data)
1238 : data_(data),
1239 hs_(hs) {}
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001240
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01001241 bool operator()(ObjPtr<mirror::Class> klass) override REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001242 std::string temp;
Vladimir Marko54159c62018-06-20 14:30:08 +01001243 StringPiece name(klass->GetDescriptor(&temp));
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001244 if (data_->image_class_descriptors_->find(name) != data_->image_class_descriptors_->end()) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001245 data_->image_classes_.push_back(hs_.NewHandle(klass));
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001246 } else {
1247 // Check whether it is initialized and has a clinit. They must be kept, too.
1248 if (klass->IsInitialized() && klass->FindClassInitializer(
1249 Runtime::Current()->GetClassLinker()->GetImagePointerSize()) != nullptr) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001250 data_->image_classes_.push_back(hs_.NewHandle(klass));
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001251 }
1252 }
1253 return true;
1254 }
1255
1256 private:
1257 ClinitImageUpdate* const data_;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001258 VariableSizedHandleScope& hs_;
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001259 };
1260
Mathieu Chartier31e88222016-10-14 18:43:19 -07001261 ClinitImageUpdate(VariableSizedHandleScope& hs,
Vladimir Marko54159c62018-06-20 14:30:08 +01001262 HashSet<std::string>* image_class_descriptors,
Mathieu Chartier31e88222016-10-14 18:43:19 -07001263 Thread* self,
1264 ClassLinker* linker) REQUIRES_SHARED(Locks::mutator_lock_)
1265 : hs_(hs),
1266 image_class_descriptors_(image_class_descriptors),
1267 self_(self) {
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001268 CHECK(linker != nullptr);
1269 CHECK(image_class_descriptors != nullptr);
1270
1271 // Make sure nobody interferes with us.
1272 old_cause_ = self->StartAssertNoThreadSuspension("Boot image closure");
1273
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001274 // Find all the already-marked classes.
1275 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001276 FindImageClassesVisitor visitor(hs_, this);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001277 linker->VisitClasses(&visitor);
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001278 }
1279
1280 void VisitClinitClassesObject(mirror::Object* object) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001281 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001282 DCHECK(object != nullptr);
1283 if (marked_objects_.find(object) != marked_objects_.end()) {
1284 // Already processed.
1285 return;
1286 }
1287
1288 // Mark it.
1289 marked_objects_.insert(object);
1290
1291 if (object->IsClass()) {
Mathieu Chartier31e88222016-10-14 18:43:19 -07001292 // Add to the TODO list since MaybeAddToImageClasses may cause thread suspension. Thread
1293 // suspensionb is not safe to do in VisitObjects or VisitReferences.
1294 to_insert_.push_back(hs_.NewHandle(object->AsClass()));
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001295 } else {
1296 // Else visit the object's class.
1297 VisitClinitClassesObject(object->GetClass());
1298 }
1299
Mathieu Chartiere401d142015-04-22 13:56:20 -07001300 // If it is not a DexCache, visit all references.
Mathieu Chartier31e88222016-10-14 18:43:19 -07001301 if (!object->IsDexCache()) {
Mathieu Chartier059ef3d2015-08-18 13:54:21 -07001302 object->VisitReferences(*this, *this);
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001303 }
1304 }
1305
Mathieu Chartier31e88222016-10-14 18:43:19 -07001306 VariableSizedHandleScope& hs_;
1307 mutable std::vector<Handle<mirror::Class>> to_insert_;
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001308 mutable std::unordered_set<mirror::Object*> marked_objects_;
Vladimir Marko54159c62018-06-20 14:30:08 +01001309 HashSet<std::string>* const image_class_descriptors_;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001310 std::vector<Handle<mirror::Class>> image_classes_;
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001311 Thread* const self_;
1312 const char* old_cause_;
1313
1314 DISALLOW_COPY_AND_ASSIGN(ClinitImageUpdate);
1315};
Brian Carlstrom7940e442013-07-12 13:46:57 -07001316
Ian Rogers3d504072014-03-01 09:16:49 -08001317void CompilerDriver::UpdateImageClasses(TimingLogger* timings) {
Vladimir Markoaad75c62016-10-03 08:46:48 +00001318 if (GetCompilerOptions().IsBootImage()) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07001319 TimingLogger::ScopedTiming t("UpdateImageClasses", timings);
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001320
Mathieu Chartier4f55e222015-09-04 13:26:21 -07001321 Runtime* runtime = Runtime::Current();
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001322
1323 // Suspend all threads.
Mathieu Chartier4f55e222015-09-04 13:26:21 -07001324 ScopedSuspendAll ssa(__FUNCTION__);
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001325
Mathieu Chartier31e88222016-10-14 18:43:19 -07001326 VariableSizedHandleScope hs(Thread::Current());
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001327 std::string error_msg;
Mathieu Chartier31e88222016-10-14 18:43:19 -07001328 std::unique_ptr<ClinitImageUpdate> update(ClinitImageUpdate::Create(hs,
Vladimir Markodc4bcce2018-06-21 16:15:42 +01001329 image_classes_,
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001330 Thread::Current(),
Mathieu Chartier31e88222016-10-14 18:43:19 -07001331 runtime->GetClassLinker()));
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001332
1333 // Do the marking.
1334 update->Walk();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001335 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001336}
1337
Vladimir Markobe0e5462014-02-26 11:24:15 +00001338void CompilerDriver::ProcessedInstanceField(bool resolved) {
1339 if (!resolved) {
1340 stats_->UnresolvedInstanceField();
1341 } else {
1342 stats_->ResolvedInstanceField();
1343 }
1344}
1345
1346void CompilerDriver::ProcessedStaticField(bool resolved, bool local) {
1347 if (!resolved) {
1348 stats_->UnresolvedStaticField();
1349 } else if (local) {
1350 stats_->ResolvedLocalStaticField();
1351 } else {
1352 stats_->ResolvedStaticField();
1353 }
1354}
1355
Mathieu Chartierc7853442015-03-27 14:35:38 -07001356ArtField* CompilerDriver::ComputeInstanceFieldInfo(uint32_t field_idx,
Vladimir Markoe11dd502017-12-08 14:09:45 +00001357 const DexCompilationUnit* mUnit,
1358 bool is_put,
Mathieu Chartierc7853442015-03-27 14:35:38 -07001359 const ScopedObjectAccess& soa) {
Vladimir Markobe0e5462014-02-26 11:24:15 +00001360 // Try to resolve the field and compiling method's class.
Mathieu Chartierc7853442015-03-27 14:35:38 -07001361 ArtField* resolved_field;
Vladimir Marko28e012a2017-12-07 11:22:59 +00001362 ObjPtr<mirror::Class> referrer_class;
Mathieu Chartier736b5602015-09-02 14:54:11 -07001363 Handle<mirror::DexCache> dex_cache(mUnit->GetDexCache());
Vladimir Markobe0e5462014-02-26 11:24:15 +00001364 {
Vladimir Markoe11dd502017-12-08 14:09:45 +00001365 Handle<mirror::ClassLoader> class_loader = mUnit->GetClassLoader();
1366 resolved_field = ResolveField(soa, dex_cache, class_loader, field_idx, /* is_static */ false);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001367 referrer_class = resolved_field != nullptr
Vladimir Markoe11dd502017-12-08 14:09:45 +00001368 ? ResolveCompilingMethodsClass(soa, dex_cache, class_loader, mUnit) : nullptr;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001369 }
Nicolas Geoffraye5038322014-07-04 09:41:32 +01001370 bool can_link = false;
Vladimir Markobe0e5462014-02-26 11:24:15 +00001371 if (resolved_field != nullptr && referrer_class != nullptr) {
Vladimir Markobe0e5462014-02-26 11:24:15 +00001372 std::pair<bool, bool> fast_path = IsFastInstanceField(
Mathieu Chartier736b5602015-09-02 14:54:11 -07001373 dex_cache.Get(), referrer_class, resolved_field, field_idx);
Nicolas Geoffraye5038322014-07-04 09:41:32 +01001374 can_link = is_put ? fast_path.second : fast_path.first;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001375 }
Nicolas Geoffraye5038322014-07-04 09:41:32 +01001376 ProcessedInstanceField(can_link);
1377 return can_link ? resolved_field : nullptr;
1378}
1379
1380bool CompilerDriver::ComputeInstanceFieldInfo(uint32_t field_idx, const DexCompilationUnit* mUnit,
1381 bool is_put, MemberOffset* field_offset,
1382 bool* is_volatile) {
1383 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartierc7853442015-03-27 14:35:38 -07001384 ArtField* resolved_field = ComputeInstanceFieldInfo(field_idx, mUnit, is_put, soa);
Nicolas Geoffraye5038322014-07-04 09:41:32 +01001385
Mathieu Chartierc7853442015-03-27 14:35:38 -07001386 if (resolved_field == nullptr) {
Vladimir Markobe0e5462014-02-26 11:24:15 +00001387 // Conservative defaults.
1388 *is_volatile = true;
1389 *field_offset = MemberOffset(static_cast<size_t>(-1));
Nicolas Geoffraye5038322014-07-04 09:41:32 +01001390 return false;
1391 } else {
1392 *is_volatile = resolved_field->IsVolatile();
1393 *field_offset = resolved_field->GetOffset();
1394 return true;
Vladimir Markobe0e5462014-02-26 11:24:15 +00001395 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001396}
1397
Vladimir Marko2730db02014-01-27 11:15:17 +00001398const VerifiedMethod* CompilerDriver::GetVerifiedMethod(const DexFile* dex_file,
1399 uint32_t method_idx) const {
1400 MethodReference ref(dex_file, method_idx);
1401 return verification_results_->GetVerifiedMethod(ref);
1402}
1403
1404bool CompilerDriver::IsSafeCast(const DexCompilationUnit* mUnit, uint32_t dex_pc) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001405 if (!compiler_options_->IsVerificationEnabled()) {
1406 // If we didn't verify, every cast has to be treated as non-safe.
1407 return false;
1408 }
Vladimir Marko2730db02014-01-27 11:15:17 +00001409 DCHECK(mUnit->GetVerifiedMethod() != nullptr);
1410 bool result = mUnit->GetVerifiedMethod()->IsSafeCast(dex_pc);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001411 if (result) {
1412 stats_->SafeCast();
1413 } else {
1414 stats_->NotASafeCast();
1415 }
1416 return result;
1417}
1418
Mathieu Chartier90443472015-07-16 20:32:27 -07001419class CompilationVisitor {
1420 public:
1421 virtual ~CompilationVisitor() {}
1422 virtual void Visit(size_t index) = 0;
1423};
1424
Brian Carlstrom7940e442013-07-12 13:46:57 -07001425class ParallelCompilationManager {
1426 public:
Brian Carlstrom7940e442013-07-12 13:46:57 -07001427 ParallelCompilationManager(ClassLinker* class_linker,
1428 jobject class_loader,
1429 CompilerDriver* compiler,
1430 const DexFile* dex_file,
Andreas Gampede7b4362014-07-28 18:38:57 -07001431 const std::vector<const DexFile*>& dex_files,
Ian Rogers3d504072014-03-01 09:16:49 -08001432 ThreadPool* thread_pool)
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001433 : index_(0),
1434 class_linker_(class_linker),
Brian Carlstrom7940e442013-07-12 13:46:57 -07001435 class_loader_(class_loader),
1436 compiler_(compiler),
1437 dex_file_(dex_file),
Andreas Gampede7b4362014-07-28 18:38:57 -07001438 dex_files_(dex_files),
Ian Rogers3d504072014-03-01 09:16:49 -08001439 thread_pool_(thread_pool) {}
Brian Carlstrom7940e442013-07-12 13:46:57 -07001440
1441 ClassLinker* GetClassLinker() const {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001442 CHECK(class_linker_ != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001443 return class_linker_;
1444 }
1445
1446 jobject GetClassLoader() const {
1447 return class_loader_;
1448 }
1449
1450 CompilerDriver* GetCompiler() const {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001451 CHECK(compiler_ != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001452 return compiler_;
1453 }
1454
1455 const DexFile* GetDexFile() const {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001456 CHECK(dex_file_ != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001457 return dex_file_;
1458 }
1459
Andreas Gampede7b4362014-07-28 18:38:57 -07001460 const std::vector<const DexFile*>& GetDexFiles() const {
1461 return dex_files_;
1462 }
1463
Mathieu Chartier90443472015-07-16 20:32:27 -07001464 void ForAll(size_t begin, size_t end, CompilationVisitor* visitor, size_t work_units)
1465 REQUIRES(!*Locks::mutator_lock_) {
Andreas Gampe3c060ad2018-01-22 13:07:49 -08001466 ForAllLambda(begin, end, [visitor](size_t index) { visitor->Visit(index); }, work_units);
1467 }
1468
1469 template <typename Fn>
1470 void ForAllLambda(size_t begin, size_t end, Fn fn, size_t work_units)
1471 REQUIRES(!*Locks::mutator_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001472 Thread* self = Thread::Current();
1473 self->AssertNoPendingException();
1474 CHECK_GT(work_units, 0U);
1475
Orion Hodson88591fe2018-03-06 13:35:43 +00001476 index_.store(begin, std::memory_order_relaxed);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001477 for (size_t i = 0; i < work_units; ++i) {
Andreas Gampe3c060ad2018-01-22 13:07:49 -08001478 thread_pool_->AddTask(self, new ForAllClosureLambda<Fn>(this, end, fn));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001479 }
1480 thread_pool_->StartWorkers(self);
1481
1482 // Ensure we're suspended while we're blocked waiting for the other threads to finish (worker
1483 // thread destructor's called below perform join).
1484 CHECK_NE(self->GetState(), kRunnable);
1485
1486 // Wait for all the worker threads to finish.
1487 thread_pool_->Wait(self, true, false);
Andreas Gampeace0dc12016-01-20 13:33:13 -08001488
1489 // And stop the workers accepting jobs.
1490 thread_pool_->StopWorkers(self);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001491 }
1492
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001493 size_t NextIndex() {
Orion Hodson88591fe2018-03-06 13:35:43 +00001494 return index_.fetch_add(1, std::memory_order_seq_cst);
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001495 }
1496
Brian Carlstrom7940e442013-07-12 13:46:57 -07001497 private:
Andreas Gampe3c060ad2018-01-22 13:07:49 -08001498 template <typename Fn>
1499 class ForAllClosureLambda : public Task {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001500 public:
Andreas Gampe3c060ad2018-01-22 13:07:49 -08001501 ForAllClosureLambda(ParallelCompilationManager* manager, size_t end, Fn fn)
Brian Carlstrom7940e442013-07-12 13:46:57 -07001502 : manager_(manager),
Brian Carlstrom7940e442013-07-12 13:46:57 -07001503 end_(end),
Andreas Gampe3c060ad2018-01-22 13:07:49 -08001504 fn_(fn) {}
Brian Carlstrom7940e442013-07-12 13:46:57 -07001505
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01001506 void Run(Thread* self) override {
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001507 while (true) {
1508 const size_t index = manager_->NextIndex();
1509 if (UNLIKELY(index >= end_)) {
1510 break;
1511 }
Andreas Gampe3c060ad2018-01-22 13:07:49 -08001512 fn_(index);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001513 self->AssertNoPendingException();
1514 }
1515 }
1516
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01001517 void Finalize() override {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001518 delete this;
1519 }
Brian Carlstrom0cd7ec22013-07-17 23:40:20 -07001520
Brian Carlstrom7940e442013-07-12 13:46:57 -07001521 private:
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001522 ParallelCompilationManager* const manager_;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001523 const size_t end_;
Andreas Gampe3c060ad2018-01-22 13:07:49 -08001524 Fn fn_;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001525 };
1526
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001527 AtomicInteger index_;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001528 ClassLinker* const class_linker_;
1529 const jobject class_loader_;
1530 CompilerDriver* const compiler_;
1531 const DexFile* const dex_file_;
Andreas Gampede7b4362014-07-28 18:38:57 -07001532 const std::vector<const DexFile*>& dex_files_;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001533 ThreadPool* const thread_pool_;
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001534
1535 DISALLOW_COPY_AND_ASSIGN(ParallelCompilationManager);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001536};
1537
Jeff Hao0e49b422013-11-08 12:16:56 -08001538// A fast version of SkipClass above if the class pointer is available
1539// that avoids the expensive FindInClassPath search.
Vladimir Marko28e012a2017-12-07 11:22:59 +00001540static bool SkipClass(jobject class_loader, const DexFile& dex_file, ObjPtr<mirror::Class> klass)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001541 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001542 DCHECK(klass != nullptr);
Jeff Hao0e49b422013-11-08 12:16:56 -08001543 const DexFile& original_dex_file = *klass->GetDexCache()->GetDexFile();
1544 if (&dex_file != &original_dex_file) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001545 if (class_loader == nullptr) {
David Sehr709b0702016-10-13 09:12:37 -07001546 LOG(WARNING) << "Skipping class " << klass->PrettyDescriptor() << " from "
Jeff Hao0e49b422013-11-08 12:16:56 -08001547 << dex_file.GetLocation() << " previously found in "
1548 << original_dex_file.GetLocation();
1549 }
1550 return true;
1551 }
1552 return false;
1553}
1554
Mathieu Chartier70b63482014-06-27 17:19:04 -07001555static void CheckAndClearResolveException(Thread* self)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001556 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier70b63482014-06-27 17:19:04 -07001557 CHECK(self->IsExceptionPending());
Nicolas Geoffray14691c52015-03-05 10:40:17 +00001558 mirror::Throwable* exception = self->GetException();
Ian Rogers1ff3c982014-08-12 02:30:58 -07001559 std::string temp;
1560 const char* descriptor = exception->GetClass()->GetDescriptor(&temp);
1561 const char* expected_exceptions[] = {
1562 "Ljava/lang/IllegalAccessError;",
1563 "Ljava/lang/IncompatibleClassChangeError;",
1564 "Ljava/lang/InstantiationError;",
Brian Carlstrom898fcb52014-08-25 23:07:30 -07001565 "Ljava/lang/LinkageError;",
Ian Rogers1ff3c982014-08-12 02:30:58 -07001566 "Ljava/lang/NoClassDefFoundError;",
1567 "Ljava/lang/NoSuchFieldError;",
1568 "Ljava/lang/NoSuchMethodError;"
1569 };
1570 bool found = false;
1571 for (size_t i = 0; (found == false) && (i < arraysize(expected_exceptions)); ++i) {
1572 if (strcmp(descriptor, expected_exceptions[i]) == 0) {
1573 found = true;
1574 }
1575 }
1576 if (!found) {
Brian Carlstrom898fcb52014-08-25 23:07:30 -07001577 LOG(FATAL) << "Unexpected exception " << exception->Dump();
Mathieu Chartier70b63482014-06-27 17:19:04 -07001578 }
1579 self->ClearException();
1580}
1581
Mathieu Chartier90443472015-07-16 20:32:27 -07001582class ResolveClassFieldsAndMethodsVisitor : public CompilationVisitor {
1583 public:
1584 explicit ResolveClassFieldsAndMethodsVisitor(const ParallelCompilationManager* manager)
1585 : manager_(manager) {}
Brian Carlstrom7940e442013-07-12 13:46:57 -07001586
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01001587 void Visit(size_t class_def_index) override REQUIRES(!Locks::mutator_lock_) {
Andreas Gampe9b827ab2017-12-07 19:32:48 -08001588 ScopedTrace trace(__FUNCTION__);
Mathieu Chartier90443472015-07-16 20:32:27 -07001589 Thread* const self = Thread::Current();
1590 jobject jclass_loader = manager_->GetClassLoader();
1591 const DexFile& dex_file = *manager_->GetDexFile();
1592 ClassLinker* class_linker = manager_->GetClassLinker();
Ian Rogerse6bb3b22013-08-19 21:51:45 -07001593
Mathieu Chartier90443472015-07-16 20:32:27 -07001594 // Method and Field are the worst. We can't resolve without either
1595 // context from the code use (to disambiguate virtual vs direct
1596 // method and instance vs static field) or from class
1597 // definitions. While the compiler will resolve what it can as it
1598 // needs it, here we try to resolve fields and methods used in class
1599 // definitions, since many of them many never be referenced by
1600 // generated code.
1601 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
1602 ScopedObjectAccess soa(self);
1603 StackHandleScope<2> hs(soa.Self());
1604 Handle<mirror::ClassLoader> class_loader(
Mathieu Chartier0795f232016-09-27 18:43:30 -07001605 hs.NewHandle(soa.Decode<mirror::ClassLoader>(jclass_loader)));
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001606 Handle<mirror::DexCache> dex_cache(hs.NewHandle(class_linker->FindDexCache(
Vladimir Markocd556b02017-02-03 11:47:34 +00001607 soa.Self(), dex_file)));
Mathieu Chartier90443472015-07-16 20:32:27 -07001608 // Resolve the class.
Vladimir Marko28e012a2017-12-07 11:22:59 +00001609 ObjPtr<mirror::Class> klass =
Vladimir Marko666ee3d2017-12-11 18:37:36 +00001610 class_linker->ResolveType(class_def.class_idx_, dex_cache, class_loader);
Mathieu Chartier90443472015-07-16 20:32:27 -07001611 bool resolve_fields_and_methods;
1612 if (klass == nullptr) {
1613 // Class couldn't be resolved, for example, super-class is in a different dex file. Don't
1614 // attempt to resolve methods and fields when there is no declaring class.
1615 CheckAndClearResolveException(soa.Self());
1616 resolve_fields_and_methods = false;
1617 } else {
1618 // We successfully resolved a class, should we skip it?
1619 if (SkipClass(jclass_loader, dex_file, klass)) {
1620 return;
Ian Rogerse6bb3b22013-08-19 21:51:45 -07001621 }
Mathieu Chartier90443472015-07-16 20:32:27 -07001622 // We want to resolve the methods and fields eagerly.
1623 resolve_fields_and_methods = true;
Ian Rogers68b56852014-08-29 20:19:11 -07001624 }
Mathieu Chartierc8c8d5f2018-05-22 11:56:14 -07001625
Vladimir Markoc1c34522018-10-31 13:56:49 +00001626 if (resolve_fields_and_methods) {
1627 ClassAccessor accessor(dex_file, class_def_index);
1628 // Optionally resolve fields and methods and figure out if we need a constructor barrier.
1629 auto method_visitor = [&](const ClassAccessor::Method& method)
1630 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierc8c8d5f2018-05-22 11:56:14 -07001631 ArtMethod* resolved = class_linker->ResolveMethod<ClassLinker::ResolveMode::kNoChecks>(
1632 method.GetIndex(),
1633 dex_cache,
1634 class_loader,
Vladimir Markoc1c34522018-10-31 13:56:49 +00001635 /*referrer=*/ nullptr,
Mathieu Chartierc8c8d5f2018-05-22 11:56:14 -07001636 method.GetInvokeType(class_def.access_flags_));
1637 if (resolved == nullptr) {
1638 CheckAndClearResolveException(soa.Self());
Mathieu Chartier90443472015-07-16 20:32:27 -07001639 }
Vladimir Markoc1c34522018-10-31 13:56:49 +00001640 };
1641 accessor.VisitFieldsAndMethods(
1642 // static fields
1643 [&](ClassAccessor::Field& field) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierc8c8d5f2018-05-22 11:56:14 -07001644 ArtField* resolved = class_linker->ResolveField(
Vladimir Markoc1c34522018-10-31 13:56:49 +00001645 field.GetIndex(), dex_cache, class_loader, /*is_static=*/ true);
Mathieu Chartierc8c8d5f2018-05-22 11:56:14 -07001646 if (resolved == nullptr) {
1647 CheckAndClearResolveException(soa.Self());
1648 }
Vladimir Markoc1c34522018-10-31 13:56:49 +00001649 },
1650 // instance fields
1651 [&](ClassAccessor::Field& field) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierc8c8d5f2018-05-22 11:56:14 -07001652 ArtField* resolved = class_linker->ResolveField(
Vladimir Markoc1c34522018-10-31 13:56:49 +00001653 field.GetIndex(), dex_cache, class_loader, /*is_static=*/ false);
Mathieu Chartierc8c8d5f2018-05-22 11:56:14 -07001654 if (resolved == nullptr) {
1655 CheckAndClearResolveException(soa.Self());
1656 }
Vladimir Markoc1c34522018-10-31 13:56:49 +00001657 },
1658 /*direct_method_visitor=*/ method_visitor,
1659 /*virtual_method_visitor=*/ method_visitor);
1660 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001661 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001662
Mathieu Chartier90443472015-07-16 20:32:27 -07001663 private:
1664 const ParallelCompilationManager* const manager_;
1665};
1666
1667class ResolveTypeVisitor : public CompilationVisitor {
1668 public:
1669 explicit ResolveTypeVisitor(const ParallelCompilationManager* manager) : manager_(manager) {
1670 }
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01001671 void Visit(size_t type_idx) override REQUIRES(!Locks::mutator_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001672 // Class derived values are more complicated, they require the linker and loader.
Mathieu Chartier90443472015-07-16 20:32:27 -07001673 ScopedObjectAccess soa(Thread::Current());
1674 ClassLinker* class_linker = manager_->GetClassLinker();
1675 const DexFile& dex_file = *manager_->GetDexFile();
1676 StackHandleScope<2> hs(soa.Self());
Mathieu Chartier90443472015-07-16 20:32:27 -07001677 Handle<mirror::ClassLoader> class_loader(
Mathieu Chartier0795f232016-09-27 18:43:30 -07001678 hs.NewHandle(soa.Decode<mirror::ClassLoader>(manager_->GetClassLoader())));
Mathieu Chartierd57d4542015-10-14 10:55:30 -07001679 Handle<mirror::DexCache> dex_cache(hs.NewHandle(class_linker->RegisterDexFile(
1680 dex_file,
Mathieu Chartierf284d442016-06-02 11:48:30 -07001681 class_loader.Get())));
Andreas Gampefa4333d2017-02-14 11:10:34 -08001682 ObjPtr<mirror::Class> klass = (dex_cache != nullptr)
Vladimir Marko666ee3d2017-12-11 18:37:36 +00001683 ? class_linker->ResolveType(dex::TypeIndex(type_idx), dex_cache, class_loader)
Vladimir Markocd556b02017-02-03 11:47:34 +00001684 : nullptr;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001685
Mathieu Chartier90443472015-07-16 20:32:27 -07001686 if (klass == nullptr) {
1687 soa.Self()->AssertPendingException();
1688 mirror::Throwable* exception = soa.Self()->GetException();
1689 VLOG(compiler) << "Exception during type resolution: " << exception->Dump();
1690 if (exception->GetClass()->DescriptorEquals("Ljava/lang/OutOfMemoryError;")) {
1691 // There's little point continuing compilation if the heap is exhausted.
1692 LOG(FATAL) << "Out of memory during type resolution for compilation";
1693 }
1694 soa.Self()->ClearException();
Ian Rogersa436fde2013-08-27 23:34:06 -07001695 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001696 }
Mathieu Chartier90443472015-07-16 20:32:27 -07001697
1698 private:
1699 const ParallelCompilationManager* const manager_;
1700};
Brian Carlstrom7940e442013-07-12 13:46:57 -07001701
Andreas Gampeace0dc12016-01-20 13:33:13 -08001702void CompilerDriver::ResolveDexFile(jobject class_loader,
1703 const DexFile& dex_file,
Andreas Gampede7b4362014-07-28 18:38:57 -07001704 const std::vector<const DexFile*>& dex_files,
Andreas Gampeace0dc12016-01-20 13:33:13 -08001705 ThreadPool* thread_pool,
1706 size_t thread_count,
1707 TimingLogger* timings) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001708 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1709
1710 // TODO: we could resolve strings here, although the string table is largely filled with class
1711 // and method names.
1712
Andreas Gampede7b4362014-07-28 18:38:57 -07001713 ParallelCompilationManager context(class_linker, class_loader, this, &dex_file, dex_files,
1714 thread_pool);
Vladimir Markoaad75c62016-10-03 08:46:48 +00001715 if (GetCompilerOptions().IsBootImage()) {
Ian Rogerse6bb3b22013-08-19 21:51:45 -07001716 // For images we resolve all types, such as array, whereas for applications just those with
1717 // classdefs are resolved by ResolveClassFieldsAndMethods.
Mathieu Chartierf5997b42014-06-20 10:37:54 -07001718 TimingLogger::ScopedTiming t("Resolve Types", timings);
Mathieu Chartier90443472015-07-16 20:32:27 -07001719 ResolveTypeVisitor visitor(&context);
Andreas Gampeace0dc12016-01-20 13:33:13 -08001720 context.ForAll(0, dex_file.NumTypeIds(), &visitor, thread_count);
Ian Rogerse6bb3b22013-08-19 21:51:45 -07001721 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001722
Mathieu Chartierf5997b42014-06-20 10:37:54 -07001723 TimingLogger::ScopedTiming t("Resolve MethodsAndFields", timings);
Mathieu Chartier90443472015-07-16 20:32:27 -07001724 ResolveClassFieldsAndMethodsVisitor visitor(&context);
Andreas Gampeace0dc12016-01-20 13:33:13 -08001725 context.ForAll(0, dex_file.NumClassDefs(), &visitor, thread_count);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001726}
1727
Andreas Gampeace0dc12016-01-20 13:33:13 -08001728void CompilerDriver::SetVerified(jobject class_loader,
1729 const std::vector<const DexFile*>& dex_files,
1730 TimingLogger* timings) {
1731 // This can be run in parallel.
Mathieu Chartier90443472015-07-16 20:32:27 -07001732 for (const DexFile* dex_file : dex_files) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001733 CHECK(dex_file != nullptr);
Andreas Gampeace0dc12016-01-20 13:33:13 -08001734 SetVerifiedDexFile(class_loader,
1735 *dex_file,
1736 dex_files,
1737 parallel_thread_pool_.get(),
1738 parallel_thread_count_,
1739 timings);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001740 }
1741}
1742
Mathieu Chartierc8c8d5f2018-05-22 11:56:14 -07001743static void LoadAndUpdateStatus(const ClassAccessor& accessor,
Vladimir Marko2c64a832018-01-04 11:31:56 +00001744 ClassStatus status,
Nicolas Geoffray0a27fd02017-01-25 16:18:54 +00001745 Handle<mirror::ClassLoader> class_loader,
1746 Thread* self)
1747 REQUIRES_SHARED(Locks::mutator_lock_) {
1748 StackHandleScope<1> hs(self);
Mathieu Chartierc8c8d5f2018-05-22 11:56:14 -07001749 const char* descriptor = accessor.GetDescriptor();
Nicolas Geoffray0a27fd02017-01-25 16:18:54 +00001750 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1751 Handle<mirror::Class> cls(hs.NewHandle<mirror::Class>(
1752 class_linker->FindClass(self, descriptor, class_loader)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08001753 if (cls != nullptr) {
Nicolas Geoffray0a27fd02017-01-25 16:18:54 +00001754 // Check that the class is resolved with the current dex file. We might get
1755 // a boot image class, or a class in a different dex file for multidex, and
1756 // we should not update the status in that case.
Mathieu Chartierc8c8d5f2018-05-22 11:56:14 -07001757 if (&cls->GetDexFile() == &accessor.GetDexFile()) {
Nicolas Geoffray0a27fd02017-01-25 16:18:54 +00001758 ObjectLock<mirror::Class> lock(self, cls);
1759 mirror::Class::SetStatus(cls, status, self);
1760 }
1761 } else {
1762 DCHECK(self->IsExceptionPending());
1763 self->ClearException();
1764 }
1765}
1766
Nicolas Geoffray74981052017-01-16 17:54:09 +00001767bool CompilerDriver::FastVerify(jobject jclass_loader,
1768 const std::vector<const DexFile*>& dex_files,
1769 TimingLogger* timings) {
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +00001770 verifier::VerifierDeps* verifier_deps =
1771 Runtime::Current()->GetCompilerCallbacks()->GetVerifierDeps();
Mathieu Chartier72041a02017-07-14 18:23:25 -07001772 // If there exist VerifierDeps that aren't the ones we just created to output, use them to verify.
1773 if (verifier_deps == nullptr || verifier_deps->OutputOnly()) {
Nicolas Geoffray74981052017-01-16 17:54:09 +00001774 return false;
1775 }
1776 TimingLogger::ScopedTiming t("Fast Verify", timings);
1777 ScopedObjectAccess soa(Thread::Current());
1778 StackHandleScope<2> hs(soa.Self());
1779 Handle<mirror::ClassLoader> class_loader(
1780 hs.NewHandle(soa.Decode<mirror::ClassLoader>(jclass_loader)));
Nicolas Geoffray74981052017-01-16 17:54:09 +00001781 if (!verifier_deps->ValidateDependencies(class_loader, soa.Self())) {
1782 return false;
1783 }
1784
Nicolas Geoffray49cda062017-04-21 13:08:25 +01001785 bool compiler_only_verifies = !GetCompilerOptions().IsAnyCompilationEnabled();
Nicolas Geoffray0a27fd02017-01-25 16:18:54 +00001786
Nicolas Geoffray74981052017-01-16 17:54:09 +00001787 // We successfully validated the dependencies, now update class status
1788 // of verified classes. Note that the dependencies also record which classes
1789 // could not be fully verified; we could try again, but that would hurt verification
1790 // time. So instead we assume these classes still need to be verified at
1791 // runtime.
1792 for (const DexFile* dex_file : dex_files) {
Mathieu Chartierbf755fe2017-08-01 13:42:56 -07001793 // Fetch the list of unverified classes.
1794 const std::set<dex::TypeIndex>& unverified_classes =
Nicolas Geoffray74981052017-01-16 17:54:09 +00001795 verifier_deps->GetUnverifiedClasses(*dex_file);
Mathieu Chartierc8c8d5f2018-05-22 11:56:14 -07001796 for (ClassAccessor accessor : dex_file->GetClasses()) {
1797 if (unverified_classes.find(accessor.GetClassIdx()) == unverified_classes.end()) {
Nicolas Geoffray0a27fd02017-01-25 16:18:54 +00001798 if (compiler_only_verifies) {
Nicolas Geoffray74981052017-01-16 17:54:09 +00001799 // Just update the compiled_classes_ map. The compiler doesn't need to resolve
1800 // the type.
Mathieu Chartier18e26872018-06-04 17:19:02 -07001801 ClassReference ref(dex_file, accessor.GetClassDefIndex());
Mathieu Chartier2eabc612018-05-25 14:31:16 -07001802 const ClassStatus existing = ClassStatus::kNotReady;
Mathieu Chartier1a088d42017-07-18 11:43:57 -07001803 ClassStateTable::InsertResult result =
Vladimir Marko2c64a832018-01-04 11:31:56 +00001804 compiled_classes_.Insert(ref, existing, ClassStatus::kVerified);
Mathieu Chartier2eabc612018-05-25 14:31:16 -07001805 CHECK_EQ(result, ClassStateTable::kInsertResultSuccess) << ref.dex_file->GetLocation();
Nicolas Geoffray74981052017-01-16 17:54:09 +00001806 } else {
Nicolas Geoffray0a27fd02017-01-25 16:18:54 +00001807 // Update the class status, so later compilation stages know they don't need to verify
Nicolas Geoffray74981052017-01-16 17:54:09 +00001808 // the class.
Mathieu Chartierc8c8d5f2018-05-22 11:56:14 -07001809 LoadAndUpdateStatus(accessor, ClassStatus::kVerified, class_loader, soa.Self());
Nicolas Geoffray74981052017-01-16 17:54:09 +00001810 // Create `VerifiedMethod`s for each methods, the compiler expects one for
1811 // quickening or compiling.
1812 // Note that this means:
1813 // - We're only going to compile methods that did verify.
1814 // - Quickening will not do checkcast ellision.
1815 // TODO(ngeoffray): Reconsider this once we refactor compiler filters.
Mathieu Chartier0d896bd2018-05-25 00:20:27 -07001816 for (const ClassAccessor::Method& method : accessor.GetMethods()) {
Mathieu Chartierc8c8d5f2018-05-22 11:56:14 -07001817 verification_results_->CreateVerifiedMethodFor(method.GetReference());
Mathieu Chartier0d896bd2018-05-25 00:20:27 -07001818 }
Nicolas Geoffray6bb7f1b2016-11-03 10:52:49 +00001819 }
Nicolas Geoffray0a27fd02017-01-25 16:18:54 +00001820 } else if (!compiler_only_verifies) {
1821 // Make sure later compilation stages know they should not try to verify
1822 // this class again.
Mathieu Chartierc8c8d5f2018-05-22 11:56:14 -07001823 LoadAndUpdateStatus(accessor,
Vladimir Marko2c64a832018-01-04 11:31:56 +00001824 ClassStatus::kRetryVerificationAtRuntime,
Nicolas Geoffray0a27fd02017-01-25 16:18:54 +00001825 class_loader,
1826 soa.Self());
Nicolas Geoffray6bb7f1b2016-11-03 10:52:49 +00001827 }
Nicolas Geoffray6bb7f1b2016-11-03 10:52:49 +00001828 }
1829 }
Nicolas Geoffray74981052017-01-16 17:54:09 +00001830 return true;
1831}
1832
1833void CompilerDriver::Verify(jobject jclass_loader,
1834 const std::vector<const DexFile*>& dex_files,
1835 TimingLogger* timings) {
1836 if (FastVerify(jclass_loader, dex_files, timings)) {
1837 return;
1838 }
Nicolas Geoffray6bb7f1b2016-11-03 10:52:49 +00001839
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +00001840 // If there is no existing `verifier_deps` (because of non-existing vdex), or
1841 // the existing `verifier_deps` is not valid anymore, create a new one for
Nicolas Geoffray6bb7f1b2016-11-03 10:52:49 +00001842 // non boot image compilation. The verifier will need it to record the new dependencies.
1843 // Then dex2oat can update the vdex file with these new dependencies.
1844 if (!GetCompilerOptions().IsBootImage()) {
Mathieu Chartier72041a02017-07-14 18:23:25 -07001845 // Dex2oat creates the verifier deps.
Nicolas Geoffray340dafa2016-11-18 16:03:10 +00001846 // Create the main VerifierDeps, and set it to this thread.
Mathieu Chartier72041a02017-07-14 18:23:25 -07001847 verifier::VerifierDeps* verifier_deps =
1848 Runtime::Current()->GetCompilerCallbacks()->GetVerifierDeps();
1849 CHECK(verifier_deps != nullptr);
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +00001850 Thread::Current()->SetVerifierDeps(verifier_deps);
Nicolas Geoffray340dafa2016-11-18 16:03:10 +00001851 // Create per-thread VerifierDeps to avoid contention on the main one.
1852 // We will merge them after verification.
1853 for (ThreadPoolWorker* worker : parallel_thread_pool_->GetWorkers()) {
Vladimir Marko213ee2d2018-06-22 11:56:34 +01001854 worker->GetThread()->SetVerifierDeps(
1855 new verifier::VerifierDeps(GetCompilerOptions().GetDexFilesForOatFile()));
Nicolas Geoffray340dafa2016-11-18 16:03:10 +00001856 }
Nicolas Geoffray6bb7f1b2016-11-03 10:52:49 +00001857 }
Nicolas Geoffray74981052017-01-16 17:54:09 +00001858
Nicolas Geoffray46847392017-04-28 14:56:39 +01001859 // Verification updates VerifierDeps and needs to run single-threaded to be deterministic.
1860 bool force_determinism = GetCompilerOptions().IsForceDeterminism();
1861 ThreadPool* verify_thread_pool =
1862 force_determinism ? single_thread_pool_.get() : parallel_thread_pool_.get();
1863 size_t verify_thread_count = force_determinism ? 1U : parallel_thread_count_;
Mathieu Chartier90443472015-07-16 20:32:27 -07001864 for (const DexFile* dex_file : dex_files) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001865 CHECK(dex_file != nullptr);
Nicolas Geoffray6bb7f1b2016-11-03 10:52:49 +00001866 VerifyDexFile(jclass_loader,
Andreas Gampeace0dc12016-01-20 13:33:13 -08001867 *dex_file,
1868 dex_files,
Nicolas Geoffray46847392017-04-28 14:56:39 +01001869 verify_thread_pool,
1870 verify_thread_count,
Andreas Gampeace0dc12016-01-20 13:33:13 -08001871 timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001872 }
Nicolas Geoffray340dafa2016-11-18 16:03:10 +00001873
1874 if (!GetCompilerOptions().IsBootImage()) {
Nicolas Geoffray340dafa2016-11-18 16:03:10 +00001875 // Merge all VerifierDeps into the main one.
Nicolas Geoffray74981052017-01-16 17:54:09 +00001876 verifier::VerifierDeps* verifier_deps = Thread::Current()->GetVerifierDeps();
Nicolas Geoffray340dafa2016-11-18 16:03:10 +00001877 for (ThreadPoolWorker* worker : parallel_thread_pool_->GetWorkers()) {
1878 verifier::VerifierDeps* thread_deps = worker->GetThread()->GetVerifierDeps();
1879 worker->GetThread()->SetVerifierDeps(nullptr);
Vladimir Marko213ee2d2018-06-22 11:56:34 +01001880 verifier_deps->MergeWith(*thread_deps, GetCompilerOptions().GetDexFilesForOatFile());
Nicolas Geoffray340dafa2016-11-18 16:03:10 +00001881 delete thread_deps;
1882 }
1883 Thread::Current()->SetVerifierDeps(nullptr);
1884 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001885}
1886
Mathieu Chartier90443472015-07-16 20:32:27 -07001887class VerifyClassVisitor : public CompilationVisitor {
1888 public:
Andreas Gampe5fd66d02016-09-12 20:22:19 -07001889 VerifyClassVisitor(const ParallelCompilationManager* manager, verifier::HardFailLogMode log_level)
Andreas Gampe6cc23ac2018-08-24 15:22:43 -07001890 : manager_(manager),
1891 log_level_(log_level),
1892 sdk_version_(Runtime::Current()->GetTargetSdkVersion()) {}
Brian Carlstrom7940e442013-07-12 13:46:57 -07001893
Roland Levillainf73caca2018-08-24 17:19:07 +01001894 void Visit(size_t class_def_index) REQUIRES(!Locks::mutator_lock_) override {
Andreas Gampe9b827ab2017-12-07 19:32:48 -08001895 ScopedTrace trace(__FUNCTION__);
Mathieu Chartier90443472015-07-16 20:32:27 -07001896 ScopedObjectAccess soa(Thread::Current());
1897 const DexFile& dex_file = *manager_->GetDexFile();
1898 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
1899 const char* descriptor = dex_file.GetClassDescriptor(class_def);
1900 ClassLinker* class_linker = manager_->GetClassLinker();
1901 jobject jclass_loader = manager_->GetClassLoader();
1902 StackHandleScope<3> hs(soa.Self());
1903 Handle<mirror::ClassLoader> class_loader(
Mathieu Chartier0795f232016-09-27 18:43:30 -07001904 hs.NewHandle(soa.Decode<mirror::ClassLoader>(jclass_loader)));
Mathieu Chartier90443472015-07-16 20:32:27 -07001905 Handle<mirror::Class> klass(
1906 hs.NewHandle(class_linker->FindClass(soa.Self(), descriptor, class_loader)));
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07001907 verifier::FailureKind failure_kind;
Andreas Gampefa4333d2017-02-14 11:10:34 -08001908 if (klass == nullptr) {
Ian Rogerse6bb3b22013-08-19 21:51:45 -07001909 CHECK(soa.Self()->IsExceptionPending());
1910 soa.Self()->ClearException();
Mathieu Chartier90443472015-07-16 20:32:27 -07001911
1912 /*
1913 * At compile time, we can still structurally verify the class even if FindClass fails.
1914 * This is to ensure the class is structurally sound for compilation. An unsound class
1915 * will be rejected by the verifier and later skipped during compilation in the compiler.
1916 */
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001917 Handle<mirror::DexCache> dex_cache(hs.NewHandle(class_linker->FindDexCache(
Vladimir Markocd556b02017-02-03 11:47:34 +00001918 soa.Self(), dex_file)));
Mathieu Chartier90443472015-07-16 20:32:27 -07001919 std::string error_msg;
Nicolas Geoffray08025182016-10-25 17:20:18 +01001920 failure_kind =
1921 verifier::MethodVerifier::VerifyClass(soa.Self(),
Andreas Gampeec6e6c12015-11-05 20:39:56 -08001922 &dex_file,
1923 dex_cache,
1924 class_loader,
David Brazdil15fc7292016-09-02 14:13:18 +01001925 class_def,
Andreas Gampe53e32d12015-12-09 21:03:23 -08001926 Runtime::Current()->GetCompilerCallbacks(),
Andreas Gampeec6e6c12015-11-05 20:39:56 -08001927 true /* allow soft failures */,
Andreas Gampe7fe30232016-03-25 16:58:00 -07001928 log_level_,
Andreas Gampe6cc23ac2018-08-24 15:22:43 -07001929 sdk_version_,
Nicolas Geoffray08025182016-10-25 17:20:18 +01001930 &error_msg);
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07001931 if (failure_kind == verifier::FailureKind::kHardFailure) {
Mathieu Chartier90443472015-07-16 20:32:27 -07001932 LOG(ERROR) << "Verification failed on class " << PrettyDescriptor(descriptor)
1933 << " because: " << error_msg;
1934 manager_->GetCompiler()->SetHadHardVerifierFailure();
Andreas Gampef39208f2017-10-19 15:06:59 -07001935 } else if (failure_kind == verifier::FailureKind::kSoftFailure) {
1936 manager_->GetCompiler()->AddSoftVerifierFailure();
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00001937 } else {
1938 // Force a soft failure for the VerifierDeps. This is a sanity measure, as
1939 // the vdex file already records that the class hasn't been resolved. It avoids
1940 // trying to do future verification optimizations when processing the vdex file.
Andreas Gampef39208f2017-10-19 15:06:59 -07001941 DCHECK(failure_kind == verifier::FailureKind::kNoFailure) << failure_kind;
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07001942 failure_kind = verifier::FailureKind::kSoftFailure;
Mathieu Chartier90443472015-07-16 20:32:27 -07001943 }
Andreas Gampebb30d5d2018-04-23 09:59:25 -07001944 } else if (&klass->GetDexFile() != &dex_file) {
1945 // Skip a duplicate class (as the resolved class is from another, earlier dex file).
1946 return; // Do not update state.
Mathieu Chartier90443472015-07-16 20:32:27 -07001947 } else if (!SkipClass(jclass_loader, dex_file, klass.Get())) {
David Sehr709b0702016-10-13 09:12:37 -07001948 CHECK(klass->IsResolved()) << klass->PrettyClass();
Nicolas Geoffray08025182016-10-25 17:20:18 +01001949 failure_kind = class_linker->VerifyClass(soa.Self(), klass, log_level_);
Mathieu Chartier90443472015-07-16 20:32:27 -07001950
1951 if (klass->IsErroneous()) {
1952 // ClassLinker::VerifyClass throws, which isn't useful in the compiler.
1953 CHECK(soa.Self()->IsExceptionPending());
1954 soa.Self()->ClearException();
1955 manager_->GetCompiler()->SetHadHardVerifierFailure();
Andreas Gampef39208f2017-10-19 15:06:59 -07001956 } else if (failure_kind == verifier::FailureKind::kSoftFailure) {
1957 manager_->GetCompiler()->AddSoftVerifierFailure();
Mathieu Chartier90443472015-07-16 20:32:27 -07001958 }
1959
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00001960 CHECK(klass->ShouldVerifyAtRuntime() || klass->IsVerified() || klass->IsErroneous())
David Sehr709b0702016-10-13 09:12:37 -07001961 << klass->PrettyDescriptor() << ": state=" << klass->GetStatus();
Mathieu Chartier90443472015-07-16 20:32:27 -07001962
Nicolas Geoffrayc7da1d62017-04-19 09:36:24 +01001963 // Class has a meaningful status for the compiler now, record it.
1964 ClassReference ref(manager_->GetDexFile(), class_def_index);
1965 manager_->GetCompiler()->RecordClassStatus(ref, klass->GetStatus());
1966
Andreas Gamped278cb42017-11-22 14:13:00 -08001967 // It is *very* problematic if there are resolution errors in the boot classpath.
1968 //
1969 // It is also bad if classes fail verification. For example, we rely on things working
1970 // OK without verification when the decryption dialog is brought up. It is thus highly
1971 // recommended to compile the boot classpath with
1972 // --abort-on-hard-verifier-error --abort-on-soft-verifier-error
1973 // which is the default build system configuration.
Narayan Kamathe3eae5e2016-10-27 11:47:30 +01001974 if (kIsDebugBuild) {
Orion Hodsonc5e0d3f2017-08-22 19:00:04 +01001975 if (manager_->GetCompiler()->GetCompilerOptions().IsBootImage()) {
Andreas Gamped278cb42017-11-22 14:13:00 -08001976 if (!klass->IsResolved() || klass->IsErroneous()) {
Andreas Gampe12fadcd2017-08-03 05:06:28 -07001977 LOG(FATAL) << "Boot classpath class " << klass->PrettyClass()
Andreas Gamped278cb42017-11-22 14:13:00 -08001978 << " failed to resolve/is erroneous: state= " << klass->GetStatus();
1979 UNREACHABLE();
Andreas Gampe12fadcd2017-08-03 05:06:28 -07001980 }
Narayan Kamathe3eae5e2016-10-27 11:47:30 +01001981 }
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00001982 if (klass->IsVerified()) {
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07001983 DCHECK_EQ(failure_kind, verifier::FailureKind::kNoFailure);
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00001984 } else if (klass->ShouldVerifyAtRuntime()) {
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07001985 DCHECK_EQ(failure_kind, verifier::FailureKind::kSoftFailure);
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00001986 } else {
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07001987 DCHECK_EQ(failure_kind, verifier::FailureKind::kHardFailure);
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00001988 }
Narayan Kamathe3eae5e2016-10-27 11:47:30 +01001989 }
Nicolas Geoffray08025182016-10-25 17:20:18 +01001990 } else {
1991 // Make the skip a soft failure, essentially being considered as verify at runtime.
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07001992 failure_kind = verifier::FailureKind::kSoftFailure;
Ian Rogerse6bb3b22013-08-19 21:51:45 -07001993 }
Nicolas Geoffray08025182016-10-25 17:20:18 +01001994 verifier::VerifierDeps::MaybeRecordVerificationStatus(
1995 dex_file, class_def.class_idx_, failure_kind);
Mathieu Chartier90443472015-07-16 20:32:27 -07001996 soa.Self()->AssertNoPendingException();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001997 }
Mathieu Chartier90443472015-07-16 20:32:27 -07001998
1999 private:
2000 const ParallelCompilationManager* const manager_;
Andreas Gampe5fd66d02016-09-12 20:22:19 -07002001 const verifier::HardFailLogMode log_level_;
Andreas Gampe6cc23ac2018-08-24 15:22:43 -07002002 const uint32_t sdk_version_;
Mathieu Chartier90443472015-07-16 20:32:27 -07002003};
Brian Carlstrom7940e442013-07-12 13:46:57 -07002004
Andreas Gampeace0dc12016-01-20 13:33:13 -08002005void CompilerDriver::VerifyDexFile(jobject class_loader,
2006 const DexFile& dex_file,
Andreas Gampede7b4362014-07-28 18:38:57 -07002007 const std::vector<const DexFile*>& dex_files,
Andreas Gampeace0dc12016-01-20 13:33:13 -08002008 ThreadPool* thread_pool,
2009 size_t thread_count,
2010 TimingLogger* timings) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07002011 TimingLogger::ScopedTiming t("Verify Dex File", timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002012 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Andreas Gampede7b4362014-07-28 18:38:57 -07002013 ParallelCompilationManager context(class_linker, class_loader, this, &dex_file, dex_files,
2014 thread_pool);
Andreas Gampef39208f2017-10-19 15:06:59 -07002015 bool abort_on_verifier_failures = GetCompilerOptions().AbortOnHardVerifierFailure()
2016 || GetCompilerOptions().AbortOnSoftVerifierFailure();
2017 verifier::HardFailLogMode log_level = abort_on_verifier_failures
Andreas Gampe5fd66d02016-09-12 20:22:19 -07002018 ? verifier::HardFailLogMode::kLogInternalFatal
2019 : verifier::HardFailLogMode::kLogWarning;
Andreas Gampe7fe30232016-03-25 16:58:00 -07002020 VerifyClassVisitor visitor(&context, log_level);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002021 context.ForAll(0, dex_file.NumClassDefs(), &visitor, thread_count);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002022}
2023
Mathieu Chartier90443472015-07-16 20:32:27 -07002024class SetVerifiedClassVisitor : public CompilationVisitor {
2025 public:
2026 explicit SetVerifiedClassVisitor(const ParallelCompilationManager* manager) : manager_(manager) {}
2027
Roland Levillainf73caca2018-08-24 17:19:07 +01002028 void Visit(size_t class_def_index) REQUIRES(!Locks::mutator_lock_) override {
Andreas Gampe9b827ab2017-12-07 19:32:48 -08002029 ScopedTrace trace(__FUNCTION__);
Mathieu Chartier90443472015-07-16 20:32:27 -07002030 ScopedObjectAccess soa(Thread::Current());
2031 const DexFile& dex_file = *manager_->GetDexFile();
2032 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
2033 const char* descriptor = dex_file.GetClassDescriptor(class_def);
2034 ClassLinker* class_linker = manager_->GetClassLinker();
2035 jobject jclass_loader = manager_->GetClassLoader();
2036 StackHandleScope<3> hs(soa.Self());
2037 Handle<mirror::ClassLoader> class_loader(
Mathieu Chartier0795f232016-09-27 18:43:30 -07002038 hs.NewHandle(soa.Decode<mirror::ClassLoader>(jclass_loader)));
Mathieu Chartier90443472015-07-16 20:32:27 -07002039 Handle<mirror::Class> klass(
2040 hs.NewHandle(class_linker->FindClass(soa.Self(), descriptor, class_loader)));
2041 // Class might have failed resolution. Then don't set it to verified.
Andreas Gampefa4333d2017-02-14 11:10:34 -08002042 if (klass != nullptr) {
Mathieu Chartier90443472015-07-16 20:32:27 -07002043 // Only do this if the class is resolved. If even resolution fails, quickening will go very,
2044 // very wrong.
Vladimir Marko72ab6842017-01-20 19:32:50 +00002045 if (klass->IsResolved() && !klass->IsErroneousResolved()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00002046 if (klass->GetStatus() < ClassStatus::kVerified) {
Mathieu Chartier90443472015-07-16 20:32:27 -07002047 ObjectLock<mirror::Class> lock(soa.Self(), klass);
2048 // Set class status to verified.
Vladimir Marko2c64a832018-01-04 11:31:56 +00002049 mirror::Class::SetStatus(klass, ClassStatus::kVerified, soa.Self());
Mathieu Chartier90443472015-07-16 20:32:27 -07002050 // Mark methods as pre-verified. If we don't do this, the interpreter will run with
2051 // access checks.
Vladimir Markoa0431112018-06-25 09:32:54 +01002052 InstructionSet instruction_set =
2053 manager_->GetCompiler()->GetCompilerOptions().GetInstructionSet();
2054 klass->SetSkipAccessChecksFlagOnAllMethods(GetInstructionSetPointerSize(instruction_set));
Igor Murashkindf707e42016-02-02 16:56:50 -08002055 klass->SetVerificationAttempted();
Mathieu Chartier90443472015-07-16 20:32:27 -07002056 }
2057 // Record the final class status if necessary.
2058 ClassReference ref(manager_->GetDexFile(), class_def_index);
2059 manager_->GetCompiler()->RecordClassStatus(ref, klass->GetStatus());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002060 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002061 } else {
2062 Thread* self = soa.Self();
2063 DCHECK(self->IsExceptionPending());
2064 self->ClearException();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002065 }
2066 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002067
2068 private:
2069 const ParallelCompilationManager* const manager_;
2070};
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002071
Andreas Gampeace0dc12016-01-20 13:33:13 -08002072void CompilerDriver::SetVerifiedDexFile(jobject class_loader,
2073 const DexFile& dex_file,
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002074 const std::vector<const DexFile*>& dex_files,
Andreas Gampeace0dc12016-01-20 13:33:13 -08002075 ThreadPool* thread_pool,
2076 size_t thread_count,
2077 TimingLogger* timings) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002078 TimingLogger::ScopedTiming t("Verify Dex File", timings);
Mathieu Chartier1a088d42017-07-18 11:43:57 -07002079 if (!compiled_classes_.HaveDexFile(&dex_file)) {
Mathieu Chartierfc8b4222017-09-17 13:44:24 -07002080 compiled_classes_.AddDexFile(&dex_file);
Mathieu Chartier1a088d42017-07-18 11:43:57 -07002081 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002082 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
2083 ParallelCompilationManager context(class_linker, class_loader, this, &dex_file, dex_files,
2084 thread_pool);
Mathieu Chartier90443472015-07-16 20:32:27 -07002085 SetVerifiedClassVisitor visitor(&context);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002086 context.ForAll(0, dex_file.NumClassDefs(), &visitor, thread_count);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002087}
2088
Mathieu Chartier90443472015-07-16 20:32:27 -07002089class InitializeClassVisitor : public CompilationVisitor {
2090 public:
2091 explicit InitializeClassVisitor(const ParallelCompilationManager* manager) : manager_(manager) {}
Ian Rogersfc0e94b2013-09-23 23:51:32 -07002092
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002093 void Visit(size_t class_def_index) override {
Andreas Gampe9b827ab2017-12-07 19:32:48 -08002094 ScopedTrace trace(__FUNCTION__);
Mathieu Chartier90443472015-07-16 20:32:27 -07002095 jobject jclass_loader = manager_->GetClassLoader();
2096 const DexFile& dex_file = *manager_->GetDexFile();
2097 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
2098 const DexFile::TypeId& class_type_id = dex_file.GetTypeId(class_def.class_idx_);
2099 const char* descriptor = dex_file.StringDataByIdx(class_type_id.descriptor_idx_);
Jeff Hao0e49b422013-11-08 12:16:56 -08002100
Mathieu Chartier90443472015-07-16 20:32:27 -07002101 ScopedObjectAccess soa(Thread::Current());
2102 StackHandleScope<3> hs(soa.Self());
2103 Handle<mirror::ClassLoader> class_loader(
Mathieu Chartier0795f232016-09-27 18:43:30 -07002104 hs.NewHandle(soa.Decode<mirror::ClassLoader>(jclass_loader)));
Mathieu Chartier90443472015-07-16 20:32:27 -07002105 Handle<mirror::Class> klass(
2106 hs.NewHandle(manager_->GetClassLinker()->FindClass(soa.Self(), descriptor, class_loader)));
2107
Mathieu Chartierf1dd69a2017-06-08 23:30:15 +00002108 if (klass != nullptr && !SkipClass(manager_->GetClassLoader(), dex_file, klass.Get())) {
2109 TryInitializeClass(klass, class_loader);
2110 }
2111 // Clear any class not found or verification exceptions.
2112 soa.Self()->ClearException();
2113 }
2114
2115 // A helper function for initializing klass.
2116 void TryInitializeClass(Handle<mirror::Class> klass, Handle<mirror::ClassLoader>& class_loader)
2117 REQUIRES_SHARED(Locks::mutator_lock_) {
2118 const DexFile& dex_file = klass->GetDexFile();
2119 const DexFile::ClassDef* class_def = klass->GetClassDef();
2120 const DexFile::TypeId& class_type_id = dex_file.GetTypeId(class_def->class_idx_);
2121 const char* descriptor = dex_file.StringDataByIdx(class_type_id.descriptor_idx_);
2122 ScopedObjectAccessUnchecked soa(Thread::Current());
2123 StackHandleScope<3> hs(soa.Self());
Mathieu Chartierdabeb3a2017-06-12 17:10:07 -07002124 const bool is_boot_image = manager_->GetCompiler()->GetCompilerOptions().IsBootImage();
Mathieu Chartier17498e52017-06-13 11:35:04 -07002125 const bool is_app_image = manager_->GetCompiler()->GetCompilerOptions().IsAppImage();
Mathieu Chartierf1dd69a2017-06-08 23:30:15 +00002126
Vladimir Marko2c64a832018-01-04 11:31:56 +00002127 ClassStatus old_status = klass->GetStatus();
Mathieu Chartier1a088d42017-07-18 11:43:57 -07002128 // Don't initialize classes in boot space when compiling app image
2129 if (is_app_image && klass->IsBootStrapClassLoaded()) {
2130 // Also return early and don't store the class status in the recorded class status.
2131 return;
2132 }
Mathieu Chartierf1dd69a2017-06-08 23:30:15 +00002133 // Only try to initialize classes that were successfully verified.
2134 if (klass->IsVerified()) {
2135 // Attempt to initialize the class but bail if we either need to initialize the super-class
2136 // or static fields.
Nicolas Geoffrayabadf022017-08-03 08:25:41 +00002137 manager_->GetClassLinker()->EnsureInitialized(soa.Self(), klass, false, false);
Mathieu Chartierf1dd69a2017-06-08 23:30:15 +00002138 old_status = klass->GetStatus();
2139 if (!klass->IsInitialized()) {
2140 // We don't want non-trivial class initialization occurring on multiple threads due to
2141 // deadlock problems. For example, a parent class is initialized (holding its lock) that
2142 // refers to a sub-class in its static/class initializer causing it to try to acquire the
2143 // sub-class' lock. While on a second thread the sub-class is initialized (holding its lock)
2144 // after first initializing its parents, whose locks are acquired. This leads to a
2145 // parent-to-child and a child-to-parent lock ordering and consequent potential deadlock.
2146 // We need to use an ObjectLock due to potential suspension in the interpreting code. Rather
2147 // than use a special Object for the purpose we use the Class of java.lang.Class.
2148 Handle<mirror::Class> h_klass(hs.NewHandle(klass->GetClass()));
2149 ObjectLock<mirror::Class> lock(soa.Self(), h_klass);
2150 // Attempt to initialize allowing initialization of parent classes but still not static
2151 // fields.
Chang Xinge602b1c2017-06-30 11:55:01 -07002152 // Initialize dependencies first only for app image, to make TryInitialize recursive.
2153 bool is_superclass_initialized = !is_app_image ? true :
2154 InitializeDependencies(klass, class_loader, soa.Self());
2155 if (!is_app_image || (is_app_image && is_superclass_initialized)) {
Nicolas Geoffrayabadf022017-08-03 08:25:41 +00002156 manager_->GetClassLinker()->EnsureInitialized(soa.Self(), klass, false, true);
Chang Xinge602b1c2017-06-30 11:55:01 -07002157 }
2158 // Otherwise it's in app image but superclasses can't be initialized, no need to proceed.
Mathieu Chartierf1dd69a2017-06-08 23:30:15 +00002159 old_status = klass->GetStatus();
Chang Xing70f689d2017-06-08 17:16:12 -07002160
Chris Wailes0c61be42018-09-26 17:27:34 -07002161 bool too_many_encoded_fields = !is_boot_image &&
2162 klass->NumStaticFields() > kMaxEncodedFields;
2163
Mathieu Chartierdabeb3a2017-06-12 17:10:07 -07002164 // If the class was not initialized, we can proceed to see if we can initialize static
Chang Xing70f689d2017-06-08 17:16:12 -07002165 // fields. Limit the max number of encoded fields.
Mathieu Chartierf1dd69a2017-06-08 23:30:15 +00002166 if (!klass->IsInitialized() &&
Mathieu Chartier17498e52017-06-13 11:35:04 -07002167 (is_app_image || is_boot_image) &&
Chang Xinge602b1c2017-06-30 11:55:01 -07002168 is_superclass_initialized &&
Chang Xing70f689d2017-06-08 17:16:12 -07002169 !too_many_encoded_fields &&
Vladimir Markodc4bcce2018-06-21 16:15:42 +01002170 manager_->GetCompiler()->GetCompilerOptions().IsImageClass(descriptor)) {
Mathieu Chartierf1dd69a2017-06-08 23:30:15 +00002171 bool can_init_static_fields = false;
Mathieu Chartierdabeb3a2017-06-12 17:10:07 -07002172 if (is_boot_image) {
Mathieu Chartier90443472015-07-16 20:32:27 -07002173 // We need to initialize static fields, we only do this for image classes that aren't
Mathieu Chartierdabeb3a2017-06-12 17:10:07 -07002174 // marked with the $NoPreloadHolder (which implies this should not be initialized
2175 // early).
Mathieu Chartierf1dd69a2017-06-08 23:30:15 +00002176 can_init_static_fields = !StringPiece(descriptor).ends_with("$NoPreloadHolder;");
2177 } else {
Mathieu Chartier17498e52017-06-13 11:35:04 -07002178 CHECK(is_app_image);
Mathieu Chartierdabeb3a2017-06-12 17:10:07 -07002179 // The boot image case doesn't need to recursively initialize the dependencies with
2180 // special logic since the class linker already does this.
Mathieu Chartierdabeb3a2017-06-12 17:10:07 -07002181 can_init_static_fields =
Mathieu Chartier0933cc52018-03-23 14:25:08 -07002182 ClassLinker::kAppImageMayContainStrings &&
Mathieu Chartierf1dd69a2017-06-08 23:30:15 +00002183 !soa.Self()->IsExceptionPending() &&
Nicolas Geoffrayabadf022017-08-03 08:25:41 +00002184 is_superclass_initialized &&
2185 NoClinitInDependency(klass, soa.Self(), &class_loader);
Mathieu Chartierf1dd69a2017-06-08 23:30:15 +00002186 // TODO The checking for clinit can be removed since it's already
2187 // checked when init superclass. Currently keep it because it contains
2188 // processing of intern strings. Will be removed later when intern strings
2189 // and clinit are both initialized.
2190 }
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002191
Mathieu Chartierf1dd69a2017-06-08 23:30:15 +00002192 if (can_init_static_fields) {
2193 VLOG(compiler) << "Initializing: " << descriptor;
2194 // TODO multithreading support. We should ensure the current compilation thread has
2195 // exclusive access to the runtime and the transaction. To achieve this, we could use
2196 // a ReaderWriterMutex but we're holding the mutator lock so we fail mutex sanity
2197 // checks in Thread::AssertThreadSuspensionIsAllowable.
2198 Runtime* const runtime = Runtime::Current();
Mathieu Chartierf1dd69a2017-06-08 23:30:15 +00002199 // Run the class initializer in transaction mode.
Chang Xing5a906fc2017-07-26 15:01:16 -07002200 runtime->EnterTransactionMode(is_app_image, klass.Get());
Mathieu Chartierf1dd69a2017-06-08 23:30:15 +00002201 bool success = manager_->GetClassLinker()->EnsureInitialized(soa.Self(), klass, true,
2202 true);
2203 // TODO we detach transaction from runtime to indicate we quit the transactional
2204 // mode which prevents the GC from visiting objects modified during the transaction.
2205 // Ensure GC is not run so don't access freed objects when aborting transaction.
Andreas Gampe9e7078b2017-03-02 13:50:36 -08002206
Mathieu Chartierf1dd69a2017-06-08 23:30:15 +00002207 {
2208 ScopedAssertNoThreadSuspension ants("Transaction end");
Chang Xing16d1dd82017-07-20 17:56:26 -07002209
2210 if (success) {
2211 runtime->ExitTransactionMode();
2212 DCHECK(!runtime->IsActiveTransaction());
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002213
Chris Wailes0c61be42018-09-26 17:27:34 -07002214 if (is_boot_image) {
2215 // For boot image, we want to put the updated status in the oat class since we
2216 // can't reject the image anyways.
2217 old_status = klass->GetStatus();
2218 }
2219 } else {
Mathieu Chartierf1dd69a2017-06-08 23:30:15 +00002220 CHECK(soa.Self()->IsExceptionPending());
2221 mirror::Throwable* exception = soa.Self()->GetException();
2222 VLOG(compiler) << "Initialization of " << descriptor << " aborted because of "
2223 << exception->Dump();
2224 std::ostream* file_log = manager_->GetCompiler()->
2225 GetCompilerOptions().GetInitFailureOutput();
2226 if (file_log != nullptr) {
2227 *file_log << descriptor << "\n";
2228 *file_log << exception->Dump() << "\n";
2229 }
2230 soa.Self()->ClearException();
Chang Xing605fe242017-07-20 15:57:21 -07002231 runtime->RollbackAllTransactions();
Mathieu Chartierf1dd69a2017-06-08 23:30:15 +00002232 CHECK_EQ(old_status, klass->GetStatus()) << "Previous class status not restored";
2233 }
2234 }
2235
Nicolas Geoffrayabadf022017-08-03 08:25:41 +00002236 if (!success) {
Mathieu Chartierf1dd69a2017-06-08 23:30:15 +00002237 // On failure, still intern strings of static fields and seen in <clinit>, as these
2238 // will be created in the zygote. This is separated from the transaction code just
2239 // above as we will allocate strings, so must be allowed to suspend.
2240 if (&klass->GetDexFile() == manager_->GetDexFile()) {
Andreas Gampe9e7078b2017-03-02 13:50:36 -08002241 InternStrings(klass, class_loader);
Mathieu Chartierdabeb3a2017-06-12 17:10:07 -07002242 } else {
2243 DCHECK(!is_boot_image) << "Boot image must have equal dex files";
Andreas Gampedbfe2542014-11-25 22:21:42 -08002244 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002245 }
2246 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002247 }
Jeff Hao0cb17282017-07-12 14:51:49 -07002248 // If the class still isn't initialized, at least try some checks that initialization
2249 // would do so they can be skipped at runtime.
2250 if (!klass->IsInitialized() &&
2251 manager_->GetClassLinker()->ValidateSuperClassDescriptors(klass)) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00002252 old_status = ClassStatus::kSuperclassValidated;
Jeff Hao0cb17282017-07-12 14:51:49 -07002253 } else {
2254 soa.Self()->ClearException();
2255 }
Mathieu Chartierf1dd69a2017-06-08 23:30:15 +00002256 soa.Self()->AssertNoPendingException();
Brian Carlstrom7940e442013-07-12 13:46:57 -07002257 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002258 }
Mathieu Chartierf1dd69a2017-06-08 23:30:15 +00002259 // Record the final class status if necessary.
2260 ClassReference ref(&dex_file, klass->GetDexClassDefIndex());
2261 // Back up the status before doing initialization for static encoded fields,
2262 // because the static encoded branch wants to keep the status to uninitialized.
2263 manager_->GetCompiler()->RecordClassStatus(ref, old_status);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002264 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002265
2266 private:
Andreas Gampe9e7078b2017-03-02 13:50:36 -08002267 void InternStrings(Handle<mirror::Class> klass, Handle<mirror::ClassLoader> class_loader)
2268 REQUIRES_SHARED(Locks::mutator_lock_) {
2269 DCHECK(manager_->GetCompiler()->GetCompilerOptions().IsBootImage());
2270 DCHECK(klass->IsVerified());
2271 DCHECK(!klass->IsInitialized());
2272
2273 StackHandleScope<1> hs(Thread::Current());
Vladimir Markoe11dd502017-12-08 14:09:45 +00002274 Handle<mirror::DexCache> dex_cache = hs.NewHandle(klass->GetDexCache());
Andreas Gampe9e7078b2017-03-02 13:50:36 -08002275 const DexFile::ClassDef* class_def = klass->GetClassDef();
2276 ClassLinker* class_linker = manager_->GetClassLinker();
2277
Andreas Gampe7bf90482017-03-02 16:41:35 -08002278 // Check encoded final field values for strings and intern.
Vladimir Markoe11dd502017-12-08 14:09:45 +00002279 annotations::RuntimeEncodedStaticFieldValueIterator value_it(dex_cache,
2280 class_loader,
Andreas Gampe9e7078b2017-03-02 13:50:36 -08002281 manager_->GetClassLinker(),
2282 *class_def);
2283 for ( ; value_it.HasNext(); value_it.Next()) {
2284 if (value_it.GetValueType() == annotations::RuntimeEncodedStaticFieldValueIterator::kString) {
2285 // Resolve the string. This will intern the string.
2286 art::ObjPtr<mirror::String> resolved = class_linker->ResolveString(
Vladimir Markoa64b52d2017-12-08 16:27:49 +00002287 dex::StringIndex(value_it.GetJavaValue().i), dex_cache);
Andreas Gampe9e7078b2017-03-02 13:50:36 -08002288 CHECK(resolved != nullptr);
2289 }
2290 }
Andreas Gampe7bf90482017-03-02 16:41:35 -08002291
2292 // Intern strings seen in <clinit>.
2293 ArtMethod* clinit = klass->FindClassInitializer(class_linker->GetImagePointerSize());
2294 if (clinit != nullptr) {
Mathieu Chartier73f21d42018-01-02 14:26:50 -08002295 for (const DexInstructionPcPair& inst : clinit->DexInstructions()) {
Mathieu Chartier2b2bef22017-10-26 17:10:19 -07002296 if (inst->Opcode() == Instruction::CONST_STRING) {
Andreas Gampe7bf90482017-03-02 16:41:35 -08002297 ObjPtr<mirror::String> s = class_linker->ResolveString(
Vladimir Markoa64b52d2017-12-08 16:27:49 +00002298 dex::StringIndex(inst->VRegB_21c()), dex_cache);
Andreas Gampe7bf90482017-03-02 16:41:35 -08002299 CHECK(s != nullptr);
Mathieu Chartier2b2bef22017-10-26 17:10:19 -07002300 } else if (inst->Opcode() == Instruction::CONST_STRING_JUMBO) {
Andreas Gampe7bf90482017-03-02 16:41:35 -08002301 ObjPtr<mirror::String> s = class_linker->ResolveString(
Vladimir Markoa64b52d2017-12-08 16:27:49 +00002302 dex::StringIndex(inst->VRegB_31c()), dex_cache);
Andreas Gampe7bf90482017-03-02 16:41:35 -08002303 CHECK(s != nullptr);
2304 }
Andreas Gampe7bf90482017-03-02 16:41:35 -08002305 }
2306 }
Andreas Gampe9e7078b2017-03-02 13:50:36 -08002307 }
2308
Mathieu Chartierf1dd69a2017-06-08 23:30:15 +00002309 bool ResolveTypesOfMethods(Thread* self, ArtMethod* m)
2310 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markob45528c2017-07-27 14:14:28 +01002311 // Return value of ResolveReturnType() is discarded because resolve will be done internally.
2312 ObjPtr<mirror::Class> rtn_type = m->ResolveReturnType();
Mathieu Chartier7a8bcfd2017-06-13 13:40:43 -07002313 if (rtn_type == nullptr) {
2314 self->ClearException();
2315 return false;
2316 }
2317 const DexFile::TypeList* types = m->GetParameterTypeList();
2318 if (types != nullptr) {
2319 for (uint32_t i = 0; i < types->Size(); ++i) {
2320 dex::TypeIndex param_type_idx = types->GetTypeItem(i).type_idx_;
Vladimir Markob45528c2017-07-27 14:14:28 +01002321 ObjPtr<mirror::Class> param_type = m->ResolveClassFromTypeIndex(param_type_idx);
Mathieu Chartier7a8bcfd2017-06-13 13:40:43 -07002322 if (param_type == nullptr) {
2323 self->ClearException();
2324 return false;
Mathieu Chartierf1dd69a2017-06-08 23:30:15 +00002325 }
2326 }
Mathieu Chartier7a8bcfd2017-06-13 13:40:43 -07002327 }
2328 return true;
Mathieu Chartierf1dd69a2017-06-08 23:30:15 +00002329 }
2330
2331 // Pre resolve types mentioned in all method signatures before start a transaction
2332 // since ResolveType doesn't work in transaction mode.
2333 bool PreResolveTypes(Thread* self, const Handle<mirror::Class>& klass)
2334 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier7a8bcfd2017-06-13 13:40:43 -07002335 PointerSize pointer_size = manager_->GetClassLinker()->GetImagePointerSize();
2336 for (ArtMethod& m : klass->GetMethods(pointer_size)) {
2337 if (!ResolveTypesOfMethods(self, &m)) {
2338 return false;
2339 }
2340 }
2341 if (klass->IsInterface()) {
2342 return true;
2343 } else if (klass->HasSuperClass()) {
2344 StackHandleScope<1> hs(self);
2345 MutableHandle<mirror::Class> super_klass(hs.NewHandle<mirror::Class>(klass->GetSuperClass()));
2346 for (int i = super_klass->GetVTableLength() - 1; i >= 0; --i) {
2347 ArtMethod* m = klass->GetVTableEntry(i, pointer_size);
2348 ArtMethod* super_m = super_klass->GetVTableEntry(i, pointer_size);
2349 if (!ResolveTypesOfMethods(self, m) || !ResolveTypesOfMethods(self, super_m)) {
Mathieu Chartierf1dd69a2017-06-08 23:30:15 +00002350 return false;
2351 }
2352 }
Mathieu Chartier7a8bcfd2017-06-13 13:40:43 -07002353 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
2354 super_klass.Assign(klass->GetIfTable()->GetInterface(i));
2355 if (klass->GetClassLoader() != super_klass->GetClassLoader()) {
2356 uint32_t num_methods = super_klass->NumVirtualMethods();
2357 for (uint32_t j = 0; j < num_methods; ++j) {
2358 ArtMethod* m = klass->GetIfTable()->GetMethodArray(i)->GetElementPtrSize<ArtMethod*>(
2359 j, pointer_size);
2360 ArtMethod* super_m = super_klass->GetVirtualMethod(j, pointer_size);
2361 if (!ResolveTypesOfMethods(self, m) || !ResolveTypesOfMethods(self, super_m)) {
2362 return false;
Mathieu Chartierf1dd69a2017-06-08 23:30:15 +00002363 }
2364 }
2365 }
2366 }
Mathieu Chartier7a8bcfd2017-06-13 13:40:43 -07002367 }
2368 return true;
Mathieu Chartierf1dd69a2017-06-08 23:30:15 +00002369 }
2370
2371 // Initialize the klass's dependencies recursively before initializing itself.
2372 // Checking for interfaces is also necessary since interfaces can contain
2373 // both default methods and static encoded fields.
2374 bool InitializeDependencies(const Handle<mirror::Class>& klass,
2375 Handle<mirror::ClassLoader> class_loader,
2376 Thread* self)
2377 REQUIRES_SHARED(Locks::mutator_lock_) {
2378 if (klass->HasSuperClass()) {
2379 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
2380 StackHandleScope<1> hs(self);
2381 Handle<mirror::Class> handle_scope_super(hs.NewHandle(super_class));
2382 if (!handle_scope_super->IsInitialized()) {
2383 this->TryInitializeClass(handle_scope_super, class_loader);
2384 if (!handle_scope_super->IsInitialized()) {
2385 return false;
2386 }
2387 }
2388 }
2389
2390 uint32_t num_if = klass->NumDirectInterfaces();
2391 for (size_t i = 0; i < num_if; i++) {
2392 ObjPtr<mirror::Class>
2393 interface = mirror::Class::GetDirectInterface(self, klass.Get(), i);
2394 StackHandleScope<1> hs(self);
2395 Handle<mirror::Class> handle_interface(hs.NewHandle(interface));
2396
2397 TryInitializeClass(handle_interface, class_loader);
2398
2399 if (!handle_interface->IsInitialized()) {
2400 return false;
2401 }
2402 }
2403
2404 return PreResolveTypes(self, klass);
2405 }
2406
2407 // In this phase the classes containing class initializers are ignored. Make sure no
2408 // clinit appears in kalss's super class chain and interfaces.
2409 bool NoClinitInDependency(const Handle<mirror::Class>& klass,
2410 Thread* self,
2411 Handle<mirror::ClassLoader>* class_loader)
2412 REQUIRES_SHARED(Locks::mutator_lock_) {
2413 ArtMethod* clinit =
2414 klass->FindClassInitializer(manager_->GetClassLinker()->GetImagePointerSize());
2415 if (clinit != nullptr) {
2416 VLOG(compiler) << klass->PrettyClass() << ' ' << clinit->PrettyMethod(true);
2417 return false;
2418 }
2419 if (klass->HasSuperClass()) {
2420 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
2421 StackHandleScope<1> hs(self);
2422 Handle<mirror::Class> handle_scope_super(hs.NewHandle(super_class));
2423 if (!NoClinitInDependency(handle_scope_super, self, class_loader)) {
2424 return false;
2425 }
2426 }
2427
2428 uint32_t num_if = klass->NumDirectInterfaces();
2429 for (size_t i = 0; i < num_if; i++) {
2430 ObjPtr<mirror::Class>
2431 interface = mirror::Class::GetDirectInterface(self, klass.Get(), i);
2432 StackHandleScope<1> hs(self);
2433 Handle<mirror::Class> handle_interface(hs.NewHandle(interface));
2434 if (!NoClinitInDependency(handle_interface, self, class_loader)) {
2435 return false;
2436 }
2437 }
2438
Chang Xingba17dbd2017-06-28 21:27:56 +00002439 return true;
Mathieu Chartierf1dd69a2017-06-08 23:30:15 +00002440 }
2441
Mathieu Chartier90443472015-07-16 20:32:27 -07002442 const ParallelCompilationManager* const manager_;
2443};
Brian Carlstrom7940e442013-07-12 13:46:57 -07002444
Andreas Gampeace0dc12016-01-20 13:33:13 -08002445void CompilerDriver::InitializeClasses(jobject jni_class_loader,
2446 const DexFile& dex_file,
Andreas Gampede7b4362014-07-28 18:38:57 -07002447 const std::vector<const DexFile*>& dex_files,
Andreas Gampeace0dc12016-01-20 13:33:13 -08002448 TimingLogger* timings) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07002449 TimingLogger::ScopedTiming t("InitializeNoClinit", timings);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002450
2451 // Initialization allocates objects and needs to run single-threaded to be deterministic.
2452 bool force_determinism = GetCompilerOptions().IsForceDeterminism();
2453 ThreadPool* init_thread_pool = force_determinism
2454 ? single_thread_pool_.get()
2455 : parallel_thread_pool_.get();
2456 size_t init_thread_count = force_determinism ? 1U : parallel_thread_count_;
2457
Brian Carlstrom7940e442013-07-12 13:46:57 -07002458 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Andreas Gampede7b4362014-07-28 18:38:57 -07002459 ParallelCompilationManager context(class_linker, jni_class_loader, this, &dex_file, dex_files,
Andreas Gampeace0dc12016-01-20 13:33:13 -08002460 init_thread_pool);
Mathieu Chartierf1dd69a2017-06-08 23:30:15 +00002461
2462 if (GetCompilerOptions().IsBootImage() || GetCompilerOptions().IsAppImage()) {
2463 // Set the concurrency thread to 1 to support initialization for App Images since transaction
2464 // doesn't support multithreading now.
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002465 // TODO: remove this when transactional mode supports multithreading.
Andreas Gampeace0dc12016-01-20 13:33:13 -08002466 init_thread_count = 1U;
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002467 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002468 InitializeClassVisitor visitor(&context);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002469 context.ForAll(0, dex_file.NumClassDefs(), &visitor, init_thread_count);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002470}
2471
Mathieu Chartier91288d82016-04-28 09:44:54 -07002472class InitializeArrayClassesAndCreateConflictTablesVisitor : public ClassVisitor {
Mathieu Chartier085a0722016-04-01 17:33:31 -07002473 public:
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002474 explicit InitializeArrayClassesAndCreateConflictTablesVisitor(VariableSizedHandleScope& hs)
2475 : hs_(hs) {}
2476
Roland Levillainf73caca2018-08-24 17:19:07 +01002477 bool operator()(ObjPtr<mirror::Class> klass) override
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002478 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier91288d82016-04-28 09:44:54 -07002479 if (Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(klass)) {
2480 return true;
2481 }
Mathieu Chartier085a0722016-04-01 17:33:31 -07002482 if (klass->IsArrayClass()) {
2483 StackHandleScope<1> hs(Thread::Current());
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002484 auto h_klass = hs.NewHandleWrapper(&klass);
2485 Runtime::Current()->GetClassLinker()->EnsureInitialized(hs.Self(), h_klass, true, true);
Mathieu Chartier085a0722016-04-01 17:33:31 -07002486 }
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002487 // Collect handles since there may be thread suspension in future EnsureInitialized.
2488 to_visit_.push_back(hs_.NewHandle(klass));
Nicolas Geoffray88f288e2016-06-29 08:17:52 +00002489 return true;
Nelli Kimbadee982016-05-13 13:08:53 +03002490 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00002491
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002492 void FillAllIMTAndConflictTables() REQUIRES_SHARED(Locks::mutator_lock_) {
2493 for (Handle<mirror::Class> c : to_visit_) {
2494 // Create the conflict tables.
2495 FillIMTAndConflictTables(c.Get());
2496 }
2497 }
2498
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00002499 private:
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002500 void FillIMTAndConflictTables(ObjPtr<mirror::Class> klass)
2501 REQUIRES_SHARED(Locks::mutator_lock_) {
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00002502 if (!klass->ShouldHaveImt()) {
2503 return;
2504 }
2505 if (visited_classes_.find(klass) != visited_classes_.end()) {
2506 return;
2507 }
2508 if (klass->HasSuperClass()) {
2509 FillIMTAndConflictTables(klass->GetSuperClass());
2510 }
2511 if (!klass->IsTemp()) {
2512 Runtime::Current()->GetClassLinker()->FillIMTAndConflictTables(klass);
2513 }
2514 visited_classes_.insert(klass);
2515 }
2516
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002517 VariableSizedHandleScope& hs_;
2518 std::vector<Handle<mirror::Class>> to_visit_;
2519 std::unordered_set<ObjPtr<mirror::Class>, HashObjPtr> visited_classes_;
Mathieu Chartier085a0722016-04-01 17:33:31 -07002520};
2521
Brian Carlstrom7940e442013-07-12 13:46:57 -07002522void CompilerDriver::InitializeClasses(jobject class_loader,
2523 const std::vector<const DexFile*>& dex_files,
Andreas Gampeace0dc12016-01-20 13:33:13 -08002524 TimingLogger* timings) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07002525 for (size_t i = 0; i != dex_files.size(); ++i) {
2526 const DexFile* dex_file = dex_files[i];
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002527 CHECK(dex_file != nullptr);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002528 InitializeClasses(class_loader, *dex_file, dex_files, timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002529 }
Vladimir Markoaad75c62016-10-03 08:46:48 +00002530 if (GetCompilerOptions().IsBootImage() || GetCompilerOptions().IsAppImage()) {
Mathieu Chartier085a0722016-04-01 17:33:31 -07002531 // Make sure that we call EnsureIntiailized on all the array classes to call
2532 // SetVerificationAttempted so that the access flags are set. If we do not do this they get
2533 // changed at runtime resulting in more dirty image pages.
Mathieu Chartier91288d82016-04-28 09:44:54 -07002534 // Also create conflict tables.
2535 // Only useful if we are compiling an image (image_classes_ is not null).
Mathieu Chartier085a0722016-04-01 17:33:31 -07002536 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002537 VariableSizedHandleScope hs(soa.Self());
2538 InitializeArrayClassesAndCreateConflictTablesVisitor visitor(hs);
Mathieu Chartier91288d82016-04-28 09:44:54 -07002539 Runtime::Current()->GetClassLinker()->VisitClassesWithoutClassesLock(&visitor);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002540 visitor.FillAllIMTAndConflictTables();
Mathieu Chartier085a0722016-04-01 17:33:31 -07002541 }
Vladimir Markoaad75c62016-10-03 08:46:48 +00002542 if (GetCompilerOptions().IsBootImage()) {
Mathieu Chartier093ef212014-08-11 13:52:12 -07002543 // Prune garbage objects created during aborted transactions.
Roland Levillainaf290312018-02-27 20:02:17 +00002544 Runtime::Current()->GetHeap()->CollectGarbage(/* clear_soft_references */ true);
Mathieu Chartier093ef212014-08-11 13:52:12 -07002545 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002546}
2547
Andreas Gampe3c060ad2018-01-22 13:07:49 -08002548template <typename CompileFn>
2549static void CompileDexFile(CompilerDriver* driver,
2550 jobject class_loader,
2551 const DexFile& dex_file,
2552 const std::vector<const DexFile*>& dex_files,
2553 ThreadPool* thread_pool,
2554 size_t thread_count,
2555 TimingLogger* timings,
2556 const char* timing_name,
2557 CompileFn compile_fn) {
2558 TimingLogger::ScopedTiming t(timing_name, timings);
2559 ParallelCompilationManager context(Runtime::Current()->GetClassLinker(),
2560 class_loader,
2561 driver,
2562 &dex_file,
2563 dex_files,
2564 thread_pool);
Vladimir Marko492a7fa2016-06-01 18:38:43 +01002565
Andreas Gampe3c060ad2018-01-22 13:07:49 -08002566 auto compile = [&context, &compile_fn](size_t class_def_index) {
Andreas Gampe3c060ad2018-01-22 13:07:49 -08002567 const DexFile& dex_file = *context.GetDexFile();
Andreas Gampe3e7f66b2018-09-06 10:08:18 -07002568 SCOPED_TRACE << "compile " << dex_file.GetLocation() << "@" << class_def_index;
Andreas Gampe3c060ad2018-01-22 13:07:49 -08002569 ClassLinker* class_linker = context.GetClassLinker();
2570 jobject jclass_loader = context.GetClassLoader();
Mathieu Chartier90443472015-07-16 20:32:27 -07002571 ClassReference ref(&dex_file, class_def_index);
Mathieu Chartierc8c8d5f2018-05-22 11:56:14 -07002572 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
Mathieu Chartier18e26872018-06-04 17:19:02 -07002573 ClassAccessor accessor(dex_file, class_def_index);
Mathieu Chartier90443472015-07-16 20:32:27 -07002574 // Skip compiling classes with generic verifier failures since they will still fail at runtime
Andreas Gampe3c060ad2018-01-22 13:07:49 -08002575 if (context.GetCompiler()->GetVerificationResults()->IsClassRejected(ref)) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07002576 return;
2577 }
Mathieu Chartier736b5602015-09-02 14:54:11 -07002578 // Use a scoped object access to perform to the quick SkipClass check.
Mathieu Chartier736b5602015-09-02 14:54:11 -07002579 ScopedObjectAccess soa(Thread::Current());
2580 StackHandleScope<3> hs(soa.Self());
2581 Handle<mirror::ClassLoader> class_loader(
Mathieu Chartier0795f232016-09-27 18:43:30 -07002582 hs.NewHandle(soa.Decode<mirror::ClassLoader>(jclass_loader)));
Mathieu Chartier736b5602015-09-02 14:54:11 -07002583 Handle<mirror::Class> klass(
Mathieu Chartierc8c8d5f2018-05-22 11:56:14 -07002584 hs.NewHandle(class_linker->FindClass(soa.Self(), accessor.GetDescriptor(), class_loader)));
Mathieu Chartier736b5602015-09-02 14:54:11 -07002585 Handle<mirror::DexCache> dex_cache;
Andreas Gampefa4333d2017-02-14 11:10:34 -08002586 if (klass == nullptr) {
Mathieu Chartier736b5602015-09-02 14:54:11 -07002587 soa.Self()->AssertPendingException();
2588 soa.Self()->ClearException();
2589 dex_cache = hs.NewHandle(class_linker->FindDexCache(soa.Self(), dex_file));
2590 } else if (SkipClass(jclass_loader, dex_file, klass.Get())) {
2591 return;
Andreas Gampebb30d5d2018-04-23 09:59:25 -07002592 } else if (&klass->GetDexFile() != &dex_file) {
2593 // Skip a duplicate class (as the resolved class is from another, earlier dex file).
2594 return; // Do not update state.
Mathieu Chartier736b5602015-09-02 14:54:11 -07002595 } else {
2596 dex_cache = hs.NewHandle(klass->GetDexCache());
2597 }
2598
Mathieu Chartierc8c8d5f2018-05-22 11:56:14 -07002599 // Avoid suspension if there are no methods to compile.
2600 if (accessor.NumDirectMethods() + accessor.NumVirtualMethods() == 0) {
Mathieu Chartier90443472015-07-16 20:32:27 -07002601 return;
Brian Carlstrom7940e442013-07-12 13:46:57 -07002602 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002603
Mathieu Chartier736b5602015-09-02 14:54:11 -07002604 // Go to native so that we don't block GC during compilation.
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07002605 ScopedThreadSuspension sts(soa.Self(), kNative);
Mathieu Chartier736b5602015-09-02 14:54:11 -07002606
Andreas Gampe3c060ad2018-01-22 13:07:49 -08002607 CompilerDriver* const driver = context.GetCompiler();
Mathieu Chartier90443472015-07-16 20:32:27 -07002608
2609 // Can we run DEX-to-DEX compiler on this class ?
Mathieu Chartiera79efdb2018-01-18 16:31:01 -08002610 optimizer::DexToDexCompiler::CompilationLevel dex_to_dex_compilation_level =
Mathieu Chartier736b5602015-09-02 14:54:11 -07002611 GetDexToDexCompilationLevel(soa.Self(), *driver, jclass_loader, dex_file, class_def);
Andreas Gampe5eb0d382015-07-23 01:19:26 -07002612
Mathieu Chartier90443472015-07-16 20:32:27 -07002613
Mathieu Chartierc8c8d5f2018-05-22 11:56:14 -07002614 const bool compilation_enabled = driver->IsClassToCompile(accessor.GetDescriptor());
Mathieu Chartier90443472015-07-16 20:32:27 -07002615
Mathieu Chartierb7c273c2017-11-10 18:07:56 -08002616 // Compile direct and virtual methods.
2617 int64_t previous_method_idx = -1;
Mathieu Chartier0d896bd2018-05-25 00:20:27 -07002618 for (const ClassAccessor::Method& method : accessor.GetMethods()) {
Mathieu Chartierc8c8d5f2018-05-22 11:56:14 -07002619 const uint32_t method_idx = method.GetIndex();
Mathieu Chartierb7c273c2017-11-10 18:07:56 -08002620 if (method_idx == previous_method_idx) {
Mathieu Chartier90443472015-07-16 20:32:27 -07002621 // smali can create dex files with two encoded_methods sharing the same method_idx
2622 // http://code.google.com/p/smali/issues/detail?id=119
Mathieu Chartier0d896bd2018-05-25 00:20:27 -07002623 continue;
Mathieu Chartier90443472015-07-16 20:32:27 -07002624 }
Mathieu Chartierb7c273c2017-11-10 18:07:56 -08002625 previous_method_idx = method_idx;
Andreas Gampe3c060ad2018-01-22 13:07:49 -08002626 compile_fn(soa.Self(),
2627 driver,
Mathieu Chartierc8c8d5f2018-05-22 11:56:14 -07002628 method.GetCodeItem(),
2629 method.GetAccessFlags(),
2630 method.GetInvokeType(class_def.access_flags_),
Andreas Gampe3c060ad2018-01-22 13:07:49 -08002631 class_def_index,
2632 method_idx,
2633 class_loader,
2634 dex_file,
2635 dex_to_dex_compilation_level,
2636 compilation_enabled,
2637 dex_cache);
Mathieu Chartier0d896bd2018-05-25 00:20:27 -07002638 }
Andreas Gampe3c060ad2018-01-22 13:07:49 -08002639 };
2640 context.ForAllLambda(0, dex_file.NumClassDefs(), compile, thread_count);
2641}
2642
2643void CompilerDriver::Compile(jobject class_loader,
2644 const std::vector<const DexFile*>& dex_files,
2645 TimingLogger* timings) {
2646 if (kDebugProfileGuidedCompilation) {
2647 LOG(INFO) << "[ProfileGuidedCompilation] " <<
2648 ((profile_compilation_info_ == nullptr)
2649 ? "null"
Mathieu Chartier0573f852018-10-01 13:52:12 -07002650 : profile_compilation_info_->DumpInfo(dex_files));
Brian Carlstrom7940e442013-07-12 13:46:57 -07002651 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002652
Andreas Gampe3c060ad2018-01-22 13:07:49 -08002653 dex_to_dex_compiler_.ClearState();
2654 for (const DexFile* dex_file : dex_files) {
2655 CHECK(dex_file != nullptr);
2656 CompileDexFile(this,
2657 class_loader,
2658 *dex_file,
2659 dex_files,
2660 parallel_thread_pool_.get(),
2661 parallel_thread_count_,
2662 timings,
2663 "Compile Dex File Quick",
2664 CompileMethodQuick);
2665 const ArenaPool* const arena_pool = Runtime::Current()->GetArenaPool();
2666 const size_t arena_alloc = arena_pool->GetBytesAllocated();
2667 max_arena_alloc_ = std::max(arena_alloc, max_arena_alloc_);
2668 Runtime::Current()->ReclaimArenaPoolMemory();
2669 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002670
Mathieu Chartier279e3a32018-01-24 18:17:55 -08002671 if (dex_to_dex_compiler_.NumCodeItemsToQuicken(Thread::Current()) > 0u) {
Andreas Gampe3c060ad2018-01-22 13:07:49 -08002672 // TODO: Not visit all of the dex files, its probably rare that only one would have quickened
2673 // methods though.
2674 for (const DexFile* dex_file : dex_files) {
2675 CompileDexFile(this,
2676 class_loader,
2677 *dex_file,
2678 dex_files,
2679 parallel_thread_pool_.get(),
2680 parallel_thread_count_,
2681 timings,
2682 "Compile Dex File Dex2Dex",
2683 CompileMethodDex2Dex);
2684 }
2685 dex_to_dex_compiler_.ClearState();
2686 }
2687
2688 VLOG(compiler) << "Compile: " << GetMemoryUsageString(false);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002689}
2690
Andreas Gampe5eb0d382015-07-23 01:19:26 -07002691void CompilerDriver::AddCompiledMethod(const MethodReference& method_ref,
Vladimir Marko8e524ad2018-07-13 10:27:43 +01002692 CompiledMethod* const compiled_method) {
Mathieu Chartierfc8b4222017-09-17 13:44:24 -07002693 DCHECK(GetCompiledMethod(method_ref) == nullptr) << method_ref.PrettyMethod();
2694 MethodTable::InsertResult result = compiled_methods_.Insert(method_ref,
2695 /*expected*/ nullptr,
2696 compiled_method);
Mathieu Chartieracab8d42016-11-23 13:45:58 -08002697 CHECK(result == MethodTable::kInsertResultSuccess);
Mathieu Chartierfc8b4222017-09-17 13:44:24 -07002698 DCHECK(GetCompiledMethod(method_ref) != nullptr) << method_ref.PrettyMethod();
Brian Carlstrom7940e442013-07-12 13:46:57 -07002699}
2700
Mathieu Chartier279e3a32018-01-24 18:17:55 -08002701CompiledMethod* CompilerDriver::RemoveCompiledMethod(const MethodReference& method_ref) {
2702 CompiledMethod* ret = nullptr;
2703 CHECK(compiled_methods_.Remove(method_ref, &ret));
2704 return ret;
2705}
2706
Vladimir Marko2c64a832018-01-04 11:31:56 +00002707bool CompilerDriver::GetCompiledClass(const ClassReference& ref, ClassStatus* status) const {
Andreas Gampebb846102017-05-11 21:03:35 -07002708 DCHECK(status != nullptr);
Mathieu Chartier1a088d42017-07-18 11:43:57 -07002709 // The table doesn't know if something wasn't inserted. For this case it will return
Vladimir Marko2c64a832018-01-04 11:31:56 +00002710 // ClassStatus::kNotReady. To handle this, just assume anything we didn't try to verify
2711 // is not compiled.
Mathieu Chartierfc8b4222017-09-17 13:44:24 -07002712 if (!compiled_classes_.Get(ref, status) ||
Vladimir Marko2c64a832018-01-04 11:31:56 +00002713 *status < ClassStatus::kRetryVerificationAtRuntime) {
Andreas Gampebb846102017-05-11 21:03:35 -07002714 return false;
Brian Carlstrom7940e442013-07-12 13:46:57 -07002715 }
Andreas Gampebb846102017-05-11 21:03:35 -07002716 return true;
Brian Carlstrom7940e442013-07-12 13:46:57 -07002717}
2718
Vladimir Marko2c64a832018-01-04 11:31:56 +00002719ClassStatus CompilerDriver::GetClassStatus(const ClassReference& ref) const {
2720 ClassStatus status = ClassStatus::kNotReady;
Nicolas Geoffray486dda02017-09-11 14:15:52 +01002721 if (!GetCompiledClass(ref, &status)) {
Mathieu Chartierfc8b4222017-09-17 13:44:24 -07002722 classpath_classes_.Get(ref, &status);
Nicolas Geoffray486dda02017-09-11 14:15:52 +01002723 }
2724 return status;
2725}
2726
Vladimir Marko2c64a832018-01-04 11:31:56 +00002727void CompilerDriver::RecordClassStatus(const ClassReference& ref, ClassStatus status) {
Nicolas Geoffrayade72d62016-12-15 13:20:02 +00002728 switch (status) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00002729 case ClassStatus::kErrorResolved:
2730 case ClassStatus::kErrorUnresolved:
2731 case ClassStatus::kNotReady:
2732 case ClassStatus::kResolved:
2733 case ClassStatus::kRetryVerificationAtRuntime:
2734 case ClassStatus::kVerified:
2735 case ClassStatus::kSuperclassValidated:
2736 case ClassStatus::kInitialized:
Nicolas Geoffrayade72d62016-12-15 13:20:02 +00002737 break; // Expected states.
2738 default:
2739 LOG(FATAL) << "Unexpected class status for class "
Mathieu Chartierfc8b4222017-09-17 13:44:24 -07002740 << PrettyDescriptor(
2741 ref.dex_file->GetClassDescriptor(ref.dex_file->GetClassDef(ref.index)))
Nicolas Geoffrayade72d62016-12-15 13:20:02 +00002742 << " of " << status;
2743 }
2744
Mathieu Chartier1a088d42017-07-18 11:43:57 -07002745 ClassStateTable::InsertResult result;
Nicolas Geoffray486dda02017-09-11 14:15:52 +01002746 ClassStateTable* table = &compiled_classes_;
Mathieu Chartier1a088d42017-07-18 11:43:57 -07002747 do {
Vladimir Marko2c64a832018-01-04 11:31:56 +00002748 ClassStatus existing = ClassStatus::kNotReady;
Mathieu Chartierfc8b4222017-09-17 13:44:24 -07002749 if (!table->Get(ref, &existing)) {
Nicolas Geoffray486dda02017-09-11 14:15:52 +01002750 // A classpath class.
Mathieu Chartier010f5cc2017-07-24 15:53:46 -07002751 if (kIsDebugBuild) {
2752 // Check to make sure it's not a dex file for an oat file we are compiling since these
2753 // should always succeed. These do not include classes in for used libraries.
Vladimir Marko213ee2d2018-06-22 11:56:34 +01002754 for (const DexFile* dex_file : GetCompilerOptions().GetDexFilesForOatFile()) {
Mathieu Chartierfc8b4222017-09-17 13:44:24 -07002755 CHECK_NE(ref.dex_file, dex_file) << ref.dex_file->GetLocation();
Mathieu Chartier010f5cc2017-07-24 15:53:46 -07002756 }
2757 }
Mathieu Chartierfc8b4222017-09-17 13:44:24 -07002758 if (!classpath_classes_.HaveDexFile(ref.dex_file)) {
Nicolas Geoffray486dda02017-09-11 14:15:52 +01002759 // Boot classpath dex file.
2760 return;
2761 }
2762 table = &classpath_classes_;
Mathieu Chartierfc8b4222017-09-17 13:44:24 -07002763 table->Get(ref, &existing);
Mathieu Chartier010f5cc2017-07-24 15:53:46 -07002764 }
Mathieu Chartier1a088d42017-07-18 11:43:57 -07002765 if (existing >= status) {
2766 // Existing status is already better than we expect, break.
2767 break;
2768 }
Nicolas Geoffrayade72d62016-12-15 13:20:02 +00002769 // Update the status if we now have a greater one. This happens with vdex,
2770 // which records a class is verified, but does not resolve it.
Mathieu Chartierfc8b4222017-09-17 13:44:24 -07002771 result = table->Insert(ref, existing, status);
2772 CHECK(result != ClassStateTable::kInsertResultInvalidDexFile) << ref.dex_file->GetLocation();
Mathieu Chartier1a088d42017-07-18 11:43:57 -07002773 } while (result != ClassStateTable::kInsertResultSuccess);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07002774}
2775
Brian Carlstrom7940e442013-07-12 13:46:57 -07002776CompiledMethod* CompilerDriver::GetCompiledMethod(MethodReference ref) const {
Mathieu Chartieracab8d42016-11-23 13:45:58 -08002777 CompiledMethod* compiled_method = nullptr;
Mathieu Chartierfc8b4222017-09-17 13:44:24 -07002778 compiled_methods_.Get(ref, &compiled_method);
Mathieu Chartieracab8d42016-11-23 13:45:58 -08002779 return compiled_method;
Brian Carlstrom7940e442013-07-12 13:46:57 -07002780}
2781
Calin Juravlef1c6d9e2015-04-13 18:42:21 +01002782bool CompilerDriver::IsMethodVerifiedWithoutFailures(uint32_t method_idx,
2783 uint16_t class_def_idx,
2784 const DexFile& dex_file) const {
2785 const VerifiedMethod* verified_method = GetVerifiedMethod(&dex_file, method_idx);
2786 if (verified_method != nullptr) {
2787 return !verified_method->HasVerificationFailures();
2788 }
2789
2790 // If we can't find verification metadata, check if this is a system class (we trust that system
2791 // classes have their methods verified). If it's not, be conservative and assume the method
2792 // has not been verified successfully.
2793
2794 // TODO: When compiling the boot image it should be safe to assume that everything is verified,
2795 // even if methods are not found in the verification cache.
2796 const char* descriptor = dex_file.GetClassDescriptor(dex_file.GetClassDef(class_def_idx));
2797 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
2798 Thread* self = Thread::Current();
2799 ScopedObjectAccess soa(self);
2800 bool is_system_class = class_linker->FindSystemClass(self, descriptor) != nullptr;
2801 if (!is_system_class) {
2802 self->ClearException();
2803 }
2804 return is_system_class;
2805}
2806
Andreas Gampe8d295f82015-01-20 14:50:21 -08002807std::string CompilerDriver::GetMemoryUsageString(bool extended) const {
Mathieu Chartierab972ef2014-12-03 17:38:22 -08002808 std::ostringstream oss;
Calin Juravle69158982016-03-16 11:53:41 +00002809 const gc::Heap* const heap = Runtime::Current()->GetHeap();
Anton Kirilovdd9473b2016-01-28 15:08:01 +00002810 const size_t java_alloc = heap->GetBytesAllocated();
Calin Juravle69158982016-03-16 11:53:41 +00002811 oss << "arena alloc=" << PrettySize(max_arena_alloc_) << " (" << max_arena_alloc_ << "B)";
Anton Kirilovdd9473b2016-01-28 15:08:01 +00002812 oss << " java alloc=" << PrettySize(java_alloc) << " (" << java_alloc << "B)";
Elliott Hughes7bf5a262015-04-02 20:55:07 -07002813#if defined(__BIONIC__) || defined(__GLIBC__)
Anton Kirilovdd9473b2016-01-28 15:08:01 +00002814 const struct mallinfo info = mallinfo();
Mathieu Chartierab972ef2014-12-03 17:38:22 -08002815 const size_t allocated_space = static_cast<size_t>(info.uordblks);
2816 const size_t free_space = static_cast<size_t>(info.fordblks);
Anton Kirilovdd9473b2016-01-28 15:08:01 +00002817 oss << " native alloc=" << PrettySize(allocated_space) << " (" << allocated_space << "B)"
2818 << " free=" << PrettySize(free_space) << " (" << free_space << "B)";
Mathieu Chartierab972ef2014-12-03 17:38:22 -08002819#endif
Vladimir Marko35831e82015-09-11 11:59:18 +01002820 compiled_method_storage_.DumpMemoryUsage(oss, extended);
Mathieu Chartierab972ef2014-12-03 17:38:22 -08002821 return oss.str();
2822}
2823
Andreas Gampeace0dc12016-01-20 13:33:13 -08002824void CompilerDriver::InitializeThreadPools() {
2825 size_t parallel_count = parallel_thread_count_ > 0 ? parallel_thread_count_ - 1 : 0;
2826 parallel_thread_pool_.reset(
2827 new ThreadPool("Compiler driver thread pool", parallel_count));
2828 single_thread_pool_.reset(new ThreadPool("Single-threaded Compiler driver thread pool", 0));
2829}
2830
2831void CompilerDriver::FreeThreadPools() {
2832 parallel_thread_pool_.reset();
2833 single_thread_pool_.reset();
2834}
2835
Nicolas Geoffray486dda02017-09-11 14:15:52 +01002836void CompilerDriver::SetClasspathDexFiles(const std::vector<const DexFile*>& dex_files) {
2837 classpath_classes_.AddDexFiles(dex_files);
Mathieu Chartier72041a02017-07-14 18:23:25 -07002838}
2839
Brian Carlstrom7940e442013-07-12 13:46:57 -07002840} // namespace art