blob: 2ec3f164e3df282b201d4ca682279512a0c6201a [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 Gampeb0f370e2014-09-25 22:51:40 -070019#include <unordered_set>
Anwar Ghuloum67f99412013-08-12 14:19:48 -070020#include <vector>
Brian Carlstrom7940e442013-07-12 13:46:57 -070021#include <unistd.h>
22
Mathieu Chartierab972ef2014-12-03 17:38:22 -080023#ifndef __APPLE__
24#include <malloc.h> // For mallinfo
25#endif
26
Mathieu Chartierc7853442015-03-27 14:35:38 -070027#include "art_field-inl.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070028#include "art_method-inl.h"
David Brazdild9c90372016-09-14 16:53:55 +010029#include "base/array_ref.h"
Vladimir Marko492a7fa2016-06-01 18:38:43 +010030#include "base/bit_vector.h"
Andreas Gampe542451c2016-07-26 09:02:02 -070031#include "base/enums.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070032#include "base/stl_util.h"
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -080033#include "base/systrace.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010034#include "base/time_utils.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070035#include "base/timing_logger.h"
Vladimir Marko3481ba22015-04-13 12:22:36 +010036#include "class_linker-inl.h"
Mingyao Yang98d1cc82014-05-15 17:02:16 -070037#include "compiled_class.h"
Vladimir Marko20f85592015-03-19 10:07:02 +000038#include "compiled_method.h"
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +000039#include "compiler.h"
Vladimir Markobe0e5462014-02-26 11:24:15 +000040#include "compiler_driver-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070041#include "dex_compilation_unit.h"
42#include "dex_file-inl.h"
Andreas Gampeace0dc12016-01-20 13:33:13 -080043#include "dex_instruction-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"
Mark Mendellae9fd932014-02-10 16:14:35 -080047#include "driver/compiler_options.h"
Nicolas Geoffray762869d2016-07-15 15:28:35 +010048#include "intrinsics_enum.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070049#include "jni_internal.h"
Ian Rogers22d5e732014-07-15 22:23:51 -070050#include "object_lock.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070051#include "runtime.h"
52#include "gc/accounting/card_table-inl.h"
53#include "gc/accounting/heap_bitmap.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070054#include "gc/space/image_space.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070055#include "gc/space/space.h"
56#include "mirror/class_loader.h"
57#include "mirror/class-inl.h"
58#include "mirror/dex_cache-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070059#include "mirror/object-inl.h"
60#include "mirror/object_array-inl.h"
61#include "mirror/throwable.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070062#include "scoped_thread_state_change-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070063#include "ScopedLocalRef.h"
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070064#include "handle_scope-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070065#include "thread.h"
Andreas Gampeb0f370e2014-09-25 22:51:40 -070066#include "thread_list.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070067#include "thread_pool.h"
Ian Rogers848871b2013-08-05 10:56:33 -070068#include "trampolines/trampoline_compiler.h"
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +010069#include "transaction.h"
Vladimir Marko20f85592015-03-19 10:07:02 +000070#include "utils/dex_cache_arrays_layout-inl.h"
Andreas Gampee21dc3d2014-12-08 16:59:43 -080071#include "utils/swap_space.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070072#include "verifier/method_verifier.h"
Vladimir Marko2bc47802014-02-10 09:43:07 +000073#include "verifier/method_verifier-inl.h"
Andreas Gampe5fd66d02016-09-12 20:22:19 -070074#include "verifier/verifier_log_mode.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070075
Brian Carlstrom7940e442013-07-12 13:46:57 -070076namespace art {
77
Mathieu Chartier8e219ae2014-08-19 14:29:46 -070078static constexpr bool kTimeCompileMethod = !kIsDebugBuild;
79
Calin Juravle226501b2015-12-11 14:41:31 +000080// Print additional info during profile guided compilation.
81static constexpr bool kDebugProfileGuidedCompilation = false;
82
Brian Carlstrom7940e442013-07-12 13:46:57 -070083static double Percentage(size_t x, size_t y) {
84 return 100.0 * (static_cast<double>(x)) / (static_cast<double>(x + y));
85}
86
87static void DumpStat(size_t x, size_t y, const char* str) {
88 if (x == 0 && y == 0) {
89 return;
90 }
Ian Rogerse732ef12013-10-09 15:22:24 -070091 LOG(INFO) << Percentage(x, y) << "% of " << str << " for " << (x + y) << " cases";
Brian Carlstrom7940e442013-07-12 13:46:57 -070092}
93
Vladimir Markof096aad2014-01-23 15:51:58 +000094class CompilerDriver::AOTCompilationStats {
Brian Carlstrom7940e442013-07-12 13:46:57 -070095 public:
96 AOTCompilationStats()
97 : stats_lock_("AOT compilation statistics lock"),
98 types_in_dex_cache_(0), types_not_in_dex_cache_(0),
99 strings_in_dex_cache_(0), strings_not_in_dex_cache_(0),
100 resolved_types_(0), unresolved_types_(0),
101 resolved_instance_fields_(0), unresolved_instance_fields_(0),
102 resolved_local_static_fields_(0), resolved_static_fields_(0), unresolved_static_fields_(0),
103 type_based_devirtualization_(0),
104 safe_casts_(0), not_safe_casts_(0) {
105 for (size_t i = 0; i <= kMaxInvokeType; i++) {
106 resolved_methods_[i] = 0;
107 unresolved_methods_[i] = 0;
108 virtual_made_direct_[i] = 0;
109 direct_calls_to_boot_[i] = 0;
110 direct_methods_to_boot_[i] = 0;
111 }
112 }
113
114 void Dump() {
115 DumpStat(types_in_dex_cache_, types_not_in_dex_cache_, "types known to be in dex cache");
116 DumpStat(strings_in_dex_cache_, strings_not_in_dex_cache_, "strings known to be in dex cache");
117 DumpStat(resolved_types_, unresolved_types_, "types resolved");
118 DumpStat(resolved_instance_fields_, unresolved_instance_fields_, "instance fields resolved");
119 DumpStat(resolved_local_static_fields_ + resolved_static_fields_, unresolved_static_fields_,
120 "static fields resolved");
121 DumpStat(resolved_local_static_fields_, resolved_static_fields_ + unresolved_static_fields_,
122 "static fields local to a class");
123 DumpStat(safe_casts_, not_safe_casts_, "check-casts removed based on type information");
124 // Note, the code below subtracts the stat value so that when added to the stat value we have
125 // 100% of samples. TODO: clean this up.
126 DumpStat(type_based_devirtualization_,
127 resolved_methods_[kVirtual] + unresolved_methods_[kVirtual] +
128 resolved_methods_[kInterface] + unresolved_methods_[kInterface] -
129 type_based_devirtualization_,
130 "virtual/interface calls made direct based on type information");
131
132 for (size_t i = 0; i <= kMaxInvokeType; i++) {
133 std::ostringstream oss;
134 oss << static_cast<InvokeType>(i) << " methods were AOT resolved";
135 DumpStat(resolved_methods_[i], unresolved_methods_[i], oss.str().c_str());
136 if (virtual_made_direct_[i] > 0) {
137 std::ostringstream oss2;
138 oss2 << static_cast<InvokeType>(i) << " methods made direct";
139 DumpStat(virtual_made_direct_[i],
140 resolved_methods_[i] + unresolved_methods_[i] - virtual_made_direct_[i],
141 oss2.str().c_str());
142 }
143 if (direct_calls_to_boot_[i] > 0) {
144 std::ostringstream oss2;
145 oss2 << static_cast<InvokeType>(i) << " method calls are direct into boot";
146 DumpStat(direct_calls_to_boot_[i],
147 resolved_methods_[i] + unresolved_methods_[i] - direct_calls_to_boot_[i],
148 oss2.str().c_str());
149 }
150 if (direct_methods_to_boot_[i] > 0) {
151 std::ostringstream oss2;
152 oss2 << static_cast<InvokeType>(i) << " method calls have methods in boot";
153 DumpStat(direct_methods_to_boot_[i],
154 resolved_methods_[i] + unresolved_methods_[i] - direct_methods_to_boot_[i],
155 oss2.str().c_str());
156 }
157 }
158 }
159
160// Allow lossy statistics in non-debug builds.
161#ifndef NDEBUG
162#define STATS_LOCK() MutexLock mu(Thread::Current(), stats_lock_)
163#else
164#define STATS_LOCK()
165#endif
166
Mathieu Chartier90443472015-07-16 20:32:27 -0700167 void TypeInDexCache() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700168 STATS_LOCK();
169 types_in_dex_cache_++;
170 }
171
Mathieu Chartier90443472015-07-16 20:32:27 -0700172 void TypeNotInDexCache() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700173 STATS_LOCK();
174 types_not_in_dex_cache_++;
175 }
176
Mathieu Chartier90443472015-07-16 20:32:27 -0700177 void StringInDexCache() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700178 STATS_LOCK();
179 strings_in_dex_cache_++;
180 }
181
Mathieu Chartier90443472015-07-16 20:32:27 -0700182 void StringNotInDexCache() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700183 STATS_LOCK();
184 strings_not_in_dex_cache_++;
185 }
186
Mathieu Chartier90443472015-07-16 20:32:27 -0700187 void TypeDoesntNeedAccessCheck() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700188 STATS_LOCK();
189 resolved_types_++;
190 }
191
Mathieu Chartier90443472015-07-16 20:32:27 -0700192 void TypeNeedsAccessCheck() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700193 STATS_LOCK();
194 unresolved_types_++;
195 }
196
Mathieu Chartier90443472015-07-16 20:32:27 -0700197 void ResolvedInstanceField() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700198 STATS_LOCK();
199 resolved_instance_fields_++;
200 }
201
Mathieu Chartier90443472015-07-16 20:32:27 -0700202 void UnresolvedInstanceField() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700203 STATS_LOCK();
204 unresolved_instance_fields_++;
205 }
206
Mathieu Chartier90443472015-07-16 20:32:27 -0700207 void ResolvedLocalStaticField() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700208 STATS_LOCK();
209 resolved_local_static_fields_++;
210 }
211
Mathieu Chartier90443472015-07-16 20:32:27 -0700212 void ResolvedStaticField() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700213 STATS_LOCK();
214 resolved_static_fields_++;
215 }
216
Mathieu Chartier90443472015-07-16 20:32:27 -0700217 void UnresolvedStaticField() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700218 STATS_LOCK();
219 unresolved_static_fields_++;
220 }
221
222 // Indicate that type information from the verifier led to devirtualization.
Mathieu Chartier90443472015-07-16 20:32:27 -0700223 void PreciseTypeDevirtualization() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700224 STATS_LOCK();
225 type_based_devirtualization_++;
226 }
227
228 // Indicate that a method of the given type was resolved at compile time.
Mathieu Chartier90443472015-07-16 20:32:27 -0700229 void ResolvedMethod(InvokeType type) REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700230 DCHECK_LE(type, kMaxInvokeType);
231 STATS_LOCK();
232 resolved_methods_[type]++;
233 }
234
235 // Indicate that a method of the given type was unresolved at compile time as it was in an
236 // unknown dex file.
Mathieu Chartier90443472015-07-16 20:32:27 -0700237 void UnresolvedMethod(InvokeType type) REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700238 DCHECK_LE(type, kMaxInvokeType);
239 STATS_LOCK();
240 unresolved_methods_[type]++;
241 }
242
243 // Indicate that a type of virtual method dispatch has been converted into a direct method
244 // dispatch.
Mathieu Chartier90443472015-07-16 20:32:27 -0700245 void VirtualMadeDirect(InvokeType type) REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700246 DCHECK(type == kVirtual || type == kInterface || type == kSuper);
247 STATS_LOCK();
248 virtual_made_direct_[type]++;
249 }
250
251 // Indicate that a method of the given type was able to call directly into boot.
Mathieu Chartier90443472015-07-16 20:32:27 -0700252 void DirectCallsToBoot(InvokeType type) REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700253 DCHECK_LE(type, kMaxInvokeType);
254 STATS_LOCK();
255 direct_calls_to_boot_[type]++;
256 }
257
258 // Indicate that a method of the given type was able to be resolved directly from boot.
Mathieu Chartier90443472015-07-16 20:32:27 -0700259 void DirectMethodsToBoot(InvokeType type) REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700260 DCHECK_LE(type, kMaxInvokeType);
261 STATS_LOCK();
262 direct_methods_to_boot_[type]++;
263 }
264
Mathieu Chartier90443472015-07-16 20:32:27 -0700265 void ProcessedInvoke(InvokeType type, int flags) REQUIRES(!stats_lock_) {
Vladimir Markof096aad2014-01-23 15:51:58 +0000266 STATS_LOCK();
267 if (flags == 0) {
268 unresolved_methods_[type]++;
269 } else {
270 DCHECK_NE((flags & kFlagMethodResolved), 0);
271 resolved_methods_[type]++;
272 if ((flags & kFlagVirtualMadeDirect) != 0) {
273 virtual_made_direct_[type]++;
274 if ((flags & kFlagPreciseTypeDevirtualization) != 0) {
275 type_based_devirtualization_++;
276 }
277 } else {
278 DCHECK_EQ((flags & kFlagPreciseTypeDevirtualization), 0);
279 }
280 if ((flags & kFlagDirectCallToBoot) != 0) {
281 direct_calls_to_boot_[type]++;
282 }
283 if ((flags & kFlagDirectMethodToBoot) != 0) {
284 direct_methods_to_boot_[type]++;
285 }
286 }
287 }
288
Brian Carlstrom7940e442013-07-12 13:46:57 -0700289 // A check-cast could be eliminated due to verifier type analysis.
Mathieu Chartier90443472015-07-16 20:32:27 -0700290 void SafeCast() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700291 STATS_LOCK();
292 safe_casts_++;
293 }
294
295 // A check-cast couldn't be eliminated due to verifier type analysis.
Mathieu Chartier90443472015-07-16 20:32:27 -0700296 void NotASafeCast() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700297 STATS_LOCK();
298 not_safe_casts_++;
299 }
300
301 private:
302 Mutex stats_lock_;
303
304 size_t types_in_dex_cache_;
305 size_t types_not_in_dex_cache_;
306
307 size_t strings_in_dex_cache_;
308 size_t strings_not_in_dex_cache_;
309
310 size_t resolved_types_;
311 size_t unresolved_types_;
312
313 size_t resolved_instance_fields_;
314 size_t unresolved_instance_fields_;
315
316 size_t resolved_local_static_fields_;
317 size_t resolved_static_fields_;
318 size_t unresolved_static_fields_;
319 // Type based devirtualization for invoke interface and virtual.
320 size_t type_based_devirtualization_;
321
322 size_t resolved_methods_[kMaxInvokeType + 1];
323 size_t unresolved_methods_[kMaxInvokeType + 1];
324 size_t virtual_made_direct_[kMaxInvokeType + 1];
325 size_t direct_calls_to_boot_[kMaxInvokeType + 1];
326 size_t direct_methods_to_boot_[kMaxInvokeType + 1];
327
328 size_t safe_casts_;
329 size_t not_safe_casts_;
330
331 DISALLOW_COPY_AND_ASSIGN(AOTCompilationStats);
332};
333
Vladimir Marko492a7fa2016-06-01 18:38:43 +0100334class CompilerDriver::DexFileMethodSet {
335 public:
336 explicit DexFileMethodSet(const DexFile& dex_file)
337 : dex_file_(dex_file),
338 method_indexes_(dex_file.NumMethodIds(), false, Allocator::GetMallocAllocator()) {
339 }
340 DexFileMethodSet(DexFileMethodSet&& other) = default;
341
342 const DexFile& GetDexFile() const { return dex_file_; }
343
344 BitVector& GetMethodIndexes() { return method_indexes_; }
345 const BitVector& GetMethodIndexes() const { return method_indexes_; }
346
347 private:
348 const DexFile& dex_file_;
349 BitVector method_indexes_;
350};
351
Jeff Haodcdc85b2015-12-04 14:06:18 -0800352CompilerDriver::CompilerDriver(
353 const CompilerOptions* compiler_options,
354 VerificationResults* verification_results,
Jeff Haodcdc85b2015-12-04 14:06:18 -0800355 Compiler::Kind compiler_kind,
356 InstructionSet instruction_set,
357 const InstructionSetFeatures* instruction_set_features,
Vladimir Marko944da602016-02-19 12:27:55 +0000358 bool boot_image,
Mathieu Chartier91288d82016-04-28 09:44:54 -0700359 bool app_image,
Vladimir Marko944da602016-02-19 12:27:55 +0000360 std::unordered_set<std::string>* image_classes,
Jeff Haodcdc85b2015-12-04 14:06:18 -0800361 std::unordered_set<std::string>* compiled_classes,
362 std::unordered_set<std::string>* compiled_methods,
Vladimir Marko944da602016-02-19 12:27:55 +0000363 size_t thread_count,
364 bool dump_stats,
365 bool dump_passes,
366 CumulativeLogger* timer,
367 int swap_fd,
Calin Juravle998c2162015-12-21 15:39:33 +0200368 const ProfileCompilationInfo* profile_compilation_info)
Calin Juravle226501b2015-12-11 14:41:31 +0000369 : compiler_options_(compiler_options),
Brian Carlstrom6449c622014-02-10 23:48:36 -0800370 verification_results_(verification_results),
Ian Rogers72d32622014-05-06 16:20:11 -0700371 compiler_(Compiler::Create(this, compiler_kind)),
Jeff Hao48699fb2015-04-06 14:21:37 -0700372 compiler_kind_(compiler_kind),
Artem Serovba6b6792016-08-15 14:22:07 +0100373 instruction_set_(instruction_set == kArm ? kThumb2: instruction_set),
Dave Allison70202782013-10-22 17:52:19 -0700374 instruction_set_features_(instruction_set_features),
Mathieu Chartierc4ae9162016-04-07 13:19:19 -0700375 requires_constructor_barrier_lock_("constructor barrier lock"),
Brian Carlstrom7940e442013-07-12 13:46:57 -0700376 compiled_classes_lock_("compiled classes lock"),
377 compiled_methods_lock_("compiled method lock"),
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800378 compiled_methods_(MethodTable::key_compare()),
Vladimir Markof4da6752014-08-01 19:04:18 +0100379 non_relative_linker_patch_count_(0u),
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800380 boot_image_(boot_image),
Mathieu Chartier91288d82016-04-28 09:44:54 -0700381 app_image_(app_image),
Brian Carlstrom7940e442013-07-12 13:46:57 -0700382 image_classes_(image_classes),
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800383 classes_to_compile_(compiled_classes),
Andreas Gampe70bef0d2015-04-15 02:37:28 -0700384 methods_to_compile_(compiled_methods),
Andreas Gampe6cf49e52015-03-05 13:08:45 -0800385 had_hard_verifier_failure_(false),
Andreas Gampeace0dc12016-01-20 13:33:13 -0800386 parallel_thread_count_(thread_count),
Brian Carlstrom7940e442013-07-12 13:46:57 -0700387 stats_(new AOTCompilationStats),
388 dump_stats_(dump_stats),
Nicolas Geoffrayea3fa0b2014-02-10 11:59:41 +0000389 dump_passes_(dump_passes),
390 timings_logger_(timer),
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700391 compiler_context_(nullptr),
Alexey Frunzee3fb2452016-05-10 16:08:05 -0700392 support_boot_image_fixup_(instruction_set != kMips64),
Vladimir Markod1eaf0d2015-10-29 12:18:29 +0000393 dex_files_for_oat_file_(nullptr),
Calin Juravle998c2162015-12-21 15:39:33 +0200394 compiled_method_storage_(swap_fd),
Calin Juravle69158982016-03-16 11:53:41 +0000395 profile_compilation_info_(profile_compilation_info),
Vladimir Marko492a7fa2016-06-01 18:38:43 +0100396 max_arena_alloc_(0),
397 dex_to_dex_references_lock_("dex-to-dex references lock"),
398 dex_to_dex_references_(),
399 current_dex_to_dex_methods_(nullptr) {
Brian Carlstrom6449c622014-02-10 23:48:36 -0800400 DCHECK(compiler_options_ != nullptr);
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700401
Ian Rogers72d32622014-05-06 16:20:11 -0700402 compiler_->Init();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700403
Mathieu Chartiera8077802016-03-16 19:08:31 -0700404 if (compiler_options->VerifyOnlyProfile()) {
405 CHECK(profile_compilation_info_ != nullptr) << "Requires profile";
406 }
Mathieu Chartierc5dd3192015-12-09 16:38:30 -0800407 if (boot_image_) {
408 CHECK(image_classes_.get() != nullptr) << "Expected image classes for boot image";
409 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700410}
411
412CompilerDriver::~CompilerDriver() {
413 Thread* self = Thread::Current();
414 {
415 MutexLock mu(self, compiled_classes_lock_);
416 STLDeleteValues(&compiled_classes_);
417 }
418 {
419 MutexLock mu(self, compiled_methods_lock_);
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800420 for (auto& pair : compiled_methods_) {
421 CompiledMethod::ReleaseSwapAllocatedCompiledMethod(this, pair.second);
422 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700423 }
Ian Rogers72d32622014-05-06 16:20:11 -0700424 compiler_->UnInit();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700425}
426
Vladimir Marko35831e82015-09-11 11:59:18 +0100427
Ian Rogersdd7624d2014-03-14 17:43:00 -0700428#define CREATE_TRAMPOLINE(type, abi, offset) \
Andreas Gampeaf13ad92014-04-11 12:07:48 -0700429 if (Is64BitInstructionSet(instruction_set_)) { \
Ian Rogersdd7624d2014-03-14 17:43:00 -0700430 return CreateTrampoline64(instruction_set_, abi, \
Andreas Gampe542451c2016-07-26 09:02:02 -0700431 type ## _ENTRYPOINT_OFFSET(PointerSize::k64, offset)); \
Ian Rogersdd7624d2014-03-14 17:43:00 -0700432 } else { \
433 return CreateTrampoline32(instruction_set_, abi, \
Andreas Gampe542451c2016-07-26 09:02:02 -0700434 type ## _ENTRYPOINT_OFFSET(PointerSize::k32, offset)); \
Ian Rogersdd7624d2014-03-14 17:43:00 -0700435 }
436
Vladimir Marko93205e32016-04-13 11:59:46 +0100437std::unique_ptr<const std::vector<uint8_t>> CompilerDriver::CreateJniDlsymLookup() const {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700438 CREATE_TRAMPOLINE(JNI, kJniAbi, pDlsymLookup)
Ian Rogers848871b2013-08-05 10:56:33 -0700439}
440
Vladimir Marko93205e32016-04-13 11:59:46 +0100441std::unique_ptr<const std::vector<uint8_t>> CompilerDriver::CreateQuickGenericJniTrampoline()
442 const {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700443 CREATE_TRAMPOLINE(QUICK, kQuickAbi, pQuickGenericJniTrampoline)
Andreas Gampe2da88232014-02-27 12:26:20 -0800444}
445
Vladimir Marko93205e32016-04-13 11:59:46 +0100446std::unique_ptr<const std::vector<uint8_t>> CompilerDriver::CreateQuickImtConflictTrampoline()
447 const {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700448 CREATE_TRAMPOLINE(QUICK, kQuickAbi, pQuickImtConflictTrampoline)
Jeff Hao88474b42013-10-23 16:24:40 -0700449}
450
Vladimir Marko93205e32016-04-13 11:59:46 +0100451std::unique_ptr<const std::vector<uint8_t>> CompilerDriver::CreateQuickResolutionTrampoline()
452 const {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700453 CREATE_TRAMPOLINE(QUICK, kQuickAbi, pQuickResolutionTrampoline)
Brian Carlstrom7940e442013-07-12 13:46:57 -0700454}
455
Vladimir Marko93205e32016-04-13 11:59:46 +0100456std::unique_ptr<const std::vector<uint8_t>> CompilerDriver::CreateQuickToInterpreterBridge()
457 const {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700458 CREATE_TRAMPOLINE(QUICK, kQuickAbi, pQuickToInterpreterBridge)
Brian Carlstrom7940e442013-07-12 13:46:57 -0700459}
Ian Rogersdd7624d2014-03-14 17:43:00 -0700460#undef CREATE_TRAMPOLINE
Brian Carlstrom7940e442013-07-12 13:46:57 -0700461
Nicolas Geoffray762869d2016-07-15 15:28:35 +0100462static void SetupIntrinsic(Thread* self,
463 Intrinsics intrinsic,
464 InvokeType invoke_type,
465 const char* class_name,
466 const char* method_name,
467 const char* signature)
468 REQUIRES_SHARED(Locks::mutator_lock_) {
469 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
470 PointerSize image_size = class_linker->GetImagePointerSize();
471 mirror::Class* cls = class_linker->FindSystemClass(self, class_name);
472 if (cls == nullptr) {
473 LOG(FATAL) << "Could not find class of intrinsic " << class_name;
474 }
475 ArtMethod* method = (invoke_type == kStatic || invoke_type == kDirect)
476 ? cls->FindDeclaredDirectMethod(method_name, signature, image_size)
477 : cls->FindDeclaredVirtualMethod(method_name, signature, image_size);
478 if (method == nullptr) {
479 LOG(FATAL) << "Could not find method of intrinsic " << class_name << method_name << signature;
480 }
481 DCHECK_EQ(method->GetInvokeType(), invoke_type);
482 method->SetIntrinsic(static_cast<uint32_t>(intrinsic));
483}
484
Brian Carlstrom7940e442013-07-12 13:46:57 -0700485void CompilerDriver::CompileAll(jobject class_loader,
Brian Carlstrom45602482013-07-21 22:07:55 -0700486 const std::vector<const DexFile*>& dex_files,
Ian Rogers3d504072014-03-01 09:16:49 -0800487 TimingLogger* timings) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700488 DCHECK(!Runtime::Current()->IsStarted());
Andreas Gampeace0dc12016-01-20 13:33:13 -0800489
490 InitializeThreadPools();
491
Andreas Gampe8d295f82015-01-20 14:50:21 -0800492 VLOG(compiler) << "Before precompile " << GetMemoryUsageString(false);
Andreas Gampe740667a2015-09-15 17:55:06 -0700493 // Precompile:
494 // 1) Load image classes
495 // 2) Resolve all classes
496 // 3) Attempt to verify all classes
497 // 4) Attempt to initialize image classes, and trivially initialized classes
Andreas Gampeace0dc12016-01-20 13:33:13 -0800498 PreCompile(class_loader, dex_files, timings);
Nicolas Geoffray762869d2016-07-15 15:28:35 +0100499 if (IsBootImage()) {
500 // We don't need to setup the intrinsics for non boot image compilation, as
501 // those compilations will pick up a boot image that have the ArtMethod already
502 // set with the intrinsics flag.
503 ScopedObjectAccess soa(Thread::Current());
504#define OPTIMIZING_INTRINSICS(Name, InvokeType, NeedsEnvironmentOrCache, SideEffects, Exceptions, ClassName, MethodName, Signature) \
505 SetupIntrinsic(soa.Self(), Intrinsics::k##Name, InvokeType, ClassName, MethodName, Signature);
506#include "intrinsics_list.h"
507INTRINSICS_LIST(OPTIMIZING_INTRINSICS)
508#undef INTRINSICS_LIST
509 }
Andreas Gampe740667a2015-09-15 17:55:06 -0700510 // Compile:
511 // 1) Compile all classes and methods enabled for compilation. May fall back to dex-to-dex
512 // compilation.
513 if (!GetCompilerOptions().VerifyAtRuntime()) {
Andreas Gampeace0dc12016-01-20 13:33:13 -0800514 Compile(class_loader, dex_files, timings);
Andreas Gampe740667a2015-09-15 17:55:06 -0700515 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700516 if (dump_stats_) {
517 stats_->Dump();
518 }
Andreas Gampeace0dc12016-01-20 13:33:13 -0800519
520 FreeThreadPools();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700521}
522
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700523static optimizer::DexToDexCompilationLevel GetDexToDexCompilationLevel(
524 Thread* self, const CompilerDriver& driver, Handle<mirror::ClassLoader> class_loader,
525 const DexFile& dex_file, const DexFile::ClassDef& class_def)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700526 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800527 auto* const runtime = Runtime::Current();
Calin Juravleffc87072016-04-20 14:22:09 +0100528 if (runtime->UseJitCompilation() || driver.GetCompilerOptions().VerifyAtRuntime()) {
Mathieu Chartiere86deef2015-03-19 13:43:37 -0700529 // Verify at runtime shouldn't dex to dex since we didn't resolve of verify.
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700530 return optimizer::DexToDexCompilationLevel::kDontDexToDexCompile;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800531 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700532 const char* descriptor = dex_file.GetClassDescriptor(class_def);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800533 ClassLinker* class_linker = runtime->GetClassLinker();
Ian Rogers98379392014-02-24 16:53:16 -0800534 mirror::Class* klass = class_linker->FindClass(self, descriptor, class_loader);
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700535 if (klass == nullptr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700536 CHECK(self->IsExceptionPending());
537 self->ClearException();
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700538 return optimizer::DexToDexCompilationLevel::kDontDexToDexCompile;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700539 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700540 // DexToDex at the kOptimize level may introduce quickened opcodes, which replace symbolic
541 // references with actual offsets. We cannot re-verify such instructions.
542 //
543 // We store the verification information in the class status in the oat file, which the linker
544 // can validate (checksums) and use to skip load-time verification. It is thus safe to
545 // optimize when a class has been fully verified before.
546 if (klass->IsVerified()) {
Sebastien Hertz75021222013-07-16 18:34:50 +0200547 // Class is verified so we can enable DEX-to-DEX compilation for performance.
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700548 return optimizer::DexToDexCompilationLevel::kOptimize;
Sebastien Hertz75021222013-07-16 18:34:50 +0200549 } else if (klass->IsCompileTimeVerified()) {
550 // Class verification has soft-failed. Anyway, ensure at least correctness.
551 DCHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime);
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700552 return optimizer::DexToDexCompilationLevel::kRequired;
Sebastien Hertz75021222013-07-16 18:34:50 +0200553 } else {
554 // Class verification has failed: do not run DEX-to-DEX compilation.
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700555 return optimizer::DexToDexCompilationLevel::kDontDexToDexCompile;
556 }
557}
558
559static optimizer::DexToDexCompilationLevel GetDexToDexCompilationLevel(
560 Thread* self,
561 const CompilerDriver& driver,
562 jobject jclass_loader,
563 const DexFile& dex_file,
564 const DexFile::ClassDef& class_def) {
565 ScopedObjectAccess soa(self);
566 StackHandleScope<1> hs(soa.Self());
567 Handle<mirror::ClassLoader> class_loader(
Mathieu Chartier0795f232016-09-27 18:43:30 -0700568 hs.NewHandle(soa.Decode<mirror::ClassLoader>(jclass_loader)));
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700569 return GetDexToDexCompilationLevel(self, driver, class_loader, dex_file, class_def);
570}
571
572// Does the runtime for the InstructionSet provide an implementation returned by
573// GetQuickGenericJniStub allowing down calls that aren't compiled using a JNI compiler?
574static bool InstructionSetHasGenericJniStub(InstructionSet isa) {
575 switch (isa) {
576 case kArm:
577 case kArm64:
578 case kThumb2:
579 case kMips:
580 case kMips64:
581 case kX86:
582 case kX86_64: return true;
583 default: return false;
584 }
585}
586
587static void CompileMethod(Thread* self,
588 CompilerDriver* driver,
589 const DexFile::CodeItem* code_item,
590 uint32_t access_flags,
591 InvokeType invoke_type,
592 uint16_t class_def_idx,
593 uint32_t method_idx,
594 jobject class_loader,
595 const DexFile& dex_file,
596 optimizer::DexToDexCompilationLevel dex_to_dex_compilation_level,
Mathieu Chartier736b5602015-09-02 14:54:11 -0700597 bool compilation_enabled,
598 Handle<mirror::DexCache> dex_cache)
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700599 REQUIRES(!driver->compiled_methods_lock_) {
600 DCHECK(driver != nullptr);
601 CompiledMethod* compiled_method = nullptr;
602 uint64_t start_ns = kTimeCompileMethod ? NanoTime() : 0;
603 MethodReference method_ref(&dex_file, method_idx);
604
Vladimir Marko492a7fa2016-06-01 18:38:43 +0100605 if (driver->GetCurrentDexToDexMethods() != nullptr) {
606 // This is the second pass when we dex-to-dex compile previously marked methods.
607 // TODO: Refactor the compilation to avoid having to distinguish the two passes
608 // here. That should be done on a higher level. http://b/29089975
609 if (driver->GetCurrentDexToDexMethods()->IsBitSet(method_idx)) {
610 const VerifiedMethod* verified_method =
611 driver->GetVerificationResults()->GetVerifiedMethod(method_ref);
612 // Do not optimize if a VerifiedMethod is missing. SafeCast elision,
613 // for example, relies on it.
614 compiled_method = optimizer::ArtCompileDEX(
615 driver,
616 code_item,
617 access_flags,
618 invoke_type,
619 class_def_idx,
620 method_idx,
621 class_loader,
622 dex_file,
623 (verified_method != nullptr)
624 ? dex_to_dex_compilation_level
625 : optimizer::DexToDexCompilationLevel::kRequired);
626 }
627 } else if ((access_flags & kAccNative) != 0) {
Igor Murashkin9aa9fa22016-09-26 10:10:17 -0700628 const InstructionSet instruction_set = driver->GetInstructionSet();
629 const bool use_generic_jni =
630 // Are we extracting only and have support for generic JNI down calls?
631 (!driver->GetCompilerOptions().IsJniCompilationEnabled() &&
632 InstructionSetHasGenericJniStub(instruction_set)) ||
633 // Always punt to generic JNI for MIPS because of no support for @CriticalNative. b/31743474
634 (instruction_set == kMips || instruction_set == kMips64);
635 if (use_generic_jni) {
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700636 // Leaving this empty will trigger the generic JNI version
637 } else {
Igor Murashkin9d4b6da2016-07-29 09:51:58 -0700638 // Look-up the ArtMethod associated with this code_item (if any)
639 // -- It is later used to lookup any [optimization] annotations for this method.
640 ScopedObjectAccess soa(self);
641 StackHandleScope<1> hs(soa.Self());
642 Handle<mirror::ClassLoader> class_loader_handle(hs.NewHandle(
Mathieu Chartier0795f232016-09-27 18:43:30 -0700643 soa.Decode<mirror::ClassLoader>(class_loader)));
Igor Murashkin9d4b6da2016-07-29 09:51:58 -0700644
645 // TODO: Lookup annotation from DexFile directly without resolving method.
646 ArtMethod* method =
647 Runtime::Current()->GetClassLinker()->ResolveMethod<ClassLinker::kNoICCECheckForCache>(
648 dex_file,
649 method_idx,
650 dex_cache,
651 class_loader_handle,
652 /* referrer */ nullptr,
653 invoke_type);
654
Igor Murashkin367f3dd2016-09-01 17:00:24 -0700655 // Query any JNI optimization annotations such as @FastNative or @CriticalNative.
656 Compiler::JniOptimizationFlags optimization_flags = Compiler::kNone;
657 if (UNLIKELY(method == nullptr)) {
Igor Murashkin9d4b6da2016-07-29 09:51:58 -0700658 // Failed method resolutions happen very rarely, e.g. ancestor class cannot be resolved.
659 DCHECK(self->IsExceptionPending());
660 self->ClearException();
Igor Murashkin367f3dd2016-09-01 17:00:24 -0700661 } else if (method->IsAnnotatedWithFastNative()) {
662 // TODO: Will no longer need this CHECK once we have verifier checking this.
663 CHECK(!method->IsAnnotatedWithCriticalNative());
664 optimization_flags = Compiler::kFastNative;
665 } else if (method->IsAnnotatedWithCriticalNative()) {
666 // TODO: Will no longer need this CHECK once we have verifier checking this.
667 CHECK(!method->IsAnnotatedWithFastNative());
668 optimization_flags = Compiler::kCriticalNative;
Igor Murashkin9d4b6da2016-07-29 09:51:58 -0700669 }
670
Igor Murashkin9d4b6da2016-07-29 09:51:58 -0700671 compiled_method = driver->GetCompiler()->JniCompile(access_flags,
672 method_idx,
673 dex_file,
674 optimization_flags);
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700675 CHECK(compiled_method != nullptr);
676 }
677 } else if ((access_flags & kAccAbstract) != 0) {
678 // Abstract methods don't have code.
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000679 } else {
Andreas Gampe0760a812015-08-26 17:12:51 -0700680 const VerifiedMethod* verified_method =
681 driver->GetVerificationResults()->GetVerifiedMethod(method_ref);
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700682 bool compile = compilation_enabled &&
683 // Basic checks, e.g., not <clinit>.
684 driver->GetVerificationResults()
685 ->IsCandidateForCompilation(method_ref, access_flags) &&
686 // Did not fail to create VerifiedMethod metadata.
Andreas Gampe0760a812015-08-26 17:12:51 -0700687 verified_method != nullptr &&
688 // Do not have failures that should punt to the interpreter.
689 !verified_method->HasRuntimeThrow() &&
690 (verified_method->GetEncounteredVerificationFailures() &
Andreas Gampea727e372015-08-25 09:22:37 -0700691 (verifier::VERIFY_ERROR_FORCE_INTERPRETER | verifier::VERIFY_ERROR_LOCKING)) == 0 &&
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700692 // Is eligable for compilation by methods-to-compile filter.
Calin Juravle226501b2015-12-11 14:41:31 +0000693 driver->IsMethodToCompile(method_ref) &&
694 driver->ShouldCompileBasedOnProfile(method_ref);
695
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700696 if (compile) {
697 // NOTE: if compiler declines to compile this method, it will return null.
698 compiled_method = driver->GetCompiler()->Compile(code_item, access_flags, invoke_type,
699 class_def_idx, method_idx, class_loader,
Mathieu Chartier736b5602015-09-02 14:54:11 -0700700 dex_file, dex_cache);
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700701 }
702 if (compiled_method == nullptr &&
703 dex_to_dex_compilation_level != optimizer::DexToDexCompilationLevel::kDontDexToDexCompile) {
Vladimir Marko492a7fa2016-06-01 18:38:43 +0100704 DCHECK(!Runtime::Current()->UseJitCompilation());
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700705 // TODO: add a command-line option to disable DEX-to-DEX compilation ?
Vladimir Marko492a7fa2016-06-01 18:38:43 +0100706 driver->MarkForDexToDexCompilation(self, method_ref);
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700707 }
708 }
709 if (kTimeCompileMethod) {
710 uint64_t duration_ns = NanoTime() - start_ns;
711 if (duration_ns > MsToNs(driver->GetCompiler()->GetMaximumCompilationTimeBeforeWarning())) {
712 LOG(WARNING) << "Compilation of " << PrettyMethod(method_idx, dex_file)
713 << " took " << PrettyDuration(duration_ns);
714 }
715 }
716
717 if (compiled_method != nullptr) {
718 // Count non-relative linker patches.
719 size_t non_relative_linker_patch_count = 0u;
720 for (const LinkerPatch& patch : compiled_method->GetPatches()) {
721 if (!patch.IsPcRelative()) {
722 ++non_relative_linker_patch_count;
723 }
724 }
725 bool compile_pic = driver->GetCompilerOptions().GetCompilePic(); // Off by default
726 // When compiling with PIC, there should be zero non-relative linker patches
727 CHECK(!compile_pic || non_relative_linker_patch_count == 0u);
728
729 driver->AddCompiledMethod(method_ref, compiled_method, non_relative_linker_patch_count);
730 }
731
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700732 if (self->IsExceptionPending()) {
733 ScopedObjectAccess soa(self);
734 LOG(FATAL) << "Unexpected exception compiling: " << PrettyMethod(method_idx, dex_file) << "\n"
735 << self->GetException()->Dump();
Sebastien Hertz75021222013-07-16 18:34:50 +0200736 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700737}
738
Mathieu Chartiere401d142015-04-22 13:56:20 -0700739void CompilerDriver::CompileOne(Thread* self, ArtMethod* method, TimingLogger* timings) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700740 DCHECK(!Runtime::Current()->IsStarted());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700741 jobject jclass_loader;
742 const DexFile* dex_file;
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700743 uint16_t class_def_idx;
Ian Rogersef7d42f2014-01-06 12:55:46 -0800744 uint32_t method_idx = method->GetDexMethodIndex();
745 uint32_t access_flags = method->GetAccessFlags();
746 InvokeType invoke_type = method->GetInvokeType();
Mathieu Chartier736b5602015-09-02 14:54:11 -0700747 StackHandleScope<1> hs(self);
748 Handle<mirror::DexCache> dex_cache(hs.NewHandle(method->GetDexCache()));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700749 {
750 ScopedObjectAccessUnchecked soa(self);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800751 ScopedLocalRef<jobject> local_class_loader(
752 soa.Env(), soa.AddLocalReference<jobject>(method->GetDeclaringClass()->GetClassLoader()));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700753 jclass_loader = soa.Env()->NewGlobalRef(local_class_loader.get());
754 // Find the dex_file
Mathieu Chartierbfd9a432014-05-21 17:43:44 -0700755 dex_file = method->GetDexFile();
756 class_def_idx = method->GetClassDefIndex();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700757 }
Ian Rogersef7d42f2014-01-06 12:55:46 -0800758 const DexFile::CodeItem* code_item = dex_file->GetCodeItem(method->GetCodeItemOffset());
Mathieu Chartier736b5602015-09-02 14:54:11 -0700759
760 // Go to native so that we don't block GC during compilation.
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700761 ScopedThreadSuspension sts(self, kNative);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700762
763 std::vector<const DexFile*> dex_files;
764 dex_files.push_back(dex_file);
765
Andreas Gampeace0dc12016-01-20 13:33:13 -0800766 InitializeThreadPools();
767
768 PreCompile(jclass_loader, dex_files, timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700769
Brian Carlstrom7940e442013-07-12 13:46:57 -0700770 // Can we run DEX-to-DEX compiler on this class ?
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700771 optimizer::DexToDexCompilationLevel dex_to_dex_compilation_level =
772 GetDexToDexCompilationLevel(self,
773 *this,
774 jclass_loader,
775 *dex_file,
776 dex_file->GetClassDef(class_def_idx));
777
Vladimir Marko492a7fa2016-06-01 18:38:43 +0100778 DCHECK(current_dex_to_dex_methods_ == nullptr);
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700779 CompileMethod(self,
780 this,
781 code_item,
782 access_flags,
783 invoke_type,
784 class_def_idx,
785 method_idx,
786 jclass_loader,
787 *dex_file,
788 dex_to_dex_compilation_level,
Mathieu Chartier736b5602015-09-02 14:54:11 -0700789 true,
790 dex_cache);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700791
Vladimir Marko492a7fa2016-06-01 18:38:43 +0100792 ArrayRef<DexFileMethodSet> dex_to_dex_references;
793 {
794 // From this point on, we shall not modify dex_to_dex_references_, so
795 // just grab a reference to it that we use without holding the mutex.
796 MutexLock lock(Thread::Current(), dex_to_dex_references_lock_);
797 dex_to_dex_references = ArrayRef<DexFileMethodSet>(dex_to_dex_references_);
798 }
799 if (!dex_to_dex_references.empty()) {
800 DCHECK_EQ(dex_to_dex_references.size(), 1u);
801 DCHECK(&dex_to_dex_references[0].GetDexFile() == dex_file);
802 current_dex_to_dex_methods_ = &dex_to_dex_references.front().GetMethodIndexes();
803 DCHECK(current_dex_to_dex_methods_->IsBitSet(method_idx));
804 DCHECK_EQ(current_dex_to_dex_methods_->NumSetBits(), 1u);
805 CompileMethod(self,
806 this,
807 code_item,
808 access_flags,
809 invoke_type,
810 class_def_idx,
811 method_idx,
812 jclass_loader,
813 *dex_file,
814 dex_to_dex_compilation_level,
815 true,
816 dex_cache);
817 current_dex_to_dex_methods_ = nullptr;
818 }
819
Andreas Gampeace0dc12016-01-20 13:33:13 -0800820 FreeThreadPools();
821
Brian Carlstrom7940e442013-07-12 13:46:57 -0700822 self->GetJniEnv()->DeleteGlobalRef(jclass_loader);
Mathieu Chartier2535abe2015-02-17 10:38:49 -0800823}
824
Andreas Gampeace0dc12016-01-20 13:33:13 -0800825void CompilerDriver::Resolve(jobject class_loader,
826 const std::vector<const DexFile*>& dex_files,
827 TimingLogger* timings) {
828 // Resolution allocates classes and needs to run single-threaded to be deterministic.
829 bool force_determinism = GetCompilerOptions().IsForceDeterminism();
830 ThreadPool* resolve_thread_pool = force_determinism
831 ? single_thread_pool_.get()
832 : parallel_thread_pool_.get();
833 size_t resolve_thread_count = force_determinism ? 1U : parallel_thread_count_;
834
Brian Carlstrom7940e442013-07-12 13:46:57 -0700835 for (size_t i = 0; i != dex_files.size(); ++i) {
836 const DexFile* dex_file = dex_files[i];
Kenny Rootd5185342014-05-13 14:47:05 -0700837 CHECK(dex_file != nullptr);
Andreas Gampeace0dc12016-01-20 13:33:13 -0800838 ResolveDexFile(class_loader,
839 *dex_file,
840 dex_files,
841 resolve_thread_pool,
842 resolve_thread_count,
843 timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700844 }
845}
846
Andreas Gampeace0dc12016-01-20 13:33:13 -0800847// Resolve const-strings in the code. Done to have deterministic allocation behavior. Right now
848// this is single-threaded for simplicity.
849// TODO: Collect the relevant string indices in parallel, then allocate them sequentially in a
850// stable order.
851
852static void ResolveConstStrings(CompilerDriver* driver,
853 const DexFile& dex_file,
854 const DexFile::CodeItem* code_item) {
855 if (code_item == nullptr) {
856 // Abstract or native method.
857 return;
858 }
859
860 const uint16_t* code_ptr = code_item->insns_;
861 const uint16_t* code_end = code_item->insns_ + code_item->insns_size_in_code_units_;
862
863 while (code_ptr < code_end) {
864 const Instruction* inst = Instruction::At(code_ptr);
865 switch (inst->Opcode()) {
866 case Instruction::CONST_STRING: {
867 uint32_t string_index = inst->VRegB_21c();
868 driver->CanAssumeStringIsPresentInDexCache(dex_file, string_index);
869 break;
870 }
871 case Instruction::CONST_STRING_JUMBO: {
872 uint32_t string_index = inst->VRegB_31c();
873 driver->CanAssumeStringIsPresentInDexCache(dex_file, string_index);
874 break;
875 }
876
877 default:
878 break;
879 }
880
881 code_ptr += inst->SizeInCodeUnits();
882 }
883}
884
885static void ResolveConstStrings(CompilerDriver* driver,
886 const std::vector<const DexFile*>& dex_files,
887 TimingLogger* timings) {
888 for (const DexFile* dex_file : dex_files) {
889 TimingLogger::ScopedTiming t("Resolve const-string Strings", timings);
890
891 size_t class_def_count = dex_file->NumClassDefs();
892 for (size_t class_def_index = 0; class_def_index < class_def_count; ++class_def_index) {
893 const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_index);
894
895 const uint8_t* class_data = dex_file->GetClassData(class_def);
896 if (class_data == nullptr) {
897 // empty class, probably a marker interface
898 continue;
899 }
900
901 ClassDataItemIterator it(*dex_file, class_data);
902 // Skip fields
903 while (it.HasNextStaticField()) {
904 it.Next();
905 }
906 while (it.HasNextInstanceField()) {
907 it.Next();
908 }
909
910 bool compilation_enabled = driver->IsClassToCompile(
911 dex_file->StringByTypeIdx(class_def.class_idx_));
912 if (!compilation_enabled) {
913 // Compilation is skipped, do not resolve const-string in code of this class.
914 // TODO: Make sure that inlining honors this.
915 continue;
916 }
917
918 // Direct methods.
919 int64_t previous_direct_method_idx = -1;
920 while (it.HasNextDirectMethod()) {
921 uint32_t method_idx = it.GetMemberIndex();
922 if (method_idx == previous_direct_method_idx) {
923 // smali can create dex files with two encoded_methods sharing the same method_idx
924 // http://code.google.com/p/smali/issues/detail?id=119
925 it.Next();
926 continue;
927 }
928 previous_direct_method_idx = method_idx;
929 ResolveConstStrings(driver, *dex_file, it.GetMethodCodeItem());
930 it.Next();
931 }
932 // Virtual methods.
933 int64_t previous_virtual_method_idx = -1;
934 while (it.HasNextVirtualMethod()) {
935 uint32_t method_idx = it.GetMemberIndex();
936 if (method_idx == previous_virtual_method_idx) {
937 // smali can create dex files with two encoded_methods sharing the same method_idx
938 // http://code.google.com/p/smali/issues/detail?id=119
939 it.Next();
940 continue;
941 }
942 previous_virtual_method_idx = method_idx;
943 ResolveConstStrings(driver, *dex_file, it.GetMethodCodeItem());
944 it.Next();
945 }
946 DCHECK(!it.HasNext());
947 }
948 }
949}
950
951inline void CompilerDriver::CheckThreadPools() {
952 DCHECK(parallel_thread_pool_ != nullptr);
953 DCHECK(single_thread_pool_ != nullptr);
954}
955
956void CompilerDriver::PreCompile(jobject class_loader,
957 const std::vector<const DexFile*>& dex_files,
958 TimingLogger* timings) {
959 CheckThreadPools();
960
Brian Carlstrom7940e442013-07-12 13:46:57 -0700961 LoadImageClasses(timings);
Andreas Gampe8d295f82015-01-20 14:50:21 -0800962 VLOG(compiler) << "LoadImageClasses: " << GetMemoryUsageString(false);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700963
Mathieu Chartiere86deef2015-03-19 13:43:37 -0700964 const bool verification_enabled = compiler_options_->IsVerificationEnabled();
965 const bool never_verify = compiler_options_->NeverVerify();
Mathieu Chartiera8077802016-03-16 19:08:31 -0700966 const bool verify_only_profile = compiler_options_->VerifyOnlyProfile();
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700967
Mathieu Chartiere86deef2015-03-19 13:43:37 -0700968 // We need to resolve for never_verify since it needs to run dex to dex to add the
969 // RETURN_VOID_NO_BARRIER.
Mathieu Chartiera8077802016-03-16 19:08:31 -0700970 // Let the verifier resolve as needed for the verify_only_profile case.
971 if ((never_verify || verification_enabled) && !verify_only_profile) {
Andreas Gampeace0dc12016-01-20 13:33:13 -0800972 Resolve(class_loader, dex_files, timings);
Mathieu Chartiere86deef2015-03-19 13:43:37 -0700973 VLOG(compiler) << "Resolve: " << GetMemoryUsageString(false);
974 }
975
976 if (never_verify) {
Mathieu Chartierab972ef2014-12-03 17:38:22 -0800977 VLOG(compiler) << "Verify none mode specified, skipping verification.";
Andreas Gampeace0dc12016-01-20 13:33:13 -0800978 SetVerified(class_loader, dex_files, timings);
Mathieu Chartiere86deef2015-03-19 13:43:37 -0700979 }
980
981 if (!verification_enabled) {
Jeff Hao4a200f52014-04-01 14:58:49 -0700982 return;
983 }
984
Andreas Gampeace0dc12016-01-20 13:33:13 -0800985 if (GetCompilerOptions().IsForceDeterminism() && IsBootImage()) {
986 // Resolve strings from const-string. Do this now to have a deterministic image.
987 ResolveConstStrings(this, dex_files, timings);
988 VLOG(compiler) << "Resolve const-strings: " << GetMemoryUsageString(false);
989 }
990
991 Verify(class_loader, dex_files, timings);
Andreas Gampe8d295f82015-01-20 14:50:21 -0800992 VLOG(compiler) << "Verify: " << GetMemoryUsageString(false);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700993
Andreas Gampe6cf49e52015-03-05 13:08:45 -0800994 if (had_hard_verifier_failure_ && GetCompilerOptions().AbortOnHardVerifierFailure()) {
995 LOG(FATAL) << "Had a hard failure verifying all classes, and was asked to abort in such "
996 << "situations. Please check the log.";
997 }
998
Andreas Gampeace0dc12016-01-20 13:33:13 -0800999 InitializeClasses(class_loader, dex_files, timings);
Andreas Gampe8d295f82015-01-20 14:50:21 -08001000 VLOG(compiler) << "InitializeClasses: " << GetMemoryUsageString(false);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001001
1002 UpdateImageClasses(timings);
Andreas Gampe8d295f82015-01-20 14:50:21 -08001003 VLOG(compiler) << "UpdateImageClasses: " << GetMemoryUsageString(false);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001004}
1005
Ian Rogersdfb325e2013-10-30 01:00:44 -07001006bool CompilerDriver::IsImageClass(const char* descriptor) const {
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08001007 if (image_classes_ != nullptr) {
1008 // If we have a set of image classes, use those.
Ian Rogersdfb325e2013-10-30 01:00:44 -07001009 return image_classes_->find(descriptor) != image_classes_->end();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001010 }
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08001011 // No set of image classes, assume we include all the classes.
1012 // NOTE: Currently only reachable from InitImageMethodVisitor for the app image case.
1013 return !IsBootImage();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001014}
1015
Andreas Gampe4bf3ae92014-11-11 13:28:29 -08001016bool CompilerDriver::IsClassToCompile(const char* descriptor) const {
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001017 if (classes_to_compile_ == nullptr) {
1018 return true;
1019 }
1020 return classes_to_compile_->find(descriptor) != classes_to_compile_->end();
Andreas Gampe4bf3ae92014-11-11 13:28:29 -08001021}
1022
Andreas Gampe70bef0d2015-04-15 02:37:28 -07001023bool CompilerDriver::IsMethodToCompile(const MethodReference& method_ref) const {
Andreas Gampe70bef0d2015-04-15 02:37:28 -07001024 if (methods_to_compile_ == nullptr) {
1025 return true;
1026 }
1027
1028 std::string tmp = PrettyMethod(method_ref.dex_method_index, *method_ref.dex_file, true);
1029 return methods_to_compile_->find(tmp.c_str()) != methods_to_compile_->end();
1030}
1031
Calin Juravle226501b2015-12-11 14:41:31 +00001032bool CompilerDriver::ShouldCompileBasedOnProfile(const MethodReference& method_ref) const {
1033 if (profile_compilation_info_ == nullptr) {
1034 // If we miss profile information it means that we don't do a profile guided compilation.
1035 // Return true, and let the other filters decide if the method should be compiled.
1036 return true;
1037 }
1038 bool result = profile_compilation_info_->ContainsMethod(method_ref);
1039
1040 if (kDebugProfileGuidedCompilation) {
1041 LOG(INFO) << "[ProfileGuidedCompilation] "
1042 << (result ? "Compiled" : "Skipped") << " method:"
1043 << PrettyMethod(method_ref.dex_method_index, *method_ref.dex_file, true);
1044 }
1045 return result;
1046}
1047
Mathieu Chartiera8077802016-03-16 19:08:31 -07001048bool CompilerDriver::ShouldVerifyClassBasedOnProfile(const DexFile& dex_file,
1049 uint16_t class_idx) const {
1050 if (!compiler_options_->VerifyOnlyProfile()) {
1051 // No profile, verify everything.
1052 return true;
1053 }
1054 DCHECK(profile_compilation_info_ != nullptr);
1055 bool result = profile_compilation_info_->ContainsClass(dex_file, class_idx);
1056 if (kDebugProfileGuidedCompilation) {
1057 LOG(INFO) << "[ProfileGuidedCompilation] "
1058 << (result ? "Verified" : "Skipped") << " method:"
1059 << dex_file.GetClassDescriptor(dex_file.GetClassDef(class_idx));
1060 }
1061 return result;
1062}
1063
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001064class ResolveCatchBlockExceptionsClassVisitor : public ClassVisitor {
1065 public:
Chih-Hung Hsieh471118e2016-04-29 14:27:41 -07001066 explicit ResolveCatchBlockExceptionsClassVisitor(
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001067 std::set<std::pair<uint16_t, const DexFile*>>& exceptions_to_resolve)
1068 : exceptions_to_resolve_(exceptions_to_resolve) {}
1069
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001070 virtual bool operator()(mirror::Class* c) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere4275c02015-08-06 15:34:15 -07001071 const auto pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
Alex Lighte64300b2015-12-15 15:02:47 -08001072 for (auto& m : c->GetMethods(pointer_size)) {
Vladimir Marko05792b92015-08-03 11:56:49 +01001073 ResolveExceptionsForMethod(&m, pointer_size);
Mathieu Chartiere4275c02015-08-06 15:34:15 -07001074 }
1075 return true;
1076 }
1077
1078 private:
Andreas Gampe542451c2016-07-26 09:02:02 -07001079 void ResolveExceptionsForMethod(ArtMethod* method_handle, PointerSize pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001080 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001081 const DexFile::CodeItem* code_item = method_handle->GetCodeItem();
1082 if (code_item == nullptr) {
1083 return; // native or abstract method
Brian Carlstrom7940e442013-07-12 13:46:57 -07001084 }
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001085 if (code_item->tries_size_ == 0) {
1086 return; // nothing to process
1087 }
1088 const uint8_t* encoded_catch_handler_list = DexFile::GetCatchHandlerData(*code_item, 0);
1089 size_t num_encoded_catch_handlers = DecodeUnsignedLeb128(&encoded_catch_handler_list);
1090 for (size_t i = 0; i < num_encoded_catch_handlers; i++) {
1091 int32_t encoded_catch_handler_size = DecodeSignedLeb128(&encoded_catch_handler_list);
1092 bool has_catch_all = false;
1093 if (encoded_catch_handler_size <= 0) {
1094 encoded_catch_handler_size = -encoded_catch_handler_size;
1095 has_catch_all = true;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001096 }
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001097 for (int32_t j = 0; j < encoded_catch_handler_size; j++) {
1098 uint16_t encoded_catch_handler_handlers_type_idx =
1099 DecodeUnsignedLeb128(&encoded_catch_handler_list);
1100 // Add to set of types to resolve if not already in the dex cache resolved types
Vladimir Marko05792b92015-08-03 11:56:49 +01001101 if (!method_handle->IsResolvedTypeIdx(encoded_catch_handler_handlers_type_idx,
1102 pointer_size)) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001103 exceptions_to_resolve_.emplace(encoded_catch_handler_handlers_type_idx,
1104 method_handle->GetDexFile());
1105 }
1106 // ignore address associated with catch handler
1107 DecodeUnsignedLeb128(&encoded_catch_handler_list);
1108 }
1109 if (has_catch_all) {
1110 // ignore catch all address
1111 DecodeUnsignedLeb128(&encoded_catch_handler_list);
1112 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001113 }
1114 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001115
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001116 std::set<std::pair<uint16_t, const DexFile*>>& exceptions_to_resolve_;
1117};
1118
1119class RecordImageClassesVisitor : public ClassVisitor {
1120 public:
1121 explicit RecordImageClassesVisitor(std::unordered_set<std::string>* image_classes)
1122 : image_classes_(image_classes) {}
1123
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001124 bool operator()(mirror::Class* klass) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001125 std::string temp;
1126 image_classes_->insert(klass->GetDescriptor(&temp));
1127 return true;
1128 }
1129
1130 private:
1131 std::unordered_set<std::string>* const image_classes_;
1132};
Brian Carlstrom7940e442013-07-12 13:46:57 -07001133
1134// Make a list of descriptors for classes to include in the image
Mathieu Chartier90443472015-07-16 20:32:27 -07001135void CompilerDriver::LoadImageClasses(TimingLogger* timings) {
Kenny Rootd5185342014-05-13 14:47:05 -07001136 CHECK(timings != nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001137 if (!IsBootImage()) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001138 return;
1139 }
1140
Mathieu Chartierf5997b42014-06-20 10:37:54 -07001141 TimingLogger::ScopedTiming t("LoadImageClasses", timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001142 // Make a first class to load all classes explicitly listed in the file
1143 Thread* self = Thread::Current();
1144 ScopedObjectAccess soa(self);
1145 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Kenny Rootd5185342014-05-13 14:47:05 -07001146 CHECK(image_classes_.get() != nullptr);
Mathieu Chartier02e25112013-08-14 16:14:24 -07001147 for (auto it = image_classes_->begin(), end = image_classes_->end(); it != end;) {
Vladimir Markoe9c36b32013-11-21 15:49:16 +00001148 const std::string& descriptor(*it);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001149 StackHandleScope<1> hs(self);
1150 Handle<mirror::Class> klass(
1151 hs.NewHandle(class_linker->FindSystemClass(self, descriptor.c_str())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001152 if (klass.Get() == nullptr) {
Ian Rogerse6bb3b22013-08-19 21:51:45 -07001153 VLOG(compiler) << "Failed to find class " << descriptor;
Vladimir Markoe9c36b32013-11-21 15:49:16 +00001154 image_classes_->erase(it++);
Ian Rogersa436fde2013-08-27 23:34:06 -07001155 self->ClearException();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001156 } else {
1157 ++it;
1158 }
1159 }
1160
1161 // Resolve exception classes referenced by the loaded classes. The catch logic assumes
1162 // exceptions are resolved by the verifier when there is a catch block in an interested method.
1163 // Do this here so that exception classes appear to have been specified image classes.
Ian Rogers700a4022014-05-19 16:49:03 -07001164 std::set<std::pair<uint16_t, const DexFile*>> unresolved_exception_types;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001165 StackHandleScope<1> hs(self);
1166 Handle<mirror::Class> java_lang_Throwable(
1167 hs.NewHandle(class_linker->FindSystemClass(self, "Ljava/lang/Throwable;")));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001168 do {
1169 unresolved_exception_types.clear();
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001170 ResolveCatchBlockExceptionsClassVisitor visitor(unresolved_exception_types);
1171 class_linker->VisitClasses(&visitor);
Mathieu Chartier02e25112013-08-14 16:14:24 -07001172 for (const std::pair<uint16_t, const DexFile*>& exception_type : unresolved_exception_types) {
1173 uint16_t exception_type_idx = exception_type.first;
1174 const DexFile* dex_file = exception_type.second;
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001175 StackHandleScope<2> hs2(self);
Mathieu Chartierf284d442016-06-02 11:48:30 -07001176 Handle<mirror::DexCache> dex_cache(hs2.NewHandle(class_linker->RegisterDexFile(*dex_file,
1177 nullptr)));
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001178 Handle<mirror::Class> klass(hs2.NewHandle(
Mathieu Chartier9865bde2015-12-21 09:58:16 -08001179 class_linker->ResolveType(*dex_file,
1180 exception_type_idx,
1181 dex_cache,
1182 ScopedNullHandle<mirror::ClassLoader>())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001183 if (klass.Get() == nullptr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001184 const DexFile::TypeId& type_id = dex_file->GetTypeId(exception_type_idx);
1185 const char* descriptor = dex_file->GetTypeDescriptor(type_id);
1186 LOG(FATAL) << "Failed to resolve class " << descriptor;
1187 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001188 DCHECK(java_lang_Throwable->IsAssignableFrom(klass.Get()));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001189 }
1190 // Resolving exceptions may load classes that reference more exceptions, iterate until no
1191 // more are found
1192 } while (!unresolved_exception_types.empty());
1193
1194 // We walk the roots looking for classes so that we'll pick up the
1195 // above classes plus any classes them depend on such super
1196 // classes, interfaces, and the required ClassLinker roots.
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001197 RecordImageClassesVisitor visitor(image_classes_.get());
1198 class_linker->VisitClasses(&visitor);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001199
1200 CHECK_NE(image_classes_->size(), 0U);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001201}
1202
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001203static void MaybeAddToImageClasses(Handle<mirror::Class> c,
1204 std::unordered_set<std::string>* image_classes)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001205 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07001206 Thread* self = Thread::Current();
1207 StackHandleScope<1> hs(self);
1208 // Make a copy of the handle so that we don't clobber it doing Assign.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07001209 MutableHandle<mirror::Class> klass(hs.NewHandle(c.Get()));
Ian Rogers1ff3c982014-08-12 02:30:58 -07001210 std::string temp;
Andreas Gampe542451c2016-07-26 09:02:02 -07001211 const PointerSize pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001212 while (!klass->IsObjectClass()) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07001213 const char* descriptor = klass->GetDescriptor(&temp);
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001214 std::pair<std::unordered_set<std::string>::iterator, bool> result =
1215 image_classes->insert(descriptor);
Ian Rogers1ff3c982014-08-12 02:30:58 -07001216 if (!result.second) { // Previously inserted.
1217 break;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001218 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07001219 VLOG(compiler) << "Adding " << descriptor << " to image classes";
Mathieu Chartierf8322842014-05-16 10:59:25 -07001220 for (size_t i = 0; i < klass->NumDirectInterfaces(); ++i) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001221 StackHandleScope<1> hs2(self);
1222 MaybeAddToImageClasses(hs2.NewHandle(mirror::Class::GetDirectInterface(self, klass, i)),
Mathieu Chartierf8322842014-05-16 10:59:25 -07001223 image_classes);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001224 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001225 for (auto& m : c->GetVirtualMethods(pointer_size)) {
Alex Light36121492016-02-22 13:43:29 -08001226 StackHandleScope<1> hs2(self);
1227 MaybeAddToImageClasses(hs2.NewHandle(m.GetDeclaringClass()), image_classes);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001228 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001229 if (klass->IsArrayClass()) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001230 StackHandleScope<1> hs2(self);
1231 MaybeAddToImageClasses(hs2.NewHandle(klass->GetComponentType()), image_classes);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001232 }
Mathieu Chartierf8322842014-05-16 10:59:25 -07001233 klass.Assign(klass->GetSuperClass());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001234 }
1235}
1236
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001237// Keeps all the data for the update together. Also doubles as the reference visitor.
1238// Note: we can use object pointers because we suspend all threads.
1239class ClinitImageUpdate {
1240 public:
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001241 static ClinitImageUpdate* Create(std::unordered_set<std::string>* image_class_descriptors,
1242 Thread* self, ClassLinker* linker, std::string* error_msg) {
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001243 std::unique_ptr<ClinitImageUpdate> res(new ClinitImageUpdate(image_class_descriptors, self,
1244 linker));
Mathieu Chartiere401d142015-04-22 13:56:20 -07001245 if (res->dex_cache_class_ == nullptr) {
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001246 *error_msg = "Could not find DexCache class.";
1247 return nullptr;
1248 }
1249
1250 return res.release();
1251 }
1252
1253 ~ClinitImageUpdate() {
1254 // Allow others to suspend again.
1255 self_->EndAssertNoThreadSuspension(old_cause_);
1256 }
1257
1258 // Visitor for VisitReferences.
1259 void operator()(mirror::Object* object, MemberOffset field_offset, bool /* is_static */) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001260 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001261 mirror::Object* ref = object->GetFieldObject<mirror::Object>(field_offset);
1262 if (ref != nullptr) {
1263 VisitClinitClassesObject(ref);
1264 }
1265 }
1266
1267 // java.lang.Reference visitor for VisitReferences.
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001268 void operator()(mirror::Class* klass ATTRIBUTE_UNUSED, mirror::Reference* ref ATTRIBUTE_UNUSED)
1269 const {}
1270
1271 // Ignore class native roots.
1272 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED)
1273 const {}
1274 void VisitRoot(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED) const {}
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001275
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001276 void Walk() REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001277 // Use the initial classes as roots for a search.
1278 for (mirror::Class* klass_root : image_classes_) {
1279 VisitClinitClassesObject(klass_root);
1280 }
1281 }
1282
1283 private:
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001284 class FindImageClassesVisitor : public ClassVisitor {
1285 public:
1286 explicit FindImageClassesVisitor(ClinitImageUpdate* data) : data_(data) {}
1287
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001288 bool operator()(mirror::Class* klass) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001289 std::string temp;
1290 const char* name = klass->GetDescriptor(&temp);
1291 if (data_->image_class_descriptors_->find(name) != data_->image_class_descriptors_->end()) {
1292 data_->image_classes_.push_back(klass);
1293 } else {
1294 // Check whether it is initialized and has a clinit. They must be kept, too.
1295 if (klass->IsInitialized() && klass->FindClassInitializer(
1296 Runtime::Current()->GetClassLinker()->GetImagePointerSize()) != nullptr) {
1297 data_->image_classes_.push_back(klass);
1298 }
1299 }
1300 return true;
1301 }
1302
1303 private:
1304 ClinitImageUpdate* const data_;
1305 };
1306
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001307 ClinitImageUpdate(std::unordered_set<std::string>* image_class_descriptors, Thread* self,
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001308 ClassLinker* linker)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001309 REQUIRES_SHARED(Locks::mutator_lock_) :
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001310 image_class_descriptors_(image_class_descriptors), self_(self) {
1311 CHECK(linker != nullptr);
1312 CHECK(image_class_descriptors != nullptr);
1313
1314 // Make sure nobody interferes with us.
1315 old_cause_ = self->StartAssertNoThreadSuspension("Boot image closure");
1316
1317 // Find the interesting classes.
Andreas Gampedc8b63c2014-12-02 14:39:52 -08001318 dex_cache_class_ = linker->LookupClass(self, "Ljava/lang/DexCache;",
1319 ComputeModifiedUtf8Hash("Ljava/lang/DexCache;"), nullptr);
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001320
1321 // Find all the already-marked classes.
1322 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001323 FindImageClassesVisitor visitor(this);
1324 linker->VisitClasses(&visitor);
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001325 }
1326
1327 void VisitClinitClassesObject(mirror::Object* object) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001328 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001329 DCHECK(object != nullptr);
1330 if (marked_objects_.find(object) != marked_objects_.end()) {
1331 // Already processed.
1332 return;
1333 }
1334
1335 // Mark it.
1336 marked_objects_.insert(object);
1337
1338 if (object->IsClass()) {
1339 // If it is a class, add it.
1340 StackHandleScope<1> hs(self_);
1341 MaybeAddToImageClasses(hs.NewHandle(object->AsClass()), image_class_descriptors_);
1342 } else {
1343 // Else visit the object's class.
1344 VisitClinitClassesObject(object->GetClass());
1345 }
1346
Mathieu Chartiere401d142015-04-22 13:56:20 -07001347 // If it is not a DexCache, visit all references.
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001348 mirror::Class* klass = object->GetClass();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001349 if (klass != dex_cache_class_) {
Mathieu Chartier059ef3d2015-08-18 13:54:21 -07001350 object->VisitReferences(*this, *this);
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001351 }
1352 }
1353
1354 mutable std::unordered_set<mirror::Object*> marked_objects_;
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001355 std::unordered_set<std::string>* const image_class_descriptors_;
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001356 std::vector<mirror::Class*> image_classes_;
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001357 const mirror::Class* dex_cache_class_;
1358 Thread* const self_;
1359 const char* old_cause_;
1360
1361 DISALLOW_COPY_AND_ASSIGN(ClinitImageUpdate);
1362};
Brian Carlstrom7940e442013-07-12 13:46:57 -07001363
Ian Rogers3d504072014-03-01 09:16:49 -08001364void CompilerDriver::UpdateImageClasses(TimingLogger* timings) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001365 if (IsBootImage()) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07001366 TimingLogger::ScopedTiming t("UpdateImageClasses", timings);
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001367
Mathieu Chartier4f55e222015-09-04 13:26:21 -07001368 Runtime* runtime = Runtime::Current();
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001369
1370 // Suspend all threads.
Mathieu Chartier4f55e222015-09-04 13:26:21 -07001371 ScopedSuspendAll ssa(__FUNCTION__);
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001372
1373 std::string error_msg;
1374 std::unique_ptr<ClinitImageUpdate> update(ClinitImageUpdate::Create(image_classes_.get(),
1375 Thread::Current(),
Mathieu Chartier4f55e222015-09-04 13:26:21 -07001376 runtime->GetClassLinker(),
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001377 &error_msg));
1378 CHECK(update.get() != nullptr) << error_msg; // TODO: Soft failure?
1379
1380 // Do the marking.
1381 update->Walk();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001382 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001383}
1384
Vladimir Marko07785bb2015-06-15 18:52:54 +01001385bool CompilerDriver::CanAssumeClassIsLoaded(mirror::Class* klass) {
1386 Runtime* runtime = Runtime::Current();
1387 if (!runtime->IsAotCompiler()) {
Calin Juravleffc87072016-04-20 14:22:09 +01001388 DCHECK(runtime->UseJitCompilation());
Vladimir Marko07785bb2015-06-15 18:52:54 +01001389 // Having the klass reference here implies that the klass is already loaded.
1390 return true;
1391 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001392 if (!IsBootImage()) {
Vladimir Marko07785bb2015-06-15 18:52:54 +01001393 // Assume loaded only if klass is in the boot image. App classes cannot be assumed
1394 // loaded because we don't even know what class loader will be used to load them.
1395 bool class_in_image = runtime->GetHeap()->FindSpaceFromObject(klass, false)->IsImageSpace();
1396 return class_in_image;
1397 }
1398 std::string temp;
1399 const char* descriptor = klass->GetDescriptor(&temp);
1400 return IsImageClass(descriptor);
1401}
1402
Vladimir Marko492a7fa2016-06-01 18:38:43 +01001403void CompilerDriver::MarkForDexToDexCompilation(Thread* self, const MethodReference& method_ref) {
1404 MutexLock lock(self, dex_to_dex_references_lock_);
1405 // Since we're compiling one dex file at a time, we need to look for the
1406 // current dex file entry only at the end of dex_to_dex_references_.
1407 if (dex_to_dex_references_.empty() ||
1408 &dex_to_dex_references_.back().GetDexFile() != method_ref.dex_file) {
1409 dex_to_dex_references_.emplace_back(*method_ref.dex_file);
1410 }
1411 dex_to_dex_references_.back().GetMethodIndexes().SetBit(method_ref.dex_method_index);
1412}
1413
Vladimir Marko3cd50df2016-04-13 19:29:26 +01001414bool CompilerDriver::CanAssumeTypeIsPresentInDexCache(Handle<mirror::DexCache> dex_cache,
1415 uint32_t type_idx) {
Nicolas Geoffray42e372e2015-11-24 15:48:56 +00001416 bool result = false;
1417 if ((IsBootImage() &&
Vladimir Marko3cd50df2016-04-13 19:29:26 +01001418 IsImageClass(dex_cache->GetDexFile()->StringDataByIdx(
1419 dex_cache->GetDexFile()->GetTypeId(type_idx).descriptor_idx_))) ||
Calin Juravleffc87072016-04-20 14:22:09 +01001420 Runtime::Current()->UseJitCompilation()) {
Nicolas Geoffray42e372e2015-11-24 15:48:56 +00001421 mirror::Class* resolved_class = dex_cache->GetResolvedType(type_idx);
1422 result = (resolved_class != nullptr);
1423 }
1424
1425 if (result) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001426 stats_->TypeInDexCache();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001427 } else {
1428 stats_->TypeNotInDexCache();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001429 }
Nicolas Geoffray42e372e2015-11-24 15:48:56 +00001430 return result;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001431}
1432
1433bool CompilerDriver::CanAssumeStringIsPresentInDexCache(const DexFile& dex_file,
1434 uint32_t string_idx) {
1435 // See also Compiler::ResolveDexFile
1436
1437 bool result = false;
Calin Juravleffc87072016-04-20 14:22:09 +01001438 if (IsBootImage() || Runtime::Current()->UseJitCompilation()) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001439 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001440 StackHandleScope<1> hs(soa.Self());
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001441 ClassLinker* const class_linker = Runtime::Current()->GetClassLinker();
1442 Handle<mirror::DexCache> dex_cache(hs.NewHandle(class_linker->FindDexCache(
1443 soa.Self(), dex_file, false)));
Nicolas Geoffray917d0162015-11-24 18:25:35 +00001444 if (IsBootImage()) {
1445 // We resolve all const-string strings when building for the image.
1446 class_linker->ResolveString(dex_file, string_idx, dex_cache);
1447 result = true;
1448 } else {
1449 // Just check whether the dex cache already has the string.
Calin Juravleffc87072016-04-20 14:22:09 +01001450 DCHECK(Runtime::Current()->UseJitCompilation());
Nicolas Geoffray917d0162015-11-24 18:25:35 +00001451 result = (dex_cache->GetResolvedString(string_idx) != nullptr);
1452 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001453 }
1454 if (result) {
1455 stats_->StringInDexCache();
1456 } else {
1457 stats_->StringNotInDexCache();
1458 }
1459 return result;
1460}
1461
Vladimir Marko3cd50df2016-04-13 19:29:26 +01001462bool CompilerDriver::CanAccessTypeWithoutChecks(uint32_t referrer_idx,
1463 Handle<mirror::DexCache> dex_cache,
1464 uint32_t type_idx) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001465 // Get type from dex cache assuming it was populated by the verifier
1466 mirror::Class* resolved_class = dex_cache->GetResolvedType(type_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001467 if (resolved_class == nullptr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001468 stats_->TypeNeedsAccessCheck();
1469 return false; // Unknown class needs access checks.
1470 }
Vladimir Marko3cd50df2016-04-13 19:29:26 +01001471 const DexFile::MethodId& method_id = dex_cache->GetDexFile()->GetMethodId(referrer_idx);
David Brazdil38f64d32016-01-18 17:13:41 +00001472 bool is_accessible = resolved_class->IsPublic(); // Public classes are always accessible.
1473 if (!is_accessible) {
1474 mirror::Class* referrer_class = dex_cache->GetResolvedType(method_id.class_idx_);
1475 if (referrer_class == nullptr) {
1476 stats_->TypeNeedsAccessCheck();
1477 return false; // Incomplete referrer knowledge needs access check.
1478 }
1479 // Perform access check, will return true if access is ok or false if we're going to have to
1480 // check this at runtime (for example for class loaders).
1481 is_accessible = referrer_class->CanAccess(resolved_class);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001482 }
David Brazdil38f64d32016-01-18 17:13:41 +00001483 if (is_accessible) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001484 stats_->TypeDoesntNeedAccessCheck();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001485 } else {
1486 stats_->TypeNeedsAccessCheck();
1487 }
David Brazdil38f64d32016-01-18 17:13:41 +00001488 return is_accessible;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001489}
1490
1491bool CompilerDriver::CanAccessInstantiableTypeWithoutChecks(uint32_t referrer_idx,
Vladimir Marko3cd50df2016-04-13 19:29:26 +01001492 Handle<mirror::DexCache> dex_cache,
Mingyao Yangfb8464a2015-11-02 10:56:59 -08001493 uint32_t type_idx,
1494 bool* finalizable) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001495 // Get type from dex cache assuming it was populated by the verifier.
1496 mirror::Class* resolved_class = dex_cache->GetResolvedType(type_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001497 if (resolved_class == nullptr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001498 stats_->TypeNeedsAccessCheck();
Mingyao Yangfb8464a2015-11-02 10:56:59 -08001499 // Be conservative.
1500 *finalizable = true;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001501 return false; // Unknown class needs access checks.
1502 }
Mingyao Yangfb8464a2015-11-02 10:56:59 -08001503 *finalizable = resolved_class->IsFinalizable();
Vladimir Marko3cd50df2016-04-13 19:29:26 +01001504 const DexFile::MethodId& method_id = dex_cache->GetDexFile()->GetMethodId(referrer_idx);
David Brazdil38f64d32016-01-18 17:13:41 +00001505 bool is_accessible = resolved_class->IsPublic(); // Public classes are always accessible.
1506 if (!is_accessible) {
1507 mirror::Class* referrer_class = dex_cache->GetResolvedType(method_id.class_idx_);
1508 if (referrer_class == nullptr) {
1509 stats_->TypeNeedsAccessCheck();
1510 return false; // Incomplete referrer knowledge needs access check.
1511 }
1512 // Perform access and instantiable checks, will return true if access is ok or false if we're
1513 // going to have to check this at runtime (for example for class loaders).
1514 is_accessible = referrer_class->CanAccess(resolved_class);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001515 }
David Brazdil38f64d32016-01-18 17:13:41 +00001516 bool result = is_accessible && resolved_class->IsInstantiable();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001517 if (result) {
1518 stats_->TypeDoesntNeedAccessCheck();
1519 } else {
1520 stats_->TypeNeedsAccessCheck();
1521 }
1522 return result;
1523}
1524
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001525bool CompilerDriver::CanEmbedTypeInCode(const DexFile& dex_file, uint32_t type_idx,
1526 bool* is_type_initialized, bool* use_direct_type_ptr,
Mathieu Chartier8668c3c2014-04-24 16:48:11 -07001527 uintptr_t* direct_type_ptr, bool* out_is_finalizable) {
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001528 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001529 Runtime* runtime = Runtime::Current();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001530 mirror::DexCache* dex_cache = runtime->GetClassLinker()->FindDexCache(
1531 soa.Self(), dex_file, false);
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001532 mirror::Class* resolved_class = dex_cache->GetResolvedType(type_idx);
1533 if (resolved_class == nullptr) {
1534 return false;
1535 }
Igor Murashkind6dee672014-10-16 18:36:16 -07001536 if (GetCompilerOptions().GetCompilePic()) {
1537 // Do not allow a direct class pointer to be used when compiling for position-independent
1538 return false;
1539 }
Mathieu Chartier8668c3c2014-04-24 16:48:11 -07001540 *out_is_finalizable = resolved_class->IsFinalizable();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001541 gc::Heap* heap = runtime->GetHeap();
1542 const bool compiling_boot = heap->IsCompilingBoot();
Alex Light6e183f22014-07-18 14:57:04 -07001543 const bool support_boot_image_fixup = GetSupportBootImageFixup();
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001544 if (compiling_boot) {
1545 // boot -> boot class pointers.
1546 // True if the class is in the image at boot compiling time.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001547 const bool is_image_class = IsBootImage() && IsImageClass(
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001548 dex_file.StringDataByIdx(dex_file.GetTypeId(type_idx).descriptor_idx_));
1549 // True if pc relative load works.
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001550 if (is_image_class && support_boot_image_fixup) {
1551 *is_type_initialized = resolved_class->IsInitialized();
1552 *use_direct_type_ptr = false;
1553 *direct_type_ptr = 0;
1554 return true;
1555 } else {
1556 return false;
1557 }
Calin Juravleffc87072016-04-20 14:22:09 +01001558 } else if (runtime->UseJitCompilation() && !heap->IsMovableObject(resolved_class)) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001559 *is_type_initialized = resolved_class->IsInitialized();
1560 // If the class may move around, then don't embed it as a direct pointer.
1561 *use_direct_type_ptr = true;
1562 *direct_type_ptr = reinterpret_cast<uintptr_t>(resolved_class);
1563 return true;
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001564 } else {
1565 // True if the class is in the image at app compiling time.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001566 const bool class_in_image = heap->FindSpaceFromObject(resolved_class, false)->IsImageSpace();
Alex Light6e183f22014-07-18 14:57:04 -07001567 if (class_in_image && support_boot_image_fixup) {
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001568 // boot -> app class pointers.
1569 *is_type_initialized = resolved_class->IsInitialized();
Alex Lighta59dd802014-07-02 16:28:08 -07001570 // TODO This is somewhat hacky. We should refactor all of this invoke codepath.
1571 *use_direct_type_ptr = !GetCompilerOptions().GetIncludePatchInformation();
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001572 *direct_type_ptr = reinterpret_cast<uintptr_t>(resolved_class);
1573 return true;
1574 } else {
1575 // app -> app class pointers.
1576 // Give up because app does not have an image and class
1577 // isn't created at compile time. TODO: implement this
1578 // if/when each app gets an image.
1579 return false;
1580 }
1581 }
1582}
1583
Fred Shihe7f82e22014-08-06 10:46:37 -07001584bool CompilerDriver::CanEmbedReferenceTypeInCode(ClassReference* ref,
1585 bool* use_direct_ptr,
1586 uintptr_t* direct_type_ptr) {
1587 CHECK(ref != nullptr);
1588 CHECK(use_direct_ptr != nullptr);
1589 CHECK(direct_type_ptr != nullptr);
1590
1591 ScopedObjectAccess soa(Thread::Current());
1592 mirror::Class* reference_class = mirror::Reference::GetJavaLangRefReference();
Andreas Gampe928f72b2014-09-09 19:53:48 -07001593 bool is_initialized = false;
Fred Shihe7f82e22014-08-06 10:46:37 -07001594 bool unused_finalizable;
1595 // Make sure we have a finished Reference class object before attempting to use it.
1596 if (!CanEmbedTypeInCode(*reference_class->GetDexCache()->GetDexFile(),
1597 reference_class->GetDexTypeIndex(), &is_initialized,
1598 use_direct_ptr, direct_type_ptr, &unused_finalizable) ||
1599 !is_initialized) {
1600 return false;
1601 }
1602 ref->first = &reference_class->GetDexFile();
1603 ref->second = reference_class->GetDexClassDefIndex();
1604 return true;
1605}
1606
1607uint32_t CompilerDriver::GetReferenceSlowFlagOffset() const {
1608 ScopedObjectAccess soa(Thread::Current());
1609 mirror::Class* klass = mirror::Reference::GetJavaLangRefReference();
1610 DCHECK(klass->IsInitialized());
1611 return klass->GetSlowPathFlagOffset().Uint32Value();
1612}
1613
1614uint32_t CompilerDriver::GetReferenceDisableFlagOffset() const {
1615 ScopedObjectAccess soa(Thread::Current());
1616 mirror::Class* klass = mirror::Reference::GetJavaLangRefReference();
1617 DCHECK(klass->IsInitialized());
1618 return klass->GetDisableIntrinsicFlagOffset().Uint32Value();
1619}
1620
Vladimir Marko20f85592015-03-19 10:07:02 +00001621DexCacheArraysLayout CompilerDriver::GetDexCacheArraysLayout(const DexFile* dex_file) {
Vladimir Markod1eaf0d2015-10-29 12:18:29 +00001622 return ContainsElement(GetDexFilesForOatFile(), dex_file)
Mathieu Chartierc7853442015-03-27 14:35:38 -07001623 ? DexCacheArraysLayout(GetInstructionSetPointerSize(instruction_set_), dex_file)
Vladimir Marko20f85592015-03-19 10:07:02 +00001624 : DexCacheArraysLayout();
1625}
1626
Vladimir Markobe0e5462014-02-26 11:24:15 +00001627void CompilerDriver::ProcessedInstanceField(bool resolved) {
1628 if (!resolved) {
1629 stats_->UnresolvedInstanceField();
1630 } else {
1631 stats_->ResolvedInstanceField();
1632 }
1633}
1634
1635void CompilerDriver::ProcessedStaticField(bool resolved, bool local) {
1636 if (!resolved) {
1637 stats_->UnresolvedStaticField();
1638 } else if (local) {
1639 stats_->ResolvedLocalStaticField();
1640 } else {
1641 stats_->ResolvedStaticField();
1642 }
1643}
1644
Vladimir Markof096aad2014-01-23 15:51:58 +00001645void CompilerDriver::ProcessedInvoke(InvokeType invoke_type, int flags) {
1646 stats_->ProcessedInvoke(invoke_type, flags);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001647}
1648
Mathieu Chartierc7853442015-03-27 14:35:38 -07001649ArtField* CompilerDriver::ComputeInstanceFieldInfo(uint32_t field_idx,
1650 const DexCompilationUnit* mUnit, bool is_put,
1651 const ScopedObjectAccess& soa) {
Vladimir Markobe0e5462014-02-26 11:24:15 +00001652 // Try to resolve the field and compiling method's class.
Mathieu Chartierc7853442015-03-27 14:35:38 -07001653 ArtField* resolved_field;
Vladimir Markobe0e5462014-02-26 11:24:15 +00001654 mirror::Class* referrer_class;
Mathieu Chartier736b5602015-09-02 14:54:11 -07001655 Handle<mirror::DexCache> dex_cache(mUnit->GetDexCache());
Vladimir Markobe0e5462014-02-26 11:24:15 +00001656 {
Mathieu Chartier736b5602015-09-02 14:54:11 -07001657 StackHandleScope<1> hs(soa.Self());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001658 Handle<mirror::ClassLoader> class_loader_handle(
Mathieu Chartier0795f232016-09-27 18:43:30 -07001659 hs.NewHandle(soa.Decode<mirror::ClassLoader>(mUnit->GetClassLoader())));
Mathieu Chartier736b5602015-09-02 14:54:11 -07001660 resolved_field = ResolveField(soa, dex_cache, class_loader_handle, mUnit, field_idx, false);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001661 referrer_class = resolved_field != nullptr
Mathieu Chartier736b5602015-09-02 14:54:11 -07001662 ? ResolveCompilingMethodsClass(soa, dex_cache, class_loader_handle, mUnit) : nullptr;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001663 }
Nicolas Geoffraye5038322014-07-04 09:41:32 +01001664 bool can_link = false;
Vladimir Markobe0e5462014-02-26 11:24:15 +00001665 if (resolved_field != nullptr && referrer_class != nullptr) {
Vladimir Markobe0e5462014-02-26 11:24:15 +00001666 std::pair<bool, bool> fast_path = IsFastInstanceField(
Mathieu Chartier736b5602015-09-02 14:54:11 -07001667 dex_cache.Get(), referrer_class, resolved_field, field_idx);
Nicolas Geoffraye5038322014-07-04 09:41:32 +01001668 can_link = is_put ? fast_path.second : fast_path.first;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001669 }
Nicolas Geoffraye5038322014-07-04 09:41:32 +01001670 ProcessedInstanceField(can_link);
1671 return can_link ? resolved_field : nullptr;
1672}
1673
1674bool CompilerDriver::ComputeInstanceFieldInfo(uint32_t field_idx, const DexCompilationUnit* mUnit,
1675 bool is_put, MemberOffset* field_offset,
1676 bool* is_volatile) {
1677 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartierc7853442015-03-27 14:35:38 -07001678 ArtField* resolved_field = ComputeInstanceFieldInfo(field_idx, mUnit, is_put, soa);
Nicolas Geoffraye5038322014-07-04 09:41:32 +01001679
Mathieu Chartierc7853442015-03-27 14:35:38 -07001680 if (resolved_field == nullptr) {
Vladimir Markobe0e5462014-02-26 11:24:15 +00001681 // Conservative defaults.
1682 *is_volatile = true;
1683 *field_offset = MemberOffset(static_cast<size_t>(-1));
Nicolas Geoffraye5038322014-07-04 09:41:32 +01001684 return false;
1685 } else {
1686 *is_volatile = resolved_field->IsVolatile();
1687 *field_offset = resolved_field->GetOffset();
1688 return true;
Vladimir Markobe0e5462014-02-26 11:24:15 +00001689 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001690}
1691
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +01001692void CompilerDriver::GetCodeAndMethodForDirectCall(const mirror::Class* referrer_class,
Mathieu Chartiere401d142015-04-22 13:56:20 -07001693 ArtMethod* method,
Ian Rogers65ec92c2013-09-06 10:49:58 -07001694 uintptr_t* direct_code,
1695 uintptr_t* direct_method) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001696 // For direct and static methods compute possible direct_code and direct_method values, ie
1697 // an address for the Method* being invoked and an address of the code for that Method*.
1698 // For interface calls compute a value for direct_method that is the interface method being
1699 // invoked, so this can be passed to the out-of-line runtime support code.
Ian Rogers65ec92c2013-09-06 10:49:58 -07001700 *direct_code = 0;
1701 *direct_method = 0;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001702 Runtime* const runtime = Runtime::Current();
1703 gc::Heap* const heap = runtime->GetHeap();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001704 auto* cl = runtime->GetClassLinker();
Igor Murashkind6dee672014-10-16 18:36:16 -07001705 bool use_dex_cache = GetCompilerOptions().GetCompilePic(); // Off by default
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001706 const bool compiling_boot = heap->IsCompilingBoot();
Alex Lighta59dd802014-07-02 16:28:08 -07001707 // TODO This is somewhat hacky. We should refactor all of this invoke codepath.
1708 const bool force_relocations = (compiling_boot ||
1709 GetCompilerOptions().GetIncludePatchInformation());
Elliott Hughes956af0f2014-12-11 14:34:28 -08001710 // TODO: support patching on all architectures.
1711 use_dex_cache = use_dex_cache || (force_relocations && !support_boot_image_fixup_);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001712 mirror::Class* declaring_class = method->GetDeclaringClass();
1713 bool method_code_in_boot = declaring_class->GetClassLoader() == nullptr;
Ian Rogers83883d72013-10-21 21:07:24 -07001714 if (!use_dex_cache) {
1715 if (!method_code_in_boot) {
1716 use_dex_cache = true;
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +01001717 } else if (method->IsStatic() &&
1718 declaring_class != referrer_class &&
1719 !declaring_class->IsInitialized()) {
1720 // Ensure we run the clinit trampoline unless we are invoking a static method in the same
1721 // class.
1722 use_dex_cache = true;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001723 }
Ian Rogers83883d72013-10-21 21:07:24 -07001724 }
Calin Juravleffc87072016-04-20 14:22:09 +01001725 if (runtime->UseJitCompilation()) {
Mathieu Chartier28a35882015-02-26 18:28:07 -08001726 // If we are the JIT, then don't allow a direct call to the interpreter bridge since this will
1727 // never be updated even after we compile the method.
Mathieu Chartiere401d142015-04-22 13:56:20 -07001728 if (cl->IsQuickToInterpreterBridge(
Mathieu Chartier28a35882015-02-26 18:28:07 -08001729 reinterpret_cast<const void*>(compiler_->GetEntryPointOf(method)))) {
1730 use_dex_cache = true;
1731 }
1732 }
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +01001733
Alex Lighta59dd802014-07-02 16:28:08 -07001734 if (!use_dex_cache && force_relocations) {
Jeff Haoa0acc2d2015-01-27 11:22:04 -08001735 bool is_in_image;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001736 if (IsBootImage()) {
Jeff Haoa0acc2d2015-01-27 11:22:04 -08001737 is_in_image = IsImageClass(method->GetDeclaringClassDescriptor());
1738 } else {
1739 is_in_image = instruction_set_ != kX86 && instruction_set_ != kX86_64 &&
Vladimir Markoc08ab292015-06-22 14:35:42 +01001740 heap->FindSpaceFromObject(method->GetDeclaringClass(), false)->IsImageSpace() &&
1741 !cl->IsQuickToInterpreterBridge(
1742 reinterpret_cast<const void*>(compiler_->GetEntryPointOf(method)));
Jeff Haoa0acc2d2015-01-27 11:22:04 -08001743 }
1744 if (!is_in_image) {
Ian Rogers83883d72013-10-21 21:07:24 -07001745 // We can only branch directly to Methods that are resolved in the DexCache.
1746 // Otherwise we won't invoke the resolution trampoline.
1747 use_dex_cache = true;
1748 }
1749 }
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +01001750
1751 if (!use_dex_cache) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001752 bool method_in_image = false;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001753 const std::vector<gc::space::ImageSpace*> image_spaces = heap->GetBootImageSpaces();
1754 for (gc::space::ImageSpace* image_space : image_spaces) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001755 const auto& method_section = image_space->GetImageHeader().GetMethodsSection();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001756 if (method_section.Contains(reinterpret_cast<uint8_t*>(method) - image_space->Begin())) {
1757 method_in_image = true;
1758 break;
1759 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001760 }
Calin Juravleffc87072016-04-20 14:22:09 +01001761 if (method_in_image || compiling_boot || runtime->UseJitCompilation()) {
Alex Lighta59dd802014-07-02 16:28:08 -07001762 // We know we must be able to get to the method in the image, so use that pointer.
Mathieu Chartier6ced4092015-02-27 16:10:48 -08001763 // In the case where we are the JIT, we can always use direct pointers since we know where
1764 // the method and its code are / will be. We don't sharpen to interpreter bridge since we
1765 // check IsQuickToInterpreterBridge above.
Vladimir Markoa51a0b02014-05-21 12:08:39 +01001766 CHECK(!method->IsAbstract());
Alex Lighta59dd802014-07-02 16:28:08 -07001767 *direct_method = force_relocations ? -1 : reinterpret_cast<uintptr_t>(method);
1768 *direct_code = force_relocations ? -1 : compiler_->GetEntryPointOf(method);
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +01001769 } else {
Vladimir Markoa51a0b02014-05-21 12:08:39 +01001770 // Set the code and rely on the dex cache for the method.
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +01001771 *direct_code = force_relocations ? -1 : compiler_->GetEntryPointOf(method);
Ian Rogers83883d72013-10-21 21:07:24 -07001772 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001773 }
1774}
1775
Vladimir Marko2730db02014-01-27 11:15:17 +00001776const VerifiedMethod* CompilerDriver::GetVerifiedMethod(const DexFile* dex_file,
1777 uint32_t method_idx) const {
1778 MethodReference ref(dex_file, method_idx);
1779 return verification_results_->GetVerifiedMethod(ref);
1780}
1781
1782bool CompilerDriver::IsSafeCast(const DexCompilationUnit* mUnit, uint32_t dex_pc) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001783 if (!compiler_options_->IsVerificationEnabled()) {
1784 // If we didn't verify, every cast has to be treated as non-safe.
1785 return false;
1786 }
Vladimir Marko2730db02014-01-27 11:15:17 +00001787 DCHECK(mUnit->GetVerifiedMethod() != nullptr);
1788 bool result = mUnit->GetVerifiedMethod()->IsSafeCast(dex_pc);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001789 if (result) {
1790 stats_->SafeCast();
1791 } else {
1792 stats_->NotASafeCast();
1793 }
1794 return result;
1795}
1796
Mathieu Chartier90443472015-07-16 20:32:27 -07001797class CompilationVisitor {
1798 public:
1799 virtual ~CompilationVisitor() {}
1800 virtual void Visit(size_t index) = 0;
1801};
1802
Brian Carlstrom7940e442013-07-12 13:46:57 -07001803class ParallelCompilationManager {
1804 public:
Brian Carlstrom7940e442013-07-12 13:46:57 -07001805 ParallelCompilationManager(ClassLinker* class_linker,
1806 jobject class_loader,
1807 CompilerDriver* compiler,
1808 const DexFile* dex_file,
Andreas Gampede7b4362014-07-28 18:38:57 -07001809 const std::vector<const DexFile*>& dex_files,
Ian Rogers3d504072014-03-01 09:16:49 -08001810 ThreadPool* thread_pool)
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001811 : index_(0),
1812 class_linker_(class_linker),
Brian Carlstrom7940e442013-07-12 13:46:57 -07001813 class_loader_(class_loader),
1814 compiler_(compiler),
1815 dex_file_(dex_file),
Andreas Gampede7b4362014-07-28 18:38:57 -07001816 dex_files_(dex_files),
Ian Rogers3d504072014-03-01 09:16:49 -08001817 thread_pool_(thread_pool) {}
Brian Carlstrom7940e442013-07-12 13:46:57 -07001818
1819 ClassLinker* GetClassLinker() const {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001820 CHECK(class_linker_ != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001821 return class_linker_;
1822 }
1823
1824 jobject GetClassLoader() const {
1825 return class_loader_;
1826 }
1827
1828 CompilerDriver* GetCompiler() const {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001829 CHECK(compiler_ != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001830 return compiler_;
1831 }
1832
1833 const DexFile* GetDexFile() const {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001834 CHECK(dex_file_ != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001835 return dex_file_;
1836 }
1837
Andreas Gampede7b4362014-07-28 18:38:57 -07001838 const std::vector<const DexFile*>& GetDexFiles() const {
1839 return dex_files_;
1840 }
1841
Mathieu Chartier90443472015-07-16 20:32:27 -07001842 void ForAll(size_t begin, size_t end, CompilationVisitor* visitor, size_t work_units)
1843 REQUIRES(!*Locks::mutator_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001844 Thread* self = Thread::Current();
1845 self->AssertNoPendingException();
1846 CHECK_GT(work_units, 0U);
1847
Ian Rogers3e5cf302014-05-20 16:40:37 -07001848 index_.StoreRelaxed(begin);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001849 for (size_t i = 0; i < work_units; ++i) {
Mathieu Chartier90443472015-07-16 20:32:27 -07001850 thread_pool_->AddTask(self, new ForAllClosure(this, end, visitor));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001851 }
1852 thread_pool_->StartWorkers(self);
1853
1854 // Ensure we're suspended while we're blocked waiting for the other threads to finish (worker
1855 // thread destructor's called below perform join).
1856 CHECK_NE(self->GetState(), kRunnable);
1857
1858 // Wait for all the worker threads to finish.
1859 thread_pool_->Wait(self, true, false);
Andreas Gampeace0dc12016-01-20 13:33:13 -08001860
1861 // And stop the workers accepting jobs.
1862 thread_pool_->StopWorkers(self);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001863 }
1864
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001865 size_t NextIndex() {
Ian Rogers3e5cf302014-05-20 16:40:37 -07001866 return index_.FetchAndAddSequentiallyConsistent(1);
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001867 }
1868
Brian Carlstrom7940e442013-07-12 13:46:57 -07001869 private:
Brian Carlstrom7940e442013-07-12 13:46:57 -07001870 class ForAllClosure : public Task {
1871 public:
Mathieu Chartier90443472015-07-16 20:32:27 -07001872 ForAllClosure(ParallelCompilationManager* manager, size_t end, CompilationVisitor* visitor)
Brian Carlstrom7940e442013-07-12 13:46:57 -07001873 : manager_(manager),
Brian Carlstrom7940e442013-07-12 13:46:57 -07001874 end_(end),
Mathieu Chartier90443472015-07-16 20:32:27 -07001875 visitor_(visitor) {}
Brian Carlstrom7940e442013-07-12 13:46:57 -07001876
1877 virtual void Run(Thread* self) {
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001878 while (true) {
1879 const size_t index = manager_->NextIndex();
1880 if (UNLIKELY(index >= end_)) {
1881 break;
1882 }
Mathieu Chartier90443472015-07-16 20:32:27 -07001883 visitor_->Visit(index);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001884 self->AssertNoPendingException();
1885 }
1886 }
1887
1888 virtual void Finalize() {
1889 delete this;
1890 }
Brian Carlstrom0cd7ec22013-07-17 23:40:20 -07001891
Brian Carlstrom7940e442013-07-12 13:46:57 -07001892 private:
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001893 ParallelCompilationManager* const manager_;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001894 const size_t end_;
Mathieu Chartier90443472015-07-16 20:32:27 -07001895 CompilationVisitor* const visitor_;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001896 };
1897
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001898 AtomicInteger index_;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001899 ClassLinker* const class_linker_;
1900 const jobject class_loader_;
1901 CompilerDriver* const compiler_;
1902 const DexFile* const dex_file_;
Andreas Gampede7b4362014-07-28 18:38:57 -07001903 const std::vector<const DexFile*>& dex_files_;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001904 ThreadPool* const thread_pool_;
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001905
1906 DISALLOW_COPY_AND_ASSIGN(ParallelCompilationManager);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001907};
1908
Jeff Hao0e49b422013-11-08 12:16:56 -08001909// A fast version of SkipClass above if the class pointer is available
1910// that avoids the expensive FindInClassPath search.
1911static bool SkipClass(jobject class_loader, const DexFile& dex_file, mirror::Class* klass)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001912 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001913 DCHECK(klass != nullptr);
Jeff Hao0e49b422013-11-08 12:16:56 -08001914 const DexFile& original_dex_file = *klass->GetDexCache()->GetDexFile();
1915 if (&dex_file != &original_dex_file) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001916 if (class_loader == nullptr) {
Jeff Hao0e49b422013-11-08 12:16:56 -08001917 LOG(WARNING) << "Skipping class " << PrettyDescriptor(klass) << " from "
1918 << dex_file.GetLocation() << " previously found in "
1919 << original_dex_file.GetLocation();
1920 }
1921 return true;
1922 }
1923 return false;
1924}
1925
Mathieu Chartier70b63482014-06-27 17:19:04 -07001926static void CheckAndClearResolveException(Thread* self)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001927 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier70b63482014-06-27 17:19:04 -07001928 CHECK(self->IsExceptionPending());
Nicolas Geoffray14691c52015-03-05 10:40:17 +00001929 mirror::Throwable* exception = self->GetException();
Ian Rogers1ff3c982014-08-12 02:30:58 -07001930 std::string temp;
1931 const char* descriptor = exception->GetClass()->GetDescriptor(&temp);
1932 const char* expected_exceptions[] = {
1933 "Ljava/lang/IllegalAccessError;",
1934 "Ljava/lang/IncompatibleClassChangeError;",
1935 "Ljava/lang/InstantiationError;",
Brian Carlstrom898fcb52014-08-25 23:07:30 -07001936 "Ljava/lang/LinkageError;",
Ian Rogers1ff3c982014-08-12 02:30:58 -07001937 "Ljava/lang/NoClassDefFoundError;",
1938 "Ljava/lang/NoSuchFieldError;",
1939 "Ljava/lang/NoSuchMethodError;"
1940 };
1941 bool found = false;
1942 for (size_t i = 0; (found == false) && (i < arraysize(expected_exceptions)); ++i) {
1943 if (strcmp(descriptor, expected_exceptions[i]) == 0) {
1944 found = true;
1945 }
1946 }
1947 if (!found) {
Brian Carlstrom898fcb52014-08-25 23:07:30 -07001948 LOG(FATAL) << "Unexpected exception " << exception->Dump();
Mathieu Chartier70b63482014-06-27 17:19:04 -07001949 }
1950 self->ClearException();
1951}
1952
Mathieu Chartierb5d38612016-04-07 10:52:52 -07001953bool CompilerDriver::RequiresConstructorBarrier(const DexFile& dex_file,
1954 uint16_t class_def_idx) const {
1955 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_idx);
1956 const uint8_t* class_data = dex_file.GetClassData(class_def);
1957 if (class_data == nullptr) {
1958 // Empty class such as a marker interface.
1959 return false;
1960 }
1961 ClassDataItemIterator it(dex_file, class_data);
1962 while (it.HasNextStaticField()) {
1963 it.Next();
1964 }
1965 // We require a constructor barrier if there are final instance fields.
1966 while (it.HasNextInstanceField()) {
1967 if (it.MemberIsFinal()) {
1968 return true;
1969 }
1970 it.Next();
1971 }
1972 return false;
1973}
1974
Mathieu Chartier90443472015-07-16 20:32:27 -07001975class ResolveClassFieldsAndMethodsVisitor : public CompilationVisitor {
1976 public:
1977 explicit ResolveClassFieldsAndMethodsVisitor(const ParallelCompilationManager* manager)
1978 : manager_(manager) {}
Brian Carlstrom7940e442013-07-12 13:46:57 -07001979
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001980 void Visit(size_t class_def_index) OVERRIDE REQUIRES(!Locks::mutator_lock_) {
Mathieu Chartier90443472015-07-16 20:32:27 -07001981 ATRACE_CALL();
1982 Thread* const self = Thread::Current();
1983 jobject jclass_loader = manager_->GetClassLoader();
1984 const DexFile& dex_file = *manager_->GetDexFile();
1985 ClassLinker* class_linker = manager_->GetClassLinker();
Ian Rogerse6bb3b22013-08-19 21:51:45 -07001986
Mathieu Chartier90443472015-07-16 20:32:27 -07001987 // If an instance field is final then we need to have a barrier on the return, static final
1988 // fields are assigned within the lock held for class initialization. Conservatively assume
1989 // constructor barriers are always required.
1990 bool requires_constructor_barrier = true;
1991
1992 // Method and Field are the worst. We can't resolve without either
1993 // context from the code use (to disambiguate virtual vs direct
1994 // method and instance vs static field) or from class
1995 // definitions. While the compiler will resolve what it can as it
1996 // needs it, here we try to resolve fields and methods used in class
1997 // definitions, since many of them many never be referenced by
1998 // generated code.
1999 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
2000 ScopedObjectAccess soa(self);
2001 StackHandleScope<2> hs(soa.Self());
2002 Handle<mirror::ClassLoader> class_loader(
Mathieu Chartier0795f232016-09-27 18:43:30 -07002003 hs.NewHandle(soa.Decode<mirror::ClassLoader>(jclass_loader)));
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002004 Handle<mirror::DexCache> dex_cache(hs.NewHandle(class_linker->FindDexCache(
2005 soa.Self(), dex_file, false)));
Mathieu Chartier90443472015-07-16 20:32:27 -07002006 // Resolve the class.
2007 mirror::Class* klass = class_linker->ResolveType(dex_file, class_def.class_idx_, dex_cache,
2008 class_loader);
2009 bool resolve_fields_and_methods;
2010 if (klass == nullptr) {
2011 // Class couldn't be resolved, for example, super-class is in a different dex file. Don't
2012 // attempt to resolve methods and fields when there is no declaring class.
2013 CheckAndClearResolveException(soa.Self());
2014 resolve_fields_and_methods = false;
2015 } else {
2016 // We successfully resolved a class, should we skip it?
2017 if (SkipClass(jclass_loader, dex_file, klass)) {
2018 return;
Ian Rogerse6bb3b22013-08-19 21:51:45 -07002019 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002020 // We want to resolve the methods and fields eagerly.
2021 resolve_fields_and_methods = true;
Ian Rogers68b56852014-08-29 20:19:11 -07002022 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002023 // Note the class_data pointer advances through the headers,
2024 // static fields, instance fields, direct methods, and virtual
2025 // methods.
2026 const uint8_t* class_data = dex_file.GetClassData(class_def);
2027 if (class_data == nullptr) {
2028 // Empty class such as a marker interface.
2029 requires_constructor_barrier = false;
2030 } else {
2031 ClassDataItemIterator it(dex_file, class_data);
2032 while (it.HasNextStaticField()) {
2033 if (resolve_fields_and_methods) {
2034 ArtField* field = class_linker->ResolveField(dex_file, it.GetMemberIndex(),
2035 dex_cache, class_loader, true);
2036 if (field == nullptr) {
2037 CheckAndClearResolveException(soa.Self());
2038 }
Ian Rogers68b56852014-08-29 20:19:11 -07002039 }
2040 it.Next();
2041 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002042 // We require a constructor barrier if there are final instance fields.
2043 requires_constructor_barrier = false;
2044 while (it.HasNextInstanceField()) {
2045 if (it.MemberIsFinal()) {
2046 requires_constructor_barrier = true;
2047 }
2048 if (resolve_fields_and_methods) {
2049 ArtField* field = class_linker->ResolveField(dex_file, it.GetMemberIndex(),
2050 dex_cache, class_loader, false);
2051 if (field == nullptr) {
2052 CheckAndClearResolveException(soa.Self());
2053 }
Ian Rogers68b56852014-08-29 20:19:11 -07002054 }
2055 it.Next();
2056 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002057 if (resolve_fields_and_methods) {
2058 while (it.HasNextDirectMethod()) {
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08002059 ArtMethod* method = class_linker->ResolveMethod<ClassLinker::kNoICCECheckForCache>(
Mathieu Chartier90443472015-07-16 20:32:27 -07002060 dex_file, it.GetMemberIndex(), dex_cache, class_loader, nullptr,
2061 it.GetMethodInvokeType(class_def));
2062 if (method == nullptr) {
2063 CheckAndClearResolveException(soa.Self());
2064 }
2065 it.Next();
2066 }
2067 while (it.HasNextVirtualMethod()) {
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08002068 ArtMethod* method = class_linker->ResolveMethod<ClassLinker::kNoICCECheckForCache>(
Mathieu Chartier90443472015-07-16 20:32:27 -07002069 dex_file, it.GetMemberIndex(), dex_cache, class_loader, nullptr,
2070 it.GetMethodInvokeType(class_def));
2071 if (method == nullptr) {
2072 CheckAndClearResolveException(soa.Self());
2073 }
2074 it.Next();
2075 }
2076 DCHECK(!it.HasNext());
2077 }
2078 }
Mathieu Chartierc4ae9162016-04-07 13:19:19 -07002079 manager_->GetCompiler()->SetRequiresConstructorBarrier(self,
2080 &dex_file,
2081 class_def_index,
2082 requires_constructor_barrier);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002083 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002084
Mathieu Chartier90443472015-07-16 20:32:27 -07002085 private:
2086 const ParallelCompilationManager* const manager_;
2087};
2088
2089class ResolveTypeVisitor : public CompilationVisitor {
2090 public:
2091 explicit ResolveTypeVisitor(const ParallelCompilationManager* manager) : manager_(manager) {
2092 }
2093 virtual void Visit(size_t type_idx) OVERRIDE REQUIRES(!Locks::mutator_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07002094 // Class derived values are more complicated, they require the linker and loader.
Mathieu Chartier90443472015-07-16 20:32:27 -07002095 ScopedObjectAccess soa(Thread::Current());
2096 ClassLinker* class_linker = manager_->GetClassLinker();
2097 const DexFile& dex_file = *manager_->GetDexFile();
2098 StackHandleScope<2> hs(soa.Self());
Mathieu Chartier90443472015-07-16 20:32:27 -07002099 Handle<mirror::ClassLoader> class_loader(
Mathieu Chartier0795f232016-09-27 18:43:30 -07002100 hs.NewHandle(soa.Decode<mirror::ClassLoader>(manager_->GetClassLoader())));
Mathieu Chartierd57d4542015-10-14 10:55:30 -07002101 Handle<mirror::DexCache> dex_cache(hs.NewHandle(class_linker->RegisterDexFile(
2102 dex_file,
Mathieu Chartierf284d442016-06-02 11:48:30 -07002103 class_loader.Get())));
Mathieu Chartier90443472015-07-16 20:32:27 -07002104 mirror::Class* klass = class_linker->ResolveType(dex_file, type_idx, dex_cache, class_loader);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002105
Mathieu Chartier90443472015-07-16 20:32:27 -07002106 if (klass == nullptr) {
2107 soa.Self()->AssertPendingException();
2108 mirror::Throwable* exception = soa.Self()->GetException();
2109 VLOG(compiler) << "Exception during type resolution: " << exception->Dump();
2110 if (exception->GetClass()->DescriptorEquals("Ljava/lang/OutOfMemoryError;")) {
2111 // There's little point continuing compilation if the heap is exhausted.
2112 LOG(FATAL) << "Out of memory during type resolution for compilation";
2113 }
2114 soa.Self()->ClearException();
Ian Rogersa436fde2013-08-27 23:34:06 -07002115 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002116 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002117
2118 private:
2119 const ParallelCompilationManager* const manager_;
2120};
Brian Carlstrom7940e442013-07-12 13:46:57 -07002121
Andreas Gampeace0dc12016-01-20 13:33:13 -08002122void CompilerDriver::ResolveDexFile(jobject class_loader,
2123 const DexFile& dex_file,
Andreas Gampede7b4362014-07-28 18:38:57 -07002124 const std::vector<const DexFile*>& dex_files,
Andreas Gampeace0dc12016-01-20 13:33:13 -08002125 ThreadPool* thread_pool,
2126 size_t thread_count,
2127 TimingLogger* timings) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07002128 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
2129
2130 // TODO: we could resolve strings here, although the string table is largely filled with class
2131 // and method names.
2132
Andreas Gampede7b4362014-07-28 18:38:57 -07002133 ParallelCompilationManager context(class_linker, class_loader, this, &dex_file, dex_files,
2134 thread_pool);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002135 if (IsBootImage()) {
Ian Rogerse6bb3b22013-08-19 21:51:45 -07002136 // For images we resolve all types, such as array, whereas for applications just those with
2137 // classdefs are resolved by ResolveClassFieldsAndMethods.
Mathieu Chartierf5997b42014-06-20 10:37:54 -07002138 TimingLogger::ScopedTiming t("Resolve Types", timings);
Mathieu Chartier90443472015-07-16 20:32:27 -07002139 ResolveTypeVisitor visitor(&context);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002140 context.ForAll(0, dex_file.NumTypeIds(), &visitor, thread_count);
Ian Rogerse6bb3b22013-08-19 21:51:45 -07002141 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002142
Mathieu Chartierf5997b42014-06-20 10:37:54 -07002143 TimingLogger::ScopedTiming t("Resolve MethodsAndFields", timings);
Mathieu Chartier90443472015-07-16 20:32:27 -07002144 ResolveClassFieldsAndMethodsVisitor visitor(&context);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002145 context.ForAll(0, dex_file.NumClassDefs(), &visitor, thread_count);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002146}
2147
Andreas Gampeace0dc12016-01-20 13:33:13 -08002148void CompilerDriver::SetVerified(jobject class_loader,
2149 const std::vector<const DexFile*>& dex_files,
2150 TimingLogger* timings) {
2151 // This can be run in parallel.
Mathieu Chartier90443472015-07-16 20:32:27 -07002152 for (const DexFile* dex_file : dex_files) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002153 CHECK(dex_file != nullptr);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002154 SetVerifiedDexFile(class_loader,
2155 *dex_file,
2156 dex_files,
2157 parallel_thread_pool_.get(),
2158 parallel_thread_count_,
2159 timings);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002160 }
2161}
2162
Andreas Gampeace0dc12016-01-20 13:33:13 -08002163void CompilerDriver::Verify(jobject class_loader,
2164 const std::vector<const DexFile*>& dex_files,
2165 TimingLogger* timings) {
2166 // Note: verification should not be pulling in classes anymore when compiling the boot image,
2167 // as all should have been resolved before. As such, doing this in parallel should still
2168 // be deterministic.
Mathieu Chartier90443472015-07-16 20:32:27 -07002169 for (const DexFile* dex_file : dex_files) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002170 CHECK(dex_file != nullptr);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002171 VerifyDexFile(class_loader,
2172 *dex_file,
2173 dex_files,
2174 parallel_thread_pool_.get(),
2175 parallel_thread_count_,
2176 timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002177 }
2178}
2179
Mathieu Chartier90443472015-07-16 20:32:27 -07002180class VerifyClassVisitor : public CompilationVisitor {
2181 public:
Andreas Gampe5fd66d02016-09-12 20:22:19 -07002182 VerifyClassVisitor(const ParallelCompilationManager* manager, verifier::HardFailLogMode log_level)
Andreas Gampe7fe30232016-03-25 16:58:00 -07002183 : manager_(manager), log_level_(log_level) {}
Brian Carlstrom7940e442013-07-12 13:46:57 -07002184
Mathieu Chartier90443472015-07-16 20:32:27 -07002185 virtual void Visit(size_t class_def_index) REQUIRES(!Locks::mutator_lock_) OVERRIDE {
2186 ATRACE_CALL();
2187 ScopedObjectAccess soa(Thread::Current());
2188 const DexFile& dex_file = *manager_->GetDexFile();
Mathieu Chartiera8077802016-03-16 19:08:31 -07002189 if (!manager_->GetCompiler()->ShouldVerifyClassBasedOnProfile(dex_file, class_def_index)) {
2190 // Skip verification since the class is not in the profile.
2191 return;
2192 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002193 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
2194 const char* descriptor = dex_file.GetClassDescriptor(class_def);
2195 ClassLinker* class_linker = manager_->GetClassLinker();
2196 jobject jclass_loader = manager_->GetClassLoader();
2197 StackHandleScope<3> hs(soa.Self());
2198 Handle<mirror::ClassLoader> class_loader(
Mathieu Chartier0795f232016-09-27 18:43:30 -07002199 hs.NewHandle(soa.Decode<mirror::ClassLoader>(jclass_loader)));
Mathieu Chartier90443472015-07-16 20:32:27 -07002200 Handle<mirror::Class> klass(
2201 hs.NewHandle(class_linker->FindClass(soa.Self(), descriptor, class_loader)));
2202 if (klass.Get() == nullptr) {
Ian Rogerse6bb3b22013-08-19 21:51:45 -07002203 CHECK(soa.Self()->IsExceptionPending());
2204 soa.Self()->ClearException();
Mathieu Chartier90443472015-07-16 20:32:27 -07002205
2206 /*
2207 * At compile time, we can still structurally verify the class even if FindClass fails.
2208 * This is to ensure the class is structurally sound for compilation. An unsound class
2209 * will be rejected by the verifier and later skipped during compilation in the compiler.
2210 */
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002211 Handle<mirror::DexCache> dex_cache(hs.NewHandle(class_linker->FindDexCache(
2212 soa.Self(), dex_file, false)));
Mathieu Chartier90443472015-07-16 20:32:27 -07002213 std::string error_msg;
Andreas Gampeec6e6c12015-11-05 20:39:56 -08002214 if (verifier::MethodVerifier::VerifyClass(soa.Self(),
2215 &dex_file,
2216 dex_cache,
2217 class_loader,
David Brazdil15fc7292016-09-02 14:13:18 +01002218 class_def,
Andreas Gampe53e32d12015-12-09 21:03:23 -08002219 Runtime::Current()->GetCompilerCallbacks(),
Andreas Gampeec6e6c12015-11-05 20:39:56 -08002220 true /* allow soft failures */,
Andreas Gampe7fe30232016-03-25 16:58:00 -07002221 log_level_,
Andreas Gampeec6e6c12015-11-05 20:39:56 -08002222 &error_msg) ==
Mathieu Chartier90443472015-07-16 20:32:27 -07002223 verifier::MethodVerifier::kHardFailure) {
2224 LOG(ERROR) << "Verification failed on class " << PrettyDescriptor(descriptor)
2225 << " because: " << error_msg;
2226 manager_->GetCompiler()->SetHadHardVerifierFailure();
2227 }
2228 } else if (!SkipClass(jclass_loader, dex_file, klass.Get())) {
2229 CHECK(klass->IsResolved()) << PrettyClass(klass.Get());
Andreas Gampe7fe30232016-03-25 16:58:00 -07002230 class_linker->VerifyClass(soa.Self(), klass, log_level_);
Mathieu Chartier90443472015-07-16 20:32:27 -07002231
2232 if (klass->IsErroneous()) {
2233 // ClassLinker::VerifyClass throws, which isn't useful in the compiler.
2234 CHECK(soa.Self()->IsExceptionPending());
2235 soa.Self()->ClearException();
2236 manager_->GetCompiler()->SetHadHardVerifierFailure();
2237 }
2238
2239 CHECK(klass->IsCompileTimeVerified() || klass->IsErroneous())
2240 << PrettyDescriptor(klass.Get()) << ": state=" << klass->GetStatus();
2241
2242 // It is *very* problematic if there are verification errors in the boot classpath. For example,
2243 // we rely on things working OK without verification when the decryption dialog is brought up.
2244 // So abort in a debug build if we find this violated.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002245 DCHECK(!manager_->GetCompiler()->IsBootImage() || klass->IsVerified())
2246 << "Boot classpath class " << PrettyClass(klass.Get()) << " failed to fully verify.";
Ian Rogerse6bb3b22013-08-19 21:51:45 -07002247 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002248 soa.Self()->AssertNoPendingException();
Brian Carlstrom7940e442013-07-12 13:46:57 -07002249 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002250
2251 private:
2252 const ParallelCompilationManager* const manager_;
Andreas Gampe5fd66d02016-09-12 20:22:19 -07002253 const verifier::HardFailLogMode log_level_;
Mathieu Chartier90443472015-07-16 20:32:27 -07002254};
Brian Carlstrom7940e442013-07-12 13:46:57 -07002255
Andreas Gampeace0dc12016-01-20 13:33:13 -08002256void CompilerDriver::VerifyDexFile(jobject class_loader,
2257 const DexFile& dex_file,
Andreas Gampede7b4362014-07-28 18:38:57 -07002258 const std::vector<const DexFile*>& dex_files,
Andreas Gampeace0dc12016-01-20 13:33:13 -08002259 ThreadPool* thread_pool,
2260 size_t thread_count,
2261 TimingLogger* timings) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07002262 TimingLogger::ScopedTiming t("Verify Dex File", timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002263 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Andreas Gampede7b4362014-07-28 18:38:57 -07002264 ParallelCompilationManager context(class_linker, class_loader, this, &dex_file, dex_files,
2265 thread_pool);
Andreas Gampe5fd66d02016-09-12 20:22:19 -07002266 verifier::HardFailLogMode log_level = GetCompilerOptions().AbortOnHardVerifierFailure()
2267 ? verifier::HardFailLogMode::kLogInternalFatal
2268 : verifier::HardFailLogMode::kLogWarning;
Andreas Gampe7fe30232016-03-25 16:58:00 -07002269 VerifyClassVisitor visitor(&context, log_level);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002270 context.ForAll(0, dex_file.NumClassDefs(), &visitor, thread_count);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002271}
2272
Mathieu Chartier90443472015-07-16 20:32:27 -07002273class SetVerifiedClassVisitor : public CompilationVisitor {
2274 public:
2275 explicit SetVerifiedClassVisitor(const ParallelCompilationManager* manager) : manager_(manager) {}
2276
2277 virtual void Visit(size_t class_def_index) REQUIRES(!Locks::mutator_lock_) OVERRIDE {
2278 ATRACE_CALL();
2279 ScopedObjectAccess soa(Thread::Current());
2280 const DexFile& dex_file = *manager_->GetDexFile();
2281 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
2282 const char* descriptor = dex_file.GetClassDescriptor(class_def);
2283 ClassLinker* class_linker = manager_->GetClassLinker();
2284 jobject jclass_loader = manager_->GetClassLoader();
2285 StackHandleScope<3> hs(soa.Self());
2286 Handle<mirror::ClassLoader> class_loader(
Mathieu Chartier0795f232016-09-27 18:43:30 -07002287 hs.NewHandle(soa.Decode<mirror::ClassLoader>(jclass_loader)));
Mathieu Chartier90443472015-07-16 20:32:27 -07002288 Handle<mirror::Class> klass(
2289 hs.NewHandle(class_linker->FindClass(soa.Self(), descriptor, class_loader)));
2290 // Class might have failed resolution. Then don't set it to verified.
2291 if (klass.Get() != nullptr) {
2292 // Only do this if the class is resolved. If even resolution fails, quickening will go very,
2293 // very wrong.
2294 if (klass->IsResolved()) {
2295 if (klass->GetStatus() < mirror::Class::kStatusVerified) {
2296 ObjectLock<mirror::Class> lock(soa.Self(), klass);
2297 // Set class status to verified.
2298 mirror::Class::SetStatus(klass, mirror::Class::kStatusVerified, soa.Self());
2299 // Mark methods as pre-verified. If we don't do this, the interpreter will run with
2300 // access checks.
Igor Murashkindf707e42016-02-02 16:56:50 -08002301 klass->SetSkipAccessChecksFlagOnAllMethods(
Mathieu Chartier90443472015-07-16 20:32:27 -07002302 GetInstructionSetPointerSize(manager_->GetCompiler()->GetInstructionSet()));
Igor Murashkindf707e42016-02-02 16:56:50 -08002303 klass->SetVerificationAttempted();
Mathieu Chartier90443472015-07-16 20:32:27 -07002304 }
2305 // Record the final class status if necessary.
2306 ClassReference ref(manager_->GetDexFile(), class_def_index);
2307 manager_->GetCompiler()->RecordClassStatus(ref, klass->GetStatus());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002308 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002309 } else {
2310 Thread* self = soa.Self();
2311 DCHECK(self->IsExceptionPending());
2312 self->ClearException();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002313 }
2314 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002315
2316 private:
2317 const ParallelCompilationManager* const manager_;
2318};
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002319
Andreas Gampeace0dc12016-01-20 13:33:13 -08002320void CompilerDriver::SetVerifiedDexFile(jobject class_loader,
2321 const DexFile& dex_file,
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002322 const std::vector<const DexFile*>& dex_files,
Andreas Gampeace0dc12016-01-20 13:33:13 -08002323 ThreadPool* thread_pool,
2324 size_t thread_count,
2325 TimingLogger* timings) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002326 TimingLogger::ScopedTiming t("Verify Dex File", timings);
2327 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
2328 ParallelCompilationManager context(class_linker, class_loader, this, &dex_file, dex_files,
2329 thread_pool);
Mathieu Chartier90443472015-07-16 20:32:27 -07002330 SetVerifiedClassVisitor visitor(&context);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002331 context.ForAll(0, dex_file.NumClassDefs(), &visitor, thread_count);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002332}
2333
Mathieu Chartier90443472015-07-16 20:32:27 -07002334class InitializeClassVisitor : public CompilationVisitor {
2335 public:
2336 explicit InitializeClassVisitor(const ParallelCompilationManager* manager) : manager_(manager) {}
Ian Rogersfc0e94b2013-09-23 23:51:32 -07002337
Mathieu Chartier90443472015-07-16 20:32:27 -07002338 virtual void Visit(size_t class_def_index) REQUIRES(!Locks::mutator_lock_) OVERRIDE {
2339 ATRACE_CALL();
2340 jobject jclass_loader = manager_->GetClassLoader();
2341 const DexFile& dex_file = *manager_->GetDexFile();
2342 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
2343 const DexFile::TypeId& class_type_id = dex_file.GetTypeId(class_def.class_idx_);
2344 const char* descriptor = dex_file.StringDataByIdx(class_type_id.descriptor_idx_);
Jeff Hao0e49b422013-11-08 12:16:56 -08002345
Mathieu Chartier90443472015-07-16 20:32:27 -07002346 ScopedObjectAccess soa(Thread::Current());
2347 StackHandleScope<3> hs(soa.Self());
2348 Handle<mirror::ClassLoader> class_loader(
Mathieu Chartier0795f232016-09-27 18:43:30 -07002349 hs.NewHandle(soa.Decode<mirror::ClassLoader>(jclass_loader)));
Mathieu Chartier90443472015-07-16 20:32:27 -07002350 Handle<mirror::Class> klass(
2351 hs.NewHandle(manager_->GetClassLinker()->FindClass(soa.Self(), descriptor, class_loader)));
2352
2353 if (klass.Get() != nullptr && !SkipClass(jclass_loader, dex_file, klass.Get())) {
2354 // Only try to initialize classes that were successfully verified.
2355 if (klass->IsVerified()) {
2356 // Attempt to initialize the class but bail if we either need to initialize the super-class
2357 // or static fields.
2358 manager_->GetClassLinker()->EnsureInitialized(soa.Self(), klass, false, false);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07002359 if (!klass->IsInitialized()) {
Mathieu Chartier90443472015-07-16 20:32:27 -07002360 // We don't want non-trivial class initialization occurring on multiple threads due to
2361 // deadlock problems. For example, a parent class is initialized (holding its lock) that
2362 // refers to a sub-class in its static/class initializer causing it to try to acquire the
2363 // sub-class' lock. While on a second thread the sub-class is initialized (holding its lock)
2364 // after first initializing its parents, whose locks are acquired. This leads to a
2365 // parent-to-child and a child-to-parent lock ordering and consequent potential deadlock.
2366 // We need to use an ObjectLock due to potential suspension in the interpreting code. Rather
2367 // than use a special Object for the purpose we use the Class of java.lang.Class.
2368 Handle<mirror::Class> h_klass(hs.NewHandle(klass->GetClass()));
2369 ObjectLock<mirror::Class> lock(soa.Self(), h_klass);
2370 // Attempt to initialize allowing initialization of parent classes but still not static
2371 // fields.
2372 manager_->GetClassLinker()->EnsureInitialized(soa.Self(), klass, false, true);
2373 if (!klass->IsInitialized()) {
2374 // We need to initialize static fields, we only do this for image classes that aren't
2375 // marked with the $NoPreloadHolder (which implies this should not be initialized early).
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002376 bool can_init_static_fields = manager_->GetCompiler()->IsBootImage() &&
Mathieu Chartier90443472015-07-16 20:32:27 -07002377 manager_->GetCompiler()->IsImageClass(descriptor) &&
2378 !StringPiece(descriptor).ends_with("$NoPreloadHolder;");
2379 if (can_init_static_fields) {
2380 VLOG(compiler) << "Initializing: " << descriptor;
2381 // TODO multithreading support. We should ensure the current compilation thread has
2382 // exclusive access to the runtime and the transaction. To achieve this, we could use
2383 // a ReaderWriterMutex but we're holding the mutator lock so we fail mutex sanity
2384 // checks in Thread::AssertThreadSuspensionIsAllowable.
2385 Runtime* const runtime = Runtime::Current();
2386 Transaction transaction;
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002387
Mathieu Chartier90443472015-07-16 20:32:27 -07002388 // Run the class initializer in transaction mode.
2389 runtime->EnterTransactionMode(&transaction);
2390 const mirror::Class::Status old_status = klass->GetStatus();
2391 bool success = manager_->GetClassLinker()->EnsureInitialized(soa.Self(), klass, true,
2392 true);
2393 // TODO we detach transaction from runtime to indicate we quit the transactional
2394 // mode which prevents the GC from visiting objects modified during the transaction.
2395 // Ensure GC is not run so don't access freed objects when aborting transaction.
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07002396
Mathieu Chartier268764d2016-09-13 12:09:38 -07002397 ScopedAssertNoThreadSuspension ants("Transaction end");
Mathieu Chartier90443472015-07-16 20:32:27 -07002398 runtime->ExitTransactionMode();
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002399
Mathieu Chartier90443472015-07-16 20:32:27 -07002400 if (!success) {
2401 CHECK(soa.Self()->IsExceptionPending());
2402 mirror::Throwable* exception = soa.Self()->GetException();
2403 VLOG(compiler) << "Initialization of " << descriptor << " aborted because of "
2404 << exception->Dump();
2405 std::ostream* file_log = manager_->GetCompiler()->
2406 GetCompilerOptions().GetInitFailureOutput();
2407 if (file_log != nullptr) {
2408 *file_log << descriptor << "\n";
2409 *file_log << exception->Dump() << "\n";
2410 }
2411 soa.Self()->ClearException();
2412 transaction.Rollback();
2413 CHECK_EQ(old_status, klass->GetStatus()) << "Previous class status not restored";
Andreas Gampedbfe2542014-11-25 22:21:42 -08002414 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002415 }
2416 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002417 soa.Self()->AssertNoPendingException();
Brian Carlstrom7940e442013-07-12 13:46:57 -07002418 }
2419 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002420 // Record the final class status if necessary.
2421 ClassReference ref(manager_->GetDexFile(), class_def_index);
2422 manager_->GetCompiler()->RecordClassStatus(ref, klass->GetStatus());
Brian Carlstrom7940e442013-07-12 13:46:57 -07002423 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002424 // Clear any class not found or verification exceptions.
2425 soa.Self()->ClearException();
Brian Carlstrom7940e442013-07-12 13:46:57 -07002426 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002427
2428 private:
2429 const ParallelCompilationManager* const manager_;
2430};
Brian Carlstrom7940e442013-07-12 13:46:57 -07002431
Andreas Gampeace0dc12016-01-20 13:33:13 -08002432void CompilerDriver::InitializeClasses(jobject jni_class_loader,
2433 const DexFile& dex_file,
Andreas Gampede7b4362014-07-28 18:38:57 -07002434 const std::vector<const DexFile*>& dex_files,
Andreas Gampeace0dc12016-01-20 13:33:13 -08002435 TimingLogger* timings) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07002436 TimingLogger::ScopedTiming t("InitializeNoClinit", timings);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002437
2438 // Initialization allocates objects and needs to run single-threaded to be deterministic.
2439 bool force_determinism = GetCompilerOptions().IsForceDeterminism();
2440 ThreadPool* init_thread_pool = force_determinism
2441 ? single_thread_pool_.get()
2442 : parallel_thread_pool_.get();
2443 size_t init_thread_count = force_determinism ? 1U : parallel_thread_count_;
2444
Brian Carlstrom7940e442013-07-12 13:46:57 -07002445 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Andreas Gampede7b4362014-07-28 18:38:57 -07002446 ParallelCompilationManager context(class_linker, jni_class_loader, this, &dex_file, dex_files,
Andreas Gampeace0dc12016-01-20 13:33:13 -08002447 init_thread_pool);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002448 if (IsBootImage()) {
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002449 // TODO: remove this when transactional mode supports multithreading.
Andreas Gampeace0dc12016-01-20 13:33:13 -08002450 init_thread_count = 1U;
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002451 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002452 InitializeClassVisitor visitor(&context);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002453 context.ForAll(0, dex_file.NumClassDefs(), &visitor, init_thread_count);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002454}
2455
Mathieu Chartier91288d82016-04-28 09:44:54 -07002456class InitializeArrayClassesAndCreateConflictTablesVisitor : public ClassVisitor {
Mathieu Chartier085a0722016-04-01 17:33:31 -07002457 public:
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002458 virtual bool operator()(mirror::Class* klass) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier91288d82016-04-28 09:44:54 -07002459 if (Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(klass)) {
2460 return true;
2461 }
Mathieu Chartier085a0722016-04-01 17:33:31 -07002462 if (klass->IsArrayClass()) {
2463 StackHandleScope<1> hs(Thread::Current());
2464 Runtime::Current()->GetClassLinker()->EnsureInitialized(hs.Self(),
2465 hs.NewHandle(klass),
2466 true,
2467 true);
2468 }
Mathieu Chartier91288d82016-04-28 09:44:54 -07002469 // Create the conflict tables.
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00002470 FillIMTAndConflictTables(klass);
Nicolas Geoffray88f288e2016-06-29 08:17:52 +00002471 return true;
Nelli Kimbadee982016-05-13 13:08:53 +03002472 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00002473
2474 private:
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002475 void FillIMTAndConflictTables(mirror::Class* klass) REQUIRES_SHARED(Locks::mutator_lock_) {
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00002476 if (!klass->ShouldHaveImt()) {
2477 return;
2478 }
2479 if (visited_classes_.find(klass) != visited_classes_.end()) {
2480 return;
2481 }
2482 if (klass->HasSuperClass()) {
2483 FillIMTAndConflictTables(klass->GetSuperClass());
2484 }
2485 if (!klass->IsTemp()) {
2486 Runtime::Current()->GetClassLinker()->FillIMTAndConflictTables(klass);
2487 }
2488 visited_classes_.insert(klass);
2489 }
2490
2491 std::set<mirror::Class*> visited_classes_;
Mathieu Chartier085a0722016-04-01 17:33:31 -07002492};
2493
Brian Carlstrom7940e442013-07-12 13:46:57 -07002494void CompilerDriver::InitializeClasses(jobject class_loader,
2495 const std::vector<const DexFile*>& dex_files,
Andreas Gampeace0dc12016-01-20 13:33:13 -08002496 TimingLogger* timings) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07002497 for (size_t i = 0; i != dex_files.size(); ++i) {
2498 const DexFile* dex_file = dex_files[i];
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002499 CHECK(dex_file != nullptr);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002500 InitializeClasses(class_loader, *dex_file, dex_files, timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002501 }
Mathieu Chartier91288d82016-04-28 09:44:54 -07002502 if (boot_image_ || app_image_) {
Mathieu Chartier085a0722016-04-01 17:33:31 -07002503 // Make sure that we call EnsureIntiailized on all the array classes to call
2504 // SetVerificationAttempted so that the access flags are set. If we do not do this they get
2505 // changed at runtime resulting in more dirty image pages.
Mathieu Chartier91288d82016-04-28 09:44:54 -07002506 // Also create conflict tables.
2507 // Only useful if we are compiling an image (image_classes_ is not null).
Mathieu Chartier085a0722016-04-01 17:33:31 -07002508 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartier91288d82016-04-28 09:44:54 -07002509 InitializeArrayClassesAndCreateConflictTablesVisitor visitor;
2510 Runtime::Current()->GetClassLinker()->VisitClassesWithoutClassesLock(&visitor);
Mathieu Chartier085a0722016-04-01 17:33:31 -07002511 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002512 if (IsBootImage()) {
Mathieu Chartier093ef212014-08-11 13:52:12 -07002513 // Prune garbage objects created during aborted transactions.
2514 Runtime::Current()->GetHeap()->CollectGarbage(true);
2515 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002516}
2517
Andreas Gampeace0dc12016-01-20 13:33:13 -08002518void CompilerDriver::Compile(jobject class_loader,
2519 const std::vector<const DexFile*>& dex_files,
2520 TimingLogger* timings) {
Calin Juravle998c2162015-12-21 15:39:33 +02002521 if (kDebugProfileGuidedCompilation) {
2522 LOG(INFO) << "[ProfileGuidedCompilation] " <<
2523 ((profile_compilation_info_ == nullptr)
2524 ? "null"
2525 : profile_compilation_info_->DumpInfo(&dex_files));
Calin Juravle226501b2015-12-11 14:41:31 +00002526 }
Vladimir Marko492a7fa2016-06-01 18:38:43 +01002527
2528 DCHECK(current_dex_to_dex_methods_ == nullptr);
2529 for (const DexFile* dex_file : dex_files) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002530 CHECK(dex_file != nullptr);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002531 CompileDexFile(class_loader,
2532 *dex_file,
2533 dex_files,
2534 parallel_thread_pool_.get(),
2535 parallel_thread_count_,
2536 timings);
Calin Juravle69158982016-03-16 11:53:41 +00002537 const ArenaPool* const arena_pool = Runtime::Current()->GetArenaPool();
2538 const size_t arena_alloc = arena_pool->GetBytesAllocated();
2539 max_arena_alloc_ = std::max(arena_alloc, max_arena_alloc_);
Jean-Philippe Halimica76a1a2016-02-02 19:48:52 +01002540 Runtime::Current()->ReclaimArenaPoolMemory();
Brian Carlstrom7940e442013-07-12 13:46:57 -07002541 }
Vladimir Marko492a7fa2016-06-01 18:38:43 +01002542
2543 ArrayRef<DexFileMethodSet> dex_to_dex_references;
2544 {
2545 // From this point on, we shall not modify dex_to_dex_references_, so
2546 // just grab a reference to it that we use without holding the mutex.
2547 MutexLock lock(Thread::Current(), dex_to_dex_references_lock_);
2548 dex_to_dex_references = ArrayRef<DexFileMethodSet>(dex_to_dex_references_);
2549 }
2550 for (const auto& method_set : dex_to_dex_references) {
2551 current_dex_to_dex_methods_ = &method_set.GetMethodIndexes();
2552 CompileDexFile(class_loader,
2553 method_set.GetDexFile(),
2554 dex_files,
2555 parallel_thread_pool_.get(),
2556 parallel_thread_count_,
2557 timings);
2558 }
2559 current_dex_to_dex_methods_ = nullptr;
2560
Andreas Gampe8d295f82015-01-20 14:50:21 -08002561 VLOG(compiler) << "Compile: " << GetMemoryUsageString(false);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002562}
2563
Mathieu Chartier90443472015-07-16 20:32:27 -07002564class CompileClassVisitor : public CompilationVisitor {
2565 public:
2566 explicit CompileClassVisitor(const ParallelCompilationManager* manager) : manager_(manager) {}
2567
2568 virtual void Visit(size_t class_def_index) REQUIRES(!Locks::mutator_lock_) OVERRIDE {
2569 ATRACE_CALL();
2570 const DexFile& dex_file = *manager_->GetDexFile();
2571 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
2572 ClassLinker* class_linker = manager_->GetClassLinker();
2573 jobject jclass_loader = manager_->GetClassLoader();
Mathieu Chartier90443472015-07-16 20:32:27 -07002574 ClassReference ref(&dex_file, class_def_index);
2575 // Skip compiling classes with generic verifier failures since they will still fail at runtime
2576 if (manager_->GetCompiler()->verification_results_->IsClassRejected(ref)) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07002577 return;
2578 }
Mathieu Chartier736b5602015-09-02 14:54:11 -07002579 // Use a scoped object access to perform to the quick SkipClass check.
2580 const char* descriptor = dex_file.GetClassDescriptor(class_def);
2581 ScopedObjectAccess soa(Thread::Current());
2582 StackHandleScope<3> hs(soa.Self());
2583 Handle<mirror::ClassLoader> class_loader(
Mathieu Chartier0795f232016-09-27 18:43:30 -07002584 hs.NewHandle(soa.Decode<mirror::ClassLoader>(jclass_loader)));
Mathieu Chartier736b5602015-09-02 14:54:11 -07002585 Handle<mirror::Class> klass(
2586 hs.NewHandle(class_linker->FindClass(soa.Self(), descriptor, class_loader)));
2587 Handle<mirror::DexCache> dex_cache;
2588 if (klass.Get() == nullptr) {
2589 soa.Self()->AssertPendingException();
2590 soa.Self()->ClearException();
2591 dex_cache = hs.NewHandle(class_linker->FindDexCache(soa.Self(), dex_file));
2592 } else if (SkipClass(jclass_loader, dex_file, klass.Get())) {
2593 return;
2594 } else {
2595 dex_cache = hs.NewHandle(klass->GetDexCache());
2596 }
2597
Mathieu Chartier90443472015-07-16 20:32:27 -07002598 const uint8_t* class_data = dex_file.GetClassData(class_def);
2599 if (class_data == nullptr) {
2600 // empty class, probably a marker interface
2601 return;
Brian Carlstrom7940e442013-07-12 13:46:57 -07002602 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002603
Mathieu Chartier736b5602015-09-02 14:54:11 -07002604 // Go to native so that we don't block GC during compilation.
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07002605 ScopedThreadSuspension sts(soa.Self(), kNative);
Mathieu Chartier736b5602015-09-02 14:54:11 -07002606
Mathieu Chartier90443472015-07-16 20:32:27 -07002607 CompilerDriver* const driver = manager_->GetCompiler();
2608
2609 // Can we run DEX-to-DEX compiler on this class ?
Andreas Gampe5eb0d382015-07-23 01:19:26 -07002610 optimizer::DexToDexCompilationLevel dex_to_dex_compilation_level =
Mathieu Chartier736b5602015-09-02 14:54:11 -07002611 GetDexToDexCompilationLevel(soa.Self(), *driver, jclass_loader, dex_file, class_def);
Andreas Gampe5eb0d382015-07-23 01:19:26 -07002612
Mathieu Chartier90443472015-07-16 20:32:27 -07002613 ClassDataItemIterator it(dex_file, class_data);
2614 // Skip fields
2615 while (it.HasNextStaticField()) {
2616 it.Next();
2617 }
2618 while (it.HasNextInstanceField()) {
2619 it.Next();
2620 }
2621
2622 bool compilation_enabled = driver->IsClassToCompile(
2623 dex_file.StringByTypeIdx(class_def.class_idx_));
2624
2625 // Compile direct methods
2626 int64_t previous_direct_method_idx = -1;
2627 while (it.HasNextDirectMethod()) {
2628 uint32_t method_idx = it.GetMemberIndex();
2629 if (method_idx == previous_direct_method_idx) {
2630 // smali can create dex files with two encoded_methods sharing the same method_idx
2631 // http://code.google.com/p/smali/issues/detail?id=119
2632 it.Next();
2633 continue;
2634 }
2635 previous_direct_method_idx = method_idx;
Mathieu Chartier736b5602015-09-02 14:54:11 -07002636 CompileMethod(soa.Self(), driver, it.GetMethodCodeItem(), it.GetMethodAccessFlags(),
Andreas Gampe5eb0d382015-07-23 01:19:26 -07002637 it.GetMethodInvokeType(class_def), class_def_index,
2638 method_idx, jclass_loader, dex_file, dex_to_dex_compilation_level,
Mathieu Chartier736b5602015-09-02 14:54:11 -07002639 compilation_enabled, dex_cache);
Mathieu Chartier90443472015-07-16 20:32:27 -07002640 it.Next();
2641 }
2642 // Compile virtual methods
2643 int64_t previous_virtual_method_idx = -1;
2644 while (it.HasNextVirtualMethod()) {
2645 uint32_t method_idx = it.GetMemberIndex();
2646 if (method_idx == previous_virtual_method_idx) {
2647 // smali can create dex files with two encoded_methods sharing the same method_idx
2648 // http://code.google.com/p/smali/issues/detail?id=119
2649 it.Next();
2650 continue;
2651 }
2652 previous_virtual_method_idx = method_idx;
Mathieu Chartier736b5602015-09-02 14:54:11 -07002653 CompileMethod(soa.Self(), driver, it.GetMethodCodeItem(), it.GetMethodAccessFlags(),
Andreas Gampe5eb0d382015-07-23 01:19:26 -07002654 it.GetMethodInvokeType(class_def), class_def_index,
2655 method_idx, jclass_loader, dex_file, dex_to_dex_compilation_level,
Mathieu Chartier736b5602015-09-02 14:54:11 -07002656 compilation_enabled, dex_cache);
Mathieu Chartier90443472015-07-16 20:32:27 -07002657 it.Next();
2658 }
2659 DCHECK(!it.HasNext());
Brian Carlstrom7940e442013-07-12 13:46:57 -07002660 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002661
2662 private:
2663 const ParallelCompilationManager* const manager_;
2664};
Brian Carlstrom7940e442013-07-12 13:46:57 -07002665
Andreas Gampeace0dc12016-01-20 13:33:13 -08002666void CompilerDriver::CompileDexFile(jobject class_loader,
2667 const DexFile& dex_file,
Andreas Gampede7b4362014-07-28 18:38:57 -07002668 const std::vector<const DexFile*>& dex_files,
Andreas Gampeace0dc12016-01-20 13:33:13 -08002669 ThreadPool* thread_pool,
2670 size_t thread_count,
2671 TimingLogger* timings) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07002672 TimingLogger::ScopedTiming t("Compile Dex File", timings);
Ian Rogersbe7149f2013-08-20 09:29:39 -07002673 ParallelCompilationManager context(Runtime::Current()->GetClassLinker(), class_loader, this,
Andreas Gampede7b4362014-07-28 18:38:57 -07002674 &dex_file, dex_files, thread_pool);
Mathieu Chartier90443472015-07-16 20:32:27 -07002675 CompileClassVisitor visitor(&context);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002676 context.ForAll(0, dex_file.NumClassDefs(), &visitor, thread_count);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002677}
2678
Andreas Gampe5eb0d382015-07-23 01:19:26 -07002679void CompilerDriver::AddCompiledMethod(const MethodReference& method_ref,
2680 CompiledMethod* const compiled_method,
2681 size_t non_relative_linker_patch_count) {
2682 DCHECK(GetCompiledMethod(method_ref) == nullptr)
2683 << PrettyMethod(method_ref.dex_method_index, *method_ref.dex_file);
2684 {
2685 MutexLock mu(Thread::Current(), compiled_methods_lock_);
2686 compiled_methods_.Put(method_ref, compiled_method);
2687 non_relative_linker_patch_count_ += non_relative_linker_patch_count;
Ian Rogersa4a3f402014-10-20 18:10:34 -07002688 }
Andreas Gampe5eb0d382015-07-23 01:19:26 -07002689 DCHECK(GetCompiledMethod(method_ref) != nullptr)
2690 << PrettyMethod(method_ref.dex_method_index, *method_ref.dex_file);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002691}
2692
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002693void CompilerDriver::RemoveCompiledMethod(const MethodReference& method_ref) {
2694 CompiledMethod* compiled_method = nullptr;
2695 {
2696 MutexLock mu(Thread::Current(), compiled_methods_lock_);
2697 auto it = compiled_methods_.find(method_ref);
2698 if (it != compiled_methods_.end()) {
2699 compiled_method = it->second;
2700 compiled_methods_.erase(it);
2701 }
2702 }
2703 if (compiled_method != nullptr) {
2704 CompiledMethod::ReleaseSwapAllocatedCompiledMethod(this, compiled_method);
2705 }
2706}
2707
Brian Carlstrom7940e442013-07-12 13:46:57 -07002708CompiledClass* CompilerDriver::GetCompiledClass(ClassReference ref) const {
2709 MutexLock mu(Thread::Current(), compiled_classes_lock_);
2710 ClassTable::const_iterator it = compiled_classes_.find(ref);
2711 if (it == compiled_classes_.end()) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002712 return nullptr;
Brian Carlstrom7940e442013-07-12 13:46:57 -07002713 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002714 CHECK(it->second != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002715 return it->second;
2716}
2717
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07002718void CompilerDriver::RecordClassStatus(ClassReference ref, mirror::Class::Status status) {
2719 MutexLock mu(Thread::Current(), compiled_classes_lock_);
2720 auto it = compiled_classes_.find(ref);
2721 if (it == compiled_classes_.end() || it->second->GetStatus() != status) {
2722 // An entry doesn't exist or the status is lower than the new status.
2723 if (it != compiled_classes_.end()) {
2724 CHECK_GT(status, it->second->GetStatus());
2725 delete it->second;
2726 }
2727 switch (status) {
2728 case mirror::Class::kStatusNotReady:
2729 case mirror::Class::kStatusError:
2730 case mirror::Class::kStatusRetryVerificationAtRuntime:
2731 case mirror::Class::kStatusVerified:
2732 case mirror::Class::kStatusInitialized:
Mathieu Chartiera8077802016-03-16 19:08:31 -07002733 case mirror::Class::kStatusResolved:
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07002734 break; // Expected states.
2735 default:
2736 LOG(FATAL) << "Unexpected class status for class "
2737 << PrettyDescriptor(ref.first->GetClassDescriptor(ref.first->GetClassDef(ref.second)))
2738 << " of " << status;
2739 }
2740 CompiledClass* compiled_class = new CompiledClass(status);
2741 compiled_classes_.Overwrite(ref, compiled_class);
2742 }
2743}
2744
Brian Carlstrom7940e442013-07-12 13:46:57 -07002745CompiledMethod* CompilerDriver::GetCompiledMethod(MethodReference ref) const {
2746 MutexLock mu(Thread::Current(), compiled_methods_lock_);
2747 MethodTable::const_iterator it = compiled_methods_.find(ref);
2748 if (it == compiled_methods_.end()) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002749 return nullptr;
Brian Carlstrom7940e442013-07-12 13:46:57 -07002750 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002751 CHECK(it->second != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002752 return it->second;
2753}
2754
Calin Juravlef1c6d9e2015-04-13 18:42:21 +01002755bool CompilerDriver::IsMethodVerifiedWithoutFailures(uint32_t method_idx,
2756 uint16_t class_def_idx,
2757 const DexFile& dex_file) const {
2758 const VerifiedMethod* verified_method = GetVerifiedMethod(&dex_file, method_idx);
2759 if (verified_method != nullptr) {
2760 return !verified_method->HasVerificationFailures();
2761 }
2762
2763 // If we can't find verification metadata, check if this is a system class (we trust that system
2764 // classes have their methods verified). If it's not, be conservative and assume the method
2765 // has not been verified successfully.
2766
2767 // TODO: When compiling the boot image it should be safe to assume that everything is verified,
2768 // even if methods are not found in the verification cache.
2769 const char* descriptor = dex_file.GetClassDescriptor(dex_file.GetClassDef(class_def_idx));
2770 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
2771 Thread* self = Thread::Current();
2772 ScopedObjectAccess soa(self);
2773 bool is_system_class = class_linker->FindSystemClass(self, descriptor) != nullptr;
2774 if (!is_system_class) {
2775 self->ClearException();
2776 }
2777 return is_system_class;
2778}
2779
Vladimir Markof4da6752014-08-01 19:04:18 +01002780size_t CompilerDriver::GetNonRelativeLinkerPatchCount() const {
2781 MutexLock mu(Thread::Current(), compiled_methods_lock_);
2782 return non_relative_linker_patch_count_;
2783}
2784
Mathieu Chartierc4ae9162016-04-07 13:19:19 -07002785void CompilerDriver::SetRequiresConstructorBarrier(Thread* self,
2786 const DexFile* dex_file,
2787 uint16_t class_def_index,
2788 bool requires) {
2789 WriterMutexLock mu(self, requires_constructor_barrier_lock_);
2790 requires_constructor_barrier_.emplace(ClassReference(dex_file, class_def_index), requires);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002791}
2792
Mathieu Chartier371bd832016-04-07 10:19:48 -07002793bool CompilerDriver::RequiresConstructorBarrier(Thread* self,
2794 const DexFile* dex_file,
Mathieu Chartierc4ae9162016-04-07 13:19:19 -07002795 uint16_t class_def_index) {
2796 ClassReference class_ref(dex_file, class_def_index);
2797 {
2798 ReaderMutexLock mu(self, requires_constructor_barrier_lock_);
2799 auto it = requires_constructor_barrier_.find(class_ref);
2800 if (it != requires_constructor_barrier_.end()) {
2801 return it->second;
2802 }
Mathieu Chartierb5d38612016-04-07 10:52:52 -07002803 }
Mathieu Chartierc4ae9162016-04-07 13:19:19 -07002804 WriterMutexLock mu(self, requires_constructor_barrier_lock_);
2805 const bool requires = RequiresConstructorBarrier(*dex_file, class_def_index);
2806 requires_constructor_barrier_.emplace(class_ref, requires);
2807 return requires;
Brian Carlstrom7940e442013-07-12 13:46:57 -07002808}
2809
Andreas Gampe8d295f82015-01-20 14:50:21 -08002810std::string CompilerDriver::GetMemoryUsageString(bool extended) const {
Mathieu Chartierab972ef2014-12-03 17:38:22 -08002811 std::ostringstream oss;
Calin Juravle69158982016-03-16 11:53:41 +00002812 const gc::Heap* const heap = Runtime::Current()->GetHeap();
Anton Kirilovdd9473b2016-01-28 15:08:01 +00002813 const size_t java_alloc = heap->GetBytesAllocated();
Calin Juravle69158982016-03-16 11:53:41 +00002814 oss << "arena alloc=" << PrettySize(max_arena_alloc_) << " (" << max_arena_alloc_ << "B)";
Anton Kirilovdd9473b2016-01-28 15:08:01 +00002815 oss << " java alloc=" << PrettySize(java_alloc) << " (" << java_alloc << "B)";
Elliott Hughes7bf5a262015-04-02 20:55:07 -07002816#if defined(__BIONIC__) || defined(__GLIBC__)
Anton Kirilovdd9473b2016-01-28 15:08:01 +00002817 const struct mallinfo info = mallinfo();
Mathieu Chartierab972ef2014-12-03 17:38:22 -08002818 const size_t allocated_space = static_cast<size_t>(info.uordblks);
2819 const size_t free_space = static_cast<size_t>(info.fordblks);
Anton Kirilovdd9473b2016-01-28 15:08:01 +00002820 oss << " native alloc=" << PrettySize(allocated_space) << " (" << allocated_space << "B)"
2821 << " free=" << PrettySize(free_space) << " (" << free_space << "B)";
Mathieu Chartierab972ef2014-12-03 17:38:22 -08002822#endif
Vladimir Marko35831e82015-09-11 11:59:18 +01002823 compiled_method_storage_.DumpMemoryUsage(oss, extended);
Mathieu Chartierab972ef2014-12-03 17:38:22 -08002824 return oss.str();
2825}
2826
Jeff Haodcdc85b2015-12-04 14:06:18 -08002827bool CompilerDriver::MayInlineInternal(const DexFile* inlined_from,
2828 const DexFile* inlined_into) const {
2829 // We're not allowed to inline across dex files if we're the no-inline-from dex file.
2830 if (inlined_from != inlined_into &&
Vladimir Marko47496c22016-01-27 16:15:08 +00002831 compiler_options_->GetNoInlineFromDexFile() != nullptr &&
2832 ContainsElement(*compiler_options_->GetNoInlineFromDexFile(), inlined_from)) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002833 return false;
2834 }
2835
2836 return true;
2837}
2838
Andreas Gampeace0dc12016-01-20 13:33:13 -08002839void CompilerDriver::InitializeThreadPools() {
2840 size_t parallel_count = parallel_thread_count_ > 0 ? parallel_thread_count_ - 1 : 0;
2841 parallel_thread_pool_.reset(
2842 new ThreadPool("Compiler driver thread pool", parallel_count));
2843 single_thread_pool_.reset(new ThreadPool("Single-threaded Compiler driver thread pool", 0));
2844}
2845
2846void CompilerDriver::FreeThreadPools() {
2847 parallel_thread_pool_.reset();
2848 single_thread_pool_.reset();
2849}
2850
Brian Carlstrom7940e442013-07-12 13:46:57 -07002851} // namespace art