blob: 7573367788e81342be2a9f19b62e3162bba70f0e [file] [log] [blame]
Brian Carlstrom7940e442013-07-12 13:46:57 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "compiler_driver.h"
18
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070019#include <unistd.h>
Andreas Gampeb0f370e2014-09-25 22:51:40 -070020#include <unordered_set>
Anwar Ghuloum67f99412013-08-12 14:19:48 -070021#include <vector>
Brian Carlstrom7940e442013-07-12 13:46:57 -070022
Mathieu Chartierab972ef2014-12-03 17:38:22 -080023#ifndef __APPLE__
24#include <malloc.h> // For mallinfo
25#endif
26
Narayan Kamathe3eae5e2016-10-27 11:47:30 +010027#include "android-base/strings.h"
28
Mathieu Chartierc7853442015-03-27 14:35:38 -070029#include "art_field-inl.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070030#include "art_method-inl.h"
Andreas Gampef0446e92017-05-16 13:51:57 -070031#include "base/arena_allocator.h"
David Brazdild9c90372016-09-14 16:53:55 +010032#include "base/array_ref.h"
Vladimir Marko492a7fa2016-06-01 18:38:43 +010033#include "base/bit_vector.h"
Andreas Gampe542451c2016-07-26 09:02:02 -070034#include "base/enums.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070035#include "base/stl_util.h"
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -080036#include "base/systrace.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010037#include "base/time_utils.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070038#include "base/timing_logger.h"
Vladimir Marko3481ba22015-04-13 12:22:36 +010039#include "class_linker-inl.h"
Vladimir Markod8dbc8d2017-09-20 13:37:47 +010040#include "compiled_method-inl.h"
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +000041#include "compiler.h"
Nicolas Geoffray6bb7f1b2016-11-03 10:52:49 +000042#include "compiler_callbacks.h"
Vladimir Markobe0e5462014-02-26 11:24:15 +000043#include "compiler_driver-inl.h"
Andreas Gampe5eb0d382015-07-23 01:19:26 -070044#include "dex/dex_to_dex_compiler.h"
Vladimir Markoc7f83202014-01-24 17:55:18 +000045#include "dex/verification_results.h"
Vladimir Marko2730db02014-01-27 11:15:17 +000046#include "dex/verified_method.h"
Steven Morelande431e272017-07-18 16:53:49 -070047#include "dex_compilation_unit.h"
48#include "dex_file-inl.h"
49#include "dex_instruction-inl.h"
Mark Mendellae9fd932014-02-10 16:14:35 -080050#include "driver/compiler_options.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070051#include "gc/accounting/card_table-inl.h"
52#include "gc/accounting/heap_bitmap.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070053#include "gc/space/image_space.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070054#include "gc/space/space.h"
Steven Morelande431e272017-07-18 16:53:49 -070055#include "handle_scope-inl.h"
56#include "intrinsics_enum.h"
57#include "jni_internal.h"
Vladimir Markod8dbc8d2017-09-20 13:37:47 +010058#include "linker/linker_patch.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070059#include "mirror/class-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -070060#include "mirror/class_loader.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070061#include "mirror/dex_cache-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070062#include "mirror/object-inl.h"
Andreas Gampec6ea7d02017-02-01 16:46:28 -080063#include "mirror/object-refvisitor-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070064#include "mirror/object_array-inl.h"
65#include "mirror/throwable.h"
Steven Morelande431e272017-07-18 16:53:49 -070066#include "nativehelper/ScopedLocalRef.h"
67#include "object_lock.h"
68#include "runtime.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070069#include "scoped_thread_state_change-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070070#include "thread.h"
Andreas Gampeb0f370e2014-09-25 22:51:40 -070071#include "thread_list.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070072#include "thread_pool.h"
Ian Rogers848871b2013-08-05 10:56:33 -070073#include "trampolines/trampoline_compiler.h"
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +010074#include "transaction.h"
Mathieu Chartier93764b82017-07-17 14:51:53 -070075#include "utils/atomic_dex_ref_map-inl.h"
Vladimir Marko20f85592015-03-19 10:07:02 +000076#include "utils/dex_cache_arrays_layout-inl.h"
Andreas Gampee21dc3d2014-12-08 16:59:43 -080077#include "utils/swap_space.h"
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +000078#include "vdex_file.h"
Vladimir Marko2bc47802014-02-10 09:43:07 +000079#include "verifier/method_verifier-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -070080#include "verifier/method_verifier.h"
Nicolas Geoffray08025182016-10-25 17:20:18 +010081#include "verifier/verifier_deps.h"
Andreas Gampe6d7abbd2017-04-24 13:19:09 -070082#include "verifier/verifier_enums.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070083
Brian Carlstrom7940e442013-07-12 13:46:57 -070084namespace art {
85
Mathieu Chartier8e219ae2014-08-19 14:29:46 -070086static constexpr bool kTimeCompileMethod = !kIsDebugBuild;
87
Calin Juravle226501b2015-12-11 14:41:31 +000088// Print additional info during profile guided compilation.
89static constexpr bool kDebugProfileGuidedCompilation = false;
90
Chang Xing70f689d2017-06-08 17:16:12 -070091// Max encoded fields allowed for initializing app image. Hardcode the number for now
92// because 5000 should be large enough.
93static constexpr uint32_t kMaxEncodedFields = 5000;
94
Brian Carlstrom7940e442013-07-12 13:46:57 -070095static double Percentage(size_t x, size_t y) {
96 return 100.0 * (static_cast<double>(x)) / (static_cast<double>(x + y));
97}
98
99static void DumpStat(size_t x, size_t y, const char* str) {
100 if (x == 0 && y == 0) {
101 return;
102 }
Ian Rogerse732ef12013-10-09 15:22:24 -0700103 LOG(INFO) << Percentage(x, y) << "% of " << str << " for " << (x + y) << " cases";
Brian Carlstrom7940e442013-07-12 13:46:57 -0700104}
105
Vladimir Markof096aad2014-01-23 15:51:58 +0000106class CompilerDriver::AOTCompilationStats {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700107 public:
108 AOTCompilationStats()
109 : stats_lock_("AOT compilation statistics lock"),
Brian Carlstrom7940e442013-07-12 13:46:57 -0700110 resolved_types_(0), unresolved_types_(0),
111 resolved_instance_fields_(0), unresolved_instance_fields_(0),
112 resolved_local_static_fields_(0), resolved_static_fields_(0), unresolved_static_fields_(0),
113 type_based_devirtualization_(0),
114 safe_casts_(0), not_safe_casts_(0) {
115 for (size_t i = 0; i <= kMaxInvokeType; i++) {
116 resolved_methods_[i] = 0;
117 unresolved_methods_[i] = 0;
118 virtual_made_direct_[i] = 0;
119 direct_calls_to_boot_[i] = 0;
120 direct_methods_to_boot_[i] = 0;
121 }
122 }
123
124 void Dump() {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700125 DumpStat(resolved_types_, unresolved_types_, "types resolved");
126 DumpStat(resolved_instance_fields_, unresolved_instance_fields_, "instance fields resolved");
127 DumpStat(resolved_local_static_fields_ + resolved_static_fields_, unresolved_static_fields_,
128 "static fields resolved");
129 DumpStat(resolved_local_static_fields_, resolved_static_fields_ + unresolved_static_fields_,
130 "static fields local to a class");
131 DumpStat(safe_casts_, not_safe_casts_, "check-casts removed based on type information");
132 // Note, the code below subtracts the stat value so that when added to the stat value we have
133 // 100% of samples. TODO: clean this up.
134 DumpStat(type_based_devirtualization_,
135 resolved_methods_[kVirtual] + unresolved_methods_[kVirtual] +
136 resolved_methods_[kInterface] + unresolved_methods_[kInterface] -
137 type_based_devirtualization_,
138 "virtual/interface calls made direct based on type information");
139
140 for (size_t i = 0; i <= kMaxInvokeType; i++) {
141 std::ostringstream oss;
142 oss << static_cast<InvokeType>(i) << " methods were AOT resolved";
143 DumpStat(resolved_methods_[i], unresolved_methods_[i], oss.str().c_str());
144 if (virtual_made_direct_[i] > 0) {
145 std::ostringstream oss2;
146 oss2 << static_cast<InvokeType>(i) << " methods made direct";
147 DumpStat(virtual_made_direct_[i],
148 resolved_methods_[i] + unresolved_methods_[i] - virtual_made_direct_[i],
149 oss2.str().c_str());
150 }
151 if (direct_calls_to_boot_[i] > 0) {
152 std::ostringstream oss2;
153 oss2 << static_cast<InvokeType>(i) << " method calls are direct into boot";
154 DumpStat(direct_calls_to_boot_[i],
155 resolved_methods_[i] + unresolved_methods_[i] - direct_calls_to_boot_[i],
156 oss2.str().c_str());
157 }
158 if (direct_methods_to_boot_[i] > 0) {
159 std::ostringstream oss2;
160 oss2 << static_cast<InvokeType>(i) << " method calls have methods in boot";
161 DumpStat(direct_methods_to_boot_[i],
162 resolved_methods_[i] + unresolved_methods_[i] - direct_methods_to_boot_[i],
163 oss2.str().c_str());
164 }
165 }
166 }
167
168// Allow lossy statistics in non-debug builds.
169#ifndef NDEBUG
170#define STATS_LOCK() MutexLock mu(Thread::Current(), stats_lock_)
171#else
172#define STATS_LOCK()
173#endif
174
Mathieu Chartier90443472015-07-16 20:32:27 -0700175 void TypeDoesntNeedAccessCheck() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700176 STATS_LOCK();
177 resolved_types_++;
178 }
179
Mathieu Chartier90443472015-07-16 20:32:27 -0700180 void TypeNeedsAccessCheck() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700181 STATS_LOCK();
182 unresolved_types_++;
183 }
184
Mathieu Chartier90443472015-07-16 20:32:27 -0700185 void ResolvedInstanceField() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700186 STATS_LOCK();
187 resolved_instance_fields_++;
188 }
189
Mathieu Chartier90443472015-07-16 20:32:27 -0700190 void UnresolvedInstanceField() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700191 STATS_LOCK();
192 unresolved_instance_fields_++;
193 }
194
Mathieu Chartier90443472015-07-16 20:32:27 -0700195 void ResolvedLocalStaticField() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700196 STATS_LOCK();
197 resolved_local_static_fields_++;
198 }
199
Mathieu Chartier90443472015-07-16 20:32:27 -0700200 void ResolvedStaticField() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700201 STATS_LOCK();
202 resolved_static_fields_++;
203 }
204
Mathieu Chartier90443472015-07-16 20:32:27 -0700205 void UnresolvedStaticField() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700206 STATS_LOCK();
207 unresolved_static_fields_++;
208 }
209
210 // Indicate that type information from the verifier led to devirtualization.
Mathieu Chartier90443472015-07-16 20:32:27 -0700211 void PreciseTypeDevirtualization() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700212 STATS_LOCK();
213 type_based_devirtualization_++;
214 }
215
Brian Carlstrom7940e442013-07-12 13:46:57 -0700216 // A check-cast could be eliminated due to verifier type analysis.
Mathieu Chartier90443472015-07-16 20:32:27 -0700217 void SafeCast() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700218 STATS_LOCK();
219 safe_casts_++;
220 }
221
222 // A check-cast couldn't be eliminated due to verifier type analysis.
Mathieu Chartier90443472015-07-16 20:32:27 -0700223 void NotASafeCast() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700224 STATS_LOCK();
225 not_safe_casts_++;
226 }
227
228 private:
229 Mutex stats_lock_;
230
Brian Carlstrom7940e442013-07-12 13:46:57 -0700231 size_t resolved_types_;
232 size_t unresolved_types_;
233
234 size_t resolved_instance_fields_;
235 size_t unresolved_instance_fields_;
236
237 size_t resolved_local_static_fields_;
238 size_t resolved_static_fields_;
239 size_t unresolved_static_fields_;
240 // Type based devirtualization for invoke interface and virtual.
241 size_t type_based_devirtualization_;
242
243 size_t resolved_methods_[kMaxInvokeType + 1];
244 size_t unresolved_methods_[kMaxInvokeType + 1];
245 size_t virtual_made_direct_[kMaxInvokeType + 1];
246 size_t direct_calls_to_boot_[kMaxInvokeType + 1];
247 size_t direct_methods_to_boot_[kMaxInvokeType + 1];
248
249 size_t safe_casts_;
250 size_t not_safe_casts_;
251
252 DISALLOW_COPY_AND_ASSIGN(AOTCompilationStats);
253};
254
Vladimir Marko492a7fa2016-06-01 18:38:43 +0100255class CompilerDriver::DexFileMethodSet {
256 public:
257 explicit DexFileMethodSet(const DexFile& dex_file)
258 : dex_file_(dex_file),
259 method_indexes_(dex_file.NumMethodIds(), false, Allocator::GetMallocAllocator()) {
260 }
261 DexFileMethodSet(DexFileMethodSet&& other) = default;
262
263 const DexFile& GetDexFile() const { return dex_file_; }
264
265 BitVector& GetMethodIndexes() { return method_indexes_; }
266 const BitVector& GetMethodIndexes() const { return method_indexes_; }
267
268 private:
269 const DexFile& dex_file_;
270 BitVector method_indexes_;
271};
272
Jeff Haodcdc85b2015-12-04 14:06:18 -0800273CompilerDriver::CompilerDriver(
274 const CompilerOptions* compiler_options,
275 VerificationResults* verification_results,
Jeff Haodcdc85b2015-12-04 14:06:18 -0800276 Compiler::Kind compiler_kind,
277 InstructionSet instruction_set,
278 const InstructionSetFeatures* instruction_set_features,
Vladimir Marko944da602016-02-19 12:27:55 +0000279 std::unordered_set<std::string>* image_classes,
Jeff Haodcdc85b2015-12-04 14:06:18 -0800280 std::unordered_set<std::string>* compiled_classes,
281 std::unordered_set<std::string>* compiled_methods,
Vladimir Marko944da602016-02-19 12:27:55 +0000282 size_t thread_count,
283 bool dump_stats,
284 bool dump_passes,
285 CumulativeLogger* timer,
286 int swap_fd,
Calin Juravle998c2162015-12-21 15:39:33 +0200287 const ProfileCompilationInfo* profile_compilation_info)
Calin Juravle226501b2015-12-11 14:41:31 +0000288 : compiler_options_(compiler_options),
Brian Carlstrom6449c622014-02-10 23:48:36 -0800289 verification_results_(verification_results),
Ian Rogers72d32622014-05-06 16:20:11 -0700290 compiler_(Compiler::Create(this, compiler_kind)),
Jeff Hao48699fb2015-04-06 14:21:37 -0700291 compiler_kind_(compiler_kind),
Roland Levillain5e8d5f02016-10-18 18:03:43 +0100292 instruction_set_(instruction_set == kArm ? kThumb2 : instruction_set),
Dave Allison70202782013-10-22 17:52:19 -0700293 instruction_set_features_(instruction_set_features),
Mathieu Chartierc4ae9162016-04-07 13:19:19 -0700294 requires_constructor_barrier_lock_("constructor barrier lock"),
Vladimir Markof4da6752014-08-01 19:04:18 +0100295 non_relative_linker_patch_count_(0u),
Brian Carlstrom7940e442013-07-12 13:46:57 -0700296 image_classes_(image_classes),
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800297 classes_to_compile_(compiled_classes),
Andreas Gampe70bef0d2015-04-15 02:37:28 -0700298 methods_to_compile_(compiled_methods),
Andreas Gampe6cf49e52015-03-05 13:08:45 -0800299 had_hard_verifier_failure_(false),
Andreas Gampeace0dc12016-01-20 13:33:13 -0800300 parallel_thread_count_(thread_count),
Brian Carlstrom7940e442013-07-12 13:46:57 -0700301 stats_(new AOTCompilationStats),
302 dump_stats_(dump_stats),
Nicolas Geoffrayea3fa0b2014-02-10 11:59:41 +0000303 dump_passes_(dump_passes),
304 timings_logger_(timer),
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700305 compiler_context_(nullptr),
Alexey Frunze19f6c692016-11-30 19:19:55 -0800306 support_boot_image_fixup_(true),
Calin Juravle998c2162015-12-21 15:39:33 +0200307 compiled_method_storage_(swap_fd),
Calin Juravle69158982016-03-16 11:53:41 +0000308 profile_compilation_info_(profile_compilation_info),
Vladimir Marko492a7fa2016-06-01 18:38:43 +0100309 max_arena_alloc_(0),
310 dex_to_dex_references_lock_("dex-to-dex references lock"),
311 dex_to_dex_references_(),
312 current_dex_to_dex_methods_(nullptr) {
Brian Carlstrom6449c622014-02-10 23:48:36 -0800313 DCHECK(compiler_options_ != nullptr);
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700314
Ian Rogers72d32622014-05-06 16:20:11 -0700315 compiler_->Init();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700316
Vladimir Markoaad75c62016-10-03 08:46:48 +0000317 if (GetCompilerOptions().IsBootImage()) {
Mathieu Chartierc5dd3192015-12-09 16:38:30 -0800318 CHECK(image_classes_.get() != nullptr) << "Expected image classes for boot image";
319 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700320}
321
322CompilerDriver::~CompilerDriver() {
Mathieu Chartier93764b82017-07-17 14:51:53 -0700323 compiled_methods_.Visit([this](const DexFileReference& ref ATTRIBUTE_UNUSED,
Mathieu Chartieracab8d42016-11-23 13:45:58 -0800324 CompiledMethod* method) {
325 if (method != nullptr) {
326 CompiledMethod::ReleaseSwapAllocatedCompiledMethod(this, method);
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800327 }
Mathieu Chartieracab8d42016-11-23 13:45:58 -0800328 });
Ian Rogers72d32622014-05-06 16:20:11 -0700329 compiler_->UnInit();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700330}
331
Vladimir Marko35831e82015-09-11 11:59:18 +0100332
Ian Rogersdd7624d2014-03-14 17:43:00 -0700333#define CREATE_TRAMPOLINE(type, abi, offset) \
Andreas Gampeaf13ad92014-04-11 12:07:48 -0700334 if (Is64BitInstructionSet(instruction_set_)) { \
Ian Rogersdd7624d2014-03-14 17:43:00 -0700335 return CreateTrampoline64(instruction_set_, abi, \
Andreas Gampe542451c2016-07-26 09:02:02 -0700336 type ## _ENTRYPOINT_OFFSET(PointerSize::k64, offset)); \
Ian Rogersdd7624d2014-03-14 17:43:00 -0700337 } else { \
338 return CreateTrampoline32(instruction_set_, abi, \
Andreas Gampe542451c2016-07-26 09:02:02 -0700339 type ## _ENTRYPOINT_OFFSET(PointerSize::k32, offset)); \
Ian Rogersdd7624d2014-03-14 17:43:00 -0700340 }
341
Vladimir Marko93205e32016-04-13 11:59:46 +0100342std::unique_ptr<const std::vector<uint8_t>> CompilerDriver::CreateJniDlsymLookup() const {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700343 CREATE_TRAMPOLINE(JNI, kJniAbi, pDlsymLookup)
Ian Rogers848871b2013-08-05 10:56:33 -0700344}
345
Vladimir Marko93205e32016-04-13 11:59:46 +0100346std::unique_ptr<const std::vector<uint8_t>> CompilerDriver::CreateQuickGenericJniTrampoline()
347 const {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700348 CREATE_TRAMPOLINE(QUICK, kQuickAbi, pQuickGenericJniTrampoline)
Andreas Gampe2da88232014-02-27 12:26:20 -0800349}
350
Vladimir Marko93205e32016-04-13 11:59:46 +0100351std::unique_ptr<const std::vector<uint8_t>> CompilerDriver::CreateQuickImtConflictTrampoline()
352 const {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700353 CREATE_TRAMPOLINE(QUICK, kQuickAbi, pQuickImtConflictTrampoline)
Jeff Hao88474b42013-10-23 16:24:40 -0700354}
355
Vladimir Marko93205e32016-04-13 11:59:46 +0100356std::unique_ptr<const std::vector<uint8_t>> CompilerDriver::CreateQuickResolutionTrampoline()
357 const {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700358 CREATE_TRAMPOLINE(QUICK, kQuickAbi, pQuickResolutionTrampoline)
Brian Carlstrom7940e442013-07-12 13:46:57 -0700359}
360
Vladimir Marko93205e32016-04-13 11:59:46 +0100361std::unique_ptr<const std::vector<uint8_t>> CompilerDriver::CreateQuickToInterpreterBridge()
362 const {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700363 CREATE_TRAMPOLINE(QUICK, kQuickAbi, pQuickToInterpreterBridge)
Brian Carlstrom7940e442013-07-12 13:46:57 -0700364}
Ian Rogersdd7624d2014-03-14 17:43:00 -0700365#undef CREATE_TRAMPOLINE
Brian Carlstrom7940e442013-07-12 13:46:57 -0700366
Nicolas Geoffray762869d2016-07-15 15:28:35 +0100367static void SetupIntrinsic(Thread* self,
368 Intrinsics intrinsic,
369 InvokeType invoke_type,
370 const char* class_name,
371 const char* method_name,
372 const char* signature)
373 REQUIRES_SHARED(Locks::mutator_lock_) {
374 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
375 PointerSize image_size = class_linker->GetImagePointerSize();
Vladimir Markoba118822017-06-12 15:41:56 +0100376 ObjPtr<mirror::Class> cls = class_linker->FindSystemClass(self, class_name);
Nicolas Geoffray762869d2016-07-15 15:28:35 +0100377 if (cls == nullptr) {
378 LOG(FATAL) << "Could not find class of intrinsic " << class_name;
379 }
Vladimir Markoba118822017-06-12 15:41:56 +0100380 ArtMethod* method = cls->FindClassMethod(method_name, signature, image_size);
381 if (method == nullptr || method->GetDeclaringClass() != cls) {
Nicolas Geoffrayb20f1fe2016-10-03 13:57:40 +0100382 LOG(FATAL) << "Could not find method of intrinsic "
383 << class_name << " " << method_name << " " << signature;
Nicolas Geoffray762869d2016-07-15 15:28:35 +0100384 }
385 DCHECK_EQ(method->GetInvokeType(), invoke_type);
386 method->SetIntrinsic(static_cast<uint32_t>(intrinsic));
387}
388
Brian Carlstrom7940e442013-07-12 13:46:57 -0700389void CompilerDriver::CompileAll(jobject class_loader,
Brian Carlstrom45602482013-07-21 22:07:55 -0700390 const std::vector<const DexFile*>& dex_files,
Ian Rogers3d504072014-03-01 09:16:49 -0800391 TimingLogger* timings) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700392 DCHECK(!Runtime::Current()->IsStarted());
Andreas Gampeace0dc12016-01-20 13:33:13 -0800393
394 InitializeThreadPools();
395
Andreas Gampe8d295f82015-01-20 14:50:21 -0800396 VLOG(compiler) << "Before precompile " << GetMemoryUsageString(false);
Andreas Gampe740667a2015-09-15 17:55:06 -0700397 // Precompile:
398 // 1) Load image classes
399 // 2) Resolve all classes
400 // 3) Attempt to verify all classes
401 // 4) Attempt to initialize image classes, and trivially initialized classes
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000402 PreCompile(class_loader, dex_files, timings);
Vladimir Markoaad75c62016-10-03 08:46:48 +0000403 if (GetCompilerOptions().IsBootImage()) {
Nicolas Geoffray762869d2016-07-15 15:28:35 +0100404 // We don't need to setup the intrinsics for non boot image compilation, as
405 // those compilations will pick up a boot image that have the ArtMethod already
406 // set with the intrinsics flag.
407 ScopedObjectAccess soa(Thread::Current());
Nicolas Geoffrayb20f1fe2016-10-03 13:57:40 +0100408#define SETUP_INTRINSICS(Name, InvokeType, NeedsEnvironmentOrCache, SideEffects, Exceptions, \
409 ClassName, MethodName, Signature) \
Nicolas Geoffray762869d2016-07-15 15:28:35 +0100410 SetupIntrinsic(soa.Self(), Intrinsics::k##Name, InvokeType, ClassName, MethodName, Signature);
411#include "intrinsics_list.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -0700412 INTRINSICS_LIST(SETUP_INTRINSICS)
Nicolas Geoffray762869d2016-07-15 15:28:35 +0100413#undef INTRINSICS_LIST
Nicolas Geoffrayb20f1fe2016-10-03 13:57:40 +0100414#undef SETUP_INTRINSICS
Nicolas Geoffray762869d2016-07-15 15:28:35 +0100415 }
Andreas Gampe740667a2015-09-15 17:55:06 -0700416 // Compile:
417 // 1) Compile all classes and methods enabled for compilation. May fall back to dex-to-dex
418 // compilation.
Nicolas Geoffray49cda062017-04-21 13:08:25 +0100419 if (GetCompilerOptions().IsAnyCompilationEnabled()) {
Andreas Gampeace0dc12016-01-20 13:33:13 -0800420 Compile(class_loader, dex_files, timings);
Andreas Gampe740667a2015-09-15 17:55:06 -0700421 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700422 if (dump_stats_) {
423 stats_->Dump();
424 }
Andreas Gampeace0dc12016-01-20 13:33:13 -0800425
426 FreeThreadPools();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700427}
428
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700429static optimizer::DexToDexCompilationLevel GetDexToDexCompilationLevel(
430 Thread* self, const CompilerDriver& driver, Handle<mirror::ClassLoader> class_loader,
431 const DexFile& dex_file, const DexFile::ClassDef& class_def)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700432 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800433 auto* const runtime = Runtime::Current();
Nicolas Geoffray49cda062017-04-21 13:08:25 +0100434 DCHECK(driver.GetCompilerOptions().IsQuickeningCompilationEnabled());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700435 const char* descriptor = dex_file.GetClassDescriptor(class_def);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800436 ClassLinker* class_linker = runtime->GetClassLinker();
Ian Rogers98379392014-02-24 16:53:16 -0800437 mirror::Class* klass = class_linker->FindClass(self, descriptor, class_loader);
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700438 if (klass == nullptr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700439 CHECK(self->IsExceptionPending());
440 self->ClearException();
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700441 return optimizer::DexToDexCompilationLevel::kDontDexToDexCompile;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700442 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700443 // DexToDex at the kOptimize level may introduce quickened opcodes, which replace symbolic
444 // references with actual offsets. We cannot re-verify such instructions.
445 //
446 // We store the verification information in the class status in the oat file, which the linker
447 // can validate (checksums) and use to skip load-time verification. It is thus safe to
448 // optimize when a class has been fully verified before.
Alex Lighte40dd382017-01-25 17:44:53 -0800449 optimizer::DexToDexCompilationLevel max_level = optimizer::DexToDexCompilationLevel::kOptimize;
450 if (driver.GetCompilerOptions().GetDebuggable()) {
451 // We are debuggable so definitions of classes might be changed. We don't want to do any
452 // optimizations that could break that.
Andreas Gampe1a4bc7f2017-03-27 14:57:30 -0700453 max_level = optimizer::DexToDexCompilationLevel::kDontDexToDexCompile;
Alex Lighte40dd382017-01-25 17:44:53 -0800454 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700455 if (klass->IsVerified()) {
Sebastien Hertz75021222013-07-16 18:34:50 +0200456 // Class is verified so we can enable DEX-to-DEX compilation for performance.
Alex Lighte40dd382017-01-25 17:44:53 -0800457 return max_level;
Sebastien Hertz75021222013-07-16 18:34:50 +0200458 } else {
Andreas Gampe1a4bc7f2017-03-27 14:57:30 -0700459 // Class verification has failed: do not run DEX-to-DEX optimizations.
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700460 return optimizer::DexToDexCompilationLevel::kDontDexToDexCompile;
461 }
462}
463
464static optimizer::DexToDexCompilationLevel GetDexToDexCompilationLevel(
465 Thread* self,
466 const CompilerDriver& driver,
467 jobject jclass_loader,
468 const DexFile& dex_file,
469 const DexFile::ClassDef& class_def) {
470 ScopedObjectAccess soa(self);
471 StackHandleScope<1> hs(soa.Self());
472 Handle<mirror::ClassLoader> class_loader(
Mathieu Chartier0795f232016-09-27 18:43:30 -0700473 hs.NewHandle(soa.Decode<mirror::ClassLoader>(jclass_loader)));
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700474 return GetDexToDexCompilationLevel(self, driver, class_loader, dex_file, class_def);
475}
476
477// Does the runtime for the InstructionSet provide an implementation returned by
478// GetQuickGenericJniStub allowing down calls that aren't compiled using a JNI compiler?
479static bool InstructionSetHasGenericJniStub(InstructionSet isa) {
480 switch (isa) {
481 case kArm:
482 case kArm64:
483 case kThumb2:
484 case kMips:
485 case kMips64:
486 case kX86:
487 case kX86_64: return true;
488 default: return false;
489 }
490}
491
492static void CompileMethod(Thread* self,
493 CompilerDriver* driver,
494 const DexFile::CodeItem* code_item,
495 uint32_t access_flags,
496 InvokeType invoke_type,
497 uint16_t class_def_idx,
498 uint32_t method_idx,
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000499 Handle<mirror::ClassLoader> class_loader,
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700500 const DexFile& dex_file,
501 optimizer::DexToDexCompilationLevel dex_to_dex_compilation_level,
Mathieu Chartier736b5602015-09-02 14:54:11 -0700502 bool compilation_enabled,
Mathieu Chartieracab8d42016-11-23 13:45:58 -0800503 Handle<mirror::DexCache> dex_cache) {
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700504 DCHECK(driver != nullptr);
505 CompiledMethod* compiled_method = nullptr;
506 uint64_t start_ns = kTimeCompileMethod ? NanoTime() : 0;
507 MethodReference method_ref(&dex_file, method_idx);
508
Vladimir Marko492a7fa2016-06-01 18:38:43 +0100509 if (driver->GetCurrentDexToDexMethods() != nullptr) {
510 // This is the second pass when we dex-to-dex compile previously marked methods.
511 // TODO: Refactor the compilation to avoid having to distinguish the two passes
512 // here. That should be done on a higher level. http://b/29089975
513 if (driver->GetCurrentDexToDexMethods()->IsBitSet(method_idx)) {
Mathieu Chartier0733dc82017-07-17 14:05:28 -0700514 VerificationResults* results = driver->GetVerificationResults();
515 DCHECK(results != nullptr);
516 const VerifiedMethod* verified_method = results->GetVerifiedMethod(method_ref);
Vladimir Marko492a7fa2016-06-01 18:38:43 +0100517 // Do not optimize if a VerifiedMethod is missing. SafeCast elision,
518 // for example, relies on it.
519 compiled_method = optimizer::ArtCompileDEX(
520 driver,
521 code_item,
522 access_flags,
523 invoke_type,
524 class_def_idx,
525 method_idx,
526 class_loader,
527 dex_file,
528 (verified_method != nullptr)
529 ? dex_to_dex_compilation_level
Andreas Gampe1a4bc7f2017-03-27 14:57:30 -0700530 : optimizer::DexToDexCompilationLevel::kDontDexToDexCompile);
Vladimir Marko492a7fa2016-06-01 18:38:43 +0100531 }
532 } else if ((access_flags & kAccNative) != 0) {
Goran Jakovljevic8d41c082016-09-28 08:49:46 +0000533 // Are we extracting only and have support for generic JNI down calls?
534 if (!driver->GetCompilerOptions().IsJniCompilationEnabled() &&
535 InstructionSetHasGenericJniStub(driver->GetInstructionSet())) {
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700536 // Leaving this empty will trigger the generic JNI version
537 } else {
Igor Murashkin9d4b6da2016-07-29 09:51:58 -0700538 // Look-up the ArtMethod associated with this code_item (if any)
539 // -- It is later used to lookup any [optimization] annotations for this method.
540 ScopedObjectAccess soa(self);
Igor Murashkin9d4b6da2016-07-29 09:51:58 -0700541
542 // TODO: Lookup annotation from DexFile directly without resolving method.
543 ArtMethod* method =
Vladimir Markoba118822017-06-12 15:41:56 +0100544 Runtime::Current()->GetClassLinker()->ResolveMethod<ClassLinker::ResolveMode::kNoChecks>(
Igor Murashkin9d4b6da2016-07-29 09:51:58 -0700545 dex_file,
546 method_idx,
547 dex_cache,
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000548 class_loader,
Igor Murashkin9d4b6da2016-07-29 09:51:58 -0700549 /* referrer */ nullptr,
550 invoke_type);
551
Igor Murashkin367f3dd2016-09-01 17:00:24 -0700552 // Query any JNI optimization annotations such as @FastNative or @CriticalNative.
553 Compiler::JniOptimizationFlags optimization_flags = Compiler::kNone;
554 if (UNLIKELY(method == nullptr)) {
Igor Murashkin9d4b6da2016-07-29 09:51:58 -0700555 // Failed method resolutions happen very rarely, e.g. ancestor class cannot be resolved.
556 DCHECK(self->IsExceptionPending());
557 self->ClearException();
Igor Murashkin367f3dd2016-09-01 17:00:24 -0700558 } else if (method->IsAnnotatedWithFastNative()) {
559 // TODO: Will no longer need this CHECK once we have verifier checking this.
560 CHECK(!method->IsAnnotatedWithCriticalNative());
561 optimization_flags = Compiler::kFastNative;
562 } else if (method->IsAnnotatedWithCriticalNative()) {
563 // TODO: Will no longer need this CHECK once we have verifier checking this.
564 CHECK(!method->IsAnnotatedWithFastNative());
565 optimization_flags = Compiler::kCriticalNative;
Igor Murashkin9d4b6da2016-07-29 09:51:58 -0700566 }
567
Igor Murashkin9d4b6da2016-07-29 09:51:58 -0700568 compiled_method = driver->GetCompiler()->JniCompile(access_flags,
569 method_idx,
570 dex_file,
571 optimization_flags);
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700572 CHECK(compiled_method != nullptr);
573 }
574 } else if ((access_flags & kAccAbstract) != 0) {
575 // Abstract methods don't have code.
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000576 } else {
Mathieu Chartier0733dc82017-07-17 14:05:28 -0700577 VerificationResults* results = driver->GetVerificationResults();
578 DCHECK(results != nullptr);
579 const VerifiedMethod* verified_method = results->GetVerifiedMethod(method_ref);
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700580 bool compile = compilation_enabled &&
581 // Basic checks, e.g., not <clinit>.
Mathieu Chartier0733dc82017-07-17 14:05:28 -0700582 results->IsCandidateForCompilation(method_ref, access_flags) &&
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700583 // Did not fail to create VerifiedMethod metadata.
Andreas Gampe0760a812015-08-26 17:12:51 -0700584 verified_method != nullptr &&
585 // Do not have failures that should punt to the interpreter.
586 !verified_method->HasRuntimeThrow() &&
587 (verified_method->GetEncounteredVerificationFailures() &
Andreas Gampea727e372015-08-25 09:22:37 -0700588 (verifier::VERIFY_ERROR_FORCE_INTERPRETER | verifier::VERIFY_ERROR_LOCKING)) == 0 &&
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700589 // Is eligable for compilation by methods-to-compile filter.
Calin Juravle226501b2015-12-11 14:41:31 +0000590 driver->IsMethodToCompile(method_ref) &&
591 driver->ShouldCompileBasedOnProfile(method_ref);
592
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700593 if (compile) {
594 // NOTE: if compiler declines to compile this method, it will return null.
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000595 compiled_method = driver->GetCompiler()->Compile(code_item,
596 access_flags,
597 invoke_type,
598 class_def_idx,
599 method_idx,
600 class_loader,
601 dex_file,
602 dex_cache);
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700603 }
604 if (compiled_method == nullptr &&
605 dex_to_dex_compilation_level != optimizer::DexToDexCompilationLevel::kDontDexToDexCompile) {
Vladimir Marko492a7fa2016-06-01 18:38:43 +0100606 DCHECK(!Runtime::Current()->UseJitCompilation());
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700607 // TODO: add a command-line option to disable DEX-to-DEX compilation ?
Vladimir Marko492a7fa2016-06-01 18:38:43 +0100608 driver->MarkForDexToDexCompilation(self, method_ref);
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700609 }
610 }
611 if (kTimeCompileMethod) {
612 uint64_t duration_ns = NanoTime() - start_ns;
613 if (duration_ns > MsToNs(driver->GetCompiler()->GetMaximumCompilationTimeBeforeWarning())) {
David Sehr709b0702016-10-13 09:12:37 -0700614 LOG(WARNING) << "Compilation of " << dex_file.PrettyMethod(method_idx)
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700615 << " took " << PrettyDuration(duration_ns);
616 }
617 }
618
619 if (compiled_method != nullptr) {
620 // Count non-relative linker patches.
621 size_t non_relative_linker_patch_count = 0u;
Vladimir Markod8dbc8d2017-09-20 13:37:47 +0100622 for (const linker::LinkerPatch& patch : compiled_method->GetPatches()) {
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700623 if (!patch.IsPcRelative()) {
624 ++non_relative_linker_patch_count;
625 }
626 }
627 bool compile_pic = driver->GetCompilerOptions().GetCompilePic(); // Off by default
628 // When compiling with PIC, there should be zero non-relative linker patches
629 CHECK(!compile_pic || non_relative_linker_patch_count == 0u);
630
631 driver->AddCompiledMethod(method_ref, compiled_method, non_relative_linker_patch_count);
632 }
633
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700634 if (self->IsExceptionPending()) {
635 ScopedObjectAccess soa(self);
David Sehr709b0702016-10-13 09:12:37 -0700636 LOG(FATAL) << "Unexpected exception compiling: " << dex_file.PrettyMethod(method_idx) << "\n"
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700637 << self->GetException()->Dump();
Sebastien Hertz75021222013-07-16 18:34:50 +0200638 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700639}
640
Mathieu Chartiere401d142015-04-22 13:56:20 -0700641void CompilerDriver::CompileOne(Thread* self, ArtMethod* method, TimingLogger* timings) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700642 DCHECK(!Runtime::Current()->IsStarted());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700643 jobject jclass_loader;
644 const DexFile* dex_file;
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700645 uint16_t class_def_idx;
Ian Rogersef7d42f2014-01-06 12:55:46 -0800646 uint32_t method_idx = method->GetDexMethodIndex();
647 uint32_t access_flags = method->GetAccessFlags();
648 InvokeType invoke_type = method->GetInvokeType();
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000649 StackHandleScope<2> hs(self);
Mathieu Chartier736b5602015-09-02 14:54:11 -0700650 Handle<mirror::DexCache> dex_cache(hs.NewHandle(method->GetDexCache()));
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000651 Handle<mirror::ClassLoader> class_loader(
652 hs.NewHandle(method->GetDeclaringClass()->GetClassLoader()));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700653 {
654 ScopedObjectAccessUnchecked soa(self);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800655 ScopedLocalRef<jobject> local_class_loader(
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000656 soa.Env(), soa.AddLocalReference<jobject>(class_loader.Get()));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700657 jclass_loader = soa.Env()->NewGlobalRef(local_class_loader.get());
658 // Find the dex_file
Mathieu Chartierbfd9a432014-05-21 17:43:44 -0700659 dex_file = method->GetDexFile();
660 class_def_idx = method->GetClassDefIndex();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700661 }
Ian Rogersef7d42f2014-01-06 12:55:46 -0800662 const DexFile::CodeItem* code_item = dex_file->GetCodeItem(method->GetCodeItemOffset());
Mathieu Chartier736b5602015-09-02 14:54:11 -0700663
664 // Go to native so that we don't block GC during compilation.
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700665 ScopedThreadSuspension sts(self, kNative);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700666
667 std::vector<const DexFile*> dex_files;
668 dex_files.push_back(dex_file);
669
Andreas Gampeace0dc12016-01-20 13:33:13 -0800670 InitializeThreadPools();
671
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000672 PreCompile(jclass_loader, dex_files, timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700673
Brian Carlstrom7940e442013-07-12 13:46:57 -0700674 // Can we run DEX-to-DEX compiler on this class ?
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700675 optimizer::DexToDexCompilationLevel dex_to_dex_compilation_level =
676 GetDexToDexCompilationLevel(self,
677 *this,
678 jclass_loader,
679 *dex_file,
680 dex_file->GetClassDef(class_def_idx));
681
Vladimir Marko492a7fa2016-06-01 18:38:43 +0100682 DCHECK(current_dex_to_dex_methods_ == nullptr);
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700683 CompileMethod(self,
684 this,
685 code_item,
686 access_flags,
687 invoke_type,
688 class_def_idx,
689 method_idx,
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000690 class_loader,
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700691 *dex_file,
692 dex_to_dex_compilation_level,
Mathieu Chartier736b5602015-09-02 14:54:11 -0700693 true,
694 dex_cache);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700695
Vladimir Marko492a7fa2016-06-01 18:38:43 +0100696 ArrayRef<DexFileMethodSet> dex_to_dex_references;
697 {
698 // From this point on, we shall not modify dex_to_dex_references_, so
699 // just grab a reference to it that we use without holding the mutex.
700 MutexLock lock(Thread::Current(), dex_to_dex_references_lock_);
701 dex_to_dex_references = ArrayRef<DexFileMethodSet>(dex_to_dex_references_);
702 }
703 if (!dex_to_dex_references.empty()) {
704 DCHECK_EQ(dex_to_dex_references.size(), 1u);
705 DCHECK(&dex_to_dex_references[0].GetDexFile() == dex_file);
706 current_dex_to_dex_methods_ = &dex_to_dex_references.front().GetMethodIndexes();
707 DCHECK(current_dex_to_dex_methods_->IsBitSet(method_idx));
708 DCHECK_EQ(current_dex_to_dex_methods_->NumSetBits(), 1u);
709 CompileMethod(self,
710 this,
711 code_item,
712 access_flags,
713 invoke_type,
714 class_def_idx,
715 method_idx,
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000716 class_loader,
Vladimir Marko492a7fa2016-06-01 18:38:43 +0100717 *dex_file,
718 dex_to_dex_compilation_level,
719 true,
720 dex_cache);
721 current_dex_to_dex_methods_ = nullptr;
722 }
723
Andreas Gampeace0dc12016-01-20 13:33:13 -0800724 FreeThreadPools();
725
Brian Carlstrom7940e442013-07-12 13:46:57 -0700726 self->GetJniEnv()->DeleteGlobalRef(jclass_loader);
Mathieu Chartier2535abe2015-02-17 10:38:49 -0800727}
728
Andreas Gampeace0dc12016-01-20 13:33:13 -0800729void CompilerDriver::Resolve(jobject class_loader,
730 const std::vector<const DexFile*>& dex_files,
731 TimingLogger* timings) {
732 // Resolution allocates classes and needs to run single-threaded to be deterministic.
733 bool force_determinism = GetCompilerOptions().IsForceDeterminism();
734 ThreadPool* resolve_thread_pool = force_determinism
735 ? single_thread_pool_.get()
736 : parallel_thread_pool_.get();
737 size_t resolve_thread_count = force_determinism ? 1U : parallel_thread_count_;
738
Brian Carlstrom7940e442013-07-12 13:46:57 -0700739 for (size_t i = 0; i != dex_files.size(); ++i) {
740 const DexFile* dex_file = dex_files[i];
Kenny Rootd5185342014-05-13 14:47:05 -0700741 CHECK(dex_file != nullptr);
Andreas Gampeace0dc12016-01-20 13:33:13 -0800742 ResolveDexFile(class_loader,
743 *dex_file,
744 dex_files,
745 resolve_thread_pool,
746 resolve_thread_count,
747 timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700748 }
749}
750
Andreas Gampeace0dc12016-01-20 13:33:13 -0800751// Resolve const-strings in the code. Done to have deterministic allocation behavior. Right now
752// this is single-threaded for simplicity.
753// TODO: Collect the relevant string indices in parallel, then allocate them sequentially in a
754// stable order.
755
Nicolas Geoffray571d2342016-10-12 13:03:15 +0000756static void ResolveConstStrings(Handle<mirror::DexCache> dex_cache,
Andreas Gampeace0dc12016-01-20 13:33:13 -0800757 const DexFile& dex_file,
Nicolas Geoffray571d2342016-10-12 13:03:15 +0000758 const DexFile::CodeItem* code_item)
759 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampeace0dc12016-01-20 13:33:13 -0800760 if (code_item == nullptr) {
761 // Abstract or native method.
762 return;
763 }
764
Nicolas Geoffray571d2342016-10-12 13:03:15 +0000765 ClassLinker* const class_linker = Runtime::Current()->GetClassLinker();
Mathieu Chartier1d2d4ff2017-09-23 16:11:06 -0700766 for (const Instruction& inst : code_item->Instructions()) {
767 switch (inst.Opcode()) {
Nicolas Geoffray571d2342016-10-12 13:03:15 +0000768 case Instruction::CONST_STRING:
Andreas Gampeace0dc12016-01-20 13:33:13 -0800769 case Instruction::CONST_STRING_JUMBO: {
Mathieu Chartier1d2d4ff2017-09-23 16:11:06 -0700770 dex::StringIndex string_index((inst.Opcode() == Instruction::CONST_STRING)
771 ? inst.VRegB_21c()
772 : inst.VRegB_31c());
Nicolas Geoffray571d2342016-10-12 13:03:15 +0000773 mirror::String* string = class_linker->ResolveString(dex_file, string_index, dex_cache);
774 CHECK(string != nullptr) << "Could not allocate a string when forcing determinism";
Andreas Gampeace0dc12016-01-20 13:33:13 -0800775 break;
776 }
777
778 default:
779 break;
780 }
Andreas Gampeace0dc12016-01-20 13:33:13 -0800781 }
782}
783
784static void ResolveConstStrings(CompilerDriver* driver,
785 const std::vector<const DexFile*>& dex_files,
786 TimingLogger* timings) {
Nicolas Geoffray571d2342016-10-12 13:03:15 +0000787 ScopedObjectAccess soa(Thread::Current());
788 StackHandleScope<1> hs(soa.Self());
789 ClassLinker* const class_linker = Runtime::Current()->GetClassLinker();
790 MutableHandle<mirror::DexCache> dex_cache(hs.NewHandle<mirror::DexCache>(nullptr));
791
Andreas Gampeace0dc12016-01-20 13:33:13 -0800792 for (const DexFile* dex_file : dex_files) {
Vladimir Markocd556b02017-02-03 11:47:34 +0000793 dex_cache.Assign(class_linker->FindDexCache(soa.Self(), *dex_file));
Andreas Gampeace0dc12016-01-20 13:33:13 -0800794 TimingLogger::ScopedTiming t("Resolve const-string Strings", timings);
795
796 size_t class_def_count = dex_file->NumClassDefs();
797 for (size_t class_def_index = 0; class_def_index < class_def_count; ++class_def_index) {
798 const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_index);
799
800 const uint8_t* class_data = dex_file->GetClassData(class_def);
801 if (class_data == nullptr) {
802 // empty class, probably a marker interface
803 continue;
804 }
805
806 ClassDataItemIterator it(*dex_file, class_data);
Mathieu Chartiere17cf242017-06-19 11:05:51 -0700807 it.SkipAllFields();
Andreas Gampeace0dc12016-01-20 13:33:13 -0800808
809 bool compilation_enabled = driver->IsClassToCompile(
810 dex_file->StringByTypeIdx(class_def.class_idx_));
811 if (!compilation_enabled) {
812 // Compilation is skipped, do not resolve const-string in code of this class.
813 // TODO: Make sure that inlining honors this.
814 continue;
815 }
816
817 // Direct methods.
818 int64_t previous_direct_method_idx = -1;
819 while (it.HasNextDirectMethod()) {
820 uint32_t method_idx = it.GetMemberIndex();
821 if (method_idx == previous_direct_method_idx) {
822 // smali can create dex files with two encoded_methods sharing the same method_idx
823 // http://code.google.com/p/smali/issues/detail?id=119
824 it.Next();
825 continue;
826 }
827 previous_direct_method_idx = method_idx;
Nicolas Geoffray571d2342016-10-12 13:03:15 +0000828 ResolveConstStrings(dex_cache, *dex_file, it.GetMethodCodeItem());
Andreas Gampeace0dc12016-01-20 13:33:13 -0800829 it.Next();
830 }
831 // Virtual methods.
832 int64_t previous_virtual_method_idx = -1;
833 while (it.HasNextVirtualMethod()) {
834 uint32_t method_idx = it.GetMemberIndex();
835 if (method_idx == previous_virtual_method_idx) {
836 // smali can create dex files with two encoded_methods sharing the same method_idx
837 // http://code.google.com/p/smali/issues/detail?id=119
838 it.Next();
839 continue;
840 }
841 previous_virtual_method_idx = method_idx;
Nicolas Geoffray571d2342016-10-12 13:03:15 +0000842 ResolveConstStrings(dex_cache, *dex_file, it.GetMethodCodeItem());
Andreas Gampeace0dc12016-01-20 13:33:13 -0800843 it.Next();
844 }
845 DCHECK(!it.HasNext());
846 }
847 }
848}
849
850inline void CompilerDriver::CheckThreadPools() {
851 DCHECK(parallel_thread_pool_ != nullptr);
852 DCHECK(single_thread_pool_ != nullptr);
853}
854
Nicolas Geoffray0a27fd02017-01-25 16:18:54 +0000855static void EnsureVerifiedOrVerifyAtRuntime(jobject jclass_loader,
856 const std::vector<const DexFile*>& dex_files) {
857 ScopedObjectAccess soa(Thread::Current());
858 StackHandleScope<2> hs(soa.Self());
859 Handle<mirror::ClassLoader> class_loader(
860 hs.NewHandle(soa.Decode<mirror::ClassLoader>(jclass_loader)));
861 MutableHandle<mirror::Class> cls(hs.NewHandle<mirror::Class>(nullptr));
862 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
863
864 for (const DexFile* dex_file : dex_files) {
865 for (uint32_t i = 0; i < dex_file->NumClassDefs(); ++i) {
866 const DexFile::ClassDef& class_def = dex_file->GetClassDef(i);
867 const char* descriptor = dex_file->GetClassDescriptor(class_def);
868 cls.Assign(class_linker->FindClass(soa.Self(), descriptor, class_loader));
Andreas Gampefa4333d2017-02-14 11:10:34 -0800869 if (cls == nullptr) {
Nicolas Geoffray0a27fd02017-01-25 16:18:54 +0000870 soa.Self()->ClearException();
871 } else if (&cls->GetDexFile() == dex_file) {
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +0000872 DCHECK(cls->IsErroneous() || cls->IsVerified() || cls->ShouldVerifyAtRuntime())
Nicolas Geoffray0a27fd02017-01-25 16:18:54 +0000873 << cls->PrettyClass()
874 << " " << cls->GetStatus();
875 }
876 }
877 }
878}
879
Andreas Gampeace0dc12016-01-20 13:33:13 -0800880void CompilerDriver::PreCompile(jobject class_loader,
881 const std::vector<const DexFile*>& dex_files,
882 TimingLogger* timings) {
883 CheckThreadPools();
884
Brian Carlstrom7940e442013-07-12 13:46:57 -0700885 LoadImageClasses(timings);
Andreas Gampe8d295f82015-01-20 14:50:21 -0800886 VLOG(compiler) << "LoadImageClasses: " << GetMemoryUsageString(false);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700887
Nicolas Geoffray49cda062017-04-21 13:08:25 +0100888 if (compiler_options_->IsAnyCompilationEnabled()) {
Mathieu Chartier88b74b62017-07-16 17:08:19 -0700889 // Avoid adding the dex files in the case where we aren't going to add compiled methods.
890 // This reduces RAM usage for this case.
891 for (const DexFile* dex_file : dex_files) {
892 // Can be already inserted if the caller is CompileOne. This happens for gtests.
893 if (!compiled_methods_.HaveDexFile(dex_file)) {
Mathieu Chartierfc8b4222017-09-17 13:44:24 -0700894 compiled_methods_.AddDexFile(dex_file);
Mathieu Chartier88b74b62017-07-16 17:08:19 -0700895 }
896 }
Nicolas Geoffray49cda062017-04-21 13:08:25 +0100897 // Resolve eagerly to prepare for compilation.
Andreas Gampeace0dc12016-01-20 13:33:13 -0800898 Resolve(class_loader, dex_files, timings);
Mathieu Chartiere86deef2015-03-19 13:43:37 -0700899 VLOG(compiler) << "Resolve: " << GetMemoryUsageString(false);
900 }
901
Nicolas Geoffray60ca9492016-12-20 21:15:00 +0000902 if (compiler_options_->AssumeClassesAreVerified()) {
Mathieu Chartierab972ef2014-12-03 17:38:22 -0800903 VLOG(compiler) << "Verify none mode specified, skipping verification.";
Andreas Gampeace0dc12016-01-20 13:33:13 -0800904 SetVerified(class_loader, dex_files, timings);
Mathieu Chartiere86deef2015-03-19 13:43:37 -0700905 }
906
Nicolas Geoffray60ca9492016-12-20 21:15:00 +0000907 if (!compiler_options_->IsVerificationEnabled()) {
Jeff Hao4a200f52014-04-01 14:58:49 -0700908 return;
909 }
910
Vladimir Markoaad75c62016-10-03 08:46:48 +0000911 if (GetCompilerOptions().IsForceDeterminism() && GetCompilerOptions().IsBootImage()) {
Andreas Gampeace0dc12016-01-20 13:33:13 -0800912 // Resolve strings from const-string. Do this now to have a deterministic image.
913 ResolveConstStrings(this, dex_files, timings);
914 VLOG(compiler) << "Resolve const-strings: " << GetMemoryUsageString(false);
915 }
916
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +0000917 Verify(class_loader, dex_files, timings);
Andreas Gampe8d295f82015-01-20 14:50:21 -0800918 VLOG(compiler) << "Verify: " << GetMemoryUsageString(false);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700919
Andreas Gampe6cf49e52015-03-05 13:08:45 -0800920 if (had_hard_verifier_failure_ && GetCompilerOptions().AbortOnHardVerifierFailure()) {
Andreas Gampefdfb4d42017-07-27 12:12:22 -0700921 // Avoid dumping threads. Even if we shut down the thread pools, there will still be three
922 // instances of this thread's stack.
923 LOG(FATAL_WITHOUT_ABORT) << "Had a hard failure verifying all classes, and was asked to abort "
924 << "in such situations. Please check the log.";
925 abort();
Andreas Gampe6cf49e52015-03-05 13:08:45 -0800926 }
927
Nicolas Geoffray49cda062017-04-21 13:08:25 +0100928 if (compiler_options_->IsAnyCompilationEnabled()) {
Nicolas Geoffray0a27fd02017-01-25 16:18:54 +0000929 if (kIsDebugBuild) {
930 EnsureVerifiedOrVerifyAtRuntime(class_loader, dex_files);
931 }
Nicolas Geoffrayade72d62016-12-15 13:20:02 +0000932 InitializeClasses(class_loader, dex_files, timings);
933 VLOG(compiler) << "InitializeClasses: " << GetMemoryUsageString(false);
934 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700935
936 UpdateImageClasses(timings);
Andreas Gampe8d295f82015-01-20 14:50:21 -0800937 VLOG(compiler) << "UpdateImageClasses: " << GetMemoryUsageString(false);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700938}
939
Ian Rogersdfb325e2013-10-30 01:00:44 -0700940bool CompilerDriver::IsImageClass(const char* descriptor) const {
Mathieu Chartierc5dd3192015-12-09 16:38:30 -0800941 if (image_classes_ != nullptr) {
942 // If we have a set of image classes, use those.
Ian Rogersdfb325e2013-10-30 01:00:44 -0700943 return image_classes_->find(descriptor) != image_classes_->end();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700944 }
Mathieu Chartierc5dd3192015-12-09 16:38:30 -0800945 // No set of image classes, assume we include all the classes.
946 // NOTE: Currently only reachable from InitImageMethodVisitor for the app image case.
Vladimir Markoaad75c62016-10-03 08:46:48 +0000947 return !GetCompilerOptions().IsBootImage();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700948}
949
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800950bool CompilerDriver::IsClassToCompile(const char* descriptor) const {
Andreas Gampeb1fcead2015-04-20 18:53:51 -0700951 if (classes_to_compile_ == nullptr) {
952 return true;
953 }
954 return classes_to_compile_->find(descriptor) != classes_to_compile_->end();
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800955}
956
Andreas Gampe70bef0d2015-04-15 02:37:28 -0700957bool CompilerDriver::IsMethodToCompile(const MethodReference& method_ref) const {
Andreas Gampe70bef0d2015-04-15 02:37:28 -0700958 if (methods_to_compile_ == nullptr) {
959 return true;
960 }
961
Mathieu Chartierfc8b4222017-09-17 13:44:24 -0700962 std::string tmp = method_ref.PrettyMethod();
Andreas Gampe70bef0d2015-04-15 02:37:28 -0700963 return methods_to_compile_->find(tmp.c_str()) != methods_to_compile_->end();
964}
965
Calin Juravle226501b2015-12-11 14:41:31 +0000966bool CompilerDriver::ShouldCompileBasedOnProfile(const MethodReference& method_ref) const {
Mathieu Chartier97ab5e32017-02-22 13:35:44 -0800967 // Profile compilation info may be null if no profile is passed.
Mathieu Chartierd0af56c2017-02-17 12:56:25 -0800968 if (!CompilerFilter::DependsOnProfile(compiler_options_->GetCompilerFilter())) {
969 // Use the compiler filter instead of the presence of profile_compilation_info_ since
970 // we may want to have full speed compilation along with profile based layout optimizations.
Calin Juravle226501b2015-12-11 14:41:31 +0000971 return true;
972 }
Mathieu Chartier97ab5e32017-02-22 13:35:44 -0800973 // If we are using a profile filter but do not have a profile compilation info, compile nothing.
974 if (profile_compilation_info_ == nullptr) {
975 return false;
976 }
Mathieu Chartier7b135c82017-06-05 12:54:01 -0700977 // Compile only hot methods, it is the profile saver's job to decide what startup methods to mark
978 // as hot.
Mathieu Chartierbbe3a5e2017-06-13 16:36:17 -0700979 bool result = profile_compilation_info_->GetMethodHotness(method_ref).IsHot();
Calin Juravle226501b2015-12-11 14:41:31 +0000980
981 if (kDebugProfileGuidedCompilation) {
982 LOG(INFO) << "[ProfileGuidedCompilation] "
Mathieu Chartierfc8b4222017-09-17 13:44:24 -0700983 << (result ? "Compiled" : "Skipped") << " method:" << method_ref.PrettyMethod(true);
Calin Juravle226501b2015-12-11 14:41:31 +0000984 }
985 return result;
986}
987
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700988class ResolveCatchBlockExceptionsClassVisitor : public ClassVisitor {
989 public:
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000990 ResolveCatchBlockExceptionsClassVisitor() : classes_() {}
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700991
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700992 virtual bool operator()(ObjPtr<mirror::Class> c) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000993 classes_.push_back(c);
Mathieu Chartiere4275c02015-08-06 15:34:15 -0700994 return true;
995 }
996
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000997 void FindExceptionTypesToResolve(
998 std::set<std::pair<dex::TypeIndex, const DexFile*>>* exceptions_to_resolve)
Vladimir Markobfb80d22017-02-14 14:08:12 +0000999 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001000 const auto pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
1001 for (ObjPtr<mirror::Class> klass : classes_) {
1002 for (ArtMethod& method : klass->GetMethods(pointer_size)) {
1003 FindExceptionTypesToResolveForMethod(&method, exceptions_to_resolve);
1004 }
1005 }
1006 }
1007
1008 private:
1009 void FindExceptionTypesToResolveForMethod(
1010 ArtMethod* method,
1011 std::set<std::pair<dex::TypeIndex, const DexFile*>>* exceptions_to_resolve)
1012 REQUIRES_SHARED(Locks::mutator_lock_) {
1013 const DexFile::CodeItem* code_item = method->GetCodeItem();
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001014 if (code_item == nullptr) {
1015 return; // native or abstract method
Brian Carlstrom7940e442013-07-12 13:46:57 -07001016 }
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001017 if (code_item->tries_size_ == 0) {
1018 return; // nothing to process
1019 }
1020 const uint8_t* encoded_catch_handler_list = DexFile::GetCatchHandlerData(*code_item, 0);
1021 size_t num_encoded_catch_handlers = DecodeUnsignedLeb128(&encoded_catch_handler_list);
1022 for (size_t i = 0; i < num_encoded_catch_handlers; i++) {
1023 int32_t encoded_catch_handler_size = DecodeSignedLeb128(&encoded_catch_handler_list);
1024 bool has_catch_all = false;
1025 if (encoded_catch_handler_size <= 0) {
1026 encoded_catch_handler_size = -encoded_catch_handler_size;
1027 has_catch_all = true;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001028 }
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001029 for (int32_t j = 0; j < encoded_catch_handler_size; j++) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08001030 dex::TypeIndex encoded_catch_handler_handlers_type_idx =
1031 dex::TypeIndex(DecodeUnsignedLeb128(&encoded_catch_handler_list));
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001032 // Add to set of types to resolve if not already in the dex cache resolved types
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001033 if (!method->IsResolvedTypeIdx(encoded_catch_handler_handlers_type_idx)) {
1034 exceptions_to_resolve->emplace(encoded_catch_handler_handlers_type_idx,
1035 method->GetDexFile());
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001036 }
1037 // ignore address associated with catch handler
1038 DecodeUnsignedLeb128(&encoded_catch_handler_list);
1039 }
1040 if (has_catch_all) {
1041 // ignore catch all address
1042 DecodeUnsignedLeb128(&encoded_catch_handler_list);
1043 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001044 }
1045 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001046
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001047 std::vector<ObjPtr<mirror::Class>> classes_;
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001048};
1049
1050class RecordImageClassesVisitor : public ClassVisitor {
1051 public:
1052 explicit RecordImageClassesVisitor(std::unordered_set<std::string>* image_classes)
1053 : image_classes_(image_classes) {}
1054
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001055 bool operator()(ObjPtr<mirror::Class> klass) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001056 std::string temp;
1057 image_classes_->insert(klass->GetDescriptor(&temp));
1058 return true;
1059 }
1060
1061 private:
1062 std::unordered_set<std::string>* const image_classes_;
1063};
Brian Carlstrom7940e442013-07-12 13:46:57 -07001064
1065// Make a list of descriptors for classes to include in the image
Mathieu Chartier90443472015-07-16 20:32:27 -07001066void CompilerDriver::LoadImageClasses(TimingLogger* timings) {
Kenny Rootd5185342014-05-13 14:47:05 -07001067 CHECK(timings != nullptr);
Vladimir Markoaad75c62016-10-03 08:46:48 +00001068 if (!GetCompilerOptions().IsBootImage()) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001069 return;
1070 }
1071
Mathieu Chartierf5997b42014-06-20 10:37:54 -07001072 TimingLogger::ScopedTiming t("LoadImageClasses", timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001073 // Make a first class to load all classes explicitly listed in the file
1074 Thread* self = Thread::Current();
1075 ScopedObjectAccess soa(self);
1076 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Kenny Rootd5185342014-05-13 14:47:05 -07001077 CHECK(image_classes_.get() != nullptr);
Mathieu Chartier02e25112013-08-14 16:14:24 -07001078 for (auto it = image_classes_->begin(), end = image_classes_->end(); it != end;) {
Vladimir Markoe9c36b32013-11-21 15:49:16 +00001079 const std::string& descriptor(*it);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001080 StackHandleScope<1> hs(self);
1081 Handle<mirror::Class> klass(
1082 hs.NewHandle(class_linker->FindSystemClass(self, descriptor.c_str())));
Andreas Gampefa4333d2017-02-14 11:10:34 -08001083 if (klass == nullptr) {
Ian Rogerse6bb3b22013-08-19 21:51:45 -07001084 VLOG(compiler) << "Failed to find class " << descriptor;
Vladimir Markoe9c36b32013-11-21 15:49:16 +00001085 image_classes_->erase(it++);
Ian Rogersa436fde2013-08-27 23:34:06 -07001086 self->ClearException();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001087 } else {
1088 ++it;
1089 }
1090 }
1091
1092 // Resolve exception classes referenced by the loaded classes. The catch logic assumes
1093 // exceptions are resolved by the verifier when there is a catch block in an interested method.
1094 // Do this here so that exception classes appear to have been specified image classes.
Andreas Gampea5b09a62016-11-17 15:21:22 -08001095 std::set<std::pair<dex::TypeIndex, const DexFile*>> unresolved_exception_types;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001096 StackHandleScope<1> hs(self);
1097 Handle<mirror::Class> java_lang_Throwable(
1098 hs.NewHandle(class_linker->FindSystemClass(self, "Ljava/lang/Throwable;")));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001099 do {
1100 unresolved_exception_types.clear();
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001101 {
1102 // Thread suspension is not allowed while ResolveCatchBlockExceptionsClassVisitor
1103 // is using a std::vector<ObjPtr<mirror::Class>>.
1104 ScopedAssertNoThreadSuspension ants(__FUNCTION__);
1105 ResolveCatchBlockExceptionsClassVisitor visitor;
1106 class_linker->VisitClasses(&visitor);
1107 visitor.FindExceptionTypesToResolve(&unresolved_exception_types);
1108 }
Andreas Gampea5b09a62016-11-17 15:21:22 -08001109 for (const auto& exception_type : unresolved_exception_types) {
1110 dex::TypeIndex exception_type_idx = exception_type.first;
Mathieu Chartier02e25112013-08-14 16:14:24 -07001111 const DexFile* dex_file = exception_type.second;
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001112 StackHandleScope<2> hs2(self);
Mathieu Chartierf284d442016-06-02 11:48:30 -07001113 Handle<mirror::DexCache> dex_cache(hs2.NewHandle(class_linker->RegisterDexFile(*dex_file,
1114 nullptr)));
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001115 Handle<mirror::Class> klass(hs2.NewHandle(
Andreas Gampefa4333d2017-02-14 11:10:34 -08001116 (dex_cache != nullptr)
Vladimir Markocd556b02017-02-03 11:47:34 +00001117 ? class_linker->ResolveType(*dex_file,
1118 exception_type_idx,
1119 dex_cache,
1120 ScopedNullHandle<mirror::ClassLoader>())
1121 : nullptr));
Andreas Gampefa4333d2017-02-14 11:10:34 -08001122 if (klass == nullptr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001123 const DexFile::TypeId& type_id = dex_file->GetTypeId(exception_type_idx);
1124 const char* descriptor = dex_file->GetTypeDescriptor(type_id);
1125 LOG(FATAL) << "Failed to resolve class " << descriptor;
1126 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001127 DCHECK(java_lang_Throwable->IsAssignableFrom(klass.Get()));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001128 }
1129 // Resolving exceptions may load classes that reference more exceptions, iterate until no
1130 // more are found
1131 } while (!unresolved_exception_types.empty());
1132
1133 // We walk the roots looking for classes so that we'll pick up the
1134 // above classes plus any classes them depend on such super
1135 // classes, interfaces, and the required ClassLinker roots.
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001136 RecordImageClassesVisitor visitor(image_classes_.get());
1137 class_linker->VisitClasses(&visitor);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001138
1139 CHECK_NE(image_classes_->size(), 0U);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001140}
1141
Vladimir Marko19a4d372016-12-08 14:41:46 +00001142static void MaybeAddToImageClasses(Thread* self,
1143 ObjPtr<mirror::Class> klass,
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001144 std::unordered_set<std::string>* image_classes)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001145 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko19a4d372016-12-08 14:41:46 +00001146 DCHECK_EQ(self, Thread::Current());
Mathieu Chartierf8322842014-05-16 10:59:25 -07001147 StackHandleScope<1> hs(self);
Ian Rogers1ff3c982014-08-12 02:30:58 -07001148 std::string temp;
Andreas Gampe542451c2016-07-26 09:02:02 -07001149 const PointerSize pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001150 while (!klass->IsObjectClass()) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07001151 const char* descriptor = klass->GetDescriptor(&temp);
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001152 std::pair<std::unordered_set<std::string>::iterator, bool> result =
1153 image_classes->insert(descriptor);
Ian Rogers1ff3c982014-08-12 02:30:58 -07001154 if (!result.second) { // Previously inserted.
1155 break;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001156 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07001157 VLOG(compiler) << "Adding " << descriptor << " to image classes";
Vladimir Marko19a4d372016-12-08 14:41:46 +00001158 for (size_t i = 0, num_interfaces = klass->NumDirectInterfaces(); i != num_interfaces; ++i) {
1159 ObjPtr<mirror::Class> interface = mirror::Class::GetDirectInterface(self, klass, i);
1160 DCHECK(interface != nullptr);
1161 MaybeAddToImageClasses(self, interface, image_classes);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001162 }
Vladimir Marko19a4d372016-12-08 14:41:46 +00001163 for (auto& m : klass->GetVirtualMethods(pointer_size)) {
1164 MaybeAddToImageClasses(self, m.GetDeclaringClass(), image_classes);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001165 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001166 if (klass->IsArrayClass()) {
Vladimir Marko19a4d372016-12-08 14:41:46 +00001167 MaybeAddToImageClasses(self, klass->GetComponentType(), image_classes);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001168 }
Mathieu Chartierf8322842014-05-16 10:59:25 -07001169 klass.Assign(klass->GetSuperClass());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001170 }
1171}
1172
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001173// Keeps all the data for the update together. Also doubles as the reference visitor.
1174// Note: we can use object pointers because we suspend all threads.
1175class ClinitImageUpdate {
1176 public:
Mathieu Chartier31e88222016-10-14 18:43:19 -07001177 static ClinitImageUpdate* Create(VariableSizedHandleScope& hs,
1178 std::unordered_set<std::string>* image_class_descriptors,
1179 Thread* self,
1180 ClassLinker* linker) {
1181 std::unique_ptr<ClinitImageUpdate> res(new ClinitImageUpdate(hs,
1182 image_class_descriptors,
1183 self,
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001184 linker));
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001185 return res.release();
1186 }
1187
1188 ~ClinitImageUpdate() {
1189 // Allow others to suspend again.
1190 self_->EndAssertNoThreadSuspension(old_cause_);
1191 }
1192
1193 // Visitor for VisitReferences.
Mathieu Chartier31e88222016-10-14 18:43:19 -07001194 void operator()(ObjPtr<mirror::Object> object,
1195 MemberOffset field_offset,
1196 bool /* is_static */) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001197 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001198 mirror::Object* ref = object->GetFieldObject<mirror::Object>(field_offset);
1199 if (ref != nullptr) {
1200 VisitClinitClassesObject(ref);
1201 }
1202 }
1203
Roland Levillain5e8d5f02016-10-18 18:03:43 +01001204 // java.lang.ref.Reference visitor for VisitReferences.
Mathieu Chartier31e88222016-10-14 18:43:19 -07001205 void operator()(ObjPtr<mirror::Class> klass ATTRIBUTE_UNUSED,
1206 ObjPtr<mirror::Reference> ref ATTRIBUTE_UNUSED) const {}
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001207
1208 // Ignore class native roots.
1209 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED)
1210 const {}
1211 void VisitRoot(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED) const {}
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001212
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001213 void Walk() REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001214 // Use the initial classes as roots for a search.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001215 for (Handle<mirror::Class> klass_root : image_classes_) {
1216 VisitClinitClassesObject(klass_root.Get());
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001217 }
Vladimir Marko19a4d372016-12-08 14:41:46 +00001218 Thread* self = Thread::Current();
1219 ScopedAssertNoThreadSuspension ants(__FUNCTION__);
Mathieu Chartier31e88222016-10-14 18:43:19 -07001220 for (Handle<mirror::Class> h_klass : to_insert_) {
Vladimir Marko19a4d372016-12-08 14:41:46 +00001221 MaybeAddToImageClasses(self, h_klass.Get(), image_class_descriptors_);
Mathieu Chartier31e88222016-10-14 18:43:19 -07001222 }
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001223 }
1224
1225 private:
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001226 class FindImageClassesVisitor : public ClassVisitor {
1227 public:
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001228 explicit FindImageClassesVisitor(VariableSizedHandleScope& hs,
1229 ClinitImageUpdate* data)
1230 : data_(data),
1231 hs_(hs) {}
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001232
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001233 bool operator()(ObjPtr<mirror::Class> klass) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001234 std::string temp;
1235 const char* name = klass->GetDescriptor(&temp);
1236 if (data_->image_class_descriptors_->find(name) != data_->image_class_descriptors_->end()) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001237 data_->image_classes_.push_back(hs_.NewHandle(klass));
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001238 } else {
1239 // Check whether it is initialized and has a clinit. They must be kept, too.
1240 if (klass->IsInitialized() && klass->FindClassInitializer(
1241 Runtime::Current()->GetClassLinker()->GetImagePointerSize()) != nullptr) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001242 data_->image_classes_.push_back(hs_.NewHandle(klass));
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001243 }
1244 }
1245 return true;
1246 }
1247
1248 private:
1249 ClinitImageUpdate* const data_;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001250 VariableSizedHandleScope& hs_;
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001251 };
1252
Mathieu Chartier31e88222016-10-14 18:43:19 -07001253 ClinitImageUpdate(VariableSizedHandleScope& hs,
1254 std::unordered_set<std::string>* image_class_descriptors,
1255 Thread* self,
1256 ClassLinker* linker) REQUIRES_SHARED(Locks::mutator_lock_)
1257 : hs_(hs),
1258 image_class_descriptors_(image_class_descriptors),
1259 self_(self) {
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001260 CHECK(linker != nullptr);
1261 CHECK(image_class_descriptors != nullptr);
1262
1263 // Make sure nobody interferes with us.
1264 old_cause_ = self->StartAssertNoThreadSuspension("Boot image closure");
1265
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001266 // Find all the already-marked classes.
1267 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001268 FindImageClassesVisitor visitor(hs_, this);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001269 linker->VisitClasses(&visitor);
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001270 }
1271
1272 void VisitClinitClassesObject(mirror::Object* object) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001273 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001274 DCHECK(object != nullptr);
1275 if (marked_objects_.find(object) != marked_objects_.end()) {
1276 // Already processed.
1277 return;
1278 }
1279
1280 // Mark it.
1281 marked_objects_.insert(object);
1282
1283 if (object->IsClass()) {
Mathieu Chartier31e88222016-10-14 18:43:19 -07001284 // Add to the TODO list since MaybeAddToImageClasses may cause thread suspension. Thread
1285 // suspensionb is not safe to do in VisitObjects or VisitReferences.
1286 to_insert_.push_back(hs_.NewHandle(object->AsClass()));
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001287 } else {
1288 // Else visit the object's class.
1289 VisitClinitClassesObject(object->GetClass());
1290 }
1291
Mathieu Chartiere401d142015-04-22 13:56:20 -07001292 // If it is not a DexCache, visit all references.
Mathieu Chartier31e88222016-10-14 18:43:19 -07001293 if (!object->IsDexCache()) {
Mathieu Chartier059ef3d2015-08-18 13:54:21 -07001294 object->VisitReferences(*this, *this);
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001295 }
1296 }
1297
Mathieu Chartier31e88222016-10-14 18:43:19 -07001298 VariableSizedHandleScope& hs_;
1299 mutable std::vector<Handle<mirror::Class>> to_insert_;
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001300 mutable std::unordered_set<mirror::Object*> marked_objects_;
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001301 std::unordered_set<std::string>* const image_class_descriptors_;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001302 std::vector<Handle<mirror::Class>> image_classes_;
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001303 Thread* const self_;
1304 const char* old_cause_;
1305
1306 DISALLOW_COPY_AND_ASSIGN(ClinitImageUpdate);
1307};
Brian Carlstrom7940e442013-07-12 13:46:57 -07001308
Ian Rogers3d504072014-03-01 09:16:49 -08001309void CompilerDriver::UpdateImageClasses(TimingLogger* timings) {
Vladimir Markoaad75c62016-10-03 08:46:48 +00001310 if (GetCompilerOptions().IsBootImage()) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07001311 TimingLogger::ScopedTiming t("UpdateImageClasses", timings);
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001312
Mathieu Chartier4f55e222015-09-04 13:26:21 -07001313 Runtime* runtime = Runtime::Current();
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001314
1315 // Suspend all threads.
Mathieu Chartier4f55e222015-09-04 13:26:21 -07001316 ScopedSuspendAll ssa(__FUNCTION__);
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001317
Mathieu Chartier31e88222016-10-14 18:43:19 -07001318 VariableSizedHandleScope hs(Thread::Current());
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001319 std::string error_msg;
Mathieu Chartier31e88222016-10-14 18:43:19 -07001320 std::unique_ptr<ClinitImageUpdate> update(ClinitImageUpdate::Create(hs,
1321 image_classes_.get(),
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001322 Thread::Current(),
Mathieu Chartier31e88222016-10-14 18:43:19 -07001323 runtime->GetClassLinker()));
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001324
1325 // Do the marking.
1326 update->Walk();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001327 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001328}
1329
Vladimir Marko07785bb2015-06-15 18:52:54 +01001330bool CompilerDriver::CanAssumeClassIsLoaded(mirror::Class* klass) {
1331 Runtime* runtime = Runtime::Current();
1332 if (!runtime->IsAotCompiler()) {
Calin Juravleffc87072016-04-20 14:22:09 +01001333 DCHECK(runtime->UseJitCompilation());
Vladimir Marko07785bb2015-06-15 18:52:54 +01001334 // Having the klass reference here implies that the klass is already loaded.
1335 return true;
1336 }
Vladimir Markoaad75c62016-10-03 08:46:48 +00001337 if (!GetCompilerOptions().IsBootImage()) {
Vladimir Marko07785bb2015-06-15 18:52:54 +01001338 // Assume loaded only if klass is in the boot image. App classes cannot be assumed
1339 // loaded because we don't even know what class loader will be used to load them.
1340 bool class_in_image = runtime->GetHeap()->FindSpaceFromObject(klass, false)->IsImageSpace();
1341 return class_in_image;
1342 }
1343 std::string temp;
1344 const char* descriptor = klass->GetDescriptor(&temp);
1345 return IsImageClass(descriptor);
1346}
1347
Vladimir Marko492a7fa2016-06-01 18:38:43 +01001348void CompilerDriver::MarkForDexToDexCompilation(Thread* self, const MethodReference& method_ref) {
1349 MutexLock lock(self, dex_to_dex_references_lock_);
1350 // Since we're compiling one dex file at a time, we need to look for the
1351 // current dex file entry only at the end of dex_to_dex_references_.
1352 if (dex_to_dex_references_.empty() ||
1353 &dex_to_dex_references_.back().GetDexFile() != method_ref.dex_file) {
1354 dex_to_dex_references_.emplace_back(*method_ref.dex_file);
1355 }
Mathieu Chartierfc8b4222017-09-17 13:44:24 -07001356 dex_to_dex_references_.back().GetMethodIndexes().SetBit(method_ref.index);
Vladimir Marko492a7fa2016-06-01 18:38:43 +01001357}
1358
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001359bool CompilerDriver::CanAccessTypeWithoutChecks(ObjPtr<mirror::Class> referrer_class,
1360 ObjPtr<mirror::Class> resolved_class) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001361 if (resolved_class == nullptr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001362 stats_->TypeNeedsAccessCheck();
1363 return false; // Unknown class needs access checks.
1364 }
David Brazdil38f64d32016-01-18 17:13:41 +00001365 bool is_accessible = resolved_class->IsPublic(); // Public classes are always accessible.
1366 if (!is_accessible) {
David Brazdil38f64d32016-01-18 17:13:41 +00001367 if (referrer_class == nullptr) {
1368 stats_->TypeNeedsAccessCheck();
1369 return false; // Incomplete referrer knowledge needs access check.
1370 }
1371 // Perform access check, will return true if access is ok or false if we're going to have to
1372 // check this at runtime (for example for class loaders).
1373 is_accessible = referrer_class->CanAccess(resolved_class);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001374 }
David Brazdil38f64d32016-01-18 17:13:41 +00001375 if (is_accessible) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001376 stats_->TypeDoesntNeedAccessCheck();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001377 } else {
1378 stats_->TypeNeedsAccessCheck();
1379 }
David Brazdil38f64d32016-01-18 17:13:41 +00001380 return is_accessible;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001381}
1382
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001383bool CompilerDriver::CanAccessInstantiableTypeWithoutChecks(ObjPtr<mirror::Class> referrer_class,
1384 ObjPtr<mirror::Class> resolved_class,
Mingyao Yangfb8464a2015-11-02 10:56:59 -08001385 bool* finalizable) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001386 if (resolved_class == nullptr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001387 stats_->TypeNeedsAccessCheck();
Mingyao Yangfb8464a2015-11-02 10:56:59 -08001388 // Be conservative.
1389 *finalizable = true;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001390 return false; // Unknown class needs access checks.
1391 }
Mingyao Yangfb8464a2015-11-02 10:56:59 -08001392 *finalizable = resolved_class->IsFinalizable();
David Brazdil38f64d32016-01-18 17:13:41 +00001393 bool is_accessible = resolved_class->IsPublic(); // Public classes are always accessible.
1394 if (!is_accessible) {
David Brazdil38f64d32016-01-18 17:13:41 +00001395 if (referrer_class == nullptr) {
1396 stats_->TypeNeedsAccessCheck();
1397 return false; // Incomplete referrer knowledge needs access check.
1398 }
1399 // Perform access and instantiable checks, will return true if access is ok or false if we're
1400 // going to have to check this at runtime (for example for class loaders).
1401 is_accessible = referrer_class->CanAccess(resolved_class);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001402 }
David Brazdil38f64d32016-01-18 17:13:41 +00001403 bool result = is_accessible && resolved_class->IsInstantiable();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001404 if (result) {
1405 stats_->TypeDoesntNeedAccessCheck();
1406 } else {
1407 stats_->TypeNeedsAccessCheck();
1408 }
1409 return result;
1410}
1411
Vladimir Markobe0e5462014-02-26 11:24:15 +00001412void CompilerDriver::ProcessedInstanceField(bool resolved) {
1413 if (!resolved) {
1414 stats_->UnresolvedInstanceField();
1415 } else {
1416 stats_->ResolvedInstanceField();
1417 }
1418}
1419
1420void CompilerDriver::ProcessedStaticField(bool resolved, bool local) {
1421 if (!resolved) {
1422 stats_->UnresolvedStaticField();
1423 } else if (local) {
1424 stats_->ResolvedLocalStaticField();
1425 } else {
1426 stats_->ResolvedStaticField();
1427 }
1428}
1429
Mathieu Chartierc7853442015-03-27 14:35:38 -07001430ArtField* CompilerDriver::ComputeInstanceFieldInfo(uint32_t field_idx,
1431 const DexCompilationUnit* mUnit, bool is_put,
1432 const ScopedObjectAccess& soa) {
Vladimir Markobe0e5462014-02-26 11:24:15 +00001433 // Try to resolve the field and compiling method's class.
Mathieu Chartierc7853442015-03-27 14:35:38 -07001434 ArtField* resolved_field;
Vladimir Markobe0e5462014-02-26 11:24:15 +00001435 mirror::Class* referrer_class;
Mathieu Chartier736b5602015-09-02 14:54:11 -07001436 Handle<mirror::DexCache> dex_cache(mUnit->GetDexCache());
Vladimir Markobe0e5462014-02-26 11:24:15 +00001437 {
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001438 Handle<mirror::ClassLoader> class_loader_handle = mUnit->GetClassLoader();
Mathieu Chartier736b5602015-09-02 14:54:11 -07001439 resolved_field = ResolveField(soa, dex_cache, class_loader_handle, mUnit, field_idx, false);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001440 referrer_class = resolved_field != nullptr
Mathieu Chartier736b5602015-09-02 14:54:11 -07001441 ? ResolveCompilingMethodsClass(soa, dex_cache, class_loader_handle, mUnit) : nullptr;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001442 }
Nicolas Geoffraye5038322014-07-04 09:41:32 +01001443 bool can_link = false;
Vladimir Markobe0e5462014-02-26 11:24:15 +00001444 if (resolved_field != nullptr && referrer_class != nullptr) {
Vladimir Markobe0e5462014-02-26 11:24:15 +00001445 std::pair<bool, bool> fast_path = IsFastInstanceField(
Mathieu Chartier736b5602015-09-02 14:54:11 -07001446 dex_cache.Get(), referrer_class, resolved_field, field_idx);
Nicolas Geoffraye5038322014-07-04 09:41:32 +01001447 can_link = is_put ? fast_path.second : fast_path.first;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001448 }
Nicolas Geoffraye5038322014-07-04 09:41:32 +01001449 ProcessedInstanceField(can_link);
1450 return can_link ? resolved_field : nullptr;
1451}
1452
1453bool CompilerDriver::ComputeInstanceFieldInfo(uint32_t field_idx, const DexCompilationUnit* mUnit,
1454 bool is_put, MemberOffset* field_offset,
1455 bool* is_volatile) {
1456 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartierc7853442015-03-27 14:35:38 -07001457 ArtField* resolved_field = ComputeInstanceFieldInfo(field_idx, mUnit, is_put, soa);
Nicolas Geoffraye5038322014-07-04 09:41:32 +01001458
Mathieu Chartierc7853442015-03-27 14:35:38 -07001459 if (resolved_field == nullptr) {
Vladimir Markobe0e5462014-02-26 11:24:15 +00001460 // Conservative defaults.
1461 *is_volatile = true;
1462 *field_offset = MemberOffset(static_cast<size_t>(-1));
Nicolas Geoffraye5038322014-07-04 09:41:32 +01001463 return false;
1464 } else {
1465 *is_volatile = resolved_field->IsVolatile();
1466 *field_offset = resolved_field->GetOffset();
1467 return true;
Vladimir Markobe0e5462014-02-26 11:24:15 +00001468 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001469}
1470
Vladimir Marko2730db02014-01-27 11:15:17 +00001471const VerifiedMethod* CompilerDriver::GetVerifiedMethod(const DexFile* dex_file,
1472 uint32_t method_idx) const {
1473 MethodReference ref(dex_file, method_idx);
1474 return verification_results_->GetVerifiedMethod(ref);
1475}
1476
1477bool CompilerDriver::IsSafeCast(const DexCompilationUnit* mUnit, uint32_t dex_pc) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001478 if (!compiler_options_->IsVerificationEnabled()) {
1479 // If we didn't verify, every cast has to be treated as non-safe.
1480 return false;
1481 }
Vladimir Marko2730db02014-01-27 11:15:17 +00001482 DCHECK(mUnit->GetVerifiedMethod() != nullptr);
1483 bool result = mUnit->GetVerifiedMethod()->IsSafeCast(dex_pc);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001484 if (result) {
1485 stats_->SafeCast();
1486 } else {
1487 stats_->NotASafeCast();
1488 }
1489 return result;
1490}
1491
Mathieu Chartier90443472015-07-16 20:32:27 -07001492class CompilationVisitor {
1493 public:
1494 virtual ~CompilationVisitor() {}
1495 virtual void Visit(size_t index) = 0;
1496};
1497
Brian Carlstrom7940e442013-07-12 13:46:57 -07001498class ParallelCompilationManager {
1499 public:
Brian Carlstrom7940e442013-07-12 13:46:57 -07001500 ParallelCompilationManager(ClassLinker* class_linker,
1501 jobject class_loader,
1502 CompilerDriver* compiler,
1503 const DexFile* dex_file,
Andreas Gampede7b4362014-07-28 18:38:57 -07001504 const std::vector<const DexFile*>& dex_files,
Ian Rogers3d504072014-03-01 09:16:49 -08001505 ThreadPool* thread_pool)
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001506 : index_(0),
1507 class_linker_(class_linker),
Brian Carlstrom7940e442013-07-12 13:46:57 -07001508 class_loader_(class_loader),
1509 compiler_(compiler),
1510 dex_file_(dex_file),
Andreas Gampede7b4362014-07-28 18:38:57 -07001511 dex_files_(dex_files),
Ian Rogers3d504072014-03-01 09:16:49 -08001512 thread_pool_(thread_pool) {}
Brian Carlstrom7940e442013-07-12 13:46:57 -07001513
1514 ClassLinker* GetClassLinker() const {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001515 CHECK(class_linker_ != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001516 return class_linker_;
1517 }
1518
1519 jobject GetClassLoader() const {
1520 return class_loader_;
1521 }
1522
1523 CompilerDriver* GetCompiler() const {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001524 CHECK(compiler_ != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001525 return compiler_;
1526 }
1527
1528 const DexFile* GetDexFile() const {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001529 CHECK(dex_file_ != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001530 return dex_file_;
1531 }
1532
Andreas Gampede7b4362014-07-28 18:38:57 -07001533 const std::vector<const DexFile*>& GetDexFiles() const {
1534 return dex_files_;
1535 }
1536
Mathieu Chartier90443472015-07-16 20:32:27 -07001537 void ForAll(size_t begin, size_t end, CompilationVisitor* visitor, size_t work_units)
1538 REQUIRES(!*Locks::mutator_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001539 Thread* self = Thread::Current();
1540 self->AssertNoPendingException();
1541 CHECK_GT(work_units, 0U);
1542
Ian Rogers3e5cf302014-05-20 16:40:37 -07001543 index_.StoreRelaxed(begin);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001544 for (size_t i = 0; i < work_units; ++i) {
Mathieu Chartier90443472015-07-16 20:32:27 -07001545 thread_pool_->AddTask(self, new ForAllClosure(this, end, visitor));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001546 }
1547 thread_pool_->StartWorkers(self);
1548
1549 // Ensure we're suspended while we're blocked waiting for the other threads to finish (worker
1550 // thread destructor's called below perform join).
1551 CHECK_NE(self->GetState(), kRunnable);
1552
1553 // Wait for all the worker threads to finish.
1554 thread_pool_->Wait(self, true, false);
Andreas Gampeace0dc12016-01-20 13:33:13 -08001555
1556 // And stop the workers accepting jobs.
1557 thread_pool_->StopWorkers(self);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001558 }
1559
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001560 size_t NextIndex() {
Ian Rogers3e5cf302014-05-20 16:40:37 -07001561 return index_.FetchAndAddSequentiallyConsistent(1);
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001562 }
1563
Brian Carlstrom7940e442013-07-12 13:46:57 -07001564 private:
Brian Carlstrom7940e442013-07-12 13:46:57 -07001565 class ForAllClosure : public Task {
1566 public:
Mathieu Chartier90443472015-07-16 20:32:27 -07001567 ForAllClosure(ParallelCompilationManager* manager, size_t end, CompilationVisitor* visitor)
Brian Carlstrom7940e442013-07-12 13:46:57 -07001568 : manager_(manager),
Brian Carlstrom7940e442013-07-12 13:46:57 -07001569 end_(end),
Mathieu Chartier90443472015-07-16 20:32:27 -07001570 visitor_(visitor) {}
Brian Carlstrom7940e442013-07-12 13:46:57 -07001571
1572 virtual void Run(Thread* self) {
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001573 while (true) {
1574 const size_t index = manager_->NextIndex();
1575 if (UNLIKELY(index >= end_)) {
1576 break;
1577 }
Mathieu Chartier90443472015-07-16 20:32:27 -07001578 visitor_->Visit(index);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001579 self->AssertNoPendingException();
1580 }
1581 }
1582
1583 virtual void Finalize() {
1584 delete this;
1585 }
Brian Carlstrom0cd7ec22013-07-17 23:40:20 -07001586
Brian Carlstrom7940e442013-07-12 13:46:57 -07001587 private:
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001588 ParallelCompilationManager* const manager_;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001589 const size_t end_;
Mathieu Chartier90443472015-07-16 20:32:27 -07001590 CompilationVisitor* const visitor_;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001591 };
1592
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001593 AtomicInteger index_;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001594 ClassLinker* const class_linker_;
1595 const jobject class_loader_;
1596 CompilerDriver* const compiler_;
1597 const DexFile* const dex_file_;
Andreas Gampede7b4362014-07-28 18:38:57 -07001598 const std::vector<const DexFile*>& dex_files_;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001599 ThreadPool* const thread_pool_;
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001600
1601 DISALLOW_COPY_AND_ASSIGN(ParallelCompilationManager);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001602};
1603
Jeff Hao0e49b422013-11-08 12:16:56 -08001604// A fast version of SkipClass above if the class pointer is available
1605// that avoids the expensive FindInClassPath search.
1606static bool SkipClass(jobject class_loader, const DexFile& dex_file, mirror::Class* klass)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001607 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001608 DCHECK(klass != nullptr);
Jeff Hao0e49b422013-11-08 12:16:56 -08001609 const DexFile& original_dex_file = *klass->GetDexCache()->GetDexFile();
1610 if (&dex_file != &original_dex_file) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001611 if (class_loader == nullptr) {
David Sehr709b0702016-10-13 09:12:37 -07001612 LOG(WARNING) << "Skipping class " << klass->PrettyDescriptor() << " from "
Jeff Hao0e49b422013-11-08 12:16:56 -08001613 << dex_file.GetLocation() << " previously found in "
1614 << original_dex_file.GetLocation();
1615 }
1616 return true;
1617 }
1618 return false;
1619}
1620
Mathieu Chartier70b63482014-06-27 17:19:04 -07001621static void CheckAndClearResolveException(Thread* self)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001622 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier70b63482014-06-27 17:19:04 -07001623 CHECK(self->IsExceptionPending());
Nicolas Geoffray14691c52015-03-05 10:40:17 +00001624 mirror::Throwable* exception = self->GetException();
Ian Rogers1ff3c982014-08-12 02:30:58 -07001625 std::string temp;
1626 const char* descriptor = exception->GetClass()->GetDescriptor(&temp);
1627 const char* expected_exceptions[] = {
1628 "Ljava/lang/IllegalAccessError;",
1629 "Ljava/lang/IncompatibleClassChangeError;",
1630 "Ljava/lang/InstantiationError;",
Brian Carlstrom898fcb52014-08-25 23:07:30 -07001631 "Ljava/lang/LinkageError;",
Ian Rogers1ff3c982014-08-12 02:30:58 -07001632 "Ljava/lang/NoClassDefFoundError;",
1633 "Ljava/lang/NoSuchFieldError;",
1634 "Ljava/lang/NoSuchMethodError;"
1635 };
1636 bool found = false;
1637 for (size_t i = 0; (found == false) && (i < arraysize(expected_exceptions)); ++i) {
1638 if (strcmp(descriptor, expected_exceptions[i]) == 0) {
1639 found = true;
1640 }
1641 }
1642 if (!found) {
Brian Carlstrom898fcb52014-08-25 23:07:30 -07001643 LOG(FATAL) << "Unexpected exception " << exception->Dump();
Mathieu Chartier70b63482014-06-27 17:19:04 -07001644 }
1645 self->ClearException();
1646}
1647
Mathieu Chartierb5d38612016-04-07 10:52:52 -07001648bool CompilerDriver::RequiresConstructorBarrier(const DexFile& dex_file,
1649 uint16_t class_def_idx) const {
1650 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_idx);
1651 const uint8_t* class_data = dex_file.GetClassData(class_def);
1652 if (class_data == nullptr) {
1653 // Empty class such as a marker interface.
1654 return false;
1655 }
1656 ClassDataItemIterator it(dex_file, class_data);
Mathieu Chartiere17cf242017-06-19 11:05:51 -07001657 it.SkipStaticFields();
Mathieu Chartierb5d38612016-04-07 10:52:52 -07001658 // We require a constructor barrier if there are final instance fields.
1659 while (it.HasNextInstanceField()) {
1660 if (it.MemberIsFinal()) {
1661 return true;
1662 }
1663 it.Next();
1664 }
1665 return false;
1666}
1667
Mathieu Chartier90443472015-07-16 20:32:27 -07001668class ResolveClassFieldsAndMethodsVisitor : public CompilationVisitor {
1669 public:
1670 explicit ResolveClassFieldsAndMethodsVisitor(const ParallelCompilationManager* manager)
1671 : manager_(manager) {}
Brian Carlstrom7940e442013-07-12 13:46:57 -07001672
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001673 void Visit(size_t class_def_index) OVERRIDE REQUIRES(!Locks::mutator_lock_) {
Mathieu Chartier90443472015-07-16 20:32:27 -07001674 ATRACE_CALL();
1675 Thread* const self = Thread::Current();
1676 jobject jclass_loader = manager_->GetClassLoader();
1677 const DexFile& dex_file = *manager_->GetDexFile();
1678 ClassLinker* class_linker = manager_->GetClassLinker();
Ian Rogerse6bb3b22013-08-19 21:51:45 -07001679
Mathieu Chartier90443472015-07-16 20:32:27 -07001680 // If an instance field is final then we need to have a barrier on the return, static final
1681 // fields are assigned within the lock held for class initialization. Conservatively assume
1682 // constructor barriers are always required.
1683 bool requires_constructor_barrier = true;
1684
1685 // Method and Field are the worst. We can't resolve without either
1686 // context from the code use (to disambiguate virtual vs direct
1687 // method and instance vs static field) or from class
1688 // definitions. While the compiler will resolve what it can as it
1689 // needs it, here we try to resolve fields and methods used in class
1690 // definitions, since many of them many never be referenced by
1691 // generated code.
1692 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
1693 ScopedObjectAccess soa(self);
1694 StackHandleScope<2> hs(soa.Self());
1695 Handle<mirror::ClassLoader> class_loader(
Mathieu Chartier0795f232016-09-27 18:43:30 -07001696 hs.NewHandle(soa.Decode<mirror::ClassLoader>(jclass_loader)));
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001697 Handle<mirror::DexCache> dex_cache(hs.NewHandle(class_linker->FindDexCache(
Vladimir Markocd556b02017-02-03 11:47:34 +00001698 soa.Self(), dex_file)));
Mathieu Chartier90443472015-07-16 20:32:27 -07001699 // Resolve the class.
1700 mirror::Class* klass = class_linker->ResolveType(dex_file, class_def.class_idx_, dex_cache,
1701 class_loader);
1702 bool resolve_fields_and_methods;
1703 if (klass == nullptr) {
1704 // Class couldn't be resolved, for example, super-class is in a different dex file. Don't
1705 // attempt to resolve methods and fields when there is no declaring class.
1706 CheckAndClearResolveException(soa.Self());
1707 resolve_fields_and_methods = false;
1708 } else {
1709 // We successfully resolved a class, should we skip it?
1710 if (SkipClass(jclass_loader, dex_file, klass)) {
1711 return;
Ian Rogerse6bb3b22013-08-19 21:51:45 -07001712 }
Mathieu Chartier90443472015-07-16 20:32:27 -07001713 // We want to resolve the methods and fields eagerly.
1714 resolve_fields_and_methods = true;
Ian Rogers68b56852014-08-29 20:19:11 -07001715 }
Mathieu Chartier90443472015-07-16 20:32:27 -07001716 // Note the class_data pointer advances through the headers,
1717 // static fields, instance fields, direct methods, and virtual
1718 // methods.
1719 const uint8_t* class_data = dex_file.GetClassData(class_def);
1720 if (class_data == nullptr) {
1721 // Empty class such as a marker interface.
1722 requires_constructor_barrier = false;
1723 } else {
1724 ClassDataItemIterator it(dex_file, class_data);
1725 while (it.HasNextStaticField()) {
1726 if (resolve_fields_and_methods) {
1727 ArtField* field = class_linker->ResolveField(dex_file, it.GetMemberIndex(),
1728 dex_cache, class_loader, true);
1729 if (field == nullptr) {
1730 CheckAndClearResolveException(soa.Self());
1731 }
Ian Rogers68b56852014-08-29 20:19:11 -07001732 }
1733 it.Next();
1734 }
Mathieu Chartier90443472015-07-16 20:32:27 -07001735 // We require a constructor barrier if there are final instance fields.
1736 requires_constructor_barrier = false;
1737 while (it.HasNextInstanceField()) {
1738 if (it.MemberIsFinal()) {
1739 requires_constructor_barrier = true;
1740 }
1741 if (resolve_fields_and_methods) {
1742 ArtField* field = class_linker->ResolveField(dex_file, it.GetMemberIndex(),
1743 dex_cache, class_loader, false);
1744 if (field == nullptr) {
1745 CheckAndClearResolveException(soa.Self());
1746 }
Ian Rogers68b56852014-08-29 20:19:11 -07001747 }
1748 it.Next();
1749 }
Mathieu Chartier90443472015-07-16 20:32:27 -07001750 if (resolve_fields_and_methods) {
1751 while (it.HasNextDirectMethod()) {
Vladimir Markoba118822017-06-12 15:41:56 +01001752 ArtMethod* method = class_linker->ResolveMethod<ClassLinker::ResolveMode::kNoChecks>(
Mathieu Chartier90443472015-07-16 20:32:27 -07001753 dex_file, it.GetMemberIndex(), dex_cache, class_loader, nullptr,
1754 it.GetMethodInvokeType(class_def));
1755 if (method == nullptr) {
1756 CheckAndClearResolveException(soa.Self());
1757 }
1758 it.Next();
1759 }
1760 while (it.HasNextVirtualMethod()) {
Vladimir Markoba118822017-06-12 15:41:56 +01001761 ArtMethod* method = class_linker->ResolveMethod<ClassLinker::ResolveMode::kNoChecks>(
Mathieu Chartier90443472015-07-16 20:32:27 -07001762 dex_file, it.GetMemberIndex(), dex_cache, class_loader, nullptr,
1763 it.GetMethodInvokeType(class_def));
1764 if (method == nullptr) {
1765 CheckAndClearResolveException(soa.Self());
1766 }
1767 it.Next();
1768 }
1769 DCHECK(!it.HasNext());
1770 }
1771 }
Mathieu Chartierc4ae9162016-04-07 13:19:19 -07001772 manager_->GetCompiler()->SetRequiresConstructorBarrier(self,
1773 &dex_file,
1774 class_def_index,
1775 requires_constructor_barrier);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001776 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001777
Mathieu Chartier90443472015-07-16 20:32:27 -07001778 private:
1779 const ParallelCompilationManager* const manager_;
1780};
1781
1782class ResolveTypeVisitor : public CompilationVisitor {
1783 public:
1784 explicit ResolveTypeVisitor(const ParallelCompilationManager* manager) : manager_(manager) {
1785 }
Andreas Gampea5b09a62016-11-17 15:21:22 -08001786 void Visit(size_t type_idx) OVERRIDE REQUIRES(!Locks::mutator_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001787 // Class derived values are more complicated, they require the linker and loader.
Mathieu Chartier90443472015-07-16 20:32:27 -07001788 ScopedObjectAccess soa(Thread::Current());
1789 ClassLinker* class_linker = manager_->GetClassLinker();
1790 const DexFile& dex_file = *manager_->GetDexFile();
1791 StackHandleScope<2> hs(soa.Self());
Mathieu Chartier90443472015-07-16 20:32:27 -07001792 Handle<mirror::ClassLoader> class_loader(
Mathieu Chartier0795f232016-09-27 18:43:30 -07001793 hs.NewHandle(soa.Decode<mirror::ClassLoader>(manager_->GetClassLoader())));
Mathieu Chartierd57d4542015-10-14 10:55:30 -07001794 Handle<mirror::DexCache> dex_cache(hs.NewHandle(class_linker->RegisterDexFile(
1795 dex_file,
Mathieu Chartierf284d442016-06-02 11:48:30 -07001796 class_loader.Get())));
Andreas Gampefa4333d2017-02-14 11:10:34 -08001797 ObjPtr<mirror::Class> klass = (dex_cache != nullptr)
Vladimir Markocd556b02017-02-03 11:47:34 +00001798 ? class_linker->ResolveType(dex_file, dex::TypeIndex(type_idx), dex_cache, class_loader)
1799 : nullptr;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001800
Mathieu Chartier90443472015-07-16 20:32:27 -07001801 if (klass == nullptr) {
1802 soa.Self()->AssertPendingException();
1803 mirror::Throwable* exception = soa.Self()->GetException();
1804 VLOG(compiler) << "Exception during type resolution: " << exception->Dump();
1805 if (exception->GetClass()->DescriptorEquals("Ljava/lang/OutOfMemoryError;")) {
1806 // There's little point continuing compilation if the heap is exhausted.
1807 LOG(FATAL) << "Out of memory during type resolution for compilation";
1808 }
1809 soa.Self()->ClearException();
Ian Rogersa436fde2013-08-27 23:34:06 -07001810 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001811 }
Mathieu Chartier90443472015-07-16 20:32:27 -07001812
1813 private:
1814 const ParallelCompilationManager* const manager_;
1815};
Brian Carlstrom7940e442013-07-12 13:46:57 -07001816
Andreas Gampeace0dc12016-01-20 13:33:13 -08001817void CompilerDriver::ResolveDexFile(jobject class_loader,
1818 const DexFile& dex_file,
Andreas Gampede7b4362014-07-28 18:38:57 -07001819 const std::vector<const DexFile*>& dex_files,
Andreas Gampeace0dc12016-01-20 13:33:13 -08001820 ThreadPool* thread_pool,
1821 size_t thread_count,
1822 TimingLogger* timings) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001823 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1824
1825 // TODO: we could resolve strings here, although the string table is largely filled with class
1826 // and method names.
1827
Andreas Gampede7b4362014-07-28 18:38:57 -07001828 ParallelCompilationManager context(class_linker, class_loader, this, &dex_file, dex_files,
1829 thread_pool);
Vladimir Markoaad75c62016-10-03 08:46:48 +00001830 if (GetCompilerOptions().IsBootImage()) {
Ian Rogerse6bb3b22013-08-19 21:51:45 -07001831 // For images we resolve all types, such as array, whereas for applications just those with
1832 // classdefs are resolved by ResolveClassFieldsAndMethods.
Mathieu Chartierf5997b42014-06-20 10:37:54 -07001833 TimingLogger::ScopedTiming t("Resolve Types", timings);
Mathieu Chartier90443472015-07-16 20:32:27 -07001834 ResolveTypeVisitor visitor(&context);
Andreas Gampeace0dc12016-01-20 13:33:13 -08001835 context.ForAll(0, dex_file.NumTypeIds(), &visitor, thread_count);
Ian Rogerse6bb3b22013-08-19 21:51:45 -07001836 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001837
Mathieu Chartierf5997b42014-06-20 10:37:54 -07001838 TimingLogger::ScopedTiming t("Resolve MethodsAndFields", timings);
Mathieu Chartier90443472015-07-16 20:32:27 -07001839 ResolveClassFieldsAndMethodsVisitor visitor(&context);
Andreas Gampeace0dc12016-01-20 13:33:13 -08001840 context.ForAll(0, dex_file.NumClassDefs(), &visitor, thread_count);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001841}
1842
Andreas Gampeace0dc12016-01-20 13:33:13 -08001843void CompilerDriver::SetVerified(jobject class_loader,
1844 const std::vector<const DexFile*>& dex_files,
1845 TimingLogger* timings) {
1846 // This can be run in parallel.
Mathieu Chartier90443472015-07-16 20:32:27 -07001847 for (const DexFile* dex_file : dex_files) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001848 CHECK(dex_file != nullptr);
Andreas Gampeace0dc12016-01-20 13:33:13 -08001849 SetVerifiedDexFile(class_loader,
1850 *dex_file,
1851 dex_files,
1852 parallel_thread_pool_.get(),
1853 parallel_thread_count_,
1854 timings);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001855 }
1856}
1857
Nicolas Geoffray51c17fa2016-11-25 15:56:12 +00001858static void PopulateVerifiedMethods(const DexFile& dex_file,
1859 uint32_t class_def_index,
1860 VerificationResults* verification_results) {
1861 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
1862 const uint8_t* class_data = dex_file.GetClassData(class_def);
1863 if (class_data == nullptr) {
1864 return;
1865 }
1866 ClassDataItemIterator it(dex_file, class_data);
Mathieu Chartiere17cf242017-06-19 11:05:51 -07001867 it.SkipAllFields();
Nicolas Geoffray51c17fa2016-11-25 15:56:12 +00001868
1869 while (it.HasNextDirectMethod()) {
1870 verification_results->CreateVerifiedMethodFor(MethodReference(&dex_file, it.GetMemberIndex()));
1871 it.Next();
1872 }
1873
1874 while (it.HasNextVirtualMethod()) {
1875 verification_results->CreateVerifiedMethodFor(MethodReference(&dex_file, it.GetMemberIndex()));
1876 it.Next();
1877 }
1878 DCHECK(!it.HasNext());
1879}
1880
Nicolas Geoffray0a27fd02017-01-25 16:18:54 +00001881static void LoadAndUpdateStatus(const DexFile& dex_file,
1882 const DexFile::ClassDef& class_def,
1883 mirror::Class::Status status,
1884 Handle<mirror::ClassLoader> class_loader,
1885 Thread* self)
1886 REQUIRES_SHARED(Locks::mutator_lock_) {
1887 StackHandleScope<1> hs(self);
1888 const char* descriptor = dex_file.GetClassDescriptor(class_def);
1889 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1890 Handle<mirror::Class> cls(hs.NewHandle<mirror::Class>(
1891 class_linker->FindClass(self, descriptor, class_loader)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08001892 if (cls != nullptr) {
Nicolas Geoffray0a27fd02017-01-25 16:18:54 +00001893 // Check that the class is resolved with the current dex file. We might get
1894 // a boot image class, or a class in a different dex file for multidex, and
1895 // we should not update the status in that case.
1896 if (&cls->GetDexFile() == &dex_file) {
1897 ObjectLock<mirror::Class> lock(self, cls);
1898 mirror::Class::SetStatus(cls, status, self);
1899 }
1900 } else {
1901 DCHECK(self->IsExceptionPending());
1902 self->ClearException();
1903 }
1904}
1905
Nicolas Geoffray74981052017-01-16 17:54:09 +00001906bool CompilerDriver::FastVerify(jobject jclass_loader,
1907 const std::vector<const DexFile*>& dex_files,
1908 TimingLogger* timings) {
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +00001909 verifier::VerifierDeps* verifier_deps =
1910 Runtime::Current()->GetCompilerCallbacks()->GetVerifierDeps();
Mathieu Chartier72041a02017-07-14 18:23:25 -07001911 // If there exist VerifierDeps that aren't the ones we just created to output, use them to verify.
1912 if (verifier_deps == nullptr || verifier_deps->OutputOnly()) {
Nicolas Geoffray74981052017-01-16 17:54:09 +00001913 return false;
1914 }
1915 TimingLogger::ScopedTiming t("Fast Verify", timings);
1916 ScopedObjectAccess soa(Thread::Current());
1917 StackHandleScope<2> hs(soa.Self());
1918 Handle<mirror::ClassLoader> class_loader(
1919 hs.NewHandle(soa.Decode<mirror::ClassLoader>(jclass_loader)));
Nicolas Geoffray74981052017-01-16 17:54:09 +00001920 if (!verifier_deps->ValidateDependencies(class_loader, soa.Self())) {
1921 return false;
1922 }
1923
Nicolas Geoffray49cda062017-04-21 13:08:25 +01001924 bool compiler_only_verifies = !GetCompilerOptions().IsAnyCompilationEnabled();
Nicolas Geoffray0a27fd02017-01-25 16:18:54 +00001925
Nicolas Geoffray74981052017-01-16 17:54:09 +00001926 // We successfully validated the dependencies, now update class status
1927 // of verified classes. Note that the dependencies also record which classes
1928 // could not be fully verified; we could try again, but that would hurt verification
1929 // time. So instead we assume these classes still need to be verified at
1930 // runtime.
1931 for (const DexFile* dex_file : dex_files) {
Mathieu Chartierbf755fe2017-08-01 13:42:56 -07001932 // Fetch the list of unverified classes.
1933 const std::set<dex::TypeIndex>& unverified_classes =
Nicolas Geoffray74981052017-01-16 17:54:09 +00001934 verifier_deps->GetUnverifiedClasses(*dex_file);
Nicolas Geoffray74981052017-01-16 17:54:09 +00001935 for (uint32_t i = 0; i < dex_file->NumClassDefs(); ++i) {
1936 const DexFile::ClassDef& class_def = dex_file->GetClassDef(i);
Mathieu Chartierbf755fe2017-08-01 13:42:56 -07001937 if (unverified_classes.find(class_def.class_idx_) == unverified_classes.end()) {
Nicolas Geoffray0a27fd02017-01-25 16:18:54 +00001938 if (compiler_only_verifies) {
Nicolas Geoffray74981052017-01-16 17:54:09 +00001939 // Just update the compiled_classes_ map. The compiler doesn't need to resolve
1940 // the type.
Mathieu Chartierfc8b4222017-09-17 13:44:24 -07001941 ClassReference ref(dex_file, i);
Mathieu Chartier1a088d42017-07-18 11:43:57 -07001942 mirror::Class::Status existing = mirror::Class::kStatusNotReady;
1943 DCHECK(compiled_classes_.Get(ref, &existing)) << ref.dex_file->GetLocation();
1944 ClassStateTable::InsertResult result =
1945 compiled_classes_.Insert(ref, existing, mirror::Class::kStatusVerified);
1946 CHECK_EQ(result, ClassStateTable::kInsertResultSuccess);
Nicolas Geoffray74981052017-01-16 17:54:09 +00001947 } else {
Nicolas Geoffray0a27fd02017-01-25 16:18:54 +00001948 // Update the class status, so later compilation stages know they don't need to verify
Nicolas Geoffray74981052017-01-16 17:54:09 +00001949 // the class.
Nicolas Geoffray0a27fd02017-01-25 16:18:54 +00001950 LoadAndUpdateStatus(
1951 *dex_file, class_def, mirror::Class::kStatusVerified, class_loader, soa.Self());
Nicolas Geoffray74981052017-01-16 17:54:09 +00001952 // Create `VerifiedMethod`s for each methods, the compiler expects one for
1953 // quickening or compiling.
1954 // Note that this means:
1955 // - We're only going to compile methods that did verify.
1956 // - Quickening will not do checkcast ellision.
1957 // TODO(ngeoffray): Reconsider this once we refactor compiler filters.
1958 PopulateVerifiedMethods(*dex_file, i, verification_results_);
Nicolas Geoffray6bb7f1b2016-11-03 10:52:49 +00001959 }
Nicolas Geoffray0a27fd02017-01-25 16:18:54 +00001960 } else if (!compiler_only_verifies) {
1961 // Make sure later compilation stages know they should not try to verify
1962 // this class again.
1963 LoadAndUpdateStatus(*dex_file,
1964 class_def,
1965 mirror::Class::kStatusRetryVerificationAtRuntime,
1966 class_loader,
1967 soa.Self());
Nicolas Geoffray6bb7f1b2016-11-03 10:52:49 +00001968 }
Nicolas Geoffray6bb7f1b2016-11-03 10:52:49 +00001969 }
1970 }
Nicolas Geoffray74981052017-01-16 17:54:09 +00001971 return true;
1972}
1973
1974void CompilerDriver::Verify(jobject jclass_loader,
1975 const std::vector<const DexFile*>& dex_files,
1976 TimingLogger* timings) {
1977 if (FastVerify(jclass_loader, dex_files, timings)) {
1978 return;
1979 }
Nicolas Geoffray6bb7f1b2016-11-03 10:52:49 +00001980
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +00001981 // If there is no existing `verifier_deps` (because of non-existing vdex), or
1982 // the existing `verifier_deps` is not valid anymore, create a new one for
Nicolas Geoffray6bb7f1b2016-11-03 10:52:49 +00001983 // non boot image compilation. The verifier will need it to record the new dependencies.
1984 // Then dex2oat can update the vdex file with these new dependencies.
1985 if (!GetCompilerOptions().IsBootImage()) {
Mathieu Chartier72041a02017-07-14 18:23:25 -07001986 // Dex2oat creates the verifier deps.
Nicolas Geoffray340dafa2016-11-18 16:03:10 +00001987 // Create the main VerifierDeps, and set it to this thread.
Mathieu Chartier72041a02017-07-14 18:23:25 -07001988 verifier::VerifierDeps* verifier_deps =
1989 Runtime::Current()->GetCompilerCallbacks()->GetVerifierDeps();
1990 CHECK(verifier_deps != nullptr);
Nicolas Geoffrayb0bbe8e2016-11-19 10:42:37 +00001991 Thread::Current()->SetVerifierDeps(verifier_deps);
Nicolas Geoffray340dafa2016-11-18 16:03:10 +00001992 // Create per-thread VerifierDeps to avoid contention on the main one.
1993 // We will merge them after verification.
1994 for (ThreadPoolWorker* worker : parallel_thread_pool_->GetWorkers()) {
Mathieu Chartier72041a02017-07-14 18:23:25 -07001995 worker->GetThread()->SetVerifierDeps(new verifier::VerifierDeps(dex_files_for_oat_file_));
Nicolas Geoffray340dafa2016-11-18 16:03:10 +00001996 }
Nicolas Geoffray6bb7f1b2016-11-03 10:52:49 +00001997 }
Nicolas Geoffray74981052017-01-16 17:54:09 +00001998
Nicolas Geoffray46847392017-04-28 14:56:39 +01001999 // Verification updates VerifierDeps and needs to run single-threaded to be deterministic.
2000 bool force_determinism = GetCompilerOptions().IsForceDeterminism();
2001 ThreadPool* verify_thread_pool =
2002 force_determinism ? single_thread_pool_.get() : parallel_thread_pool_.get();
2003 size_t verify_thread_count = force_determinism ? 1U : parallel_thread_count_;
Mathieu Chartier90443472015-07-16 20:32:27 -07002004 for (const DexFile* dex_file : dex_files) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002005 CHECK(dex_file != nullptr);
Nicolas Geoffray6bb7f1b2016-11-03 10:52:49 +00002006 VerifyDexFile(jclass_loader,
Andreas Gampeace0dc12016-01-20 13:33:13 -08002007 *dex_file,
2008 dex_files,
Nicolas Geoffray46847392017-04-28 14:56:39 +01002009 verify_thread_pool,
2010 verify_thread_count,
Andreas Gampeace0dc12016-01-20 13:33:13 -08002011 timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002012 }
Nicolas Geoffray340dafa2016-11-18 16:03:10 +00002013
2014 if (!GetCompilerOptions().IsBootImage()) {
Nicolas Geoffray340dafa2016-11-18 16:03:10 +00002015 // Merge all VerifierDeps into the main one.
Nicolas Geoffray74981052017-01-16 17:54:09 +00002016 verifier::VerifierDeps* verifier_deps = Thread::Current()->GetVerifierDeps();
Nicolas Geoffray340dafa2016-11-18 16:03:10 +00002017 for (ThreadPoolWorker* worker : parallel_thread_pool_->GetWorkers()) {
2018 verifier::VerifierDeps* thread_deps = worker->GetThread()->GetVerifierDeps();
2019 worker->GetThread()->SetVerifierDeps(nullptr);
Mathieu Chartier72041a02017-07-14 18:23:25 -07002020 verifier_deps->MergeWith(*thread_deps, dex_files_for_oat_file_);
Nicolas Geoffray340dafa2016-11-18 16:03:10 +00002021 delete thread_deps;
2022 }
2023 Thread::Current()->SetVerifierDeps(nullptr);
2024 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002025}
2026
Mathieu Chartier90443472015-07-16 20:32:27 -07002027class VerifyClassVisitor : public CompilationVisitor {
2028 public:
Andreas Gampe5fd66d02016-09-12 20:22:19 -07002029 VerifyClassVisitor(const ParallelCompilationManager* manager, verifier::HardFailLogMode log_level)
Andreas Gampe7fe30232016-03-25 16:58:00 -07002030 : manager_(manager), log_level_(log_level) {}
Brian Carlstrom7940e442013-07-12 13:46:57 -07002031
Mathieu Chartier90443472015-07-16 20:32:27 -07002032 virtual void Visit(size_t class_def_index) REQUIRES(!Locks::mutator_lock_) OVERRIDE {
2033 ATRACE_CALL();
2034 ScopedObjectAccess soa(Thread::Current());
2035 const DexFile& dex_file = *manager_->GetDexFile();
2036 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
2037 const char* descriptor = dex_file.GetClassDescriptor(class_def);
2038 ClassLinker* class_linker = manager_->GetClassLinker();
2039 jobject jclass_loader = manager_->GetClassLoader();
2040 StackHandleScope<3> hs(soa.Self());
2041 Handle<mirror::ClassLoader> class_loader(
Mathieu Chartier0795f232016-09-27 18:43:30 -07002042 hs.NewHandle(soa.Decode<mirror::ClassLoader>(jclass_loader)));
Mathieu Chartier90443472015-07-16 20:32:27 -07002043 Handle<mirror::Class> klass(
2044 hs.NewHandle(class_linker->FindClass(soa.Self(), descriptor, class_loader)));
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07002045 verifier::FailureKind failure_kind;
Andreas Gampefa4333d2017-02-14 11:10:34 -08002046 if (klass == nullptr) {
Ian Rogerse6bb3b22013-08-19 21:51:45 -07002047 CHECK(soa.Self()->IsExceptionPending());
2048 soa.Self()->ClearException();
Mathieu Chartier90443472015-07-16 20:32:27 -07002049
2050 /*
2051 * At compile time, we can still structurally verify the class even if FindClass fails.
2052 * This is to ensure the class is structurally sound for compilation. An unsound class
2053 * will be rejected by the verifier and later skipped during compilation in the compiler.
2054 */
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002055 Handle<mirror::DexCache> dex_cache(hs.NewHandle(class_linker->FindDexCache(
Vladimir Markocd556b02017-02-03 11:47:34 +00002056 soa.Self(), dex_file)));
Mathieu Chartier90443472015-07-16 20:32:27 -07002057 std::string error_msg;
Nicolas Geoffray08025182016-10-25 17:20:18 +01002058 failure_kind =
2059 verifier::MethodVerifier::VerifyClass(soa.Self(),
Andreas Gampeec6e6c12015-11-05 20:39:56 -08002060 &dex_file,
2061 dex_cache,
2062 class_loader,
David Brazdil15fc7292016-09-02 14:13:18 +01002063 class_def,
Andreas Gampe53e32d12015-12-09 21:03:23 -08002064 Runtime::Current()->GetCompilerCallbacks(),
Andreas Gampeec6e6c12015-11-05 20:39:56 -08002065 true /* allow soft failures */,
Andreas Gampe7fe30232016-03-25 16:58:00 -07002066 log_level_,
Nicolas Geoffray08025182016-10-25 17:20:18 +01002067 &error_msg);
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07002068 if (failure_kind == verifier::FailureKind::kHardFailure) {
Mathieu Chartier90443472015-07-16 20:32:27 -07002069 LOG(ERROR) << "Verification failed on class " << PrettyDescriptor(descriptor)
2070 << " because: " << error_msg;
2071 manager_->GetCompiler()->SetHadHardVerifierFailure();
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00002072 } else {
2073 // Force a soft failure for the VerifierDeps. This is a sanity measure, as
2074 // the vdex file already records that the class hasn't been resolved. It avoids
2075 // trying to do future verification optimizations when processing the vdex file.
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07002076 DCHECK(failure_kind == verifier::FailureKind::kSoftFailure ||
2077 failure_kind == verifier::FailureKind::kNoFailure)
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00002078 << failure_kind;
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07002079 failure_kind = verifier::FailureKind::kSoftFailure;
Mathieu Chartier90443472015-07-16 20:32:27 -07002080 }
2081 } else if (!SkipClass(jclass_loader, dex_file, klass.Get())) {
David Sehr709b0702016-10-13 09:12:37 -07002082 CHECK(klass->IsResolved()) << klass->PrettyClass();
Nicolas Geoffray08025182016-10-25 17:20:18 +01002083 failure_kind = class_linker->VerifyClass(soa.Self(), klass, log_level_);
Mathieu Chartier90443472015-07-16 20:32:27 -07002084
2085 if (klass->IsErroneous()) {
2086 // ClassLinker::VerifyClass throws, which isn't useful in the compiler.
2087 CHECK(soa.Self()->IsExceptionPending());
2088 soa.Self()->ClearException();
2089 manager_->GetCompiler()->SetHadHardVerifierFailure();
2090 }
2091
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00002092 CHECK(klass->ShouldVerifyAtRuntime() || klass->IsVerified() || klass->IsErroneous())
David Sehr709b0702016-10-13 09:12:37 -07002093 << klass->PrettyDescriptor() << ": state=" << klass->GetStatus();
Mathieu Chartier90443472015-07-16 20:32:27 -07002094
Nicolas Geoffrayc7da1d62017-04-19 09:36:24 +01002095 // Class has a meaningful status for the compiler now, record it.
2096 ClassReference ref(manager_->GetDexFile(), class_def_index);
2097 manager_->GetCompiler()->RecordClassStatus(ref, klass->GetStatus());
2098
Orion Hodsonc5e0d3f2017-08-22 19:00:04 +01002099 // It is *very* problematic if there are verification errors in the boot classpath.
2100 // For example, we rely on things working OK without verification when the decryption dialog
2101 // is brought up. So abort in a debug build if we find this violated.
Narayan Kamathe3eae5e2016-10-27 11:47:30 +01002102 if (kIsDebugBuild) {
Orion Hodsonc5e0d3f2017-08-22 19:00:04 +01002103 if (manager_->GetCompiler()->GetCompilerOptions().IsBootImage()) {
Andreas Gampe12fadcd2017-08-03 05:06:28 -07002104 if (!klass->IsVerified()) {
2105 // Re-run verification to get all failure messages if it soft-failed.
2106 if (!klass->IsErroneous()) {
2107 gLogVerbosity.verifier = true;
2108 // Note: We can't call ClassLinker::VerifyClass, as it will elide the second
2109 // verification.
2110 Runtime* runtime = Runtime::Current();
2111 std::string v_error;
2112 verifier::MethodVerifier::VerifyClass(soa.Self(),
2113 klass.Get(),
2114 runtime->GetCompilerCallbacks(),
2115 runtime->IsAotCompiler(),
2116 verifier::HardFailLogMode::kLogInternalFatal,
2117 &v_error);
2118 }
2119 LOG(FATAL) << "Boot classpath class " << klass->PrettyClass()
2120 << " failed to fully verify: state= " << klass->GetStatus();
2121 }
Narayan Kamathe3eae5e2016-10-27 11:47:30 +01002122 }
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00002123 if (klass->IsVerified()) {
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07002124 DCHECK_EQ(failure_kind, verifier::FailureKind::kNoFailure);
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00002125 } else if (klass->ShouldVerifyAtRuntime()) {
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07002126 DCHECK_EQ(failure_kind, verifier::FailureKind::kSoftFailure);
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00002127 } else {
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07002128 DCHECK_EQ(failure_kind, verifier::FailureKind::kHardFailure);
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00002129 }
Narayan Kamathe3eae5e2016-10-27 11:47:30 +01002130 }
Nicolas Geoffray08025182016-10-25 17:20:18 +01002131 } else {
2132 // Make the skip a soft failure, essentially being considered as verify at runtime.
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07002133 failure_kind = verifier::FailureKind::kSoftFailure;
Ian Rogerse6bb3b22013-08-19 21:51:45 -07002134 }
Nicolas Geoffray08025182016-10-25 17:20:18 +01002135 verifier::VerifierDeps::MaybeRecordVerificationStatus(
2136 dex_file, class_def.class_idx_, failure_kind);
Mathieu Chartier90443472015-07-16 20:32:27 -07002137 soa.Self()->AssertNoPendingException();
Brian Carlstrom7940e442013-07-12 13:46:57 -07002138 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002139
2140 private:
2141 const ParallelCompilationManager* const manager_;
Andreas Gampe5fd66d02016-09-12 20:22:19 -07002142 const verifier::HardFailLogMode log_level_;
Mathieu Chartier90443472015-07-16 20:32:27 -07002143};
Brian Carlstrom7940e442013-07-12 13:46:57 -07002144
Andreas Gampeace0dc12016-01-20 13:33:13 -08002145void CompilerDriver::VerifyDexFile(jobject class_loader,
2146 const DexFile& dex_file,
Andreas Gampede7b4362014-07-28 18:38:57 -07002147 const std::vector<const DexFile*>& dex_files,
Andreas Gampeace0dc12016-01-20 13:33:13 -08002148 ThreadPool* thread_pool,
2149 size_t thread_count,
2150 TimingLogger* timings) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07002151 TimingLogger::ScopedTiming t("Verify Dex File", timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002152 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Andreas Gampede7b4362014-07-28 18:38:57 -07002153 ParallelCompilationManager context(class_linker, class_loader, this, &dex_file, dex_files,
2154 thread_pool);
Andreas Gampe5fd66d02016-09-12 20:22:19 -07002155 verifier::HardFailLogMode log_level = GetCompilerOptions().AbortOnHardVerifierFailure()
2156 ? verifier::HardFailLogMode::kLogInternalFatal
2157 : verifier::HardFailLogMode::kLogWarning;
Andreas Gampe7fe30232016-03-25 16:58:00 -07002158 VerifyClassVisitor visitor(&context, log_level);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002159 context.ForAll(0, dex_file.NumClassDefs(), &visitor, thread_count);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002160}
2161
Mathieu Chartier90443472015-07-16 20:32:27 -07002162class SetVerifiedClassVisitor : public CompilationVisitor {
2163 public:
2164 explicit SetVerifiedClassVisitor(const ParallelCompilationManager* manager) : manager_(manager) {}
2165
2166 virtual void Visit(size_t class_def_index) REQUIRES(!Locks::mutator_lock_) OVERRIDE {
2167 ATRACE_CALL();
2168 ScopedObjectAccess soa(Thread::Current());
2169 const DexFile& dex_file = *manager_->GetDexFile();
2170 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
2171 const char* descriptor = dex_file.GetClassDescriptor(class_def);
2172 ClassLinker* class_linker = manager_->GetClassLinker();
2173 jobject jclass_loader = manager_->GetClassLoader();
2174 StackHandleScope<3> hs(soa.Self());
2175 Handle<mirror::ClassLoader> class_loader(
Mathieu Chartier0795f232016-09-27 18:43:30 -07002176 hs.NewHandle(soa.Decode<mirror::ClassLoader>(jclass_loader)));
Mathieu Chartier90443472015-07-16 20:32:27 -07002177 Handle<mirror::Class> klass(
2178 hs.NewHandle(class_linker->FindClass(soa.Self(), descriptor, class_loader)));
2179 // Class might have failed resolution. Then don't set it to verified.
Andreas Gampefa4333d2017-02-14 11:10:34 -08002180 if (klass != nullptr) {
Mathieu Chartier90443472015-07-16 20:32:27 -07002181 // Only do this if the class is resolved. If even resolution fails, quickening will go very,
2182 // very wrong.
Vladimir Marko72ab6842017-01-20 19:32:50 +00002183 if (klass->IsResolved() && !klass->IsErroneousResolved()) {
Mathieu Chartier90443472015-07-16 20:32:27 -07002184 if (klass->GetStatus() < mirror::Class::kStatusVerified) {
2185 ObjectLock<mirror::Class> lock(soa.Self(), klass);
2186 // Set class status to verified.
2187 mirror::Class::SetStatus(klass, mirror::Class::kStatusVerified, soa.Self());
2188 // Mark methods as pre-verified. If we don't do this, the interpreter will run with
2189 // access checks.
Igor Murashkindf707e42016-02-02 16:56:50 -08002190 klass->SetSkipAccessChecksFlagOnAllMethods(
Mathieu Chartier90443472015-07-16 20:32:27 -07002191 GetInstructionSetPointerSize(manager_->GetCompiler()->GetInstructionSet()));
Igor Murashkindf707e42016-02-02 16:56:50 -08002192 klass->SetVerificationAttempted();
Mathieu Chartier90443472015-07-16 20:32:27 -07002193 }
2194 // Record the final class status if necessary.
2195 ClassReference ref(manager_->GetDexFile(), class_def_index);
2196 manager_->GetCompiler()->RecordClassStatus(ref, klass->GetStatus());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002197 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002198 } else {
2199 Thread* self = soa.Self();
2200 DCHECK(self->IsExceptionPending());
2201 self->ClearException();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002202 }
2203 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002204
2205 private:
2206 const ParallelCompilationManager* const manager_;
2207};
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002208
Andreas Gampeace0dc12016-01-20 13:33:13 -08002209void CompilerDriver::SetVerifiedDexFile(jobject class_loader,
2210 const DexFile& dex_file,
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002211 const std::vector<const DexFile*>& dex_files,
Andreas Gampeace0dc12016-01-20 13:33:13 -08002212 ThreadPool* thread_pool,
2213 size_t thread_count,
2214 TimingLogger* timings) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002215 TimingLogger::ScopedTiming t("Verify Dex File", timings);
Mathieu Chartier1a088d42017-07-18 11:43:57 -07002216 if (!compiled_classes_.HaveDexFile(&dex_file)) {
Mathieu Chartierfc8b4222017-09-17 13:44:24 -07002217 compiled_classes_.AddDexFile(&dex_file);
Mathieu Chartier1a088d42017-07-18 11:43:57 -07002218 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002219 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
2220 ParallelCompilationManager context(class_linker, class_loader, this, &dex_file, dex_files,
2221 thread_pool);
Mathieu Chartier90443472015-07-16 20:32:27 -07002222 SetVerifiedClassVisitor visitor(&context);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002223 context.ForAll(0, dex_file.NumClassDefs(), &visitor, thread_count);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002224}
2225
Mathieu Chartier90443472015-07-16 20:32:27 -07002226class InitializeClassVisitor : public CompilationVisitor {
2227 public:
2228 explicit InitializeClassVisitor(const ParallelCompilationManager* manager) : manager_(manager) {}
Ian Rogersfc0e94b2013-09-23 23:51:32 -07002229
Mathieu Chartierf1dd69a2017-06-08 23:30:15 +00002230 void Visit(size_t class_def_index) OVERRIDE {
Mathieu Chartier90443472015-07-16 20:32:27 -07002231 ATRACE_CALL();
2232 jobject jclass_loader = manager_->GetClassLoader();
2233 const DexFile& dex_file = *manager_->GetDexFile();
2234 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
2235 const DexFile::TypeId& class_type_id = dex_file.GetTypeId(class_def.class_idx_);
2236 const char* descriptor = dex_file.StringDataByIdx(class_type_id.descriptor_idx_);
Jeff Hao0e49b422013-11-08 12:16:56 -08002237
Mathieu Chartier90443472015-07-16 20:32:27 -07002238 ScopedObjectAccess soa(Thread::Current());
2239 StackHandleScope<3> hs(soa.Self());
2240 Handle<mirror::ClassLoader> class_loader(
Mathieu Chartier0795f232016-09-27 18:43:30 -07002241 hs.NewHandle(soa.Decode<mirror::ClassLoader>(jclass_loader)));
Mathieu Chartier90443472015-07-16 20:32:27 -07002242 Handle<mirror::Class> klass(
2243 hs.NewHandle(manager_->GetClassLinker()->FindClass(soa.Self(), descriptor, class_loader)));
2244
Mathieu Chartierf1dd69a2017-06-08 23:30:15 +00002245 if (klass != nullptr && !SkipClass(manager_->GetClassLoader(), dex_file, klass.Get())) {
2246 TryInitializeClass(klass, class_loader);
2247 }
2248 // Clear any class not found or verification exceptions.
2249 soa.Self()->ClearException();
2250 }
2251
2252 // A helper function for initializing klass.
2253 void TryInitializeClass(Handle<mirror::Class> klass, Handle<mirror::ClassLoader>& class_loader)
2254 REQUIRES_SHARED(Locks::mutator_lock_) {
2255 const DexFile& dex_file = klass->GetDexFile();
2256 const DexFile::ClassDef* class_def = klass->GetClassDef();
2257 const DexFile::TypeId& class_type_id = dex_file.GetTypeId(class_def->class_idx_);
2258 const char* descriptor = dex_file.StringDataByIdx(class_type_id.descriptor_idx_);
2259 ScopedObjectAccessUnchecked soa(Thread::Current());
2260 StackHandleScope<3> hs(soa.Self());
Mathieu Chartierdabeb3a2017-06-12 17:10:07 -07002261 const bool is_boot_image = manager_->GetCompiler()->GetCompilerOptions().IsBootImage();
Mathieu Chartier17498e52017-06-13 11:35:04 -07002262 const bool is_app_image = manager_->GetCompiler()->GetCompilerOptions().IsAppImage();
Mathieu Chartierf1dd69a2017-06-08 23:30:15 +00002263
Jeff Hao0cb17282017-07-12 14:51:49 -07002264 mirror::Class::Status old_status = klass->GetStatus();
Mathieu Chartier1a088d42017-07-18 11:43:57 -07002265 // Don't initialize classes in boot space when compiling app image
2266 if (is_app_image && klass->IsBootStrapClassLoaded()) {
2267 // Also return early and don't store the class status in the recorded class status.
2268 return;
2269 }
Mathieu Chartierf1dd69a2017-06-08 23:30:15 +00002270 // Only try to initialize classes that were successfully verified.
2271 if (klass->IsVerified()) {
2272 // Attempt to initialize the class but bail if we either need to initialize the super-class
2273 // or static fields.
Nicolas Geoffrayabadf022017-08-03 08:25:41 +00002274 manager_->GetClassLinker()->EnsureInitialized(soa.Self(), klass, false, false);
Mathieu Chartierf1dd69a2017-06-08 23:30:15 +00002275 old_status = klass->GetStatus();
2276 if (!klass->IsInitialized()) {
2277 // We don't want non-trivial class initialization occurring on multiple threads due to
2278 // deadlock problems. For example, a parent class is initialized (holding its lock) that
2279 // refers to a sub-class in its static/class initializer causing it to try to acquire the
2280 // sub-class' lock. While on a second thread the sub-class is initialized (holding its lock)
2281 // after first initializing its parents, whose locks are acquired. This leads to a
2282 // parent-to-child and a child-to-parent lock ordering and consequent potential deadlock.
2283 // We need to use an ObjectLock due to potential suspension in the interpreting code. Rather
2284 // than use a special Object for the purpose we use the Class of java.lang.Class.
2285 Handle<mirror::Class> h_klass(hs.NewHandle(klass->GetClass()));
2286 ObjectLock<mirror::Class> lock(soa.Self(), h_klass);
2287 // Attempt to initialize allowing initialization of parent classes but still not static
2288 // fields.
Chang Xinge602b1c2017-06-30 11:55:01 -07002289 // Initialize dependencies first only for app image, to make TryInitialize recursive.
2290 bool is_superclass_initialized = !is_app_image ? true :
2291 InitializeDependencies(klass, class_loader, soa.Self());
2292 if (!is_app_image || (is_app_image && is_superclass_initialized)) {
Nicolas Geoffrayabadf022017-08-03 08:25:41 +00002293 manager_->GetClassLinker()->EnsureInitialized(soa.Self(), klass, false, true);
Chang Xinge602b1c2017-06-30 11:55:01 -07002294 }
2295 // Otherwise it's in app image but superclasses can't be initialized, no need to proceed.
Mathieu Chartierf1dd69a2017-06-08 23:30:15 +00002296 old_status = klass->GetStatus();
Chang Xing70f689d2017-06-08 17:16:12 -07002297
2298 bool too_many_encoded_fields = false;
2299 if (!is_boot_image && klass->NumStaticFields() > kMaxEncodedFields) {
2300 too_many_encoded_fields = true;
2301 }
Mathieu Chartierdabeb3a2017-06-12 17:10:07 -07002302 // If the class was not initialized, we can proceed to see if we can initialize static
Chang Xing70f689d2017-06-08 17:16:12 -07002303 // fields. Limit the max number of encoded fields.
Mathieu Chartierf1dd69a2017-06-08 23:30:15 +00002304 if (!klass->IsInitialized() &&
Mathieu Chartier17498e52017-06-13 11:35:04 -07002305 (is_app_image || is_boot_image) &&
Chang Xinge602b1c2017-06-30 11:55:01 -07002306 is_superclass_initialized &&
Chang Xing70f689d2017-06-08 17:16:12 -07002307 !too_many_encoded_fields &&
Mathieu Chartierf1dd69a2017-06-08 23:30:15 +00002308 manager_->GetCompiler()->IsImageClass(descriptor)) {
2309 bool can_init_static_fields = false;
Mathieu Chartierdabeb3a2017-06-12 17:10:07 -07002310 if (is_boot_image) {
Mathieu Chartier90443472015-07-16 20:32:27 -07002311 // We need to initialize static fields, we only do this for image classes that aren't
Mathieu Chartierdabeb3a2017-06-12 17:10:07 -07002312 // marked with the $NoPreloadHolder (which implies this should not be initialized
2313 // early).
Mathieu Chartierf1dd69a2017-06-08 23:30:15 +00002314 can_init_static_fields = !StringPiece(descriptor).ends_with("$NoPreloadHolder;");
2315 } else {
Mathieu Chartier17498e52017-06-13 11:35:04 -07002316 CHECK(is_app_image);
Mathieu Chartierdabeb3a2017-06-12 17:10:07 -07002317 // The boot image case doesn't need to recursively initialize the dependencies with
2318 // special logic since the class linker already does this.
Mathieu Chartierdabeb3a2017-06-12 17:10:07 -07002319 can_init_static_fields =
Mathieu Chartierf1dd69a2017-06-08 23:30:15 +00002320 !soa.Self()->IsExceptionPending() &&
Nicolas Geoffrayabadf022017-08-03 08:25:41 +00002321 is_superclass_initialized &&
2322 NoClinitInDependency(klass, soa.Self(), &class_loader);
Mathieu Chartierf1dd69a2017-06-08 23:30:15 +00002323 // TODO The checking for clinit can be removed since it's already
2324 // checked when init superclass. Currently keep it because it contains
2325 // processing of intern strings. Will be removed later when intern strings
2326 // and clinit are both initialized.
2327 }
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002328
Mathieu Chartierf1dd69a2017-06-08 23:30:15 +00002329 if (can_init_static_fields) {
2330 VLOG(compiler) << "Initializing: " << descriptor;
2331 // TODO multithreading support. We should ensure the current compilation thread has
2332 // exclusive access to the runtime and the transaction. To achieve this, we could use
2333 // a ReaderWriterMutex but we're holding the mutator lock so we fail mutex sanity
2334 // checks in Thread::AssertThreadSuspensionIsAllowable.
2335 Runtime* const runtime = Runtime::Current();
Mathieu Chartierf1dd69a2017-06-08 23:30:15 +00002336 // Run the class initializer in transaction mode.
Chang Xing5a906fc2017-07-26 15:01:16 -07002337 runtime->EnterTransactionMode(is_app_image, klass.Get());
Mathieu Chartierf1dd69a2017-06-08 23:30:15 +00002338 bool success = manager_->GetClassLinker()->EnsureInitialized(soa.Self(), klass, true,
2339 true);
2340 // TODO we detach transaction from runtime to indicate we quit the transactional
2341 // mode which prevents the GC from visiting objects modified during the transaction.
2342 // Ensure GC is not run so don't access freed objects when aborting transaction.
Andreas Gampe9e7078b2017-03-02 13:50:36 -08002343
Mathieu Chartierf1dd69a2017-06-08 23:30:15 +00002344 {
2345 ScopedAssertNoThreadSuspension ants("Transaction end");
Chang Xing16d1dd82017-07-20 17:56:26 -07002346
2347 if (success) {
2348 runtime->ExitTransactionMode();
2349 DCHECK(!runtime->IsActiveTransaction());
2350 }
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002351
Mathieu Chartier90443472015-07-16 20:32:27 -07002352 if (!success) {
Mathieu Chartierf1dd69a2017-06-08 23:30:15 +00002353 CHECK(soa.Self()->IsExceptionPending());
2354 mirror::Throwable* exception = soa.Self()->GetException();
2355 VLOG(compiler) << "Initialization of " << descriptor << " aborted because of "
2356 << exception->Dump();
2357 std::ostream* file_log = manager_->GetCompiler()->
2358 GetCompilerOptions().GetInitFailureOutput();
2359 if (file_log != nullptr) {
2360 *file_log << descriptor << "\n";
2361 *file_log << exception->Dump() << "\n";
2362 }
2363 soa.Self()->ClearException();
Chang Xing605fe242017-07-20 15:57:21 -07002364 runtime->RollbackAllTransactions();
Mathieu Chartierf1dd69a2017-06-08 23:30:15 +00002365 CHECK_EQ(old_status, klass->GetStatus()) << "Previous class status not restored";
Mathieu Chartierdabeb3a2017-06-12 17:10:07 -07002366 } else if (is_boot_image) {
2367 // For boot image, we want to put the updated status in the oat class since we can't
2368 // reject the image anyways.
2369 old_status = klass->GetStatus();
Mathieu Chartierf1dd69a2017-06-08 23:30:15 +00002370 }
2371 }
2372
Nicolas Geoffrayabadf022017-08-03 08:25:41 +00002373 if (!success) {
Mathieu Chartierf1dd69a2017-06-08 23:30:15 +00002374 // On failure, still intern strings of static fields and seen in <clinit>, as these
2375 // will be created in the zygote. This is separated from the transaction code just
2376 // above as we will allocate strings, so must be allowed to suspend.
2377 if (&klass->GetDexFile() == manager_->GetDexFile()) {
Andreas Gampe9e7078b2017-03-02 13:50:36 -08002378 InternStrings(klass, class_loader);
Mathieu Chartierdabeb3a2017-06-12 17:10:07 -07002379 } else {
2380 DCHECK(!is_boot_image) << "Boot image must have equal dex files";
Andreas Gampedbfe2542014-11-25 22:21:42 -08002381 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002382 }
2383 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002384 }
Jeff Hao0cb17282017-07-12 14:51:49 -07002385 // If the class still isn't initialized, at least try some checks that initialization
2386 // would do so they can be skipped at runtime.
2387 if (!klass->IsInitialized() &&
2388 manager_->GetClassLinker()->ValidateSuperClassDescriptors(klass)) {
2389 old_status = mirror::Class::kStatusSuperclassValidated;
2390 } else {
2391 soa.Self()->ClearException();
2392 }
Mathieu Chartierf1dd69a2017-06-08 23:30:15 +00002393 soa.Self()->AssertNoPendingException();
Brian Carlstrom7940e442013-07-12 13:46:57 -07002394 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002395 }
Mathieu Chartierf1dd69a2017-06-08 23:30:15 +00002396 // Record the final class status if necessary.
2397 ClassReference ref(&dex_file, klass->GetDexClassDefIndex());
2398 // Back up the status before doing initialization for static encoded fields,
2399 // because the static encoded branch wants to keep the status to uninitialized.
2400 manager_->GetCompiler()->RecordClassStatus(ref, old_status);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002401 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002402
2403 private:
Andreas Gampe9e7078b2017-03-02 13:50:36 -08002404 void InternStrings(Handle<mirror::Class> klass, Handle<mirror::ClassLoader> class_loader)
2405 REQUIRES_SHARED(Locks::mutator_lock_) {
2406 DCHECK(manager_->GetCompiler()->GetCompilerOptions().IsBootImage());
2407 DCHECK(klass->IsVerified());
2408 DCHECK(!klass->IsInitialized());
2409
2410 StackHandleScope<1> hs(Thread::Current());
2411 Handle<mirror::DexCache> h_dex_cache = hs.NewHandle(klass->GetDexCache());
2412 const DexFile* dex_file = manager_->GetDexFile();
2413 const DexFile::ClassDef* class_def = klass->GetClassDef();
2414 ClassLinker* class_linker = manager_->GetClassLinker();
2415
Andreas Gampe7bf90482017-03-02 16:41:35 -08002416 // Check encoded final field values for strings and intern.
Andreas Gampe9e7078b2017-03-02 13:50:36 -08002417 annotations::RuntimeEncodedStaticFieldValueIterator value_it(*dex_file,
2418 &h_dex_cache,
2419 &class_loader,
2420 manager_->GetClassLinker(),
2421 *class_def);
2422 for ( ; value_it.HasNext(); value_it.Next()) {
2423 if (value_it.GetValueType() == annotations::RuntimeEncodedStaticFieldValueIterator::kString) {
2424 // Resolve the string. This will intern the string.
2425 art::ObjPtr<mirror::String> resolved = class_linker->ResolveString(
2426 *dex_file, dex::StringIndex(value_it.GetJavaValue().i), h_dex_cache);
2427 CHECK(resolved != nullptr);
2428 }
2429 }
Andreas Gampe7bf90482017-03-02 16:41:35 -08002430
2431 // Intern strings seen in <clinit>.
2432 ArtMethod* clinit = klass->FindClassInitializer(class_linker->GetImagePointerSize());
2433 if (clinit != nullptr) {
2434 const DexFile::CodeItem* code_item = clinit->GetCodeItem();
2435 DCHECK(code_item != nullptr);
Mathieu Chartier1d2d4ff2017-09-23 16:11:06 -07002436 for (const Instruction& inst : code_item->Instructions()) {
2437 if (inst.Opcode() == Instruction::CONST_STRING) {
Andreas Gampe7bf90482017-03-02 16:41:35 -08002438 ObjPtr<mirror::String> s = class_linker->ResolveString(
Mathieu Chartier1d2d4ff2017-09-23 16:11:06 -07002439 *dex_file, dex::StringIndex(inst.VRegB_21c()), h_dex_cache);
Andreas Gampe7bf90482017-03-02 16:41:35 -08002440 CHECK(s != nullptr);
Mathieu Chartier1d2d4ff2017-09-23 16:11:06 -07002441 } else if (inst.Opcode() == Instruction::CONST_STRING_JUMBO) {
Andreas Gampe7bf90482017-03-02 16:41:35 -08002442 ObjPtr<mirror::String> s = class_linker->ResolveString(
Mathieu Chartier1d2d4ff2017-09-23 16:11:06 -07002443 *dex_file, dex::StringIndex(inst.VRegB_31c()), h_dex_cache);
Andreas Gampe7bf90482017-03-02 16:41:35 -08002444 CHECK(s != nullptr);
2445 }
Andreas Gampe7bf90482017-03-02 16:41:35 -08002446 }
2447 }
Andreas Gampe9e7078b2017-03-02 13:50:36 -08002448 }
2449
Mathieu Chartierf1dd69a2017-06-08 23:30:15 +00002450 bool ResolveTypesOfMethods(Thread* self, ArtMethod* m)
2451 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markob45528c2017-07-27 14:14:28 +01002452 // Return value of ResolveReturnType() is discarded because resolve will be done internally.
2453 ObjPtr<mirror::Class> rtn_type = m->ResolveReturnType();
Mathieu Chartier7a8bcfd2017-06-13 13:40:43 -07002454 if (rtn_type == nullptr) {
2455 self->ClearException();
2456 return false;
2457 }
2458 const DexFile::TypeList* types = m->GetParameterTypeList();
2459 if (types != nullptr) {
2460 for (uint32_t i = 0; i < types->Size(); ++i) {
2461 dex::TypeIndex param_type_idx = types->GetTypeItem(i).type_idx_;
Vladimir Markob45528c2017-07-27 14:14:28 +01002462 ObjPtr<mirror::Class> param_type = m->ResolveClassFromTypeIndex(param_type_idx);
Mathieu Chartier7a8bcfd2017-06-13 13:40:43 -07002463 if (param_type == nullptr) {
2464 self->ClearException();
2465 return false;
Mathieu Chartierf1dd69a2017-06-08 23:30:15 +00002466 }
2467 }
Mathieu Chartier7a8bcfd2017-06-13 13:40:43 -07002468 }
2469 return true;
Mathieu Chartierf1dd69a2017-06-08 23:30:15 +00002470 }
2471
2472 // Pre resolve types mentioned in all method signatures before start a transaction
2473 // since ResolveType doesn't work in transaction mode.
2474 bool PreResolveTypes(Thread* self, const Handle<mirror::Class>& klass)
2475 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier7a8bcfd2017-06-13 13:40:43 -07002476 PointerSize pointer_size = manager_->GetClassLinker()->GetImagePointerSize();
2477 for (ArtMethod& m : klass->GetMethods(pointer_size)) {
2478 if (!ResolveTypesOfMethods(self, &m)) {
2479 return false;
2480 }
2481 }
2482 if (klass->IsInterface()) {
2483 return true;
2484 } else if (klass->HasSuperClass()) {
2485 StackHandleScope<1> hs(self);
2486 MutableHandle<mirror::Class> super_klass(hs.NewHandle<mirror::Class>(klass->GetSuperClass()));
2487 for (int i = super_klass->GetVTableLength() - 1; i >= 0; --i) {
2488 ArtMethod* m = klass->GetVTableEntry(i, pointer_size);
2489 ArtMethod* super_m = super_klass->GetVTableEntry(i, pointer_size);
2490 if (!ResolveTypesOfMethods(self, m) || !ResolveTypesOfMethods(self, super_m)) {
Mathieu Chartierf1dd69a2017-06-08 23:30:15 +00002491 return false;
2492 }
2493 }
Mathieu Chartier7a8bcfd2017-06-13 13:40:43 -07002494 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
2495 super_klass.Assign(klass->GetIfTable()->GetInterface(i));
2496 if (klass->GetClassLoader() != super_klass->GetClassLoader()) {
2497 uint32_t num_methods = super_klass->NumVirtualMethods();
2498 for (uint32_t j = 0; j < num_methods; ++j) {
2499 ArtMethod* m = klass->GetIfTable()->GetMethodArray(i)->GetElementPtrSize<ArtMethod*>(
2500 j, pointer_size);
2501 ArtMethod* super_m = super_klass->GetVirtualMethod(j, pointer_size);
2502 if (!ResolveTypesOfMethods(self, m) || !ResolveTypesOfMethods(self, super_m)) {
2503 return false;
Mathieu Chartierf1dd69a2017-06-08 23:30:15 +00002504 }
2505 }
2506 }
2507 }
Mathieu Chartier7a8bcfd2017-06-13 13:40:43 -07002508 }
2509 return true;
Mathieu Chartierf1dd69a2017-06-08 23:30:15 +00002510 }
2511
2512 // Initialize the klass's dependencies recursively before initializing itself.
2513 // Checking for interfaces is also necessary since interfaces can contain
2514 // both default methods and static encoded fields.
2515 bool InitializeDependencies(const Handle<mirror::Class>& klass,
2516 Handle<mirror::ClassLoader> class_loader,
2517 Thread* self)
2518 REQUIRES_SHARED(Locks::mutator_lock_) {
2519 if (klass->HasSuperClass()) {
2520 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
2521 StackHandleScope<1> hs(self);
2522 Handle<mirror::Class> handle_scope_super(hs.NewHandle(super_class));
2523 if (!handle_scope_super->IsInitialized()) {
2524 this->TryInitializeClass(handle_scope_super, class_loader);
2525 if (!handle_scope_super->IsInitialized()) {
2526 return false;
2527 }
2528 }
2529 }
2530
2531 uint32_t num_if = klass->NumDirectInterfaces();
2532 for (size_t i = 0; i < num_if; i++) {
2533 ObjPtr<mirror::Class>
2534 interface = mirror::Class::GetDirectInterface(self, klass.Get(), i);
2535 StackHandleScope<1> hs(self);
2536 Handle<mirror::Class> handle_interface(hs.NewHandle(interface));
2537
2538 TryInitializeClass(handle_interface, class_loader);
2539
2540 if (!handle_interface->IsInitialized()) {
2541 return false;
2542 }
2543 }
2544
2545 return PreResolveTypes(self, klass);
2546 }
2547
2548 // In this phase the classes containing class initializers are ignored. Make sure no
2549 // clinit appears in kalss's super class chain and interfaces.
2550 bool NoClinitInDependency(const Handle<mirror::Class>& klass,
2551 Thread* self,
2552 Handle<mirror::ClassLoader>* class_loader)
2553 REQUIRES_SHARED(Locks::mutator_lock_) {
2554 ArtMethod* clinit =
2555 klass->FindClassInitializer(manager_->GetClassLinker()->GetImagePointerSize());
2556 if (clinit != nullptr) {
2557 VLOG(compiler) << klass->PrettyClass() << ' ' << clinit->PrettyMethod(true);
2558 return false;
2559 }
2560 if (klass->HasSuperClass()) {
2561 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
2562 StackHandleScope<1> hs(self);
2563 Handle<mirror::Class> handle_scope_super(hs.NewHandle(super_class));
2564 if (!NoClinitInDependency(handle_scope_super, self, class_loader)) {
2565 return false;
2566 }
2567 }
2568
2569 uint32_t num_if = klass->NumDirectInterfaces();
2570 for (size_t i = 0; i < num_if; i++) {
2571 ObjPtr<mirror::Class>
2572 interface = mirror::Class::GetDirectInterface(self, klass.Get(), i);
2573 StackHandleScope<1> hs(self);
2574 Handle<mirror::Class> handle_interface(hs.NewHandle(interface));
2575 if (!NoClinitInDependency(handle_interface, self, class_loader)) {
2576 return false;
2577 }
2578 }
2579
Chang Xingba17dbd2017-06-28 21:27:56 +00002580 return true;
Mathieu Chartierf1dd69a2017-06-08 23:30:15 +00002581 }
2582
Mathieu Chartier90443472015-07-16 20:32:27 -07002583 const ParallelCompilationManager* const manager_;
2584};
Brian Carlstrom7940e442013-07-12 13:46:57 -07002585
Andreas Gampeace0dc12016-01-20 13:33:13 -08002586void CompilerDriver::InitializeClasses(jobject jni_class_loader,
2587 const DexFile& dex_file,
Andreas Gampede7b4362014-07-28 18:38:57 -07002588 const std::vector<const DexFile*>& dex_files,
Andreas Gampeace0dc12016-01-20 13:33:13 -08002589 TimingLogger* timings) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07002590 TimingLogger::ScopedTiming t("InitializeNoClinit", timings);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002591
2592 // Initialization allocates objects and needs to run single-threaded to be deterministic.
2593 bool force_determinism = GetCompilerOptions().IsForceDeterminism();
2594 ThreadPool* init_thread_pool = force_determinism
2595 ? single_thread_pool_.get()
2596 : parallel_thread_pool_.get();
2597 size_t init_thread_count = force_determinism ? 1U : parallel_thread_count_;
2598
Brian Carlstrom7940e442013-07-12 13:46:57 -07002599 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Andreas Gampede7b4362014-07-28 18:38:57 -07002600 ParallelCompilationManager context(class_linker, jni_class_loader, this, &dex_file, dex_files,
Andreas Gampeace0dc12016-01-20 13:33:13 -08002601 init_thread_pool);
Mathieu Chartierf1dd69a2017-06-08 23:30:15 +00002602
2603 if (GetCompilerOptions().IsBootImage() || GetCompilerOptions().IsAppImage()) {
2604 // Set the concurrency thread to 1 to support initialization for App Images since transaction
2605 // doesn't support multithreading now.
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002606 // TODO: remove this when transactional mode supports multithreading.
Andreas Gampeace0dc12016-01-20 13:33:13 -08002607 init_thread_count = 1U;
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002608 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002609 InitializeClassVisitor visitor(&context);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002610 context.ForAll(0, dex_file.NumClassDefs(), &visitor, init_thread_count);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002611}
2612
Mathieu Chartier91288d82016-04-28 09:44:54 -07002613class InitializeArrayClassesAndCreateConflictTablesVisitor : public ClassVisitor {
Mathieu Chartier085a0722016-04-01 17:33:31 -07002614 public:
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002615 explicit InitializeArrayClassesAndCreateConflictTablesVisitor(VariableSizedHandleScope& hs)
2616 : hs_(hs) {}
2617
2618 virtual bool operator()(ObjPtr<mirror::Class> klass) OVERRIDE
2619 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier91288d82016-04-28 09:44:54 -07002620 if (Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(klass)) {
2621 return true;
2622 }
Mathieu Chartier085a0722016-04-01 17:33:31 -07002623 if (klass->IsArrayClass()) {
2624 StackHandleScope<1> hs(Thread::Current());
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002625 auto h_klass = hs.NewHandleWrapper(&klass);
2626 Runtime::Current()->GetClassLinker()->EnsureInitialized(hs.Self(), h_klass, true, true);
Mathieu Chartier085a0722016-04-01 17:33:31 -07002627 }
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002628 // Collect handles since there may be thread suspension in future EnsureInitialized.
2629 to_visit_.push_back(hs_.NewHandle(klass));
Nicolas Geoffray88f288e2016-06-29 08:17:52 +00002630 return true;
Nelli Kimbadee982016-05-13 13:08:53 +03002631 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00002632
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002633 void FillAllIMTAndConflictTables() REQUIRES_SHARED(Locks::mutator_lock_) {
2634 for (Handle<mirror::Class> c : to_visit_) {
2635 // Create the conflict tables.
2636 FillIMTAndConflictTables(c.Get());
2637 }
2638 }
2639
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00002640 private:
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002641 void FillIMTAndConflictTables(ObjPtr<mirror::Class> klass)
2642 REQUIRES_SHARED(Locks::mutator_lock_) {
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00002643 if (!klass->ShouldHaveImt()) {
2644 return;
2645 }
2646 if (visited_classes_.find(klass) != visited_classes_.end()) {
2647 return;
2648 }
2649 if (klass->HasSuperClass()) {
2650 FillIMTAndConflictTables(klass->GetSuperClass());
2651 }
2652 if (!klass->IsTemp()) {
2653 Runtime::Current()->GetClassLinker()->FillIMTAndConflictTables(klass);
2654 }
2655 visited_classes_.insert(klass);
2656 }
2657
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002658 VariableSizedHandleScope& hs_;
2659 std::vector<Handle<mirror::Class>> to_visit_;
2660 std::unordered_set<ObjPtr<mirror::Class>, HashObjPtr> visited_classes_;
Mathieu Chartier085a0722016-04-01 17:33:31 -07002661};
2662
Brian Carlstrom7940e442013-07-12 13:46:57 -07002663void CompilerDriver::InitializeClasses(jobject class_loader,
2664 const std::vector<const DexFile*>& dex_files,
Andreas Gampeace0dc12016-01-20 13:33:13 -08002665 TimingLogger* timings) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07002666 for (size_t i = 0; i != dex_files.size(); ++i) {
2667 const DexFile* dex_file = dex_files[i];
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002668 CHECK(dex_file != nullptr);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002669 InitializeClasses(class_loader, *dex_file, dex_files, timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002670 }
Vladimir Markoaad75c62016-10-03 08:46:48 +00002671 if (GetCompilerOptions().IsBootImage() || GetCompilerOptions().IsAppImage()) {
Mathieu Chartier085a0722016-04-01 17:33:31 -07002672 // Make sure that we call EnsureIntiailized on all the array classes to call
2673 // SetVerificationAttempted so that the access flags are set. If we do not do this they get
2674 // changed at runtime resulting in more dirty image pages.
Mathieu Chartier91288d82016-04-28 09:44:54 -07002675 // Also create conflict tables.
2676 // Only useful if we are compiling an image (image_classes_ is not null).
Mathieu Chartier085a0722016-04-01 17:33:31 -07002677 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002678 VariableSizedHandleScope hs(soa.Self());
2679 InitializeArrayClassesAndCreateConflictTablesVisitor visitor(hs);
Mathieu Chartier91288d82016-04-28 09:44:54 -07002680 Runtime::Current()->GetClassLinker()->VisitClassesWithoutClassesLock(&visitor);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002681 visitor.FillAllIMTAndConflictTables();
Mathieu Chartier085a0722016-04-01 17:33:31 -07002682 }
Vladimir Markoaad75c62016-10-03 08:46:48 +00002683 if (GetCompilerOptions().IsBootImage()) {
Mathieu Chartier093ef212014-08-11 13:52:12 -07002684 // Prune garbage objects created during aborted transactions.
2685 Runtime::Current()->GetHeap()->CollectGarbage(true);
2686 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002687}
2688
Andreas Gampeace0dc12016-01-20 13:33:13 -08002689void CompilerDriver::Compile(jobject class_loader,
2690 const std::vector<const DexFile*>& dex_files,
2691 TimingLogger* timings) {
Calin Juravle998c2162015-12-21 15:39:33 +02002692 if (kDebugProfileGuidedCompilation) {
2693 LOG(INFO) << "[ProfileGuidedCompilation] " <<
2694 ((profile_compilation_info_ == nullptr)
2695 ? "null"
2696 : profile_compilation_info_->DumpInfo(&dex_files));
Calin Juravle226501b2015-12-11 14:41:31 +00002697 }
Vladimir Marko492a7fa2016-06-01 18:38:43 +01002698
Mathieu Chartier72041a02017-07-14 18:23:25 -07002699 current_dex_to_dex_methods_ = nullptr;
2700 Thread* const self = Thread::Current();
2701 {
2702 // Clear in case we aren't the first call to Compile.
2703 MutexLock mu(self, dex_to_dex_references_lock_);
2704 dex_to_dex_references_.clear();
2705 }
2706
Vladimir Marko492a7fa2016-06-01 18:38:43 +01002707 for (const DexFile* dex_file : dex_files) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002708 CHECK(dex_file != nullptr);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002709 CompileDexFile(class_loader,
2710 *dex_file,
2711 dex_files,
2712 parallel_thread_pool_.get(),
2713 parallel_thread_count_,
2714 timings);
Calin Juravle69158982016-03-16 11:53:41 +00002715 const ArenaPool* const arena_pool = Runtime::Current()->GetArenaPool();
2716 const size_t arena_alloc = arena_pool->GetBytesAllocated();
2717 max_arena_alloc_ = std::max(arena_alloc, max_arena_alloc_);
Jean-Philippe Halimica76a1a2016-02-02 19:48:52 +01002718 Runtime::Current()->ReclaimArenaPoolMemory();
Brian Carlstrom7940e442013-07-12 13:46:57 -07002719 }
Vladimir Marko492a7fa2016-06-01 18:38:43 +01002720
2721 ArrayRef<DexFileMethodSet> dex_to_dex_references;
2722 {
2723 // From this point on, we shall not modify dex_to_dex_references_, so
2724 // just grab a reference to it that we use without holding the mutex.
Mathieu Chartier72041a02017-07-14 18:23:25 -07002725 MutexLock lock(self, dex_to_dex_references_lock_);
Vladimir Marko492a7fa2016-06-01 18:38:43 +01002726 dex_to_dex_references = ArrayRef<DexFileMethodSet>(dex_to_dex_references_);
2727 }
2728 for (const auto& method_set : dex_to_dex_references) {
2729 current_dex_to_dex_methods_ = &method_set.GetMethodIndexes();
2730 CompileDexFile(class_loader,
2731 method_set.GetDexFile(),
2732 dex_files,
2733 parallel_thread_pool_.get(),
2734 parallel_thread_count_,
2735 timings);
2736 }
2737 current_dex_to_dex_methods_ = nullptr;
2738
Andreas Gampe8d295f82015-01-20 14:50:21 -08002739 VLOG(compiler) << "Compile: " << GetMemoryUsageString(false);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002740}
2741
Mathieu Chartier90443472015-07-16 20:32:27 -07002742class CompileClassVisitor : public CompilationVisitor {
2743 public:
2744 explicit CompileClassVisitor(const ParallelCompilationManager* manager) : manager_(manager) {}
2745
2746 virtual void Visit(size_t class_def_index) REQUIRES(!Locks::mutator_lock_) OVERRIDE {
2747 ATRACE_CALL();
2748 const DexFile& dex_file = *manager_->GetDexFile();
2749 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
2750 ClassLinker* class_linker = manager_->GetClassLinker();
2751 jobject jclass_loader = manager_->GetClassLoader();
Mathieu Chartier90443472015-07-16 20:32:27 -07002752 ClassReference ref(&dex_file, class_def_index);
2753 // Skip compiling classes with generic verifier failures since they will still fail at runtime
2754 if (manager_->GetCompiler()->verification_results_->IsClassRejected(ref)) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07002755 return;
2756 }
Mathieu Chartier736b5602015-09-02 14:54:11 -07002757 // Use a scoped object access to perform to the quick SkipClass check.
2758 const char* descriptor = dex_file.GetClassDescriptor(class_def);
2759 ScopedObjectAccess soa(Thread::Current());
2760 StackHandleScope<3> hs(soa.Self());
2761 Handle<mirror::ClassLoader> class_loader(
Mathieu Chartier0795f232016-09-27 18:43:30 -07002762 hs.NewHandle(soa.Decode<mirror::ClassLoader>(jclass_loader)));
Mathieu Chartier736b5602015-09-02 14:54:11 -07002763 Handle<mirror::Class> klass(
2764 hs.NewHandle(class_linker->FindClass(soa.Self(), descriptor, class_loader)));
2765 Handle<mirror::DexCache> dex_cache;
Andreas Gampefa4333d2017-02-14 11:10:34 -08002766 if (klass == nullptr) {
Mathieu Chartier736b5602015-09-02 14:54:11 -07002767 soa.Self()->AssertPendingException();
2768 soa.Self()->ClearException();
2769 dex_cache = hs.NewHandle(class_linker->FindDexCache(soa.Self(), dex_file));
2770 } else if (SkipClass(jclass_loader, dex_file, klass.Get())) {
2771 return;
2772 } else {
2773 dex_cache = hs.NewHandle(klass->GetDexCache());
2774 }
2775
Mathieu Chartier90443472015-07-16 20:32:27 -07002776 const uint8_t* class_data = dex_file.GetClassData(class_def);
2777 if (class_data == nullptr) {
2778 // empty class, probably a marker interface
2779 return;
Brian Carlstrom7940e442013-07-12 13:46:57 -07002780 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002781
Mathieu Chartier736b5602015-09-02 14:54:11 -07002782 // Go to native so that we don't block GC during compilation.
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07002783 ScopedThreadSuspension sts(soa.Self(), kNative);
Mathieu Chartier736b5602015-09-02 14:54:11 -07002784
Mathieu Chartier90443472015-07-16 20:32:27 -07002785 CompilerDriver* const driver = manager_->GetCompiler();
2786
2787 // Can we run DEX-to-DEX compiler on this class ?
Andreas Gampe5eb0d382015-07-23 01:19:26 -07002788 optimizer::DexToDexCompilationLevel dex_to_dex_compilation_level =
Mathieu Chartier736b5602015-09-02 14:54:11 -07002789 GetDexToDexCompilationLevel(soa.Self(), *driver, jclass_loader, dex_file, class_def);
Andreas Gampe5eb0d382015-07-23 01:19:26 -07002790
Mathieu Chartier90443472015-07-16 20:32:27 -07002791 ClassDataItemIterator it(dex_file, class_data);
Mathieu Chartiere17cf242017-06-19 11:05:51 -07002792 it.SkipAllFields();
Mathieu Chartier90443472015-07-16 20:32:27 -07002793
2794 bool compilation_enabled = driver->IsClassToCompile(
2795 dex_file.StringByTypeIdx(class_def.class_idx_));
2796
2797 // Compile direct methods
2798 int64_t previous_direct_method_idx = -1;
2799 while (it.HasNextDirectMethod()) {
2800 uint32_t method_idx = it.GetMemberIndex();
2801 if (method_idx == previous_direct_method_idx) {
2802 // smali can create dex files with two encoded_methods sharing the same method_idx
2803 // http://code.google.com/p/smali/issues/detail?id=119
2804 it.Next();
2805 continue;
2806 }
2807 previous_direct_method_idx = method_idx;
Vladimir Marko8d6768d2017-03-14 10:13:21 +00002808 CompileMethod(soa.Self(),
2809 driver,
2810 it.GetMethodCodeItem(),
2811 it.GetMethodAccessFlags(),
2812 it.GetMethodInvokeType(class_def),
2813 class_def_index,
2814 method_idx,
2815 class_loader,
2816 dex_file,
2817 dex_to_dex_compilation_level,
2818 compilation_enabled,
2819 dex_cache);
Mathieu Chartier90443472015-07-16 20:32:27 -07002820 it.Next();
2821 }
2822 // Compile virtual methods
2823 int64_t previous_virtual_method_idx = -1;
2824 while (it.HasNextVirtualMethod()) {
2825 uint32_t method_idx = it.GetMemberIndex();
2826 if (method_idx == previous_virtual_method_idx) {
2827 // smali can create dex files with two encoded_methods sharing the same method_idx
2828 // http://code.google.com/p/smali/issues/detail?id=119
2829 it.Next();
2830 continue;
2831 }
2832 previous_virtual_method_idx = method_idx;
Vladimir Marko8d6768d2017-03-14 10:13:21 +00002833 CompileMethod(soa.Self(),
2834 driver, it.GetMethodCodeItem(),
2835 it.GetMethodAccessFlags(),
2836 it.GetMethodInvokeType(class_def),
2837 class_def_index,
2838 method_idx,
2839 class_loader,
2840 dex_file,
2841 dex_to_dex_compilation_level,
2842 compilation_enabled,
2843 dex_cache);
Mathieu Chartier90443472015-07-16 20:32:27 -07002844 it.Next();
2845 }
2846 DCHECK(!it.HasNext());
Brian Carlstrom7940e442013-07-12 13:46:57 -07002847 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002848
2849 private:
2850 const ParallelCompilationManager* const manager_;
2851};
Brian Carlstrom7940e442013-07-12 13:46:57 -07002852
Andreas Gampeace0dc12016-01-20 13:33:13 -08002853void CompilerDriver::CompileDexFile(jobject class_loader,
2854 const DexFile& dex_file,
Andreas Gampede7b4362014-07-28 18:38:57 -07002855 const std::vector<const DexFile*>& dex_files,
Andreas Gampeace0dc12016-01-20 13:33:13 -08002856 ThreadPool* thread_pool,
2857 size_t thread_count,
2858 TimingLogger* timings) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07002859 TimingLogger::ScopedTiming t("Compile Dex File", timings);
Ian Rogersbe7149f2013-08-20 09:29:39 -07002860 ParallelCompilationManager context(Runtime::Current()->GetClassLinker(), class_loader, this,
Andreas Gampede7b4362014-07-28 18:38:57 -07002861 &dex_file, dex_files, thread_pool);
Mathieu Chartier90443472015-07-16 20:32:27 -07002862 CompileClassVisitor visitor(&context);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002863 context.ForAll(0, dex_file.NumClassDefs(), &visitor, thread_count);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002864}
2865
Andreas Gampe5eb0d382015-07-23 01:19:26 -07002866void CompilerDriver::AddCompiledMethod(const MethodReference& method_ref,
2867 CompiledMethod* const compiled_method,
2868 size_t non_relative_linker_patch_count) {
Mathieu Chartierfc8b4222017-09-17 13:44:24 -07002869 DCHECK(GetCompiledMethod(method_ref) == nullptr) << method_ref.PrettyMethod();
2870 MethodTable::InsertResult result = compiled_methods_.Insert(method_ref,
2871 /*expected*/ nullptr,
2872 compiled_method);
Mathieu Chartieracab8d42016-11-23 13:45:58 -08002873 CHECK(result == MethodTable::kInsertResultSuccess);
2874 non_relative_linker_patch_count_.FetchAndAddRelaxed(non_relative_linker_patch_count);
Mathieu Chartierfc8b4222017-09-17 13:44:24 -07002875 DCHECK(GetCompiledMethod(method_ref) != nullptr) << method_ref.PrettyMethod();
Brian Carlstrom7940e442013-07-12 13:46:57 -07002876}
2877
Mathieu Chartierfc8b4222017-09-17 13:44:24 -07002878bool CompilerDriver::GetCompiledClass(const ClassReference& ref,
2879 mirror::Class::Status* status) const {
Andreas Gampebb846102017-05-11 21:03:35 -07002880 DCHECK(status != nullptr);
Mathieu Chartier1a088d42017-07-18 11:43:57 -07002881 // The table doesn't know if something wasn't inserted. For this case it will return
Jeff Haof1aa2652017-08-03 17:09:33 -07002882 // kStatusNotReady. To handle this, just assume anything we didn't try to verify is not compiled.
Mathieu Chartierfc8b4222017-09-17 13:44:24 -07002883 if (!compiled_classes_.Get(ref, status) ||
Jeff Haof1aa2652017-08-03 17:09:33 -07002884 *status < mirror::Class::kStatusRetryVerificationAtRuntime) {
Andreas Gampebb846102017-05-11 21:03:35 -07002885 return false;
Brian Carlstrom7940e442013-07-12 13:46:57 -07002886 }
Andreas Gampebb846102017-05-11 21:03:35 -07002887 return true;
Brian Carlstrom7940e442013-07-12 13:46:57 -07002888}
2889
Mathieu Chartierfc8b4222017-09-17 13:44:24 -07002890mirror::Class::Status CompilerDriver::GetClassStatus(const ClassReference& ref) const {
Nicolas Geoffray486dda02017-09-11 14:15:52 +01002891 mirror::Class::Status status = ClassStatus::kStatusNotReady;
2892 if (!GetCompiledClass(ref, &status)) {
Mathieu Chartierfc8b4222017-09-17 13:44:24 -07002893 classpath_classes_.Get(ref, &status);
Nicolas Geoffray486dda02017-09-11 14:15:52 +01002894 }
2895 return status;
2896}
2897
Mathieu Chartierfc8b4222017-09-17 13:44:24 -07002898void CompilerDriver::RecordClassStatus(const ClassReference& ref, mirror::Class::Status status) {
Nicolas Geoffrayade72d62016-12-15 13:20:02 +00002899 switch (status) {
Vladimir Marko72ab6842017-01-20 19:32:50 +00002900 case mirror::Class::kStatusErrorResolved:
2901 case mirror::Class::kStatusErrorUnresolved:
Jeff Hao0cb17282017-07-12 14:51:49 -07002902 case mirror::Class::kStatusNotReady:
2903 case mirror::Class::kStatusResolved:
Nicolas Geoffrayade72d62016-12-15 13:20:02 +00002904 case mirror::Class::kStatusRetryVerificationAtRuntime:
2905 case mirror::Class::kStatusVerified:
Jeff Hao0cb17282017-07-12 14:51:49 -07002906 case mirror::Class::kStatusSuperclassValidated:
Nicolas Geoffrayade72d62016-12-15 13:20:02 +00002907 case mirror::Class::kStatusInitialized:
Nicolas Geoffrayade72d62016-12-15 13:20:02 +00002908 break; // Expected states.
2909 default:
2910 LOG(FATAL) << "Unexpected class status for class "
Mathieu Chartierfc8b4222017-09-17 13:44:24 -07002911 << PrettyDescriptor(
2912 ref.dex_file->GetClassDescriptor(ref.dex_file->GetClassDef(ref.index)))
Nicolas Geoffrayade72d62016-12-15 13:20:02 +00002913 << " of " << status;
2914 }
2915
Mathieu Chartier1a088d42017-07-18 11:43:57 -07002916 ClassStateTable::InsertResult result;
Nicolas Geoffray486dda02017-09-11 14:15:52 +01002917 ClassStateTable* table = &compiled_classes_;
Mathieu Chartier1a088d42017-07-18 11:43:57 -07002918 do {
Mathieu Chartier1a088d42017-07-18 11:43:57 -07002919 mirror::Class::Status existing = mirror::Class::kStatusNotReady;
Mathieu Chartierfc8b4222017-09-17 13:44:24 -07002920 if (!table->Get(ref, &existing)) {
Nicolas Geoffray486dda02017-09-11 14:15:52 +01002921 // A classpath class.
Mathieu Chartier010f5cc2017-07-24 15:53:46 -07002922 if (kIsDebugBuild) {
2923 // Check to make sure it's not a dex file for an oat file we are compiling since these
2924 // should always succeed. These do not include classes in for used libraries.
Mathieu Chartier72041a02017-07-14 18:23:25 -07002925 for (const DexFile* dex_file : GetDexFilesForOatFile()) {
Mathieu Chartierfc8b4222017-09-17 13:44:24 -07002926 CHECK_NE(ref.dex_file, dex_file) << ref.dex_file->GetLocation();
Mathieu Chartier010f5cc2017-07-24 15:53:46 -07002927 }
2928 }
Mathieu Chartierfc8b4222017-09-17 13:44:24 -07002929 if (!classpath_classes_.HaveDexFile(ref.dex_file)) {
Nicolas Geoffray486dda02017-09-11 14:15:52 +01002930 // Boot classpath dex file.
2931 return;
2932 }
2933 table = &classpath_classes_;
Mathieu Chartierfc8b4222017-09-17 13:44:24 -07002934 table->Get(ref, &existing);
Mathieu Chartier010f5cc2017-07-24 15:53:46 -07002935 }
Mathieu Chartier1a088d42017-07-18 11:43:57 -07002936 if (existing >= status) {
2937 // Existing status is already better than we expect, break.
2938 break;
2939 }
Nicolas Geoffrayade72d62016-12-15 13:20:02 +00002940 // Update the status if we now have a greater one. This happens with vdex,
2941 // which records a class is verified, but does not resolve it.
Mathieu Chartierfc8b4222017-09-17 13:44:24 -07002942 result = table->Insert(ref, existing, status);
2943 CHECK(result != ClassStateTable::kInsertResultInvalidDexFile) << ref.dex_file->GetLocation();
Mathieu Chartier1a088d42017-07-18 11:43:57 -07002944 } while (result != ClassStateTable::kInsertResultSuccess);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07002945}
2946
Brian Carlstrom7940e442013-07-12 13:46:57 -07002947CompiledMethod* CompilerDriver::GetCompiledMethod(MethodReference ref) const {
Mathieu Chartieracab8d42016-11-23 13:45:58 -08002948 CompiledMethod* compiled_method = nullptr;
Mathieu Chartierfc8b4222017-09-17 13:44:24 -07002949 compiled_methods_.Get(ref, &compiled_method);
Mathieu Chartieracab8d42016-11-23 13:45:58 -08002950 return compiled_method;
Brian Carlstrom7940e442013-07-12 13:46:57 -07002951}
2952
Calin Juravlef1c6d9e2015-04-13 18:42:21 +01002953bool CompilerDriver::IsMethodVerifiedWithoutFailures(uint32_t method_idx,
2954 uint16_t class_def_idx,
2955 const DexFile& dex_file) const {
2956 const VerifiedMethod* verified_method = GetVerifiedMethod(&dex_file, method_idx);
2957 if (verified_method != nullptr) {
2958 return !verified_method->HasVerificationFailures();
2959 }
2960
2961 // If we can't find verification metadata, check if this is a system class (we trust that system
2962 // classes have their methods verified). If it's not, be conservative and assume the method
2963 // has not been verified successfully.
2964
2965 // TODO: When compiling the boot image it should be safe to assume that everything is verified,
2966 // even if methods are not found in the verification cache.
2967 const char* descriptor = dex_file.GetClassDescriptor(dex_file.GetClassDef(class_def_idx));
2968 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
2969 Thread* self = Thread::Current();
2970 ScopedObjectAccess soa(self);
2971 bool is_system_class = class_linker->FindSystemClass(self, descriptor) != nullptr;
2972 if (!is_system_class) {
2973 self->ClearException();
2974 }
2975 return is_system_class;
2976}
2977
Vladimir Markof4da6752014-08-01 19:04:18 +01002978size_t CompilerDriver::GetNonRelativeLinkerPatchCount() const {
Mathieu Chartieracab8d42016-11-23 13:45:58 -08002979 return non_relative_linker_patch_count_.LoadRelaxed();
Vladimir Markof4da6752014-08-01 19:04:18 +01002980}
2981
Mathieu Chartierc4ae9162016-04-07 13:19:19 -07002982void CompilerDriver::SetRequiresConstructorBarrier(Thread* self,
2983 const DexFile* dex_file,
2984 uint16_t class_def_index,
2985 bool requires) {
2986 WriterMutexLock mu(self, requires_constructor_barrier_lock_);
2987 requires_constructor_barrier_.emplace(ClassReference(dex_file, class_def_index), requires);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002988}
2989
Mathieu Chartier371bd832016-04-07 10:19:48 -07002990bool CompilerDriver::RequiresConstructorBarrier(Thread* self,
2991 const DexFile* dex_file,
Mathieu Chartierc4ae9162016-04-07 13:19:19 -07002992 uint16_t class_def_index) {
2993 ClassReference class_ref(dex_file, class_def_index);
2994 {
2995 ReaderMutexLock mu(self, requires_constructor_barrier_lock_);
2996 auto it = requires_constructor_barrier_.find(class_ref);
2997 if (it != requires_constructor_barrier_.end()) {
2998 return it->second;
2999 }
Mathieu Chartierb5d38612016-04-07 10:52:52 -07003000 }
Mathieu Chartierc4ae9162016-04-07 13:19:19 -07003001 WriterMutexLock mu(self, requires_constructor_barrier_lock_);
3002 const bool requires = RequiresConstructorBarrier(*dex_file, class_def_index);
3003 requires_constructor_barrier_.emplace(class_ref, requires);
3004 return requires;
Brian Carlstrom7940e442013-07-12 13:46:57 -07003005}
3006
Andreas Gampe8d295f82015-01-20 14:50:21 -08003007std::string CompilerDriver::GetMemoryUsageString(bool extended) const {
Mathieu Chartierab972ef2014-12-03 17:38:22 -08003008 std::ostringstream oss;
Calin Juravle69158982016-03-16 11:53:41 +00003009 const gc::Heap* const heap = Runtime::Current()->GetHeap();
Anton Kirilovdd9473b2016-01-28 15:08:01 +00003010 const size_t java_alloc = heap->GetBytesAllocated();
Calin Juravle69158982016-03-16 11:53:41 +00003011 oss << "arena alloc=" << PrettySize(max_arena_alloc_) << " (" << max_arena_alloc_ << "B)";
Anton Kirilovdd9473b2016-01-28 15:08:01 +00003012 oss << " java alloc=" << PrettySize(java_alloc) << " (" << java_alloc << "B)";
Elliott Hughes7bf5a262015-04-02 20:55:07 -07003013#if defined(__BIONIC__) || defined(__GLIBC__)
Anton Kirilovdd9473b2016-01-28 15:08:01 +00003014 const struct mallinfo info = mallinfo();
Mathieu Chartierab972ef2014-12-03 17:38:22 -08003015 const size_t allocated_space = static_cast<size_t>(info.uordblks);
3016 const size_t free_space = static_cast<size_t>(info.fordblks);
Anton Kirilovdd9473b2016-01-28 15:08:01 +00003017 oss << " native alloc=" << PrettySize(allocated_space) << " (" << allocated_space << "B)"
3018 << " free=" << PrettySize(free_space) << " (" << free_space << "B)";
Mathieu Chartierab972ef2014-12-03 17:38:22 -08003019#endif
Vladimir Marko35831e82015-09-11 11:59:18 +01003020 compiled_method_storage_.DumpMemoryUsage(oss, extended);
Mathieu Chartierab972ef2014-12-03 17:38:22 -08003021 return oss.str();
3022}
3023
Jeff Haodcdc85b2015-12-04 14:06:18 -08003024bool CompilerDriver::MayInlineInternal(const DexFile* inlined_from,
3025 const DexFile* inlined_into) const {
3026 // We're not allowed to inline across dex files if we're the no-inline-from dex file.
3027 if (inlined_from != inlined_into &&
Vladimir Marko47496c22016-01-27 16:15:08 +00003028 compiler_options_->GetNoInlineFromDexFile() != nullptr &&
3029 ContainsElement(*compiler_options_->GetNoInlineFromDexFile(), inlined_from)) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08003030 return false;
3031 }
3032
3033 return true;
3034}
3035
Andreas Gampeace0dc12016-01-20 13:33:13 -08003036void CompilerDriver::InitializeThreadPools() {
3037 size_t parallel_count = parallel_thread_count_ > 0 ? parallel_thread_count_ - 1 : 0;
3038 parallel_thread_pool_.reset(
3039 new ThreadPool("Compiler driver thread pool", parallel_count));
3040 single_thread_pool_.reset(new ThreadPool("Single-threaded Compiler driver thread pool", 0));
3041}
3042
3043void CompilerDriver::FreeThreadPools() {
3044 parallel_thread_pool_.reset();
3045 single_thread_pool_.reset();
3046}
3047
Mathieu Chartier72041a02017-07-14 18:23:25 -07003048void CompilerDriver::SetDexFilesForOatFile(const std::vector<const DexFile*>& dex_files) {
3049 dex_files_for_oat_file_ = dex_files;
Nicolas Geoffray486dda02017-09-11 14:15:52 +01003050 compiled_classes_.AddDexFiles(dex_files);
3051}
3052
3053void CompilerDriver::SetClasspathDexFiles(const std::vector<const DexFile*>& dex_files) {
3054 classpath_classes_.AddDexFiles(dex_files);
Mathieu Chartier72041a02017-07-14 18:23:25 -07003055}
3056
Brian Carlstrom7940e442013-07-12 13:46:57 -07003057} // namespace art