blob: 53e068edf2547ff56b88eadefa26aec0a1fda7fc [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"
Vladimir Marko492a7fa2016-06-01 18:38:43 +010029#include "base/bit_vector.h"
Andreas Gampe542451c2016-07-26 09:02:02 -070030#include "base/enums.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070031#include "base/stl_util.h"
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -080032#include "base/systrace.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010033#include "base/time_utils.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070034#include "base/timing_logger.h"
Vladimir Marko3481ba22015-04-13 12:22:36 +010035#include "class_linker-inl.h"
Mingyao Yang98d1cc82014-05-15 17:02:16 -070036#include "compiled_class.h"
Vladimir Marko20f85592015-03-19 10:07:02 +000037#include "compiled_method.h"
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +000038#include "compiler.h"
Vladimir Markobe0e5462014-02-26 11:24:15 +000039#include "compiler_driver-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070040#include "dex_compilation_unit.h"
41#include "dex_file-inl.h"
Andreas Gampeace0dc12016-01-20 13:33:13 -080042#include "dex_instruction-inl.h"
Andreas Gampe5eb0d382015-07-23 01:19:26 -070043#include "dex/dex_to_dex_compiler.h"
Vladimir Markoc7f83202014-01-24 17:55:18 +000044#include "dex/verification_results.h"
Vladimir Marko2730db02014-01-27 11:15:17 +000045#include "dex/verified_method.h"
Vladimir Marko2bc47802014-02-10 09:43:07 +000046#include "dex/quick/dex_file_method_inliner.h"
Jeff Hao848f70a2014-01-15 13:49:50 -080047#include "dex/quick/dex_file_to_method_inliner_map.h"
Mark Mendellae9fd932014-02-10 16:14:35 -080048#include "driver/compiler_options.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"
62#include "scoped_thread_state_change.h"
63#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 Marko492a7fa2016-06-01 18:38:43 +010070#include "utils/array_ref.h"
Vladimir Marko20f85592015-03-19 10:07:02 +000071#include "utils/dex_cache_arrays_layout-inl.h"
Andreas Gampee21dc3d2014-12-08 16:59:43 -080072#include "utils/swap_space.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070073#include "verifier/method_verifier.h"
Vladimir Marko2bc47802014-02-10 09:43:07 +000074#include "verifier/method_verifier-inl.h"
Andreas Gampe5fd66d02016-09-12 20:22:19 -070075#include "verifier/verifier_log_mode.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070076
Brian Carlstrom7940e442013-07-12 13:46:57 -070077namespace art {
78
Mathieu Chartier8e219ae2014-08-19 14:29:46 -070079static constexpr bool kTimeCompileMethod = !kIsDebugBuild;
80
Calin Juravle226501b2015-12-11 14:41:31 +000081// Print additional info during profile guided compilation.
82static constexpr bool kDebugProfileGuidedCompilation = false;
83
Brian Carlstrom7940e442013-07-12 13:46:57 -070084static double Percentage(size_t x, size_t y) {
85 return 100.0 * (static_cast<double>(x)) / (static_cast<double>(x + y));
86}
87
88static void DumpStat(size_t x, size_t y, const char* str) {
89 if (x == 0 && y == 0) {
90 return;
91 }
Ian Rogerse732ef12013-10-09 15:22:24 -070092 LOG(INFO) << Percentage(x, y) << "% of " << str << " for " << (x + y) << " cases";
Brian Carlstrom7940e442013-07-12 13:46:57 -070093}
94
Vladimir Markof096aad2014-01-23 15:51:58 +000095class CompilerDriver::AOTCompilationStats {
Brian Carlstrom7940e442013-07-12 13:46:57 -070096 public:
97 AOTCompilationStats()
98 : stats_lock_("AOT compilation statistics lock"),
99 types_in_dex_cache_(0), types_not_in_dex_cache_(0),
100 strings_in_dex_cache_(0), strings_not_in_dex_cache_(0),
101 resolved_types_(0), unresolved_types_(0),
102 resolved_instance_fields_(0), unresolved_instance_fields_(0),
103 resolved_local_static_fields_(0), resolved_static_fields_(0), unresolved_static_fields_(0),
104 type_based_devirtualization_(0),
105 safe_casts_(0), not_safe_casts_(0) {
106 for (size_t i = 0; i <= kMaxInvokeType; i++) {
107 resolved_methods_[i] = 0;
108 unresolved_methods_[i] = 0;
109 virtual_made_direct_[i] = 0;
110 direct_calls_to_boot_[i] = 0;
111 direct_methods_to_boot_[i] = 0;
112 }
113 }
114
115 void Dump() {
116 DumpStat(types_in_dex_cache_, types_not_in_dex_cache_, "types known to be in dex cache");
117 DumpStat(strings_in_dex_cache_, strings_not_in_dex_cache_, "strings known to be in dex cache");
118 DumpStat(resolved_types_, unresolved_types_, "types resolved");
119 DumpStat(resolved_instance_fields_, unresolved_instance_fields_, "instance fields resolved");
120 DumpStat(resolved_local_static_fields_ + resolved_static_fields_, unresolved_static_fields_,
121 "static fields resolved");
122 DumpStat(resolved_local_static_fields_, resolved_static_fields_ + unresolved_static_fields_,
123 "static fields local to a class");
124 DumpStat(safe_casts_, not_safe_casts_, "check-casts removed based on type information");
125 // Note, the code below subtracts the stat value so that when added to the stat value we have
126 // 100% of samples. TODO: clean this up.
127 DumpStat(type_based_devirtualization_,
128 resolved_methods_[kVirtual] + unresolved_methods_[kVirtual] +
129 resolved_methods_[kInterface] + unresolved_methods_[kInterface] -
130 type_based_devirtualization_,
131 "virtual/interface calls made direct based on type information");
132
133 for (size_t i = 0; i <= kMaxInvokeType; i++) {
134 std::ostringstream oss;
135 oss << static_cast<InvokeType>(i) << " methods were AOT resolved";
136 DumpStat(resolved_methods_[i], unresolved_methods_[i], oss.str().c_str());
137 if (virtual_made_direct_[i] > 0) {
138 std::ostringstream oss2;
139 oss2 << static_cast<InvokeType>(i) << " methods made direct";
140 DumpStat(virtual_made_direct_[i],
141 resolved_methods_[i] + unresolved_methods_[i] - virtual_made_direct_[i],
142 oss2.str().c_str());
143 }
144 if (direct_calls_to_boot_[i] > 0) {
145 std::ostringstream oss2;
146 oss2 << static_cast<InvokeType>(i) << " method calls are direct into boot";
147 DumpStat(direct_calls_to_boot_[i],
148 resolved_methods_[i] + unresolved_methods_[i] - direct_calls_to_boot_[i],
149 oss2.str().c_str());
150 }
151 if (direct_methods_to_boot_[i] > 0) {
152 std::ostringstream oss2;
153 oss2 << static_cast<InvokeType>(i) << " method calls have methods in boot";
154 DumpStat(direct_methods_to_boot_[i],
155 resolved_methods_[i] + unresolved_methods_[i] - direct_methods_to_boot_[i],
156 oss2.str().c_str());
157 }
158 }
159 }
160
161// Allow lossy statistics in non-debug builds.
162#ifndef NDEBUG
163#define STATS_LOCK() MutexLock mu(Thread::Current(), stats_lock_)
164#else
165#define STATS_LOCK()
166#endif
167
Mathieu Chartier90443472015-07-16 20:32:27 -0700168 void TypeInDexCache() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700169 STATS_LOCK();
170 types_in_dex_cache_++;
171 }
172
Mathieu Chartier90443472015-07-16 20:32:27 -0700173 void TypeNotInDexCache() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700174 STATS_LOCK();
175 types_not_in_dex_cache_++;
176 }
177
Mathieu Chartier90443472015-07-16 20:32:27 -0700178 void StringInDexCache() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700179 STATS_LOCK();
180 strings_in_dex_cache_++;
181 }
182
Mathieu Chartier90443472015-07-16 20:32:27 -0700183 void StringNotInDexCache() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700184 STATS_LOCK();
185 strings_not_in_dex_cache_++;
186 }
187
Mathieu Chartier90443472015-07-16 20:32:27 -0700188 void TypeDoesntNeedAccessCheck() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700189 STATS_LOCK();
190 resolved_types_++;
191 }
192
Mathieu Chartier90443472015-07-16 20:32:27 -0700193 void TypeNeedsAccessCheck() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700194 STATS_LOCK();
195 unresolved_types_++;
196 }
197
Mathieu Chartier90443472015-07-16 20:32:27 -0700198 void ResolvedInstanceField() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700199 STATS_LOCK();
200 resolved_instance_fields_++;
201 }
202
Mathieu Chartier90443472015-07-16 20:32:27 -0700203 void UnresolvedInstanceField() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700204 STATS_LOCK();
205 unresolved_instance_fields_++;
206 }
207
Mathieu Chartier90443472015-07-16 20:32:27 -0700208 void ResolvedLocalStaticField() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700209 STATS_LOCK();
210 resolved_local_static_fields_++;
211 }
212
Mathieu Chartier90443472015-07-16 20:32:27 -0700213 void ResolvedStaticField() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700214 STATS_LOCK();
215 resolved_static_fields_++;
216 }
217
Mathieu Chartier90443472015-07-16 20:32:27 -0700218 void UnresolvedStaticField() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700219 STATS_LOCK();
220 unresolved_static_fields_++;
221 }
222
223 // Indicate that type information from the verifier led to devirtualization.
Mathieu Chartier90443472015-07-16 20:32:27 -0700224 void PreciseTypeDevirtualization() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700225 STATS_LOCK();
226 type_based_devirtualization_++;
227 }
228
229 // Indicate that a method of the given type was resolved at compile time.
Mathieu Chartier90443472015-07-16 20:32:27 -0700230 void ResolvedMethod(InvokeType type) REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700231 DCHECK_LE(type, kMaxInvokeType);
232 STATS_LOCK();
233 resolved_methods_[type]++;
234 }
235
236 // Indicate that a method of the given type was unresolved at compile time as it was in an
237 // unknown dex file.
Mathieu Chartier90443472015-07-16 20:32:27 -0700238 void UnresolvedMethod(InvokeType type) REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700239 DCHECK_LE(type, kMaxInvokeType);
240 STATS_LOCK();
241 unresolved_methods_[type]++;
242 }
243
244 // Indicate that a type of virtual method dispatch has been converted into a direct method
245 // dispatch.
Mathieu Chartier90443472015-07-16 20:32:27 -0700246 void VirtualMadeDirect(InvokeType type) REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700247 DCHECK(type == kVirtual || type == kInterface || type == kSuper);
248 STATS_LOCK();
249 virtual_made_direct_[type]++;
250 }
251
252 // Indicate that a method of the given type was able to call directly into boot.
Mathieu Chartier90443472015-07-16 20:32:27 -0700253 void DirectCallsToBoot(InvokeType type) REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700254 DCHECK_LE(type, kMaxInvokeType);
255 STATS_LOCK();
256 direct_calls_to_boot_[type]++;
257 }
258
259 // Indicate that a method of the given type was able to be resolved directly from boot.
Mathieu Chartier90443472015-07-16 20:32:27 -0700260 void DirectMethodsToBoot(InvokeType type) REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700261 DCHECK_LE(type, kMaxInvokeType);
262 STATS_LOCK();
263 direct_methods_to_boot_[type]++;
264 }
265
Mathieu Chartier90443472015-07-16 20:32:27 -0700266 void ProcessedInvoke(InvokeType type, int flags) REQUIRES(!stats_lock_) {
Vladimir Markof096aad2014-01-23 15:51:58 +0000267 STATS_LOCK();
268 if (flags == 0) {
269 unresolved_methods_[type]++;
270 } else {
271 DCHECK_NE((flags & kFlagMethodResolved), 0);
272 resolved_methods_[type]++;
273 if ((flags & kFlagVirtualMadeDirect) != 0) {
274 virtual_made_direct_[type]++;
275 if ((flags & kFlagPreciseTypeDevirtualization) != 0) {
276 type_based_devirtualization_++;
277 }
278 } else {
279 DCHECK_EQ((flags & kFlagPreciseTypeDevirtualization), 0);
280 }
281 if ((flags & kFlagDirectCallToBoot) != 0) {
282 direct_calls_to_boot_[type]++;
283 }
284 if ((flags & kFlagDirectMethodToBoot) != 0) {
285 direct_methods_to_boot_[type]++;
286 }
287 }
288 }
289
Brian Carlstrom7940e442013-07-12 13:46:57 -0700290 // A check-cast could be eliminated due to verifier type analysis.
Mathieu Chartier90443472015-07-16 20:32:27 -0700291 void SafeCast() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700292 STATS_LOCK();
293 safe_casts_++;
294 }
295
296 // A check-cast couldn't be eliminated due to verifier type analysis.
Mathieu Chartier90443472015-07-16 20:32:27 -0700297 void NotASafeCast() REQUIRES(!stats_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700298 STATS_LOCK();
299 not_safe_casts_++;
300 }
301
302 private:
303 Mutex stats_lock_;
304
305 size_t types_in_dex_cache_;
306 size_t types_not_in_dex_cache_;
307
308 size_t strings_in_dex_cache_;
309 size_t strings_not_in_dex_cache_;
310
311 size_t resolved_types_;
312 size_t unresolved_types_;
313
314 size_t resolved_instance_fields_;
315 size_t unresolved_instance_fields_;
316
317 size_t resolved_local_static_fields_;
318 size_t resolved_static_fields_;
319 size_t unresolved_static_fields_;
320 // Type based devirtualization for invoke interface and virtual.
321 size_t type_based_devirtualization_;
322
323 size_t resolved_methods_[kMaxInvokeType + 1];
324 size_t unresolved_methods_[kMaxInvokeType + 1];
325 size_t virtual_made_direct_[kMaxInvokeType + 1];
326 size_t direct_calls_to_boot_[kMaxInvokeType + 1];
327 size_t direct_methods_to_boot_[kMaxInvokeType + 1];
328
329 size_t safe_casts_;
330 size_t not_safe_casts_;
331
332 DISALLOW_COPY_AND_ASSIGN(AOTCompilationStats);
333};
334
Vladimir Marko492a7fa2016-06-01 18:38:43 +0100335class CompilerDriver::DexFileMethodSet {
336 public:
337 explicit DexFileMethodSet(const DexFile& dex_file)
338 : dex_file_(dex_file),
339 method_indexes_(dex_file.NumMethodIds(), false, Allocator::GetMallocAllocator()) {
340 }
341 DexFileMethodSet(DexFileMethodSet&& other) = default;
342
343 const DexFile& GetDexFile() const { return dex_file_; }
344
345 BitVector& GetMethodIndexes() { return method_indexes_; }
346 const BitVector& GetMethodIndexes() const { return method_indexes_; }
347
348 private:
349 const DexFile& dex_file_;
350 BitVector method_indexes_;
351};
352
Jeff Haodcdc85b2015-12-04 14:06:18 -0800353CompilerDriver::CompilerDriver(
354 const CompilerOptions* compiler_options,
355 VerificationResults* verification_results,
356 DexFileToMethodInlinerMap* method_inliner_map,
357 Compiler::Kind compiler_kind,
358 InstructionSet instruction_set,
359 const InstructionSetFeatures* instruction_set_features,
Vladimir Marko944da602016-02-19 12:27:55 +0000360 bool boot_image,
Mathieu Chartier91288d82016-04-28 09:44:54 -0700361 bool app_image,
Vladimir Marko944da602016-02-19 12:27:55 +0000362 std::unordered_set<std::string>* image_classes,
Jeff Haodcdc85b2015-12-04 14:06:18 -0800363 std::unordered_set<std::string>* compiled_classes,
364 std::unordered_set<std::string>* compiled_methods,
Vladimir Marko944da602016-02-19 12:27:55 +0000365 size_t thread_count,
366 bool dump_stats,
367 bool dump_passes,
368 CumulativeLogger* timer,
369 int swap_fd,
Calin Juravle998c2162015-12-21 15:39:33 +0200370 const ProfileCompilationInfo* profile_compilation_info)
Calin Juravle226501b2015-12-11 14:41:31 +0000371 : compiler_options_(compiler_options),
Brian Carlstrom6449c622014-02-10 23:48:36 -0800372 verification_results_(verification_results),
Vladimir Marko5816ed42013-11-27 17:04:20 +0000373 method_inliner_map_(method_inliner_map),
Ian Rogers72d32622014-05-06 16:20:11 -0700374 compiler_(Compiler::Create(this, compiler_kind)),
Jeff Hao48699fb2015-04-06 14:21:37 -0700375 compiler_kind_(compiler_kind),
Artem Serovba6b6792016-08-15 14:22:07 +0100376 instruction_set_(instruction_set == kArm ? kThumb2: instruction_set),
Dave Allison70202782013-10-22 17:52:19 -0700377 instruction_set_features_(instruction_set_features),
Mathieu Chartierc4ae9162016-04-07 13:19:19 -0700378 requires_constructor_barrier_lock_("constructor barrier lock"),
Brian Carlstrom7940e442013-07-12 13:46:57 -0700379 compiled_classes_lock_("compiled classes lock"),
380 compiled_methods_lock_("compiled method lock"),
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800381 compiled_methods_(MethodTable::key_compare()),
Vladimir Markof4da6752014-08-01 19:04:18 +0100382 non_relative_linker_patch_count_(0u),
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800383 boot_image_(boot_image),
Mathieu Chartier91288d82016-04-28 09:44:54 -0700384 app_image_(app_image),
Brian Carlstrom7940e442013-07-12 13:46:57 -0700385 image_classes_(image_classes),
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800386 classes_to_compile_(compiled_classes),
Andreas Gampe70bef0d2015-04-15 02:37:28 -0700387 methods_to_compile_(compiled_methods),
Andreas Gampe6cf49e52015-03-05 13:08:45 -0800388 had_hard_verifier_failure_(false),
Andreas Gampeace0dc12016-01-20 13:33:13 -0800389 parallel_thread_count_(thread_count),
Brian Carlstrom7940e442013-07-12 13:46:57 -0700390 stats_(new AOTCompilationStats),
391 dump_stats_(dump_stats),
Nicolas Geoffrayea3fa0b2014-02-10 11:59:41 +0000392 dump_passes_(dump_passes),
393 timings_logger_(timer),
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700394 compiler_context_(nullptr),
Alexey Frunzee3fb2452016-05-10 16:08:05 -0700395 support_boot_image_fixup_(instruction_set != kMips64),
Vladimir Markod1eaf0d2015-10-29 12:18:29 +0000396 dex_files_for_oat_file_(nullptr),
Calin Juravle998c2162015-12-21 15:39:33 +0200397 compiled_method_storage_(swap_fd),
Calin Juravle69158982016-03-16 11:53:41 +0000398 profile_compilation_info_(profile_compilation_info),
Vladimir Marko492a7fa2016-06-01 18:38:43 +0100399 max_arena_alloc_(0),
400 dex_to_dex_references_lock_("dex-to-dex references lock"),
401 dex_to_dex_references_(),
402 current_dex_to_dex_methods_(nullptr) {
Brian Carlstrom6449c622014-02-10 23:48:36 -0800403 DCHECK(compiler_options_ != nullptr);
Brian Carlstrom6449c622014-02-10 23:48:36 -0800404 DCHECK(method_inliner_map_ != nullptr);
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700405
Ian Rogers72d32622014-05-06 16:20:11 -0700406 compiler_->Init();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700407
Mathieu Chartiera8077802016-03-16 19:08:31 -0700408 if (compiler_options->VerifyOnlyProfile()) {
409 CHECK(profile_compilation_info_ != nullptr) << "Requires profile";
410 }
Mathieu Chartierc5dd3192015-12-09 16:38:30 -0800411 if (boot_image_) {
412 CHECK(image_classes_.get() != nullptr) << "Expected image classes for boot image";
413 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700414}
415
416CompilerDriver::~CompilerDriver() {
417 Thread* self = Thread::Current();
418 {
419 MutexLock mu(self, compiled_classes_lock_);
420 STLDeleteValues(&compiled_classes_);
421 }
422 {
423 MutexLock mu(self, compiled_methods_lock_);
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800424 for (auto& pair : compiled_methods_) {
425 CompiledMethod::ReleaseSwapAllocatedCompiledMethod(this, pair.second);
426 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700427 }
Ian Rogers72d32622014-05-06 16:20:11 -0700428 compiler_->UnInit();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700429}
430
Vladimir Marko35831e82015-09-11 11:59:18 +0100431
Ian Rogersdd7624d2014-03-14 17:43:00 -0700432#define CREATE_TRAMPOLINE(type, abi, offset) \
Andreas Gampeaf13ad92014-04-11 12:07:48 -0700433 if (Is64BitInstructionSet(instruction_set_)) { \
Ian Rogersdd7624d2014-03-14 17:43:00 -0700434 return CreateTrampoline64(instruction_set_, abi, \
Andreas Gampe542451c2016-07-26 09:02:02 -0700435 type ## _ENTRYPOINT_OFFSET(PointerSize::k64, offset)); \
Ian Rogersdd7624d2014-03-14 17:43:00 -0700436 } else { \
437 return CreateTrampoline32(instruction_set_, abi, \
Andreas Gampe542451c2016-07-26 09:02:02 -0700438 type ## _ENTRYPOINT_OFFSET(PointerSize::k32, offset)); \
Ian Rogersdd7624d2014-03-14 17:43:00 -0700439 }
440
Vladimir Marko93205e32016-04-13 11:59:46 +0100441std::unique_ptr<const std::vector<uint8_t>> CompilerDriver::CreateJniDlsymLookup() const {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700442 CREATE_TRAMPOLINE(JNI, kJniAbi, pDlsymLookup)
Ian Rogers848871b2013-08-05 10:56:33 -0700443}
444
Vladimir Marko93205e32016-04-13 11:59:46 +0100445std::unique_ptr<const std::vector<uint8_t>> CompilerDriver::CreateQuickGenericJniTrampoline()
446 const {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700447 CREATE_TRAMPOLINE(QUICK, kQuickAbi, pQuickGenericJniTrampoline)
Andreas Gampe2da88232014-02-27 12:26:20 -0800448}
449
Vladimir Marko93205e32016-04-13 11:59:46 +0100450std::unique_ptr<const std::vector<uint8_t>> CompilerDriver::CreateQuickImtConflictTrampoline()
451 const {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700452 CREATE_TRAMPOLINE(QUICK, kQuickAbi, pQuickImtConflictTrampoline)
Jeff Hao88474b42013-10-23 16:24:40 -0700453}
454
Vladimir Marko93205e32016-04-13 11:59:46 +0100455std::unique_ptr<const std::vector<uint8_t>> CompilerDriver::CreateQuickResolutionTrampoline()
456 const {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700457 CREATE_TRAMPOLINE(QUICK, kQuickAbi, pQuickResolutionTrampoline)
Brian Carlstrom7940e442013-07-12 13:46:57 -0700458}
459
Vladimir Marko93205e32016-04-13 11:59:46 +0100460std::unique_ptr<const std::vector<uint8_t>> CompilerDriver::CreateQuickToInterpreterBridge()
461 const {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700462 CREATE_TRAMPOLINE(QUICK, kQuickAbi, pQuickToInterpreterBridge)
Brian Carlstrom7940e442013-07-12 13:46:57 -0700463}
Ian Rogersdd7624d2014-03-14 17:43:00 -0700464#undef CREATE_TRAMPOLINE
Brian Carlstrom7940e442013-07-12 13:46:57 -0700465
466void CompilerDriver::CompileAll(jobject class_loader,
Brian Carlstrom45602482013-07-21 22:07:55 -0700467 const std::vector<const DexFile*>& dex_files,
Ian Rogers3d504072014-03-01 09:16:49 -0800468 TimingLogger* timings) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700469 DCHECK(!Runtime::Current()->IsStarted());
Andreas Gampeace0dc12016-01-20 13:33:13 -0800470
471 InitializeThreadPools();
472
Andreas Gampe8d295f82015-01-20 14:50:21 -0800473 VLOG(compiler) << "Before precompile " << GetMemoryUsageString(false);
Andreas Gampe740667a2015-09-15 17:55:06 -0700474 // Precompile:
475 // 1) Load image classes
476 // 2) Resolve all classes
477 // 3) Attempt to verify all classes
478 // 4) Attempt to initialize image classes, and trivially initialized classes
Andreas Gampeace0dc12016-01-20 13:33:13 -0800479 PreCompile(class_loader, dex_files, timings);
Andreas Gampe740667a2015-09-15 17:55:06 -0700480 // Compile:
481 // 1) Compile all classes and methods enabled for compilation. May fall back to dex-to-dex
482 // compilation.
483 if (!GetCompilerOptions().VerifyAtRuntime()) {
Andreas Gampeace0dc12016-01-20 13:33:13 -0800484 Compile(class_loader, dex_files, timings);
Andreas Gampe740667a2015-09-15 17:55:06 -0700485 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700486 if (dump_stats_) {
487 stats_->Dump();
488 }
Andreas Gampeace0dc12016-01-20 13:33:13 -0800489
490 FreeThreadPools();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700491}
492
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700493static optimizer::DexToDexCompilationLevel GetDexToDexCompilationLevel(
494 Thread* self, const CompilerDriver& driver, Handle<mirror::ClassLoader> class_loader,
495 const DexFile& dex_file, const DexFile::ClassDef& class_def)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700496 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800497 auto* const runtime = Runtime::Current();
Calin Juravleffc87072016-04-20 14:22:09 +0100498 if (runtime->UseJitCompilation() || driver.GetCompilerOptions().VerifyAtRuntime()) {
Mathieu Chartiere86deef2015-03-19 13:43:37 -0700499 // Verify at runtime shouldn't dex to dex since we didn't resolve of verify.
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700500 return optimizer::DexToDexCompilationLevel::kDontDexToDexCompile;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800501 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700502 const char* descriptor = dex_file.GetClassDescriptor(class_def);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800503 ClassLinker* class_linker = runtime->GetClassLinker();
Ian Rogers98379392014-02-24 16:53:16 -0800504 mirror::Class* klass = class_linker->FindClass(self, descriptor, class_loader);
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700505 if (klass == nullptr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700506 CHECK(self->IsExceptionPending());
507 self->ClearException();
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700508 return optimizer::DexToDexCompilationLevel::kDontDexToDexCompile;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700509 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700510 // DexToDex at the kOptimize level may introduce quickened opcodes, which replace symbolic
511 // references with actual offsets. We cannot re-verify such instructions.
512 //
513 // We store the verification information in the class status in the oat file, which the linker
514 // can validate (checksums) and use to skip load-time verification. It is thus safe to
515 // optimize when a class has been fully verified before.
516 if (klass->IsVerified()) {
Sebastien Hertz75021222013-07-16 18:34:50 +0200517 // Class is verified so we can enable DEX-to-DEX compilation for performance.
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700518 return optimizer::DexToDexCompilationLevel::kOptimize;
Sebastien Hertz75021222013-07-16 18:34:50 +0200519 } else if (klass->IsCompileTimeVerified()) {
520 // Class verification has soft-failed. Anyway, ensure at least correctness.
521 DCHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime);
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700522 return optimizer::DexToDexCompilationLevel::kRequired;
Sebastien Hertz75021222013-07-16 18:34:50 +0200523 } else {
524 // Class verification has failed: do not run DEX-to-DEX compilation.
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700525 return optimizer::DexToDexCompilationLevel::kDontDexToDexCompile;
526 }
527}
528
529static optimizer::DexToDexCompilationLevel GetDexToDexCompilationLevel(
530 Thread* self,
531 const CompilerDriver& driver,
532 jobject jclass_loader,
533 const DexFile& dex_file,
534 const DexFile::ClassDef& class_def) {
535 ScopedObjectAccess soa(self);
536 StackHandleScope<1> hs(soa.Self());
537 Handle<mirror::ClassLoader> class_loader(
538 hs.NewHandle(soa.Decode<mirror::ClassLoader*>(jclass_loader)));
539 return GetDexToDexCompilationLevel(self, driver, class_loader, dex_file, class_def);
540}
541
542// Does the runtime for the InstructionSet provide an implementation returned by
543// GetQuickGenericJniStub allowing down calls that aren't compiled using a JNI compiler?
544static bool InstructionSetHasGenericJniStub(InstructionSet isa) {
545 switch (isa) {
546 case kArm:
547 case kArm64:
548 case kThumb2:
549 case kMips:
550 case kMips64:
551 case kX86:
552 case kX86_64: return true;
553 default: return false;
554 }
555}
556
557static void CompileMethod(Thread* self,
558 CompilerDriver* driver,
559 const DexFile::CodeItem* code_item,
560 uint32_t access_flags,
561 InvokeType invoke_type,
562 uint16_t class_def_idx,
563 uint32_t method_idx,
564 jobject class_loader,
565 const DexFile& dex_file,
566 optimizer::DexToDexCompilationLevel dex_to_dex_compilation_level,
Mathieu Chartier736b5602015-09-02 14:54:11 -0700567 bool compilation_enabled,
568 Handle<mirror::DexCache> dex_cache)
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700569 REQUIRES(!driver->compiled_methods_lock_) {
570 DCHECK(driver != nullptr);
571 CompiledMethod* compiled_method = nullptr;
572 uint64_t start_ns = kTimeCompileMethod ? NanoTime() : 0;
573 MethodReference method_ref(&dex_file, method_idx);
574
Vladimir Marko492a7fa2016-06-01 18:38:43 +0100575 if (driver->GetCurrentDexToDexMethods() != nullptr) {
576 // This is the second pass when we dex-to-dex compile previously marked methods.
577 // TODO: Refactor the compilation to avoid having to distinguish the two passes
578 // here. That should be done on a higher level. http://b/29089975
579 if (driver->GetCurrentDexToDexMethods()->IsBitSet(method_idx)) {
580 const VerifiedMethod* verified_method =
581 driver->GetVerificationResults()->GetVerifiedMethod(method_ref);
582 // Do not optimize if a VerifiedMethod is missing. SafeCast elision,
583 // for example, relies on it.
584 compiled_method = optimizer::ArtCompileDEX(
585 driver,
586 code_item,
587 access_flags,
588 invoke_type,
589 class_def_idx,
590 method_idx,
591 class_loader,
592 dex_file,
593 (verified_method != nullptr)
594 ? dex_to_dex_compilation_level
595 : optimizer::DexToDexCompilationLevel::kRequired);
596 }
597 } else if ((access_flags & kAccNative) != 0) {
Vladimir Markof6d1e0f2016-05-23 15:32:42 +0100598 // Are we extracting only and have support for generic JNI down calls?
599 if (!driver->GetCompilerOptions().IsJniCompilationEnabled() &&
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700600 InstructionSetHasGenericJniStub(driver->GetInstructionSet())) {
601 // Leaving this empty will trigger the generic JNI version
602 } else {
Igor Murashkin9d4b6da2016-07-29 09:51:58 -0700603 // Look-up the ArtMethod associated with this code_item (if any)
604 // -- It is later used to lookup any [optimization] annotations for this method.
605 ScopedObjectAccess soa(self);
606 StackHandleScope<1> hs(soa.Self());
607 Handle<mirror::ClassLoader> class_loader_handle(hs.NewHandle(
608 soa.Decode<mirror::ClassLoader*>(class_loader)));
609
610 // TODO: Lookup annotation from DexFile directly without resolving method.
611 ArtMethod* method =
612 Runtime::Current()->GetClassLinker()->ResolveMethod<ClassLinker::kNoICCECheckForCache>(
613 dex_file,
614 method_idx,
615 dex_cache,
616 class_loader_handle,
617 /* referrer */ nullptr,
618 invoke_type);
619
Igor Murashkin367f3dd2016-09-01 17:00:24 -0700620 // Query any JNI optimization annotations such as @FastNative or @CriticalNative.
621 Compiler::JniOptimizationFlags optimization_flags = Compiler::kNone;
622 if (UNLIKELY(method == nullptr)) {
Igor Murashkin9d4b6da2016-07-29 09:51:58 -0700623 // Failed method resolutions happen very rarely, e.g. ancestor class cannot be resolved.
624 DCHECK(self->IsExceptionPending());
625 self->ClearException();
Igor Murashkin367f3dd2016-09-01 17:00:24 -0700626 } else if (method->IsAnnotatedWithFastNative()) {
627 // TODO: Will no longer need this CHECK once we have verifier checking this.
628 CHECK(!method->IsAnnotatedWithCriticalNative());
629 optimization_flags = Compiler::kFastNative;
630 } else if (method->IsAnnotatedWithCriticalNative()) {
631 // TODO: Will no longer need this CHECK once we have verifier checking this.
632 CHECK(!method->IsAnnotatedWithFastNative());
633 optimization_flags = Compiler::kCriticalNative;
Igor Murashkin9d4b6da2016-07-29 09:51:58 -0700634 }
635
Igor Murashkin9d4b6da2016-07-29 09:51:58 -0700636 compiled_method = driver->GetCompiler()->JniCompile(access_flags,
637 method_idx,
638 dex_file,
639 optimization_flags);
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700640 CHECK(compiled_method != nullptr);
641 }
642 } else if ((access_flags & kAccAbstract) != 0) {
643 // Abstract methods don't have code.
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000644 } else {
Andreas Gampe0760a812015-08-26 17:12:51 -0700645 const VerifiedMethod* verified_method =
646 driver->GetVerificationResults()->GetVerifiedMethod(method_ref);
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700647 bool compile = compilation_enabled &&
648 // Basic checks, e.g., not <clinit>.
649 driver->GetVerificationResults()
650 ->IsCandidateForCompilation(method_ref, access_flags) &&
651 // Did not fail to create VerifiedMethod metadata.
Andreas Gampe0760a812015-08-26 17:12:51 -0700652 verified_method != nullptr &&
653 // Do not have failures that should punt to the interpreter.
654 !verified_method->HasRuntimeThrow() &&
655 (verified_method->GetEncounteredVerificationFailures() &
Andreas Gampea727e372015-08-25 09:22:37 -0700656 (verifier::VERIFY_ERROR_FORCE_INTERPRETER | verifier::VERIFY_ERROR_LOCKING)) == 0 &&
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700657 // Is eligable for compilation by methods-to-compile filter.
Calin Juravle226501b2015-12-11 14:41:31 +0000658 driver->IsMethodToCompile(method_ref) &&
659 driver->ShouldCompileBasedOnProfile(method_ref);
660
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700661 if (compile) {
662 // NOTE: if compiler declines to compile this method, it will return null.
663 compiled_method = driver->GetCompiler()->Compile(code_item, access_flags, invoke_type,
664 class_def_idx, method_idx, class_loader,
Mathieu Chartier736b5602015-09-02 14:54:11 -0700665 dex_file, dex_cache);
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700666 }
667 if (compiled_method == nullptr &&
668 dex_to_dex_compilation_level != optimizer::DexToDexCompilationLevel::kDontDexToDexCompile) {
Vladimir Marko492a7fa2016-06-01 18:38:43 +0100669 DCHECK(!Runtime::Current()->UseJitCompilation());
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700670 // TODO: add a command-line option to disable DEX-to-DEX compilation ?
Vladimir Marko492a7fa2016-06-01 18:38:43 +0100671 driver->MarkForDexToDexCompilation(self, method_ref);
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700672 }
673 }
674 if (kTimeCompileMethod) {
675 uint64_t duration_ns = NanoTime() - start_ns;
676 if (duration_ns > MsToNs(driver->GetCompiler()->GetMaximumCompilationTimeBeforeWarning())) {
677 LOG(WARNING) << "Compilation of " << PrettyMethod(method_idx, dex_file)
678 << " took " << PrettyDuration(duration_ns);
679 }
680 }
681
682 if (compiled_method != nullptr) {
683 // Count non-relative linker patches.
684 size_t non_relative_linker_patch_count = 0u;
685 for (const LinkerPatch& patch : compiled_method->GetPatches()) {
686 if (!patch.IsPcRelative()) {
687 ++non_relative_linker_patch_count;
688 }
689 }
690 bool compile_pic = driver->GetCompilerOptions().GetCompilePic(); // Off by default
691 // When compiling with PIC, there should be zero non-relative linker patches
692 CHECK(!compile_pic || non_relative_linker_patch_count == 0u);
693
694 driver->AddCompiledMethod(method_ref, compiled_method, non_relative_linker_patch_count);
695 }
696
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700697 if (self->IsExceptionPending()) {
698 ScopedObjectAccess soa(self);
699 LOG(FATAL) << "Unexpected exception compiling: " << PrettyMethod(method_idx, dex_file) << "\n"
700 << self->GetException()->Dump();
Sebastien Hertz75021222013-07-16 18:34:50 +0200701 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700702}
703
Mathieu Chartiere401d142015-04-22 13:56:20 -0700704void CompilerDriver::CompileOne(Thread* self, ArtMethod* method, TimingLogger* timings) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700705 DCHECK(!Runtime::Current()->IsStarted());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700706 jobject jclass_loader;
707 const DexFile* dex_file;
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700708 uint16_t class_def_idx;
Ian Rogersef7d42f2014-01-06 12:55:46 -0800709 uint32_t method_idx = method->GetDexMethodIndex();
710 uint32_t access_flags = method->GetAccessFlags();
711 InvokeType invoke_type = method->GetInvokeType();
Mathieu Chartier736b5602015-09-02 14:54:11 -0700712 StackHandleScope<1> hs(self);
713 Handle<mirror::DexCache> dex_cache(hs.NewHandle(method->GetDexCache()));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700714 {
715 ScopedObjectAccessUnchecked soa(self);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800716 ScopedLocalRef<jobject> local_class_loader(
717 soa.Env(), soa.AddLocalReference<jobject>(method->GetDeclaringClass()->GetClassLoader()));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700718 jclass_loader = soa.Env()->NewGlobalRef(local_class_loader.get());
719 // Find the dex_file
Mathieu Chartierbfd9a432014-05-21 17:43:44 -0700720 dex_file = method->GetDexFile();
721 class_def_idx = method->GetClassDefIndex();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700722 }
Ian Rogersef7d42f2014-01-06 12:55:46 -0800723 const DexFile::CodeItem* code_item = dex_file->GetCodeItem(method->GetCodeItemOffset());
Mathieu Chartier736b5602015-09-02 14:54:11 -0700724
725 // Go to native so that we don't block GC during compilation.
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700726 ScopedThreadSuspension sts(self, kNative);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700727
728 std::vector<const DexFile*> dex_files;
729 dex_files.push_back(dex_file);
730
Andreas Gampeace0dc12016-01-20 13:33:13 -0800731 InitializeThreadPools();
732
733 PreCompile(jclass_loader, dex_files, timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700734
Brian Carlstrom7940e442013-07-12 13:46:57 -0700735 // Can we run DEX-to-DEX compiler on this class ?
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700736 optimizer::DexToDexCompilationLevel dex_to_dex_compilation_level =
737 GetDexToDexCompilationLevel(self,
738 *this,
739 jclass_loader,
740 *dex_file,
741 dex_file->GetClassDef(class_def_idx));
742
Vladimir Marko492a7fa2016-06-01 18:38:43 +0100743 DCHECK(current_dex_to_dex_methods_ == nullptr);
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700744 CompileMethod(self,
745 this,
746 code_item,
747 access_flags,
748 invoke_type,
749 class_def_idx,
750 method_idx,
751 jclass_loader,
752 *dex_file,
753 dex_to_dex_compilation_level,
Mathieu Chartier736b5602015-09-02 14:54:11 -0700754 true,
755 dex_cache);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700756
Vladimir Marko492a7fa2016-06-01 18:38:43 +0100757 ArrayRef<DexFileMethodSet> dex_to_dex_references;
758 {
759 // From this point on, we shall not modify dex_to_dex_references_, so
760 // just grab a reference to it that we use without holding the mutex.
761 MutexLock lock(Thread::Current(), dex_to_dex_references_lock_);
762 dex_to_dex_references = ArrayRef<DexFileMethodSet>(dex_to_dex_references_);
763 }
764 if (!dex_to_dex_references.empty()) {
765 DCHECK_EQ(dex_to_dex_references.size(), 1u);
766 DCHECK(&dex_to_dex_references[0].GetDexFile() == dex_file);
767 current_dex_to_dex_methods_ = &dex_to_dex_references.front().GetMethodIndexes();
768 DCHECK(current_dex_to_dex_methods_->IsBitSet(method_idx));
769 DCHECK_EQ(current_dex_to_dex_methods_->NumSetBits(), 1u);
770 CompileMethod(self,
771 this,
772 code_item,
773 access_flags,
774 invoke_type,
775 class_def_idx,
776 method_idx,
777 jclass_loader,
778 *dex_file,
779 dex_to_dex_compilation_level,
780 true,
781 dex_cache);
782 current_dex_to_dex_methods_ = nullptr;
783 }
784
Andreas Gampeace0dc12016-01-20 13:33:13 -0800785 FreeThreadPools();
786
Brian Carlstrom7940e442013-07-12 13:46:57 -0700787 self->GetJniEnv()->DeleteGlobalRef(jclass_loader);
Mathieu Chartier2535abe2015-02-17 10:38:49 -0800788}
789
Andreas Gampeace0dc12016-01-20 13:33:13 -0800790void CompilerDriver::Resolve(jobject class_loader,
791 const std::vector<const DexFile*>& dex_files,
792 TimingLogger* timings) {
793 // Resolution allocates classes and needs to run single-threaded to be deterministic.
794 bool force_determinism = GetCompilerOptions().IsForceDeterminism();
795 ThreadPool* resolve_thread_pool = force_determinism
796 ? single_thread_pool_.get()
797 : parallel_thread_pool_.get();
798 size_t resolve_thread_count = force_determinism ? 1U : parallel_thread_count_;
799
Brian Carlstrom7940e442013-07-12 13:46:57 -0700800 for (size_t i = 0; i != dex_files.size(); ++i) {
801 const DexFile* dex_file = dex_files[i];
Kenny Rootd5185342014-05-13 14:47:05 -0700802 CHECK(dex_file != nullptr);
Andreas Gampeace0dc12016-01-20 13:33:13 -0800803 ResolveDexFile(class_loader,
804 *dex_file,
805 dex_files,
806 resolve_thread_pool,
807 resolve_thread_count,
808 timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700809 }
810}
811
Andreas Gampeace0dc12016-01-20 13:33:13 -0800812// Resolve const-strings in the code. Done to have deterministic allocation behavior. Right now
813// this is single-threaded for simplicity.
814// TODO: Collect the relevant string indices in parallel, then allocate them sequentially in a
815// stable order.
816
817static void ResolveConstStrings(CompilerDriver* driver,
818 const DexFile& dex_file,
819 const DexFile::CodeItem* code_item) {
820 if (code_item == nullptr) {
821 // Abstract or native method.
822 return;
823 }
824
825 const uint16_t* code_ptr = code_item->insns_;
826 const uint16_t* code_end = code_item->insns_ + code_item->insns_size_in_code_units_;
827
828 while (code_ptr < code_end) {
829 const Instruction* inst = Instruction::At(code_ptr);
830 switch (inst->Opcode()) {
831 case Instruction::CONST_STRING: {
832 uint32_t string_index = inst->VRegB_21c();
833 driver->CanAssumeStringIsPresentInDexCache(dex_file, string_index);
834 break;
835 }
836 case Instruction::CONST_STRING_JUMBO: {
837 uint32_t string_index = inst->VRegB_31c();
838 driver->CanAssumeStringIsPresentInDexCache(dex_file, string_index);
839 break;
840 }
841
842 default:
843 break;
844 }
845
846 code_ptr += inst->SizeInCodeUnits();
847 }
848}
849
850static void ResolveConstStrings(CompilerDriver* driver,
851 const std::vector<const DexFile*>& dex_files,
852 TimingLogger* timings) {
853 for (const DexFile* dex_file : dex_files) {
854 TimingLogger::ScopedTiming t("Resolve const-string Strings", timings);
855
856 size_t class_def_count = dex_file->NumClassDefs();
857 for (size_t class_def_index = 0; class_def_index < class_def_count; ++class_def_index) {
858 const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_index);
859
860 const uint8_t* class_data = dex_file->GetClassData(class_def);
861 if (class_data == nullptr) {
862 // empty class, probably a marker interface
863 continue;
864 }
865
866 ClassDataItemIterator it(*dex_file, class_data);
867 // Skip fields
868 while (it.HasNextStaticField()) {
869 it.Next();
870 }
871 while (it.HasNextInstanceField()) {
872 it.Next();
873 }
874
875 bool compilation_enabled = driver->IsClassToCompile(
876 dex_file->StringByTypeIdx(class_def.class_idx_));
877 if (!compilation_enabled) {
878 // Compilation is skipped, do not resolve const-string in code of this class.
879 // TODO: Make sure that inlining honors this.
880 continue;
881 }
882
883 // Direct methods.
884 int64_t previous_direct_method_idx = -1;
885 while (it.HasNextDirectMethod()) {
886 uint32_t method_idx = it.GetMemberIndex();
887 if (method_idx == previous_direct_method_idx) {
888 // smali can create dex files with two encoded_methods sharing the same method_idx
889 // http://code.google.com/p/smali/issues/detail?id=119
890 it.Next();
891 continue;
892 }
893 previous_direct_method_idx = method_idx;
894 ResolveConstStrings(driver, *dex_file, it.GetMethodCodeItem());
895 it.Next();
896 }
897 // Virtual methods.
898 int64_t previous_virtual_method_idx = -1;
899 while (it.HasNextVirtualMethod()) {
900 uint32_t method_idx = it.GetMemberIndex();
901 if (method_idx == previous_virtual_method_idx) {
902 // smali can create dex files with two encoded_methods sharing the same method_idx
903 // http://code.google.com/p/smali/issues/detail?id=119
904 it.Next();
905 continue;
906 }
907 previous_virtual_method_idx = method_idx;
908 ResolveConstStrings(driver, *dex_file, it.GetMethodCodeItem());
909 it.Next();
910 }
911 DCHECK(!it.HasNext());
912 }
913 }
914}
915
916inline void CompilerDriver::CheckThreadPools() {
917 DCHECK(parallel_thread_pool_ != nullptr);
918 DCHECK(single_thread_pool_ != nullptr);
919}
920
921void CompilerDriver::PreCompile(jobject class_loader,
922 const std::vector<const DexFile*>& dex_files,
923 TimingLogger* timings) {
924 CheckThreadPools();
925
Brian Carlstrom7940e442013-07-12 13:46:57 -0700926 LoadImageClasses(timings);
Andreas Gampe8d295f82015-01-20 14:50:21 -0800927 VLOG(compiler) << "LoadImageClasses: " << GetMemoryUsageString(false);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700928
Mathieu Chartiere86deef2015-03-19 13:43:37 -0700929 const bool verification_enabled = compiler_options_->IsVerificationEnabled();
930 const bool never_verify = compiler_options_->NeverVerify();
Mathieu Chartiera8077802016-03-16 19:08:31 -0700931 const bool verify_only_profile = compiler_options_->VerifyOnlyProfile();
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700932
Mathieu Chartiere86deef2015-03-19 13:43:37 -0700933 // We need to resolve for never_verify since it needs to run dex to dex to add the
934 // RETURN_VOID_NO_BARRIER.
Mathieu Chartiera8077802016-03-16 19:08:31 -0700935 // Let the verifier resolve as needed for the verify_only_profile case.
936 if ((never_verify || verification_enabled) && !verify_only_profile) {
Andreas Gampeace0dc12016-01-20 13:33:13 -0800937 Resolve(class_loader, dex_files, timings);
Mathieu Chartiere86deef2015-03-19 13:43:37 -0700938 VLOG(compiler) << "Resolve: " << GetMemoryUsageString(false);
939 }
940
941 if (never_verify) {
Mathieu Chartierab972ef2014-12-03 17:38:22 -0800942 VLOG(compiler) << "Verify none mode specified, skipping verification.";
Andreas Gampeace0dc12016-01-20 13:33:13 -0800943 SetVerified(class_loader, dex_files, timings);
Mathieu Chartiere86deef2015-03-19 13:43:37 -0700944 }
945
946 if (!verification_enabled) {
Jeff Hao4a200f52014-04-01 14:58:49 -0700947 return;
948 }
949
Andreas Gampeace0dc12016-01-20 13:33:13 -0800950 if (GetCompilerOptions().IsForceDeterminism() && IsBootImage()) {
951 // Resolve strings from const-string. Do this now to have a deterministic image.
952 ResolveConstStrings(this, dex_files, timings);
953 VLOG(compiler) << "Resolve const-strings: " << GetMemoryUsageString(false);
954 }
955
956 Verify(class_loader, dex_files, timings);
Andreas Gampe8d295f82015-01-20 14:50:21 -0800957 VLOG(compiler) << "Verify: " << GetMemoryUsageString(false);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700958
Andreas Gampe6cf49e52015-03-05 13:08:45 -0800959 if (had_hard_verifier_failure_ && GetCompilerOptions().AbortOnHardVerifierFailure()) {
960 LOG(FATAL) << "Had a hard failure verifying all classes, and was asked to abort in such "
961 << "situations. Please check the log.";
962 }
963
Andreas Gampeace0dc12016-01-20 13:33:13 -0800964 InitializeClasses(class_loader, dex_files, timings);
Andreas Gampe8d295f82015-01-20 14:50:21 -0800965 VLOG(compiler) << "InitializeClasses: " << GetMemoryUsageString(false);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700966
967 UpdateImageClasses(timings);
Andreas Gampe8d295f82015-01-20 14:50:21 -0800968 VLOG(compiler) << "UpdateImageClasses: " << GetMemoryUsageString(false);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700969}
970
Ian Rogersdfb325e2013-10-30 01:00:44 -0700971bool CompilerDriver::IsImageClass(const char* descriptor) const {
Mathieu Chartierc5dd3192015-12-09 16:38:30 -0800972 if (image_classes_ != nullptr) {
973 // If we have a set of image classes, use those.
Ian Rogersdfb325e2013-10-30 01:00:44 -0700974 return image_classes_->find(descriptor) != image_classes_->end();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700975 }
Mathieu Chartierc5dd3192015-12-09 16:38:30 -0800976 // No set of image classes, assume we include all the classes.
977 // NOTE: Currently only reachable from InitImageMethodVisitor for the app image case.
978 return !IsBootImage();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700979}
980
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800981bool CompilerDriver::IsClassToCompile(const char* descriptor) const {
Andreas Gampeb1fcead2015-04-20 18:53:51 -0700982 if (classes_to_compile_ == nullptr) {
983 return true;
984 }
985 return classes_to_compile_->find(descriptor) != classes_to_compile_->end();
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800986}
987
Andreas Gampe70bef0d2015-04-15 02:37:28 -0700988bool CompilerDriver::IsMethodToCompile(const MethodReference& method_ref) const {
Andreas Gampe70bef0d2015-04-15 02:37:28 -0700989 if (methods_to_compile_ == nullptr) {
990 return true;
991 }
992
993 std::string tmp = PrettyMethod(method_ref.dex_method_index, *method_ref.dex_file, true);
994 return methods_to_compile_->find(tmp.c_str()) != methods_to_compile_->end();
995}
996
Calin Juravle226501b2015-12-11 14:41:31 +0000997bool CompilerDriver::ShouldCompileBasedOnProfile(const MethodReference& method_ref) const {
998 if (profile_compilation_info_ == nullptr) {
999 // If we miss profile information it means that we don't do a profile guided compilation.
1000 // Return true, and let the other filters decide if the method should be compiled.
1001 return true;
1002 }
1003 bool result = profile_compilation_info_->ContainsMethod(method_ref);
1004
1005 if (kDebugProfileGuidedCompilation) {
1006 LOG(INFO) << "[ProfileGuidedCompilation] "
1007 << (result ? "Compiled" : "Skipped") << " method:"
1008 << PrettyMethod(method_ref.dex_method_index, *method_ref.dex_file, true);
1009 }
1010 return result;
1011}
1012
Mathieu Chartiera8077802016-03-16 19:08:31 -07001013bool CompilerDriver::ShouldVerifyClassBasedOnProfile(const DexFile& dex_file,
1014 uint16_t class_idx) const {
1015 if (!compiler_options_->VerifyOnlyProfile()) {
1016 // No profile, verify everything.
1017 return true;
1018 }
1019 DCHECK(profile_compilation_info_ != nullptr);
1020 bool result = profile_compilation_info_->ContainsClass(dex_file, class_idx);
1021 if (kDebugProfileGuidedCompilation) {
1022 LOG(INFO) << "[ProfileGuidedCompilation] "
1023 << (result ? "Verified" : "Skipped") << " method:"
1024 << dex_file.GetClassDescriptor(dex_file.GetClassDef(class_idx));
1025 }
1026 return result;
1027}
1028
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001029class ResolveCatchBlockExceptionsClassVisitor : public ClassVisitor {
1030 public:
Chih-Hung Hsieh471118e2016-04-29 14:27:41 -07001031 explicit ResolveCatchBlockExceptionsClassVisitor(
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001032 std::set<std::pair<uint16_t, const DexFile*>>& exceptions_to_resolve)
1033 : exceptions_to_resolve_(exceptions_to_resolve) {}
1034
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001035 virtual bool operator()(mirror::Class* c) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere4275c02015-08-06 15:34:15 -07001036 const auto pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
Alex Lighte64300b2015-12-15 15:02:47 -08001037 for (auto& m : c->GetMethods(pointer_size)) {
Vladimir Marko05792b92015-08-03 11:56:49 +01001038 ResolveExceptionsForMethod(&m, pointer_size);
Mathieu Chartiere4275c02015-08-06 15:34:15 -07001039 }
1040 return true;
1041 }
1042
1043 private:
Andreas Gampe542451c2016-07-26 09:02:02 -07001044 void ResolveExceptionsForMethod(ArtMethod* method_handle, PointerSize pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001045 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001046 const DexFile::CodeItem* code_item = method_handle->GetCodeItem();
1047 if (code_item == nullptr) {
1048 return; // native or abstract method
Brian Carlstrom7940e442013-07-12 13:46:57 -07001049 }
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001050 if (code_item->tries_size_ == 0) {
1051 return; // nothing to process
1052 }
1053 const uint8_t* encoded_catch_handler_list = DexFile::GetCatchHandlerData(*code_item, 0);
1054 size_t num_encoded_catch_handlers = DecodeUnsignedLeb128(&encoded_catch_handler_list);
1055 for (size_t i = 0; i < num_encoded_catch_handlers; i++) {
1056 int32_t encoded_catch_handler_size = DecodeSignedLeb128(&encoded_catch_handler_list);
1057 bool has_catch_all = false;
1058 if (encoded_catch_handler_size <= 0) {
1059 encoded_catch_handler_size = -encoded_catch_handler_size;
1060 has_catch_all = true;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001061 }
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001062 for (int32_t j = 0; j < encoded_catch_handler_size; j++) {
1063 uint16_t encoded_catch_handler_handlers_type_idx =
1064 DecodeUnsignedLeb128(&encoded_catch_handler_list);
1065 // Add to set of types to resolve if not already in the dex cache resolved types
Vladimir Marko05792b92015-08-03 11:56:49 +01001066 if (!method_handle->IsResolvedTypeIdx(encoded_catch_handler_handlers_type_idx,
1067 pointer_size)) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001068 exceptions_to_resolve_.emplace(encoded_catch_handler_handlers_type_idx,
1069 method_handle->GetDexFile());
1070 }
1071 // ignore address associated with catch handler
1072 DecodeUnsignedLeb128(&encoded_catch_handler_list);
1073 }
1074 if (has_catch_all) {
1075 // ignore catch all address
1076 DecodeUnsignedLeb128(&encoded_catch_handler_list);
1077 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001078 }
1079 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001080
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001081 std::set<std::pair<uint16_t, const DexFile*>>& exceptions_to_resolve_;
1082};
1083
1084class RecordImageClassesVisitor : public ClassVisitor {
1085 public:
1086 explicit RecordImageClassesVisitor(std::unordered_set<std::string>* image_classes)
1087 : image_classes_(image_classes) {}
1088
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001089 bool operator()(mirror::Class* klass) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001090 std::string temp;
1091 image_classes_->insert(klass->GetDescriptor(&temp));
1092 return true;
1093 }
1094
1095 private:
1096 std::unordered_set<std::string>* const image_classes_;
1097};
Brian Carlstrom7940e442013-07-12 13:46:57 -07001098
1099// Make a list of descriptors for classes to include in the image
Mathieu Chartier90443472015-07-16 20:32:27 -07001100void CompilerDriver::LoadImageClasses(TimingLogger* timings) {
Kenny Rootd5185342014-05-13 14:47:05 -07001101 CHECK(timings != nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001102 if (!IsBootImage()) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001103 return;
1104 }
1105
Mathieu Chartierf5997b42014-06-20 10:37:54 -07001106 TimingLogger::ScopedTiming t("LoadImageClasses", timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001107 // Make a first class to load all classes explicitly listed in the file
1108 Thread* self = Thread::Current();
1109 ScopedObjectAccess soa(self);
1110 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Kenny Rootd5185342014-05-13 14:47:05 -07001111 CHECK(image_classes_.get() != nullptr);
Mathieu Chartier02e25112013-08-14 16:14:24 -07001112 for (auto it = image_classes_->begin(), end = image_classes_->end(); it != end;) {
Vladimir Markoe9c36b32013-11-21 15:49:16 +00001113 const std::string& descriptor(*it);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001114 StackHandleScope<1> hs(self);
1115 Handle<mirror::Class> klass(
1116 hs.NewHandle(class_linker->FindSystemClass(self, descriptor.c_str())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001117 if (klass.Get() == nullptr) {
Ian Rogerse6bb3b22013-08-19 21:51:45 -07001118 VLOG(compiler) << "Failed to find class " << descriptor;
Vladimir Markoe9c36b32013-11-21 15:49:16 +00001119 image_classes_->erase(it++);
Ian Rogersa436fde2013-08-27 23:34:06 -07001120 self->ClearException();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001121 } else {
1122 ++it;
1123 }
1124 }
1125
1126 // Resolve exception classes referenced by the loaded classes. The catch logic assumes
1127 // exceptions are resolved by the verifier when there is a catch block in an interested method.
1128 // Do this here so that exception classes appear to have been specified image classes.
Ian Rogers700a4022014-05-19 16:49:03 -07001129 std::set<std::pair<uint16_t, const DexFile*>> unresolved_exception_types;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001130 StackHandleScope<1> hs(self);
1131 Handle<mirror::Class> java_lang_Throwable(
1132 hs.NewHandle(class_linker->FindSystemClass(self, "Ljava/lang/Throwable;")));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001133 do {
1134 unresolved_exception_types.clear();
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001135 ResolveCatchBlockExceptionsClassVisitor visitor(unresolved_exception_types);
1136 class_linker->VisitClasses(&visitor);
Mathieu Chartier02e25112013-08-14 16:14:24 -07001137 for (const std::pair<uint16_t, const DexFile*>& exception_type : unresolved_exception_types) {
1138 uint16_t exception_type_idx = exception_type.first;
1139 const DexFile* dex_file = exception_type.second;
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001140 StackHandleScope<2> hs2(self);
Mathieu Chartierf284d442016-06-02 11:48:30 -07001141 Handle<mirror::DexCache> dex_cache(hs2.NewHandle(class_linker->RegisterDexFile(*dex_file,
1142 nullptr)));
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001143 Handle<mirror::Class> klass(hs2.NewHandle(
Mathieu Chartier9865bde2015-12-21 09:58:16 -08001144 class_linker->ResolveType(*dex_file,
1145 exception_type_idx,
1146 dex_cache,
1147 ScopedNullHandle<mirror::ClassLoader>())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001148 if (klass.Get() == nullptr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001149 const DexFile::TypeId& type_id = dex_file->GetTypeId(exception_type_idx);
1150 const char* descriptor = dex_file->GetTypeDescriptor(type_id);
1151 LOG(FATAL) << "Failed to resolve class " << descriptor;
1152 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001153 DCHECK(java_lang_Throwable->IsAssignableFrom(klass.Get()));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001154 }
1155 // Resolving exceptions may load classes that reference more exceptions, iterate until no
1156 // more are found
1157 } while (!unresolved_exception_types.empty());
1158
1159 // We walk the roots looking for classes so that we'll pick up the
1160 // above classes plus any classes them depend on such super
1161 // classes, interfaces, and the required ClassLinker roots.
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001162 RecordImageClassesVisitor visitor(image_classes_.get());
1163 class_linker->VisitClasses(&visitor);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001164
1165 CHECK_NE(image_classes_->size(), 0U);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001166}
1167
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001168static void MaybeAddToImageClasses(Handle<mirror::Class> c,
1169 std::unordered_set<std::string>* image_classes)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001170 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07001171 Thread* self = Thread::Current();
1172 StackHandleScope<1> hs(self);
1173 // Make a copy of the handle so that we don't clobber it doing Assign.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07001174 MutableHandle<mirror::Class> klass(hs.NewHandle(c.Get()));
Ian Rogers1ff3c982014-08-12 02:30:58 -07001175 std::string temp;
Andreas Gampe542451c2016-07-26 09:02:02 -07001176 const PointerSize pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001177 while (!klass->IsObjectClass()) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07001178 const char* descriptor = klass->GetDescriptor(&temp);
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001179 std::pair<std::unordered_set<std::string>::iterator, bool> result =
1180 image_classes->insert(descriptor);
Ian Rogers1ff3c982014-08-12 02:30:58 -07001181 if (!result.second) { // Previously inserted.
1182 break;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001183 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07001184 VLOG(compiler) << "Adding " << descriptor << " to image classes";
Mathieu Chartierf8322842014-05-16 10:59:25 -07001185 for (size_t i = 0; i < klass->NumDirectInterfaces(); ++i) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001186 StackHandleScope<1> hs2(self);
1187 MaybeAddToImageClasses(hs2.NewHandle(mirror::Class::GetDirectInterface(self, klass, i)),
Mathieu Chartierf8322842014-05-16 10:59:25 -07001188 image_classes);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001189 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001190 for (auto& m : c->GetVirtualMethods(pointer_size)) {
Alex Light36121492016-02-22 13:43:29 -08001191 StackHandleScope<1> hs2(self);
1192 MaybeAddToImageClasses(hs2.NewHandle(m.GetDeclaringClass()), image_classes);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001193 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001194 if (klass->IsArrayClass()) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001195 StackHandleScope<1> hs2(self);
1196 MaybeAddToImageClasses(hs2.NewHandle(klass->GetComponentType()), image_classes);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001197 }
Mathieu Chartierf8322842014-05-16 10:59:25 -07001198 klass.Assign(klass->GetSuperClass());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001199 }
1200}
1201
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001202// Keeps all the data for the update together. Also doubles as the reference visitor.
1203// Note: we can use object pointers because we suspend all threads.
1204class ClinitImageUpdate {
1205 public:
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001206 static ClinitImageUpdate* Create(std::unordered_set<std::string>* image_class_descriptors,
1207 Thread* self, ClassLinker* linker, std::string* error_msg) {
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001208 std::unique_ptr<ClinitImageUpdate> res(new ClinitImageUpdate(image_class_descriptors, self,
1209 linker));
Mathieu Chartiere401d142015-04-22 13:56:20 -07001210 if (res->dex_cache_class_ == nullptr) {
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001211 *error_msg = "Could not find DexCache class.";
1212 return nullptr;
1213 }
1214
1215 return res.release();
1216 }
1217
1218 ~ClinitImageUpdate() {
1219 // Allow others to suspend again.
1220 self_->EndAssertNoThreadSuspension(old_cause_);
1221 }
1222
1223 // Visitor for VisitReferences.
1224 void operator()(mirror::Object* object, MemberOffset field_offset, bool /* is_static */) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001225 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001226 mirror::Object* ref = object->GetFieldObject<mirror::Object>(field_offset);
1227 if (ref != nullptr) {
1228 VisitClinitClassesObject(ref);
1229 }
1230 }
1231
1232 // java.lang.Reference visitor for VisitReferences.
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001233 void operator()(mirror::Class* klass ATTRIBUTE_UNUSED, mirror::Reference* ref ATTRIBUTE_UNUSED)
1234 const {}
1235
1236 // Ignore class native roots.
1237 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED)
1238 const {}
1239 void VisitRoot(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED) const {}
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001240
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001241 void Walk() REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001242 // Use the initial classes as roots for a search.
1243 for (mirror::Class* klass_root : image_classes_) {
1244 VisitClinitClassesObject(klass_root);
1245 }
1246 }
1247
1248 private:
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001249 class FindImageClassesVisitor : public ClassVisitor {
1250 public:
1251 explicit FindImageClassesVisitor(ClinitImageUpdate* data) : data_(data) {}
1252
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001253 bool operator()(mirror::Class* klass) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001254 std::string temp;
1255 const char* name = klass->GetDescriptor(&temp);
1256 if (data_->image_class_descriptors_->find(name) != data_->image_class_descriptors_->end()) {
1257 data_->image_classes_.push_back(klass);
1258 } else {
1259 // Check whether it is initialized and has a clinit. They must be kept, too.
1260 if (klass->IsInitialized() && klass->FindClassInitializer(
1261 Runtime::Current()->GetClassLinker()->GetImagePointerSize()) != nullptr) {
1262 data_->image_classes_.push_back(klass);
1263 }
1264 }
1265 return true;
1266 }
1267
1268 private:
1269 ClinitImageUpdate* const data_;
1270 };
1271
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001272 ClinitImageUpdate(std::unordered_set<std::string>* image_class_descriptors, Thread* self,
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001273 ClassLinker* linker)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001274 REQUIRES_SHARED(Locks::mutator_lock_) :
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001275 image_class_descriptors_(image_class_descriptors), self_(self) {
1276 CHECK(linker != nullptr);
1277 CHECK(image_class_descriptors != nullptr);
1278
1279 // Make sure nobody interferes with us.
1280 old_cause_ = self->StartAssertNoThreadSuspension("Boot image closure");
1281
1282 // Find the interesting classes.
Andreas Gampedc8b63c2014-12-02 14:39:52 -08001283 dex_cache_class_ = linker->LookupClass(self, "Ljava/lang/DexCache;",
1284 ComputeModifiedUtf8Hash("Ljava/lang/DexCache;"), nullptr);
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001285
1286 // Find all the already-marked classes.
1287 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001288 FindImageClassesVisitor visitor(this);
1289 linker->VisitClasses(&visitor);
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001290 }
1291
1292 void VisitClinitClassesObject(mirror::Object* object) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001293 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001294 DCHECK(object != nullptr);
1295 if (marked_objects_.find(object) != marked_objects_.end()) {
1296 // Already processed.
1297 return;
1298 }
1299
1300 // Mark it.
1301 marked_objects_.insert(object);
1302
1303 if (object->IsClass()) {
1304 // If it is a class, add it.
1305 StackHandleScope<1> hs(self_);
1306 MaybeAddToImageClasses(hs.NewHandle(object->AsClass()), image_class_descriptors_);
1307 } else {
1308 // Else visit the object's class.
1309 VisitClinitClassesObject(object->GetClass());
1310 }
1311
Mathieu Chartiere401d142015-04-22 13:56:20 -07001312 // If it is not a DexCache, visit all references.
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001313 mirror::Class* klass = object->GetClass();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001314 if (klass != dex_cache_class_) {
Mathieu Chartier059ef3d2015-08-18 13:54:21 -07001315 object->VisitReferences(*this, *this);
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001316 }
1317 }
1318
1319 mutable std::unordered_set<mirror::Object*> marked_objects_;
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001320 std::unordered_set<std::string>* const image_class_descriptors_;
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001321 std::vector<mirror::Class*> image_classes_;
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001322 const mirror::Class* dex_cache_class_;
1323 Thread* const self_;
1324 const char* old_cause_;
1325
1326 DISALLOW_COPY_AND_ASSIGN(ClinitImageUpdate);
1327};
Brian Carlstrom7940e442013-07-12 13:46:57 -07001328
Ian Rogers3d504072014-03-01 09:16:49 -08001329void CompilerDriver::UpdateImageClasses(TimingLogger* timings) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001330 if (IsBootImage()) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07001331 TimingLogger::ScopedTiming t("UpdateImageClasses", timings);
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001332
Mathieu Chartier4f55e222015-09-04 13:26:21 -07001333 Runtime* runtime = Runtime::Current();
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001334
1335 // Suspend all threads.
Mathieu Chartier4f55e222015-09-04 13:26:21 -07001336 ScopedSuspendAll ssa(__FUNCTION__);
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001337
1338 std::string error_msg;
1339 std::unique_ptr<ClinitImageUpdate> update(ClinitImageUpdate::Create(image_classes_.get(),
1340 Thread::Current(),
Mathieu Chartier4f55e222015-09-04 13:26:21 -07001341 runtime->GetClassLinker(),
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001342 &error_msg));
1343 CHECK(update.get() != nullptr) << error_msg; // TODO: Soft failure?
1344
1345 // Do the marking.
1346 update->Walk();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001347 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001348}
1349
Vladimir Marko07785bb2015-06-15 18:52:54 +01001350bool CompilerDriver::CanAssumeClassIsLoaded(mirror::Class* klass) {
1351 Runtime* runtime = Runtime::Current();
1352 if (!runtime->IsAotCompiler()) {
Calin Juravleffc87072016-04-20 14:22:09 +01001353 DCHECK(runtime->UseJitCompilation());
Vladimir Marko07785bb2015-06-15 18:52:54 +01001354 // Having the klass reference here implies that the klass is already loaded.
1355 return true;
1356 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001357 if (!IsBootImage()) {
Vladimir Marko07785bb2015-06-15 18:52:54 +01001358 // Assume loaded only if klass is in the boot image. App classes cannot be assumed
1359 // loaded because we don't even know what class loader will be used to load them.
1360 bool class_in_image = runtime->GetHeap()->FindSpaceFromObject(klass, false)->IsImageSpace();
1361 return class_in_image;
1362 }
1363 std::string temp;
1364 const char* descriptor = klass->GetDescriptor(&temp);
1365 return IsImageClass(descriptor);
1366}
1367
Vladimir Marko492a7fa2016-06-01 18:38:43 +01001368void CompilerDriver::MarkForDexToDexCompilation(Thread* self, const MethodReference& method_ref) {
1369 MutexLock lock(self, dex_to_dex_references_lock_);
1370 // Since we're compiling one dex file at a time, we need to look for the
1371 // current dex file entry only at the end of dex_to_dex_references_.
1372 if (dex_to_dex_references_.empty() ||
1373 &dex_to_dex_references_.back().GetDexFile() != method_ref.dex_file) {
1374 dex_to_dex_references_.emplace_back(*method_ref.dex_file);
1375 }
1376 dex_to_dex_references_.back().GetMethodIndexes().SetBit(method_ref.dex_method_index);
1377}
1378
Vladimir Marko3cd50df2016-04-13 19:29:26 +01001379bool CompilerDriver::CanAssumeTypeIsPresentInDexCache(Handle<mirror::DexCache> dex_cache,
1380 uint32_t type_idx) {
Nicolas Geoffray42e372e2015-11-24 15:48:56 +00001381 bool result = false;
1382 if ((IsBootImage() &&
Vladimir Marko3cd50df2016-04-13 19:29:26 +01001383 IsImageClass(dex_cache->GetDexFile()->StringDataByIdx(
1384 dex_cache->GetDexFile()->GetTypeId(type_idx).descriptor_idx_))) ||
Calin Juravleffc87072016-04-20 14:22:09 +01001385 Runtime::Current()->UseJitCompilation()) {
Nicolas Geoffray42e372e2015-11-24 15:48:56 +00001386 mirror::Class* resolved_class = dex_cache->GetResolvedType(type_idx);
1387 result = (resolved_class != nullptr);
1388 }
1389
1390 if (result) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001391 stats_->TypeInDexCache();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001392 } else {
1393 stats_->TypeNotInDexCache();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001394 }
Nicolas Geoffray42e372e2015-11-24 15:48:56 +00001395 return result;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001396}
1397
1398bool CompilerDriver::CanAssumeStringIsPresentInDexCache(const DexFile& dex_file,
1399 uint32_t string_idx) {
1400 // See also Compiler::ResolveDexFile
1401
1402 bool result = false;
Calin Juravleffc87072016-04-20 14:22:09 +01001403 if (IsBootImage() || Runtime::Current()->UseJitCompilation()) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001404 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001405 StackHandleScope<1> hs(soa.Self());
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001406 ClassLinker* const class_linker = Runtime::Current()->GetClassLinker();
1407 Handle<mirror::DexCache> dex_cache(hs.NewHandle(class_linker->FindDexCache(
1408 soa.Self(), dex_file, false)));
Nicolas Geoffray917d0162015-11-24 18:25:35 +00001409 if (IsBootImage()) {
1410 // We resolve all const-string strings when building for the image.
1411 class_linker->ResolveString(dex_file, string_idx, dex_cache);
1412 result = true;
1413 } else {
1414 // Just check whether the dex cache already has the string.
Calin Juravleffc87072016-04-20 14:22:09 +01001415 DCHECK(Runtime::Current()->UseJitCompilation());
Nicolas Geoffray917d0162015-11-24 18:25:35 +00001416 result = (dex_cache->GetResolvedString(string_idx) != nullptr);
1417 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001418 }
1419 if (result) {
1420 stats_->StringInDexCache();
1421 } else {
1422 stats_->StringNotInDexCache();
1423 }
1424 return result;
1425}
1426
Vladimir Marko3cd50df2016-04-13 19:29:26 +01001427bool CompilerDriver::CanAccessTypeWithoutChecks(uint32_t referrer_idx,
1428 Handle<mirror::DexCache> dex_cache,
1429 uint32_t type_idx) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001430 // Get type from dex cache assuming it was populated by the verifier
1431 mirror::Class* resolved_class = dex_cache->GetResolvedType(type_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001432 if (resolved_class == nullptr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001433 stats_->TypeNeedsAccessCheck();
1434 return false; // Unknown class needs access checks.
1435 }
Vladimir Marko3cd50df2016-04-13 19:29:26 +01001436 const DexFile::MethodId& method_id = dex_cache->GetDexFile()->GetMethodId(referrer_idx);
David Brazdil38f64d32016-01-18 17:13:41 +00001437 bool is_accessible = resolved_class->IsPublic(); // Public classes are always accessible.
1438 if (!is_accessible) {
1439 mirror::Class* referrer_class = dex_cache->GetResolvedType(method_id.class_idx_);
1440 if (referrer_class == nullptr) {
1441 stats_->TypeNeedsAccessCheck();
1442 return false; // Incomplete referrer knowledge needs access check.
1443 }
1444 // Perform access check, will return true if access is ok or false if we're going to have to
1445 // check this at runtime (for example for class loaders).
1446 is_accessible = referrer_class->CanAccess(resolved_class);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001447 }
David Brazdil38f64d32016-01-18 17:13:41 +00001448 if (is_accessible) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001449 stats_->TypeDoesntNeedAccessCheck();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001450 } else {
1451 stats_->TypeNeedsAccessCheck();
1452 }
David Brazdil38f64d32016-01-18 17:13:41 +00001453 return is_accessible;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001454}
1455
1456bool CompilerDriver::CanAccessInstantiableTypeWithoutChecks(uint32_t referrer_idx,
Vladimir Marko3cd50df2016-04-13 19:29:26 +01001457 Handle<mirror::DexCache> dex_cache,
Mingyao Yangfb8464a2015-11-02 10:56:59 -08001458 uint32_t type_idx,
1459 bool* finalizable) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001460 // Get type from dex cache assuming it was populated by the verifier.
1461 mirror::Class* resolved_class = dex_cache->GetResolvedType(type_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001462 if (resolved_class == nullptr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001463 stats_->TypeNeedsAccessCheck();
Mingyao Yangfb8464a2015-11-02 10:56:59 -08001464 // Be conservative.
1465 *finalizable = true;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001466 return false; // Unknown class needs access checks.
1467 }
Mingyao Yangfb8464a2015-11-02 10:56:59 -08001468 *finalizable = resolved_class->IsFinalizable();
Vladimir Marko3cd50df2016-04-13 19:29:26 +01001469 const DexFile::MethodId& method_id = dex_cache->GetDexFile()->GetMethodId(referrer_idx);
David Brazdil38f64d32016-01-18 17:13:41 +00001470 bool is_accessible = resolved_class->IsPublic(); // Public classes are always accessible.
1471 if (!is_accessible) {
1472 mirror::Class* referrer_class = dex_cache->GetResolvedType(method_id.class_idx_);
1473 if (referrer_class == nullptr) {
1474 stats_->TypeNeedsAccessCheck();
1475 return false; // Incomplete referrer knowledge needs access check.
1476 }
1477 // Perform access and instantiable checks, will return true if access is ok or false if we're
1478 // going to have to check this at runtime (for example for class loaders).
1479 is_accessible = referrer_class->CanAccess(resolved_class);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001480 }
David Brazdil38f64d32016-01-18 17:13:41 +00001481 bool result = is_accessible && resolved_class->IsInstantiable();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001482 if (result) {
1483 stats_->TypeDoesntNeedAccessCheck();
1484 } else {
1485 stats_->TypeNeedsAccessCheck();
1486 }
1487 return result;
1488}
1489
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001490bool CompilerDriver::CanEmbedTypeInCode(const DexFile& dex_file, uint32_t type_idx,
1491 bool* is_type_initialized, bool* use_direct_type_ptr,
Mathieu Chartier8668c3c2014-04-24 16:48:11 -07001492 uintptr_t* direct_type_ptr, bool* out_is_finalizable) {
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001493 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001494 Runtime* runtime = Runtime::Current();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001495 mirror::DexCache* dex_cache = runtime->GetClassLinker()->FindDexCache(
1496 soa.Self(), dex_file, false);
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001497 mirror::Class* resolved_class = dex_cache->GetResolvedType(type_idx);
1498 if (resolved_class == nullptr) {
1499 return false;
1500 }
Igor Murashkind6dee672014-10-16 18:36:16 -07001501 if (GetCompilerOptions().GetCompilePic()) {
1502 // Do not allow a direct class pointer to be used when compiling for position-independent
1503 return false;
1504 }
Mathieu Chartier8668c3c2014-04-24 16:48:11 -07001505 *out_is_finalizable = resolved_class->IsFinalizable();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001506 gc::Heap* heap = runtime->GetHeap();
1507 const bool compiling_boot = heap->IsCompilingBoot();
Alex Light6e183f22014-07-18 14:57:04 -07001508 const bool support_boot_image_fixup = GetSupportBootImageFixup();
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001509 if (compiling_boot) {
1510 // boot -> boot class pointers.
1511 // True if the class is in the image at boot compiling time.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001512 const bool is_image_class = IsBootImage() && IsImageClass(
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001513 dex_file.StringDataByIdx(dex_file.GetTypeId(type_idx).descriptor_idx_));
1514 // True if pc relative load works.
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001515 if (is_image_class && support_boot_image_fixup) {
1516 *is_type_initialized = resolved_class->IsInitialized();
1517 *use_direct_type_ptr = false;
1518 *direct_type_ptr = 0;
1519 return true;
1520 } else {
1521 return false;
1522 }
Calin Juravleffc87072016-04-20 14:22:09 +01001523 } else if (runtime->UseJitCompilation() && !heap->IsMovableObject(resolved_class)) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001524 *is_type_initialized = resolved_class->IsInitialized();
1525 // If the class may move around, then don't embed it as a direct pointer.
1526 *use_direct_type_ptr = true;
1527 *direct_type_ptr = reinterpret_cast<uintptr_t>(resolved_class);
1528 return true;
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001529 } else {
1530 // True if the class is in the image at app compiling time.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001531 const bool class_in_image = heap->FindSpaceFromObject(resolved_class, false)->IsImageSpace();
Alex Light6e183f22014-07-18 14:57:04 -07001532 if (class_in_image && support_boot_image_fixup) {
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001533 // boot -> app class pointers.
1534 *is_type_initialized = resolved_class->IsInitialized();
Alex Lighta59dd802014-07-02 16:28:08 -07001535 // TODO This is somewhat hacky. We should refactor all of this invoke codepath.
1536 *use_direct_type_ptr = !GetCompilerOptions().GetIncludePatchInformation();
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001537 *direct_type_ptr = reinterpret_cast<uintptr_t>(resolved_class);
1538 return true;
1539 } else {
1540 // app -> app class pointers.
1541 // Give up because app does not have an image and class
1542 // isn't created at compile time. TODO: implement this
1543 // if/when each app gets an image.
1544 return false;
1545 }
1546 }
1547}
1548
Fred Shihe7f82e22014-08-06 10:46:37 -07001549bool CompilerDriver::CanEmbedReferenceTypeInCode(ClassReference* ref,
1550 bool* use_direct_ptr,
1551 uintptr_t* direct_type_ptr) {
1552 CHECK(ref != nullptr);
1553 CHECK(use_direct_ptr != nullptr);
1554 CHECK(direct_type_ptr != nullptr);
1555
1556 ScopedObjectAccess soa(Thread::Current());
1557 mirror::Class* reference_class = mirror::Reference::GetJavaLangRefReference();
Andreas Gampe928f72b2014-09-09 19:53:48 -07001558 bool is_initialized = false;
Fred Shihe7f82e22014-08-06 10:46:37 -07001559 bool unused_finalizable;
1560 // Make sure we have a finished Reference class object before attempting to use it.
1561 if (!CanEmbedTypeInCode(*reference_class->GetDexCache()->GetDexFile(),
1562 reference_class->GetDexTypeIndex(), &is_initialized,
1563 use_direct_ptr, direct_type_ptr, &unused_finalizable) ||
1564 !is_initialized) {
1565 return false;
1566 }
1567 ref->first = &reference_class->GetDexFile();
1568 ref->second = reference_class->GetDexClassDefIndex();
1569 return true;
1570}
1571
1572uint32_t CompilerDriver::GetReferenceSlowFlagOffset() const {
1573 ScopedObjectAccess soa(Thread::Current());
1574 mirror::Class* klass = mirror::Reference::GetJavaLangRefReference();
1575 DCHECK(klass->IsInitialized());
1576 return klass->GetSlowPathFlagOffset().Uint32Value();
1577}
1578
1579uint32_t CompilerDriver::GetReferenceDisableFlagOffset() const {
1580 ScopedObjectAccess soa(Thread::Current());
1581 mirror::Class* klass = mirror::Reference::GetJavaLangRefReference();
1582 DCHECK(klass->IsInitialized());
1583 return klass->GetDisableIntrinsicFlagOffset().Uint32Value();
1584}
1585
Vladimir Marko20f85592015-03-19 10:07:02 +00001586DexCacheArraysLayout CompilerDriver::GetDexCacheArraysLayout(const DexFile* dex_file) {
Vladimir Markod1eaf0d2015-10-29 12:18:29 +00001587 return ContainsElement(GetDexFilesForOatFile(), dex_file)
Mathieu Chartierc7853442015-03-27 14:35:38 -07001588 ? DexCacheArraysLayout(GetInstructionSetPointerSize(instruction_set_), dex_file)
Vladimir Marko20f85592015-03-19 10:07:02 +00001589 : DexCacheArraysLayout();
1590}
1591
Vladimir Markobe0e5462014-02-26 11:24:15 +00001592void CompilerDriver::ProcessedInstanceField(bool resolved) {
1593 if (!resolved) {
1594 stats_->UnresolvedInstanceField();
1595 } else {
1596 stats_->ResolvedInstanceField();
1597 }
1598}
1599
1600void CompilerDriver::ProcessedStaticField(bool resolved, bool local) {
1601 if (!resolved) {
1602 stats_->UnresolvedStaticField();
1603 } else if (local) {
1604 stats_->ResolvedLocalStaticField();
1605 } else {
1606 stats_->ResolvedStaticField();
1607 }
1608}
1609
Vladimir Markof096aad2014-01-23 15:51:58 +00001610void CompilerDriver::ProcessedInvoke(InvokeType invoke_type, int flags) {
1611 stats_->ProcessedInvoke(invoke_type, flags);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001612}
1613
Mathieu Chartierc7853442015-03-27 14:35:38 -07001614ArtField* CompilerDriver::ComputeInstanceFieldInfo(uint32_t field_idx,
1615 const DexCompilationUnit* mUnit, bool is_put,
1616 const ScopedObjectAccess& soa) {
Vladimir Markobe0e5462014-02-26 11:24:15 +00001617 // Try to resolve the field and compiling method's class.
Mathieu Chartierc7853442015-03-27 14:35:38 -07001618 ArtField* resolved_field;
Vladimir Markobe0e5462014-02-26 11:24:15 +00001619 mirror::Class* referrer_class;
Mathieu Chartier736b5602015-09-02 14:54:11 -07001620 Handle<mirror::DexCache> dex_cache(mUnit->GetDexCache());
Vladimir Markobe0e5462014-02-26 11:24:15 +00001621 {
Mathieu Chartier736b5602015-09-02 14:54:11 -07001622 StackHandleScope<1> hs(soa.Self());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001623 Handle<mirror::ClassLoader> class_loader_handle(
1624 hs.NewHandle(soa.Decode<mirror::ClassLoader*>(mUnit->GetClassLoader())));
Mathieu Chartier736b5602015-09-02 14:54:11 -07001625 resolved_field = ResolveField(soa, dex_cache, class_loader_handle, mUnit, field_idx, false);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001626 referrer_class = resolved_field != nullptr
Mathieu Chartier736b5602015-09-02 14:54:11 -07001627 ? ResolveCompilingMethodsClass(soa, dex_cache, class_loader_handle, mUnit) : nullptr;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001628 }
Nicolas Geoffraye5038322014-07-04 09:41:32 +01001629 bool can_link = false;
Vladimir Markobe0e5462014-02-26 11:24:15 +00001630 if (resolved_field != nullptr && referrer_class != nullptr) {
Vladimir Markobe0e5462014-02-26 11:24:15 +00001631 std::pair<bool, bool> fast_path = IsFastInstanceField(
Mathieu Chartier736b5602015-09-02 14:54:11 -07001632 dex_cache.Get(), referrer_class, resolved_field, field_idx);
Nicolas Geoffraye5038322014-07-04 09:41:32 +01001633 can_link = is_put ? fast_path.second : fast_path.first;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001634 }
Nicolas Geoffraye5038322014-07-04 09:41:32 +01001635 ProcessedInstanceField(can_link);
1636 return can_link ? resolved_field : nullptr;
1637}
1638
1639bool CompilerDriver::ComputeInstanceFieldInfo(uint32_t field_idx, const DexCompilationUnit* mUnit,
1640 bool is_put, MemberOffset* field_offset,
1641 bool* is_volatile) {
1642 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartierc7853442015-03-27 14:35:38 -07001643 ArtField* resolved_field = ComputeInstanceFieldInfo(field_idx, mUnit, is_put, soa);
Nicolas Geoffraye5038322014-07-04 09:41:32 +01001644
Mathieu Chartierc7853442015-03-27 14:35:38 -07001645 if (resolved_field == nullptr) {
Vladimir Markobe0e5462014-02-26 11:24:15 +00001646 // Conservative defaults.
1647 *is_volatile = true;
1648 *field_offset = MemberOffset(static_cast<size_t>(-1));
Nicolas Geoffraye5038322014-07-04 09:41:32 +01001649 return false;
1650 } else {
1651 *is_volatile = resolved_field->IsVolatile();
1652 *field_offset = resolved_field->GetOffset();
1653 return true;
Vladimir Markobe0e5462014-02-26 11:24:15 +00001654 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001655}
1656
Ian Rogers83883d72013-10-21 21:07:24 -07001657void CompilerDriver::GetCodeAndMethodForDirectCall(InvokeType* type, InvokeType sharp_type,
1658 bool no_guarantee_of_dex_cache_entry,
Igor Murashkind6dee672014-10-16 18:36:16 -07001659 const mirror::Class* referrer_class,
Mathieu Chartiere401d142015-04-22 13:56:20 -07001660 ArtMethod* method,
Vladimir Markof096aad2014-01-23 15:51:58 +00001661 int* stats_flags,
Ian Rogers83883d72013-10-21 21:07:24 -07001662 MethodReference* target_method,
Ian Rogers65ec92c2013-09-06 10:49:58 -07001663 uintptr_t* direct_code,
1664 uintptr_t* direct_method) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001665 // For direct and static methods compute possible direct_code and direct_method values, ie
1666 // an address for the Method* being invoked and an address of the code for that Method*.
1667 // For interface calls compute a value for direct_method that is the interface method being
1668 // invoked, so this can be passed to the out-of-line runtime support code.
Ian Rogers65ec92c2013-09-06 10:49:58 -07001669 *direct_code = 0;
1670 *direct_method = 0;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001671 Runtime* const runtime = Runtime::Current();
1672 gc::Heap* const heap = runtime->GetHeap();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001673 auto* cl = runtime->GetClassLinker();
1674 const auto pointer_size = cl->GetImagePointerSize();
Igor Murashkind6dee672014-10-16 18:36:16 -07001675 bool use_dex_cache = GetCompilerOptions().GetCompilePic(); // Off by default
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001676 const bool compiling_boot = heap->IsCompilingBoot();
Alex Lighta59dd802014-07-02 16:28:08 -07001677 // TODO This is somewhat hacky. We should refactor all of this invoke codepath.
1678 const bool force_relocations = (compiling_boot ||
1679 GetCompilerOptions().GetIncludePatchInformation());
Elliott Hughes956af0f2014-12-11 14:34:28 -08001680 if (sharp_type != kStatic && sharp_type != kDirect) {
1681 return;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001682 }
Elliott Hughes956af0f2014-12-11 14:34:28 -08001683 // TODO: support patching on all architectures.
1684 use_dex_cache = use_dex_cache || (force_relocations && !support_boot_image_fixup_);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001685 mirror::Class* declaring_class = method->GetDeclaringClass();
1686 bool method_code_in_boot = declaring_class->GetClassLoader() == nullptr;
Ian Rogers83883d72013-10-21 21:07:24 -07001687 if (!use_dex_cache) {
1688 if (!method_code_in_boot) {
1689 use_dex_cache = true;
1690 } else {
Brian Carlstrom14247b62015-01-31 21:35:32 -08001691 bool has_clinit_trampoline =
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001692 method->IsStatic() && !declaring_class->IsInitialized();
1693 if (has_clinit_trampoline && declaring_class != referrer_class) {
Ian Rogers83883d72013-10-21 21:07:24 -07001694 // Ensure we run the clinit trampoline unless we are invoking a static method in the same
1695 // class.
1696 use_dex_cache = true;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001697 }
1698 }
Ian Rogers83883d72013-10-21 21:07:24 -07001699 }
Calin Juravleffc87072016-04-20 14:22:09 +01001700 if (runtime->UseJitCompilation()) {
Mathieu Chartier28a35882015-02-26 18:28:07 -08001701 // If we are the JIT, then don't allow a direct call to the interpreter bridge since this will
1702 // never be updated even after we compile the method.
Mathieu Chartiere401d142015-04-22 13:56:20 -07001703 if (cl->IsQuickToInterpreterBridge(
Mathieu Chartier28a35882015-02-26 18:28:07 -08001704 reinterpret_cast<const void*>(compiler_->GetEntryPointOf(method)))) {
1705 use_dex_cache = true;
1706 }
1707 }
Vladimir Markof096aad2014-01-23 15:51:58 +00001708 if (method_code_in_boot) {
1709 *stats_flags |= kFlagDirectCallToBoot | kFlagDirectMethodToBoot;
Ian Rogers83883d72013-10-21 21:07:24 -07001710 }
Alex Lighta59dd802014-07-02 16:28:08 -07001711 if (!use_dex_cache && force_relocations) {
Jeff Haoa0acc2d2015-01-27 11:22:04 -08001712 bool is_in_image;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001713 if (IsBootImage()) {
Jeff Haoa0acc2d2015-01-27 11:22:04 -08001714 is_in_image = IsImageClass(method->GetDeclaringClassDescriptor());
1715 } else {
1716 is_in_image = instruction_set_ != kX86 && instruction_set_ != kX86_64 &&
Vladimir Markoc08ab292015-06-22 14:35:42 +01001717 heap->FindSpaceFromObject(method->GetDeclaringClass(), false)->IsImageSpace() &&
1718 !cl->IsQuickToInterpreterBridge(
1719 reinterpret_cast<const void*>(compiler_->GetEntryPointOf(method)));
Jeff Haoa0acc2d2015-01-27 11:22:04 -08001720 }
1721 if (!is_in_image) {
Ian Rogers83883d72013-10-21 21:07:24 -07001722 // We can only branch directly to Methods that are resolved in the DexCache.
1723 // Otherwise we won't invoke the resolution trampoline.
1724 use_dex_cache = true;
1725 }
1726 }
1727 // The method is defined not within this dex file. We need a dex cache slot within the current
1728 // dex file or direct pointers.
1729 bool must_use_direct_pointers = false;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001730 mirror::DexCache* dex_cache = declaring_class->GetDexCache();
1731 if (target_method->dex_file == dex_cache->GetDexFile() &&
Calin Juravleffc87072016-04-20 14:22:09 +01001732 !(runtime->UseJitCompilation() && dex_cache->GetResolvedMethod(
Mathieu Chartiere401d142015-04-22 13:56:20 -07001733 method->GetDexMethodIndex(), pointer_size) == nullptr)) {
Ian Rogers83883d72013-10-21 21:07:24 -07001734 target_method->dex_method_index = method->GetDexMethodIndex();
1735 } else {
Ian Rogers83883d72013-10-21 21:07:24 -07001736 if (no_guarantee_of_dex_cache_entry) {
1737 // See if the method is also declared in this dex cache.
Mathieu Chartiere401d142015-04-22 13:56:20 -07001738 uint32_t dex_method_idx = method->FindDexMethodIndexInOtherDexFile(
1739 *target_method->dex_file, target_method->dex_method_index);
Ian Rogers83883d72013-10-21 21:07:24 -07001740 if (dex_method_idx != DexFile::kDexNoIndex) {
1741 target_method->dex_method_index = dex_method_idx;
1742 } else {
Alex Lighta59dd802014-07-02 16:28:08 -07001743 if (force_relocations && !use_dex_cache) {
Jeff Hao49161ce2014-03-12 11:05:25 -07001744 target_method->dex_method_index = method->GetDexMethodIndex();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001745 target_method->dex_file = dex_cache->GetDexFile();
Jeff Hao49161ce2014-03-12 11:05:25 -07001746 }
Ian Rogers83883d72013-10-21 21:07:24 -07001747 must_use_direct_pointers = true;
1748 }
1749 }
1750 }
1751 if (use_dex_cache) {
1752 if (must_use_direct_pointers) {
1753 // Fail. Test above showed the only safe dispatch was via the dex cache, however, the direct
1754 // pointers are required as the dex cache lacks an appropriate entry.
1755 VLOG(compiler) << "Dex cache devirtualization failed for: " << PrettyMethod(method);
1756 } else {
1757 *type = sharp_type;
1758 }
1759 } else {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001760 bool method_in_image = false;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001761 const std::vector<gc::space::ImageSpace*> image_spaces = heap->GetBootImageSpaces();
1762 for (gc::space::ImageSpace* image_space : image_spaces) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001763 const auto& method_section = image_space->GetImageHeader().GetMethodsSection();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001764 if (method_section.Contains(reinterpret_cast<uint8_t*>(method) - image_space->Begin())) {
1765 method_in_image = true;
1766 break;
1767 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001768 }
Calin Juravleffc87072016-04-20 14:22:09 +01001769 if (method_in_image || compiling_boot || runtime->UseJitCompilation()) {
Alex Lighta59dd802014-07-02 16:28:08 -07001770 // 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 -08001771 // In the case where we are the JIT, we can always use direct pointers since we know where
1772 // the method and its code are / will be. We don't sharpen to interpreter bridge since we
1773 // check IsQuickToInterpreterBridge above.
Vladimir Markoa51a0b02014-05-21 12:08:39 +01001774 CHECK(!method->IsAbstract());
Ian Rogers83883d72013-10-21 21:07:24 -07001775 *type = sharp_type;
Alex Lighta59dd802014-07-02 16:28:08 -07001776 *direct_method = force_relocations ? -1 : reinterpret_cast<uintptr_t>(method);
1777 *direct_code = force_relocations ? -1 : compiler_->GetEntryPointOf(method);
Brian Carlstrom14247b62015-01-31 21:35:32 -08001778 target_method->dex_file = method->GetDeclaringClass()->GetDexCache()->GetDexFile();
Vladimir Markoa51a0b02014-05-21 12:08:39 +01001779 target_method->dex_method_index = method->GetDexMethodIndex();
1780 } else if (!must_use_direct_pointers) {
1781 // Set the code and rely on the dex cache for the method.
1782 *type = sharp_type;
Alex Lighta59dd802014-07-02 16:28:08 -07001783 if (force_relocations) {
1784 *direct_code = -1;
Brian Carlstrom14247b62015-01-31 21:35:32 -08001785 target_method->dex_file = method->GetDeclaringClass()->GetDexCache()->GetDexFile();
Alex Lighta59dd802014-07-02 16:28:08 -07001786 target_method->dex_method_index = method->GetDexMethodIndex();
1787 } else {
1788 *direct_code = compiler_->GetEntryPointOf(method);
1789 }
Ian Rogers83883d72013-10-21 21:07:24 -07001790 } else {
Vladimir Markoa51a0b02014-05-21 12:08:39 +01001791 // Direct pointers were required but none were available.
1792 VLOG(compiler) << "Dex cache devirtualization failed for: " << PrettyMethod(method);
Ian Rogers83883d72013-10-21 21:07:24 -07001793 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001794 }
1795}
1796
1797bool CompilerDriver::ComputeInvokeInfo(const DexCompilationUnit* mUnit, const uint32_t dex_pc,
Ian Rogers65ec92c2013-09-06 10:49:58 -07001798 bool update_stats, bool enable_devirtualization,
1799 InvokeType* invoke_type, MethodReference* target_method,
1800 int* vtable_idx, uintptr_t* direct_code,
1801 uintptr_t* direct_method) {
Vladimir Markof096aad2014-01-23 15:51:58 +00001802 InvokeType orig_invoke_type = *invoke_type;
1803 int stats_flags = 0;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001804 ScopedObjectAccess soa(Thread::Current());
Vladimir Markof096aad2014-01-23 15:51:58 +00001805 // Try to resolve the method and compiling method's class.
Mathieu Chartier736b5602015-09-02 14:54:11 -07001806 StackHandleScope<2> hs(soa.Self());
1807 Handle<mirror::DexCache> dex_cache(mUnit->GetDexCache());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001808 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(
1809 soa.Decode<mirror::ClassLoader*>(mUnit->GetClassLoader())));
Mathieu Chartiere401d142015-04-22 13:56:20 -07001810 uint32_t method_idx = target_method->dex_method_index;
1811 ArtMethod* resolved_method = ResolveMethod(
1812 soa, dex_cache, class_loader, mUnit, method_idx, orig_invoke_type);
1813 auto h_referrer_class = hs.NewHandle(resolved_method != nullptr ?
1814 ResolveCompilingMethodsClass(soa, dex_cache, class_loader, mUnit) : nullptr);
Vladimir Markof096aad2014-01-23 15:51:58 +00001815 bool result = false;
1816 if (resolved_method != nullptr) {
1817 *vtable_idx = GetResolvedMethodVTableIndex(resolved_method, orig_invoke_type);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001818
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001819 if (enable_devirtualization && mUnit->GetVerifiedMethod() != nullptr) {
Vladimir Markof096aad2014-01-23 15:51:58 +00001820 const MethodReference* devirt_target = mUnit->GetVerifiedMethod()->GetDevirtTarget(dex_pc);
1821
1822 stats_flags = IsFastInvoke(
Mathieu Chartiere401d142015-04-22 13:56:20 -07001823 soa, dex_cache, class_loader, mUnit, h_referrer_class.Get(), resolved_method,
Vladimir Markof096aad2014-01-23 15:51:58 +00001824 invoke_type, target_method, devirt_target, direct_code, direct_method);
1825 result = stats_flags != 0;
1826 } else {
1827 // Devirtualization not enabled. Inline IsFastInvoke(), dropping the devirtualization parts.
Mathieu Chartiere401d142015-04-22 13:56:20 -07001828 if (UNLIKELY(h_referrer_class.Get() == nullptr) ||
1829 UNLIKELY(!h_referrer_class->CanAccessResolvedMethod(resolved_method->GetDeclaringClass(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001830 resolved_method, dex_cache.Get(),
Vladimir Markof096aad2014-01-23 15:51:58 +00001831 target_method->dex_method_index)) ||
1832 *invoke_type == kSuper) {
1833 // Slow path. (Without devirtualization, all super calls go slow path as well.)
1834 } else {
1835 // Sharpening failed so generate a regular resolved method dispatch.
1836 stats_flags = kFlagMethodResolved;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001837 GetCodeAndMethodForDirectCall(
1838 invoke_type, *invoke_type, false, h_referrer_class.Get(), resolved_method, &stats_flags,
1839 target_method, direct_code, direct_method);
Vladimir Markof096aad2014-01-23 15:51:58 +00001840 result = true;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001841 }
1842 }
1843 }
Vladimir Markof096aad2014-01-23 15:51:58 +00001844 if (!result) {
1845 // Conservative defaults.
1846 *vtable_idx = -1;
1847 *direct_code = 0u;
1848 *direct_method = 0u;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001849 }
1850 if (update_stats) {
Vladimir Markof096aad2014-01-23 15:51:58 +00001851 ProcessedInvoke(orig_invoke_type, stats_flags);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001852 }
Vladimir Markof096aad2014-01-23 15:51:58 +00001853 return result;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001854}
1855
Vladimir Marko2730db02014-01-27 11:15:17 +00001856const VerifiedMethod* CompilerDriver::GetVerifiedMethod(const DexFile* dex_file,
1857 uint32_t method_idx) const {
1858 MethodReference ref(dex_file, method_idx);
1859 return verification_results_->GetVerifiedMethod(ref);
1860}
1861
1862bool CompilerDriver::IsSafeCast(const DexCompilationUnit* mUnit, uint32_t dex_pc) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001863 if (!compiler_options_->IsVerificationEnabled()) {
1864 // If we didn't verify, every cast has to be treated as non-safe.
1865 return false;
1866 }
Vladimir Marko2730db02014-01-27 11:15:17 +00001867 DCHECK(mUnit->GetVerifiedMethod() != nullptr);
1868 bool result = mUnit->GetVerifiedMethod()->IsSafeCast(dex_pc);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001869 if (result) {
1870 stats_->SafeCast();
1871 } else {
1872 stats_->NotASafeCast();
1873 }
1874 return result;
1875}
1876
Mathieu Chartier90443472015-07-16 20:32:27 -07001877class CompilationVisitor {
1878 public:
1879 virtual ~CompilationVisitor() {}
1880 virtual void Visit(size_t index) = 0;
1881};
1882
Brian Carlstrom7940e442013-07-12 13:46:57 -07001883class ParallelCompilationManager {
1884 public:
Brian Carlstrom7940e442013-07-12 13:46:57 -07001885 ParallelCompilationManager(ClassLinker* class_linker,
1886 jobject class_loader,
1887 CompilerDriver* compiler,
1888 const DexFile* dex_file,
Andreas Gampede7b4362014-07-28 18:38:57 -07001889 const std::vector<const DexFile*>& dex_files,
Ian Rogers3d504072014-03-01 09:16:49 -08001890 ThreadPool* thread_pool)
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001891 : index_(0),
1892 class_linker_(class_linker),
Brian Carlstrom7940e442013-07-12 13:46:57 -07001893 class_loader_(class_loader),
1894 compiler_(compiler),
1895 dex_file_(dex_file),
Andreas Gampede7b4362014-07-28 18:38:57 -07001896 dex_files_(dex_files),
Ian Rogers3d504072014-03-01 09:16:49 -08001897 thread_pool_(thread_pool) {}
Brian Carlstrom7940e442013-07-12 13:46:57 -07001898
1899 ClassLinker* GetClassLinker() const {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001900 CHECK(class_linker_ != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001901 return class_linker_;
1902 }
1903
1904 jobject GetClassLoader() const {
1905 return class_loader_;
1906 }
1907
1908 CompilerDriver* GetCompiler() const {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001909 CHECK(compiler_ != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001910 return compiler_;
1911 }
1912
1913 const DexFile* GetDexFile() const {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001914 CHECK(dex_file_ != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001915 return dex_file_;
1916 }
1917
Andreas Gampede7b4362014-07-28 18:38:57 -07001918 const std::vector<const DexFile*>& GetDexFiles() const {
1919 return dex_files_;
1920 }
1921
Mathieu Chartier90443472015-07-16 20:32:27 -07001922 void ForAll(size_t begin, size_t end, CompilationVisitor* visitor, size_t work_units)
1923 REQUIRES(!*Locks::mutator_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001924 Thread* self = Thread::Current();
1925 self->AssertNoPendingException();
1926 CHECK_GT(work_units, 0U);
1927
Ian Rogers3e5cf302014-05-20 16:40:37 -07001928 index_.StoreRelaxed(begin);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001929 for (size_t i = 0; i < work_units; ++i) {
Mathieu Chartier90443472015-07-16 20:32:27 -07001930 thread_pool_->AddTask(self, new ForAllClosure(this, end, visitor));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001931 }
1932 thread_pool_->StartWorkers(self);
1933
1934 // Ensure we're suspended while we're blocked waiting for the other threads to finish (worker
1935 // thread destructor's called below perform join).
1936 CHECK_NE(self->GetState(), kRunnable);
1937
1938 // Wait for all the worker threads to finish.
1939 thread_pool_->Wait(self, true, false);
Andreas Gampeace0dc12016-01-20 13:33:13 -08001940
1941 // And stop the workers accepting jobs.
1942 thread_pool_->StopWorkers(self);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001943 }
1944
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001945 size_t NextIndex() {
Ian Rogers3e5cf302014-05-20 16:40:37 -07001946 return index_.FetchAndAddSequentiallyConsistent(1);
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001947 }
1948
Brian Carlstrom7940e442013-07-12 13:46:57 -07001949 private:
Brian Carlstrom7940e442013-07-12 13:46:57 -07001950 class ForAllClosure : public Task {
1951 public:
Mathieu Chartier90443472015-07-16 20:32:27 -07001952 ForAllClosure(ParallelCompilationManager* manager, size_t end, CompilationVisitor* visitor)
Brian Carlstrom7940e442013-07-12 13:46:57 -07001953 : manager_(manager),
Brian Carlstrom7940e442013-07-12 13:46:57 -07001954 end_(end),
Mathieu Chartier90443472015-07-16 20:32:27 -07001955 visitor_(visitor) {}
Brian Carlstrom7940e442013-07-12 13:46:57 -07001956
1957 virtual void Run(Thread* self) {
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001958 while (true) {
1959 const size_t index = manager_->NextIndex();
1960 if (UNLIKELY(index >= end_)) {
1961 break;
1962 }
Mathieu Chartier90443472015-07-16 20:32:27 -07001963 visitor_->Visit(index);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001964 self->AssertNoPendingException();
1965 }
1966 }
1967
1968 virtual void Finalize() {
1969 delete this;
1970 }
Brian Carlstrom0cd7ec22013-07-17 23:40:20 -07001971
Brian Carlstrom7940e442013-07-12 13:46:57 -07001972 private:
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001973 ParallelCompilationManager* const manager_;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001974 const size_t end_;
Mathieu Chartier90443472015-07-16 20:32:27 -07001975 CompilationVisitor* const visitor_;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001976 };
1977
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001978 AtomicInteger index_;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001979 ClassLinker* const class_linker_;
1980 const jobject class_loader_;
1981 CompilerDriver* const compiler_;
1982 const DexFile* const dex_file_;
Andreas Gampede7b4362014-07-28 18:38:57 -07001983 const std::vector<const DexFile*>& dex_files_;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001984 ThreadPool* const thread_pool_;
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001985
1986 DISALLOW_COPY_AND_ASSIGN(ParallelCompilationManager);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001987};
1988
Jeff Hao0e49b422013-11-08 12:16:56 -08001989// A fast version of SkipClass above if the class pointer is available
1990// that avoids the expensive FindInClassPath search.
1991static bool SkipClass(jobject class_loader, const DexFile& dex_file, mirror::Class* klass)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001992 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001993 DCHECK(klass != nullptr);
Jeff Hao0e49b422013-11-08 12:16:56 -08001994 const DexFile& original_dex_file = *klass->GetDexCache()->GetDexFile();
1995 if (&dex_file != &original_dex_file) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001996 if (class_loader == nullptr) {
Jeff Hao0e49b422013-11-08 12:16:56 -08001997 LOG(WARNING) << "Skipping class " << PrettyDescriptor(klass) << " from "
1998 << dex_file.GetLocation() << " previously found in "
1999 << original_dex_file.GetLocation();
2000 }
2001 return true;
2002 }
2003 return false;
2004}
2005
Mathieu Chartier70b63482014-06-27 17:19:04 -07002006static void CheckAndClearResolveException(Thread* self)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002007 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier70b63482014-06-27 17:19:04 -07002008 CHECK(self->IsExceptionPending());
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002009 mirror::Throwable* exception = self->GetException();
Ian Rogers1ff3c982014-08-12 02:30:58 -07002010 std::string temp;
2011 const char* descriptor = exception->GetClass()->GetDescriptor(&temp);
2012 const char* expected_exceptions[] = {
2013 "Ljava/lang/IllegalAccessError;",
2014 "Ljava/lang/IncompatibleClassChangeError;",
2015 "Ljava/lang/InstantiationError;",
Brian Carlstrom898fcb52014-08-25 23:07:30 -07002016 "Ljava/lang/LinkageError;",
Ian Rogers1ff3c982014-08-12 02:30:58 -07002017 "Ljava/lang/NoClassDefFoundError;",
2018 "Ljava/lang/NoSuchFieldError;",
2019 "Ljava/lang/NoSuchMethodError;"
2020 };
2021 bool found = false;
2022 for (size_t i = 0; (found == false) && (i < arraysize(expected_exceptions)); ++i) {
2023 if (strcmp(descriptor, expected_exceptions[i]) == 0) {
2024 found = true;
2025 }
2026 }
2027 if (!found) {
Brian Carlstrom898fcb52014-08-25 23:07:30 -07002028 LOG(FATAL) << "Unexpected exception " << exception->Dump();
Mathieu Chartier70b63482014-06-27 17:19:04 -07002029 }
2030 self->ClearException();
2031}
2032
Mathieu Chartierb5d38612016-04-07 10:52:52 -07002033bool CompilerDriver::RequiresConstructorBarrier(const DexFile& dex_file,
2034 uint16_t class_def_idx) const {
2035 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_idx);
2036 const uint8_t* class_data = dex_file.GetClassData(class_def);
2037 if (class_data == nullptr) {
2038 // Empty class such as a marker interface.
2039 return false;
2040 }
2041 ClassDataItemIterator it(dex_file, class_data);
2042 while (it.HasNextStaticField()) {
2043 it.Next();
2044 }
2045 // We require a constructor barrier if there are final instance fields.
2046 while (it.HasNextInstanceField()) {
2047 if (it.MemberIsFinal()) {
2048 return true;
2049 }
2050 it.Next();
2051 }
2052 return false;
2053}
2054
Mathieu Chartier90443472015-07-16 20:32:27 -07002055class ResolveClassFieldsAndMethodsVisitor : public CompilationVisitor {
2056 public:
2057 explicit ResolveClassFieldsAndMethodsVisitor(const ParallelCompilationManager* manager)
2058 : manager_(manager) {}
Brian Carlstrom7940e442013-07-12 13:46:57 -07002059
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002060 void Visit(size_t class_def_index) OVERRIDE REQUIRES(!Locks::mutator_lock_) {
Mathieu Chartier90443472015-07-16 20:32:27 -07002061 ATRACE_CALL();
2062 Thread* const self = Thread::Current();
2063 jobject jclass_loader = manager_->GetClassLoader();
2064 const DexFile& dex_file = *manager_->GetDexFile();
2065 ClassLinker* class_linker = manager_->GetClassLinker();
Ian Rogerse6bb3b22013-08-19 21:51:45 -07002066
Mathieu Chartier90443472015-07-16 20:32:27 -07002067 // If an instance field is final then we need to have a barrier on the return, static final
2068 // fields are assigned within the lock held for class initialization. Conservatively assume
2069 // constructor barriers are always required.
2070 bool requires_constructor_barrier = true;
2071
2072 // Method and Field are the worst. We can't resolve without either
2073 // context from the code use (to disambiguate virtual vs direct
2074 // method and instance vs static field) or from class
2075 // definitions. While the compiler will resolve what it can as it
2076 // needs it, here we try to resolve fields and methods used in class
2077 // definitions, since many of them many never be referenced by
2078 // generated code.
2079 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
2080 ScopedObjectAccess soa(self);
2081 StackHandleScope<2> hs(soa.Self());
2082 Handle<mirror::ClassLoader> class_loader(
2083 hs.NewHandle(soa.Decode<mirror::ClassLoader*>(jclass_loader)));
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002084 Handle<mirror::DexCache> dex_cache(hs.NewHandle(class_linker->FindDexCache(
2085 soa.Self(), dex_file, false)));
Mathieu Chartier90443472015-07-16 20:32:27 -07002086 // Resolve the class.
2087 mirror::Class* klass = class_linker->ResolveType(dex_file, class_def.class_idx_, dex_cache,
2088 class_loader);
2089 bool resolve_fields_and_methods;
2090 if (klass == nullptr) {
2091 // Class couldn't be resolved, for example, super-class is in a different dex file. Don't
2092 // attempt to resolve methods and fields when there is no declaring class.
2093 CheckAndClearResolveException(soa.Self());
2094 resolve_fields_and_methods = false;
2095 } else {
2096 // We successfully resolved a class, should we skip it?
2097 if (SkipClass(jclass_loader, dex_file, klass)) {
2098 return;
Ian Rogerse6bb3b22013-08-19 21:51:45 -07002099 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002100 // We want to resolve the methods and fields eagerly.
2101 resolve_fields_and_methods = true;
Ian Rogers68b56852014-08-29 20:19:11 -07002102 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002103 // Note the class_data pointer advances through the headers,
2104 // static fields, instance fields, direct methods, and virtual
2105 // methods.
2106 const uint8_t* class_data = dex_file.GetClassData(class_def);
2107 if (class_data == nullptr) {
2108 // Empty class such as a marker interface.
2109 requires_constructor_barrier = false;
2110 } else {
2111 ClassDataItemIterator it(dex_file, class_data);
2112 while (it.HasNextStaticField()) {
2113 if (resolve_fields_and_methods) {
2114 ArtField* field = class_linker->ResolveField(dex_file, it.GetMemberIndex(),
2115 dex_cache, class_loader, true);
2116 if (field == nullptr) {
2117 CheckAndClearResolveException(soa.Self());
2118 }
Ian Rogers68b56852014-08-29 20:19:11 -07002119 }
2120 it.Next();
2121 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002122 // We require a constructor barrier if there are final instance fields.
2123 requires_constructor_barrier = false;
2124 while (it.HasNextInstanceField()) {
2125 if (it.MemberIsFinal()) {
2126 requires_constructor_barrier = true;
2127 }
2128 if (resolve_fields_and_methods) {
2129 ArtField* field = class_linker->ResolveField(dex_file, it.GetMemberIndex(),
2130 dex_cache, class_loader, false);
2131 if (field == nullptr) {
2132 CheckAndClearResolveException(soa.Self());
2133 }
Ian Rogers68b56852014-08-29 20:19:11 -07002134 }
2135 it.Next();
2136 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002137 if (resolve_fields_and_methods) {
2138 while (it.HasNextDirectMethod()) {
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08002139 ArtMethod* method = class_linker->ResolveMethod<ClassLinker::kNoICCECheckForCache>(
Mathieu Chartier90443472015-07-16 20:32:27 -07002140 dex_file, it.GetMemberIndex(), dex_cache, class_loader, nullptr,
2141 it.GetMethodInvokeType(class_def));
2142 if (method == nullptr) {
2143 CheckAndClearResolveException(soa.Self());
2144 }
2145 it.Next();
2146 }
2147 while (it.HasNextVirtualMethod()) {
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08002148 ArtMethod* method = class_linker->ResolveMethod<ClassLinker::kNoICCECheckForCache>(
Mathieu Chartier90443472015-07-16 20:32:27 -07002149 dex_file, it.GetMemberIndex(), dex_cache, class_loader, nullptr,
2150 it.GetMethodInvokeType(class_def));
2151 if (method == nullptr) {
2152 CheckAndClearResolveException(soa.Self());
2153 }
2154 it.Next();
2155 }
2156 DCHECK(!it.HasNext());
2157 }
2158 }
Mathieu Chartierc4ae9162016-04-07 13:19:19 -07002159 manager_->GetCompiler()->SetRequiresConstructorBarrier(self,
2160 &dex_file,
2161 class_def_index,
2162 requires_constructor_barrier);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002163 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002164
Mathieu Chartier90443472015-07-16 20:32:27 -07002165 private:
2166 const ParallelCompilationManager* const manager_;
2167};
2168
2169class ResolveTypeVisitor : public CompilationVisitor {
2170 public:
2171 explicit ResolveTypeVisitor(const ParallelCompilationManager* manager) : manager_(manager) {
2172 }
2173 virtual void Visit(size_t type_idx) OVERRIDE REQUIRES(!Locks::mutator_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07002174 // Class derived values are more complicated, they require the linker and loader.
Mathieu Chartier90443472015-07-16 20:32:27 -07002175 ScopedObjectAccess soa(Thread::Current());
2176 ClassLinker* class_linker = manager_->GetClassLinker();
2177 const DexFile& dex_file = *manager_->GetDexFile();
2178 StackHandleScope<2> hs(soa.Self());
Mathieu Chartier90443472015-07-16 20:32:27 -07002179 Handle<mirror::ClassLoader> class_loader(
2180 hs.NewHandle(soa.Decode<mirror::ClassLoader*>(manager_->GetClassLoader())));
Mathieu Chartierd57d4542015-10-14 10:55:30 -07002181 Handle<mirror::DexCache> dex_cache(hs.NewHandle(class_linker->RegisterDexFile(
2182 dex_file,
Mathieu Chartierf284d442016-06-02 11:48:30 -07002183 class_loader.Get())));
Mathieu Chartier90443472015-07-16 20:32:27 -07002184 mirror::Class* klass = class_linker->ResolveType(dex_file, type_idx, dex_cache, class_loader);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002185
Mathieu Chartier90443472015-07-16 20:32:27 -07002186 if (klass == nullptr) {
2187 soa.Self()->AssertPendingException();
2188 mirror::Throwable* exception = soa.Self()->GetException();
2189 VLOG(compiler) << "Exception during type resolution: " << exception->Dump();
2190 if (exception->GetClass()->DescriptorEquals("Ljava/lang/OutOfMemoryError;")) {
2191 // There's little point continuing compilation if the heap is exhausted.
2192 LOG(FATAL) << "Out of memory during type resolution for compilation";
2193 }
2194 soa.Self()->ClearException();
Ian Rogersa436fde2013-08-27 23:34:06 -07002195 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002196 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002197
2198 private:
2199 const ParallelCompilationManager* const manager_;
2200};
Brian Carlstrom7940e442013-07-12 13:46:57 -07002201
Andreas Gampeace0dc12016-01-20 13:33:13 -08002202void CompilerDriver::ResolveDexFile(jobject class_loader,
2203 const DexFile& dex_file,
Andreas Gampede7b4362014-07-28 18:38:57 -07002204 const std::vector<const DexFile*>& dex_files,
Andreas Gampeace0dc12016-01-20 13:33:13 -08002205 ThreadPool* thread_pool,
2206 size_t thread_count,
2207 TimingLogger* timings) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07002208 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
2209
2210 // TODO: we could resolve strings here, although the string table is largely filled with class
2211 // and method names.
2212
Andreas Gampede7b4362014-07-28 18:38:57 -07002213 ParallelCompilationManager context(class_linker, class_loader, this, &dex_file, dex_files,
2214 thread_pool);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002215 if (IsBootImage()) {
Ian Rogerse6bb3b22013-08-19 21:51:45 -07002216 // For images we resolve all types, such as array, whereas for applications just those with
2217 // classdefs are resolved by ResolveClassFieldsAndMethods.
Mathieu Chartierf5997b42014-06-20 10:37:54 -07002218 TimingLogger::ScopedTiming t("Resolve Types", timings);
Mathieu Chartier90443472015-07-16 20:32:27 -07002219 ResolveTypeVisitor visitor(&context);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002220 context.ForAll(0, dex_file.NumTypeIds(), &visitor, thread_count);
Ian Rogerse6bb3b22013-08-19 21:51:45 -07002221 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002222
Mathieu Chartierf5997b42014-06-20 10:37:54 -07002223 TimingLogger::ScopedTiming t("Resolve MethodsAndFields", timings);
Mathieu Chartier90443472015-07-16 20:32:27 -07002224 ResolveClassFieldsAndMethodsVisitor visitor(&context);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002225 context.ForAll(0, dex_file.NumClassDefs(), &visitor, thread_count);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002226}
2227
Andreas Gampeace0dc12016-01-20 13:33:13 -08002228void CompilerDriver::SetVerified(jobject class_loader,
2229 const std::vector<const DexFile*>& dex_files,
2230 TimingLogger* timings) {
2231 // This can be run in parallel.
Mathieu Chartier90443472015-07-16 20:32:27 -07002232 for (const DexFile* dex_file : dex_files) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002233 CHECK(dex_file != nullptr);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002234 SetVerifiedDexFile(class_loader,
2235 *dex_file,
2236 dex_files,
2237 parallel_thread_pool_.get(),
2238 parallel_thread_count_,
2239 timings);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002240 }
2241}
2242
Andreas Gampeace0dc12016-01-20 13:33:13 -08002243void CompilerDriver::Verify(jobject class_loader,
2244 const std::vector<const DexFile*>& dex_files,
2245 TimingLogger* timings) {
2246 // Note: verification should not be pulling in classes anymore when compiling the boot image,
2247 // as all should have been resolved before. As such, doing this in parallel should still
2248 // be deterministic.
Mathieu Chartier90443472015-07-16 20:32:27 -07002249 for (const DexFile* dex_file : dex_files) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002250 CHECK(dex_file != nullptr);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002251 VerifyDexFile(class_loader,
2252 *dex_file,
2253 dex_files,
2254 parallel_thread_pool_.get(),
2255 parallel_thread_count_,
2256 timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002257 }
2258}
2259
Mathieu Chartier90443472015-07-16 20:32:27 -07002260class VerifyClassVisitor : public CompilationVisitor {
2261 public:
Andreas Gampe5fd66d02016-09-12 20:22:19 -07002262 VerifyClassVisitor(const ParallelCompilationManager* manager, verifier::HardFailLogMode log_level)
Andreas Gampe7fe30232016-03-25 16:58:00 -07002263 : manager_(manager), log_level_(log_level) {}
Brian Carlstrom7940e442013-07-12 13:46:57 -07002264
Mathieu Chartier90443472015-07-16 20:32:27 -07002265 virtual void Visit(size_t class_def_index) REQUIRES(!Locks::mutator_lock_) OVERRIDE {
2266 ATRACE_CALL();
2267 ScopedObjectAccess soa(Thread::Current());
2268 const DexFile& dex_file = *manager_->GetDexFile();
Mathieu Chartiera8077802016-03-16 19:08:31 -07002269 if (!manager_->GetCompiler()->ShouldVerifyClassBasedOnProfile(dex_file, class_def_index)) {
2270 // Skip verification since the class is not in the profile.
2271 return;
2272 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002273 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
2274 const char* descriptor = dex_file.GetClassDescriptor(class_def);
2275 ClassLinker* class_linker = manager_->GetClassLinker();
2276 jobject jclass_loader = manager_->GetClassLoader();
2277 StackHandleScope<3> hs(soa.Self());
2278 Handle<mirror::ClassLoader> class_loader(
2279 hs.NewHandle(soa.Decode<mirror::ClassLoader*>(jclass_loader)));
2280 Handle<mirror::Class> klass(
2281 hs.NewHandle(class_linker->FindClass(soa.Self(), descriptor, class_loader)));
2282 if (klass.Get() == nullptr) {
Ian Rogerse6bb3b22013-08-19 21:51:45 -07002283 CHECK(soa.Self()->IsExceptionPending());
2284 soa.Self()->ClearException();
Mathieu Chartier90443472015-07-16 20:32:27 -07002285
2286 /*
2287 * At compile time, we can still structurally verify the class even if FindClass fails.
2288 * This is to ensure the class is structurally sound for compilation. An unsound class
2289 * will be rejected by the verifier and later skipped during compilation in the compiler.
2290 */
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002291 Handle<mirror::DexCache> dex_cache(hs.NewHandle(class_linker->FindDexCache(
2292 soa.Self(), dex_file, false)));
Mathieu Chartier90443472015-07-16 20:32:27 -07002293 std::string error_msg;
Andreas Gampeec6e6c12015-11-05 20:39:56 -08002294 if (verifier::MethodVerifier::VerifyClass(soa.Self(),
2295 &dex_file,
2296 dex_cache,
2297 class_loader,
David Brazdil15fc7292016-09-02 14:13:18 +01002298 class_def,
Andreas Gampe53e32d12015-12-09 21:03:23 -08002299 Runtime::Current()->GetCompilerCallbacks(),
Andreas Gampeec6e6c12015-11-05 20:39:56 -08002300 true /* allow soft failures */,
Andreas Gampe7fe30232016-03-25 16:58:00 -07002301 log_level_,
Andreas Gampeec6e6c12015-11-05 20:39:56 -08002302 &error_msg) ==
Mathieu Chartier90443472015-07-16 20:32:27 -07002303 verifier::MethodVerifier::kHardFailure) {
2304 LOG(ERROR) << "Verification failed on class " << PrettyDescriptor(descriptor)
2305 << " because: " << error_msg;
2306 manager_->GetCompiler()->SetHadHardVerifierFailure();
2307 }
2308 } else if (!SkipClass(jclass_loader, dex_file, klass.Get())) {
2309 CHECK(klass->IsResolved()) << PrettyClass(klass.Get());
Andreas Gampe7fe30232016-03-25 16:58:00 -07002310 class_linker->VerifyClass(soa.Self(), klass, log_level_);
Mathieu Chartier90443472015-07-16 20:32:27 -07002311
2312 if (klass->IsErroneous()) {
2313 // ClassLinker::VerifyClass throws, which isn't useful in the compiler.
2314 CHECK(soa.Self()->IsExceptionPending());
2315 soa.Self()->ClearException();
2316 manager_->GetCompiler()->SetHadHardVerifierFailure();
2317 }
2318
2319 CHECK(klass->IsCompileTimeVerified() || klass->IsErroneous())
2320 << PrettyDescriptor(klass.Get()) << ": state=" << klass->GetStatus();
2321
2322 // It is *very* problematic if there are verification errors in the boot classpath. For example,
2323 // we rely on things working OK without verification when the decryption dialog is brought up.
2324 // So abort in a debug build if we find this violated.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002325 DCHECK(!manager_->GetCompiler()->IsBootImage() || klass->IsVerified())
2326 << "Boot classpath class " << PrettyClass(klass.Get()) << " failed to fully verify.";
Ian Rogerse6bb3b22013-08-19 21:51:45 -07002327 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002328 soa.Self()->AssertNoPendingException();
Brian Carlstrom7940e442013-07-12 13:46:57 -07002329 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002330
2331 private:
2332 const ParallelCompilationManager* const manager_;
Andreas Gampe5fd66d02016-09-12 20:22:19 -07002333 const verifier::HardFailLogMode log_level_;
Mathieu Chartier90443472015-07-16 20:32:27 -07002334};
Brian Carlstrom7940e442013-07-12 13:46:57 -07002335
Andreas Gampeace0dc12016-01-20 13:33:13 -08002336void CompilerDriver::VerifyDexFile(jobject class_loader,
2337 const DexFile& dex_file,
Andreas Gampede7b4362014-07-28 18:38:57 -07002338 const std::vector<const DexFile*>& dex_files,
Andreas Gampeace0dc12016-01-20 13:33:13 -08002339 ThreadPool* thread_pool,
2340 size_t thread_count,
2341 TimingLogger* timings) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07002342 TimingLogger::ScopedTiming t("Verify Dex File", timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002343 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Andreas Gampede7b4362014-07-28 18:38:57 -07002344 ParallelCompilationManager context(class_linker, class_loader, this, &dex_file, dex_files,
2345 thread_pool);
Andreas Gampe5fd66d02016-09-12 20:22:19 -07002346 verifier::HardFailLogMode log_level = GetCompilerOptions().AbortOnHardVerifierFailure()
2347 ? verifier::HardFailLogMode::kLogInternalFatal
2348 : verifier::HardFailLogMode::kLogWarning;
Andreas Gampe7fe30232016-03-25 16:58:00 -07002349 VerifyClassVisitor visitor(&context, log_level);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002350 context.ForAll(0, dex_file.NumClassDefs(), &visitor, thread_count);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002351}
2352
Mathieu Chartier90443472015-07-16 20:32:27 -07002353class SetVerifiedClassVisitor : public CompilationVisitor {
2354 public:
2355 explicit SetVerifiedClassVisitor(const ParallelCompilationManager* manager) : manager_(manager) {}
2356
2357 virtual void Visit(size_t class_def_index) REQUIRES(!Locks::mutator_lock_) OVERRIDE {
2358 ATRACE_CALL();
2359 ScopedObjectAccess soa(Thread::Current());
2360 const DexFile& dex_file = *manager_->GetDexFile();
2361 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
2362 const char* descriptor = dex_file.GetClassDescriptor(class_def);
2363 ClassLinker* class_linker = manager_->GetClassLinker();
2364 jobject jclass_loader = manager_->GetClassLoader();
2365 StackHandleScope<3> hs(soa.Self());
2366 Handle<mirror::ClassLoader> class_loader(
2367 hs.NewHandle(soa.Decode<mirror::ClassLoader*>(jclass_loader)));
2368 Handle<mirror::Class> klass(
2369 hs.NewHandle(class_linker->FindClass(soa.Self(), descriptor, class_loader)));
2370 // Class might have failed resolution. Then don't set it to verified.
2371 if (klass.Get() != nullptr) {
2372 // Only do this if the class is resolved. If even resolution fails, quickening will go very,
2373 // very wrong.
2374 if (klass->IsResolved()) {
2375 if (klass->GetStatus() < mirror::Class::kStatusVerified) {
2376 ObjectLock<mirror::Class> lock(soa.Self(), klass);
2377 // Set class status to verified.
2378 mirror::Class::SetStatus(klass, mirror::Class::kStatusVerified, soa.Self());
2379 // Mark methods as pre-verified. If we don't do this, the interpreter will run with
2380 // access checks.
Igor Murashkindf707e42016-02-02 16:56:50 -08002381 klass->SetSkipAccessChecksFlagOnAllMethods(
Mathieu Chartier90443472015-07-16 20:32:27 -07002382 GetInstructionSetPointerSize(manager_->GetCompiler()->GetInstructionSet()));
Igor Murashkindf707e42016-02-02 16:56:50 -08002383 klass->SetVerificationAttempted();
Mathieu Chartier90443472015-07-16 20:32:27 -07002384 }
2385 // Record the final class status if necessary.
2386 ClassReference ref(manager_->GetDexFile(), class_def_index);
2387 manager_->GetCompiler()->RecordClassStatus(ref, klass->GetStatus());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002388 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002389 } else {
2390 Thread* self = soa.Self();
2391 DCHECK(self->IsExceptionPending());
2392 self->ClearException();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002393 }
2394 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002395
2396 private:
2397 const ParallelCompilationManager* const manager_;
2398};
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002399
Andreas Gampeace0dc12016-01-20 13:33:13 -08002400void CompilerDriver::SetVerifiedDexFile(jobject class_loader,
2401 const DexFile& dex_file,
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002402 const std::vector<const DexFile*>& dex_files,
Andreas Gampeace0dc12016-01-20 13:33:13 -08002403 ThreadPool* thread_pool,
2404 size_t thread_count,
2405 TimingLogger* timings) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002406 TimingLogger::ScopedTiming t("Verify Dex File", timings);
2407 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
2408 ParallelCompilationManager context(class_linker, class_loader, this, &dex_file, dex_files,
2409 thread_pool);
Mathieu Chartier90443472015-07-16 20:32:27 -07002410 SetVerifiedClassVisitor visitor(&context);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002411 context.ForAll(0, dex_file.NumClassDefs(), &visitor, thread_count);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002412}
2413
Mathieu Chartier90443472015-07-16 20:32:27 -07002414class InitializeClassVisitor : public CompilationVisitor {
2415 public:
2416 explicit InitializeClassVisitor(const ParallelCompilationManager* manager) : manager_(manager) {}
Ian Rogersfc0e94b2013-09-23 23:51:32 -07002417
Mathieu Chartier90443472015-07-16 20:32:27 -07002418 virtual void Visit(size_t class_def_index) REQUIRES(!Locks::mutator_lock_) OVERRIDE {
2419 ATRACE_CALL();
2420 jobject jclass_loader = manager_->GetClassLoader();
2421 const DexFile& dex_file = *manager_->GetDexFile();
2422 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
2423 const DexFile::TypeId& class_type_id = dex_file.GetTypeId(class_def.class_idx_);
2424 const char* descriptor = dex_file.StringDataByIdx(class_type_id.descriptor_idx_);
Jeff Hao0e49b422013-11-08 12:16:56 -08002425
Mathieu Chartier90443472015-07-16 20:32:27 -07002426 ScopedObjectAccess soa(Thread::Current());
2427 StackHandleScope<3> hs(soa.Self());
2428 Handle<mirror::ClassLoader> class_loader(
2429 hs.NewHandle(soa.Decode<mirror::ClassLoader*>(jclass_loader)));
2430 Handle<mirror::Class> klass(
2431 hs.NewHandle(manager_->GetClassLinker()->FindClass(soa.Self(), descriptor, class_loader)));
2432
2433 if (klass.Get() != nullptr && !SkipClass(jclass_loader, dex_file, klass.Get())) {
2434 // Only try to initialize classes that were successfully verified.
2435 if (klass->IsVerified()) {
2436 // Attempt to initialize the class but bail if we either need to initialize the super-class
2437 // or static fields.
2438 manager_->GetClassLinker()->EnsureInitialized(soa.Self(), klass, false, false);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07002439 if (!klass->IsInitialized()) {
Mathieu Chartier90443472015-07-16 20:32:27 -07002440 // We don't want non-trivial class initialization occurring on multiple threads due to
2441 // deadlock problems. For example, a parent class is initialized (holding its lock) that
2442 // refers to a sub-class in its static/class initializer causing it to try to acquire the
2443 // sub-class' lock. While on a second thread the sub-class is initialized (holding its lock)
2444 // after first initializing its parents, whose locks are acquired. This leads to a
2445 // parent-to-child and a child-to-parent lock ordering and consequent potential deadlock.
2446 // We need to use an ObjectLock due to potential suspension in the interpreting code. Rather
2447 // than use a special Object for the purpose we use the Class of java.lang.Class.
2448 Handle<mirror::Class> h_klass(hs.NewHandle(klass->GetClass()));
2449 ObjectLock<mirror::Class> lock(soa.Self(), h_klass);
2450 // Attempt to initialize allowing initialization of parent classes but still not static
2451 // fields.
2452 manager_->GetClassLinker()->EnsureInitialized(soa.Self(), klass, false, true);
2453 if (!klass->IsInitialized()) {
2454 // We need to initialize static fields, we only do this for image classes that aren't
2455 // marked with the $NoPreloadHolder (which implies this should not be initialized early).
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002456 bool can_init_static_fields = manager_->GetCompiler()->IsBootImage() &&
Mathieu Chartier90443472015-07-16 20:32:27 -07002457 manager_->GetCompiler()->IsImageClass(descriptor) &&
2458 !StringPiece(descriptor).ends_with("$NoPreloadHolder;");
2459 if (can_init_static_fields) {
2460 VLOG(compiler) << "Initializing: " << descriptor;
2461 // TODO multithreading support. We should ensure the current compilation thread has
2462 // exclusive access to the runtime and the transaction. To achieve this, we could use
2463 // a ReaderWriterMutex but we're holding the mutator lock so we fail mutex sanity
2464 // checks in Thread::AssertThreadSuspensionIsAllowable.
2465 Runtime* const runtime = Runtime::Current();
2466 Transaction transaction;
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002467
Mathieu Chartier90443472015-07-16 20:32:27 -07002468 // Run the class initializer in transaction mode.
2469 runtime->EnterTransactionMode(&transaction);
2470 const mirror::Class::Status old_status = klass->GetStatus();
2471 bool success = manager_->GetClassLinker()->EnsureInitialized(soa.Self(), klass, true,
2472 true);
2473 // TODO we detach transaction from runtime to indicate we quit the transactional
2474 // mode which prevents the GC from visiting objects modified during the transaction.
2475 // Ensure GC is not run so don't access freed objects when aborting transaction.
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07002476
Mathieu Chartier90443472015-07-16 20:32:27 -07002477 ScopedAssertNoThreadSuspension ants(soa.Self(), "Transaction end");
2478 runtime->ExitTransactionMode();
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002479
Mathieu Chartier90443472015-07-16 20:32:27 -07002480 if (!success) {
2481 CHECK(soa.Self()->IsExceptionPending());
2482 mirror::Throwable* exception = soa.Self()->GetException();
2483 VLOG(compiler) << "Initialization of " << descriptor << " aborted because of "
2484 << exception->Dump();
2485 std::ostream* file_log = manager_->GetCompiler()->
2486 GetCompilerOptions().GetInitFailureOutput();
2487 if (file_log != nullptr) {
2488 *file_log << descriptor << "\n";
2489 *file_log << exception->Dump() << "\n";
2490 }
2491 soa.Self()->ClearException();
2492 transaction.Rollback();
2493 CHECK_EQ(old_status, klass->GetStatus()) << "Previous class status not restored";
Andreas Gampedbfe2542014-11-25 22:21:42 -08002494 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002495 }
2496 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002497 soa.Self()->AssertNoPendingException();
Brian Carlstrom7940e442013-07-12 13:46:57 -07002498 }
2499 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002500 // Record the final class status if necessary.
2501 ClassReference ref(manager_->GetDexFile(), class_def_index);
2502 manager_->GetCompiler()->RecordClassStatus(ref, klass->GetStatus());
Brian Carlstrom7940e442013-07-12 13:46:57 -07002503 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002504 // Clear any class not found or verification exceptions.
2505 soa.Self()->ClearException();
Brian Carlstrom7940e442013-07-12 13:46:57 -07002506 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002507
2508 private:
2509 const ParallelCompilationManager* const manager_;
2510};
Brian Carlstrom7940e442013-07-12 13:46:57 -07002511
Andreas Gampeace0dc12016-01-20 13:33:13 -08002512void CompilerDriver::InitializeClasses(jobject jni_class_loader,
2513 const DexFile& dex_file,
Andreas Gampede7b4362014-07-28 18:38:57 -07002514 const std::vector<const DexFile*>& dex_files,
Andreas Gampeace0dc12016-01-20 13:33:13 -08002515 TimingLogger* timings) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07002516 TimingLogger::ScopedTiming t("InitializeNoClinit", timings);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002517
2518 // Initialization allocates objects and needs to run single-threaded to be deterministic.
2519 bool force_determinism = GetCompilerOptions().IsForceDeterminism();
2520 ThreadPool* init_thread_pool = force_determinism
2521 ? single_thread_pool_.get()
2522 : parallel_thread_pool_.get();
2523 size_t init_thread_count = force_determinism ? 1U : parallel_thread_count_;
2524
Brian Carlstrom7940e442013-07-12 13:46:57 -07002525 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Andreas Gampede7b4362014-07-28 18:38:57 -07002526 ParallelCompilationManager context(class_linker, jni_class_loader, this, &dex_file, dex_files,
Andreas Gampeace0dc12016-01-20 13:33:13 -08002527 init_thread_pool);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002528 if (IsBootImage()) {
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002529 // TODO: remove this when transactional mode supports multithreading.
Andreas Gampeace0dc12016-01-20 13:33:13 -08002530 init_thread_count = 1U;
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002531 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002532 InitializeClassVisitor visitor(&context);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002533 context.ForAll(0, dex_file.NumClassDefs(), &visitor, init_thread_count);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002534}
2535
Mathieu Chartier91288d82016-04-28 09:44:54 -07002536class InitializeArrayClassesAndCreateConflictTablesVisitor : public ClassVisitor {
Mathieu Chartier085a0722016-04-01 17:33:31 -07002537 public:
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002538 virtual bool operator()(mirror::Class* klass) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier91288d82016-04-28 09:44:54 -07002539 if (Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(klass)) {
2540 return true;
2541 }
Mathieu Chartier085a0722016-04-01 17:33:31 -07002542 if (klass->IsArrayClass()) {
2543 StackHandleScope<1> hs(Thread::Current());
2544 Runtime::Current()->GetClassLinker()->EnsureInitialized(hs.Self(),
2545 hs.NewHandle(klass),
2546 true,
2547 true);
2548 }
Mathieu Chartier91288d82016-04-28 09:44:54 -07002549 // Create the conflict tables.
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00002550 FillIMTAndConflictTables(klass);
Nicolas Geoffray88f288e2016-06-29 08:17:52 +00002551 return true;
Nelli Kimbadee982016-05-13 13:08:53 +03002552 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00002553
2554 private:
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002555 void FillIMTAndConflictTables(mirror::Class* klass) REQUIRES_SHARED(Locks::mutator_lock_) {
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00002556 if (!klass->ShouldHaveImt()) {
2557 return;
2558 }
2559 if (visited_classes_.find(klass) != visited_classes_.end()) {
2560 return;
2561 }
2562 if (klass->HasSuperClass()) {
2563 FillIMTAndConflictTables(klass->GetSuperClass());
2564 }
2565 if (!klass->IsTemp()) {
2566 Runtime::Current()->GetClassLinker()->FillIMTAndConflictTables(klass);
2567 }
2568 visited_classes_.insert(klass);
2569 }
2570
2571 std::set<mirror::Class*> visited_classes_;
Mathieu Chartier085a0722016-04-01 17:33:31 -07002572};
2573
Brian Carlstrom7940e442013-07-12 13:46:57 -07002574void CompilerDriver::InitializeClasses(jobject class_loader,
2575 const std::vector<const DexFile*>& dex_files,
Andreas Gampeace0dc12016-01-20 13:33:13 -08002576 TimingLogger* timings) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07002577 for (size_t i = 0; i != dex_files.size(); ++i) {
2578 const DexFile* dex_file = dex_files[i];
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002579 CHECK(dex_file != nullptr);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002580 InitializeClasses(class_loader, *dex_file, dex_files, timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002581 }
Mathieu Chartier91288d82016-04-28 09:44:54 -07002582 if (boot_image_ || app_image_) {
Mathieu Chartier085a0722016-04-01 17:33:31 -07002583 // Make sure that we call EnsureIntiailized on all the array classes to call
2584 // SetVerificationAttempted so that the access flags are set. If we do not do this they get
2585 // changed at runtime resulting in more dirty image pages.
Mathieu Chartier91288d82016-04-28 09:44:54 -07002586 // Also create conflict tables.
2587 // Only useful if we are compiling an image (image_classes_ is not null).
Mathieu Chartier085a0722016-04-01 17:33:31 -07002588 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartier91288d82016-04-28 09:44:54 -07002589 InitializeArrayClassesAndCreateConflictTablesVisitor visitor;
2590 Runtime::Current()->GetClassLinker()->VisitClassesWithoutClassesLock(&visitor);
Mathieu Chartier085a0722016-04-01 17:33:31 -07002591 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002592 if (IsBootImage()) {
Mathieu Chartier093ef212014-08-11 13:52:12 -07002593 // Prune garbage objects created during aborted transactions.
2594 Runtime::Current()->GetHeap()->CollectGarbage(true);
2595 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002596}
2597
Andreas Gampeace0dc12016-01-20 13:33:13 -08002598void CompilerDriver::Compile(jobject class_loader,
2599 const std::vector<const DexFile*>& dex_files,
2600 TimingLogger* timings) {
Calin Juravle998c2162015-12-21 15:39:33 +02002601 if (kDebugProfileGuidedCompilation) {
2602 LOG(INFO) << "[ProfileGuidedCompilation] " <<
2603 ((profile_compilation_info_ == nullptr)
2604 ? "null"
2605 : profile_compilation_info_->DumpInfo(&dex_files));
Calin Juravle226501b2015-12-11 14:41:31 +00002606 }
Vladimir Marko492a7fa2016-06-01 18:38:43 +01002607
2608 DCHECK(current_dex_to_dex_methods_ == nullptr);
2609 for (const DexFile* dex_file : dex_files) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002610 CHECK(dex_file != nullptr);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002611 CompileDexFile(class_loader,
2612 *dex_file,
2613 dex_files,
2614 parallel_thread_pool_.get(),
2615 parallel_thread_count_,
2616 timings);
Calin Juravle69158982016-03-16 11:53:41 +00002617 const ArenaPool* const arena_pool = Runtime::Current()->GetArenaPool();
2618 const size_t arena_alloc = arena_pool->GetBytesAllocated();
2619 max_arena_alloc_ = std::max(arena_alloc, max_arena_alloc_);
Jean-Philippe Halimica76a1a2016-02-02 19:48:52 +01002620 Runtime::Current()->ReclaimArenaPoolMemory();
Brian Carlstrom7940e442013-07-12 13:46:57 -07002621 }
Vladimir Marko492a7fa2016-06-01 18:38:43 +01002622
2623 ArrayRef<DexFileMethodSet> dex_to_dex_references;
2624 {
2625 // From this point on, we shall not modify dex_to_dex_references_, so
2626 // just grab a reference to it that we use without holding the mutex.
2627 MutexLock lock(Thread::Current(), dex_to_dex_references_lock_);
2628 dex_to_dex_references = ArrayRef<DexFileMethodSet>(dex_to_dex_references_);
2629 }
2630 for (const auto& method_set : dex_to_dex_references) {
2631 current_dex_to_dex_methods_ = &method_set.GetMethodIndexes();
2632 CompileDexFile(class_loader,
2633 method_set.GetDexFile(),
2634 dex_files,
2635 parallel_thread_pool_.get(),
2636 parallel_thread_count_,
2637 timings);
2638 }
2639 current_dex_to_dex_methods_ = nullptr;
2640
Andreas Gampe8d295f82015-01-20 14:50:21 -08002641 VLOG(compiler) << "Compile: " << GetMemoryUsageString(false);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002642}
2643
Mathieu Chartier90443472015-07-16 20:32:27 -07002644class CompileClassVisitor : public CompilationVisitor {
2645 public:
2646 explicit CompileClassVisitor(const ParallelCompilationManager* manager) : manager_(manager) {}
2647
2648 virtual void Visit(size_t class_def_index) REQUIRES(!Locks::mutator_lock_) OVERRIDE {
2649 ATRACE_CALL();
2650 const DexFile& dex_file = *manager_->GetDexFile();
2651 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
2652 ClassLinker* class_linker = manager_->GetClassLinker();
2653 jobject jclass_loader = manager_->GetClassLoader();
Mathieu Chartier90443472015-07-16 20:32:27 -07002654 ClassReference ref(&dex_file, class_def_index);
2655 // Skip compiling classes with generic verifier failures since they will still fail at runtime
2656 if (manager_->GetCompiler()->verification_results_->IsClassRejected(ref)) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07002657 return;
2658 }
Mathieu Chartier736b5602015-09-02 14:54:11 -07002659 // Use a scoped object access to perform to the quick SkipClass check.
2660 const char* descriptor = dex_file.GetClassDescriptor(class_def);
2661 ScopedObjectAccess soa(Thread::Current());
2662 StackHandleScope<3> hs(soa.Self());
2663 Handle<mirror::ClassLoader> class_loader(
2664 hs.NewHandle(soa.Decode<mirror::ClassLoader*>(jclass_loader)));
2665 Handle<mirror::Class> klass(
2666 hs.NewHandle(class_linker->FindClass(soa.Self(), descriptor, class_loader)));
2667 Handle<mirror::DexCache> dex_cache;
2668 if (klass.Get() == nullptr) {
2669 soa.Self()->AssertPendingException();
2670 soa.Self()->ClearException();
2671 dex_cache = hs.NewHandle(class_linker->FindDexCache(soa.Self(), dex_file));
2672 } else if (SkipClass(jclass_loader, dex_file, klass.Get())) {
2673 return;
2674 } else {
2675 dex_cache = hs.NewHandle(klass->GetDexCache());
2676 }
2677
Mathieu Chartier90443472015-07-16 20:32:27 -07002678 const uint8_t* class_data = dex_file.GetClassData(class_def);
2679 if (class_data == nullptr) {
2680 // empty class, probably a marker interface
2681 return;
Brian Carlstrom7940e442013-07-12 13:46:57 -07002682 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002683
Mathieu Chartier736b5602015-09-02 14:54:11 -07002684 // Go to native so that we don't block GC during compilation.
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07002685 ScopedThreadSuspension sts(soa.Self(), kNative);
Mathieu Chartier736b5602015-09-02 14:54:11 -07002686
Mathieu Chartier90443472015-07-16 20:32:27 -07002687 CompilerDriver* const driver = manager_->GetCompiler();
2688
2689 // Can we run DEX-to-DEX compiler on this class ?
Andreas Gampe5eb0d382015-07-23 01:19:26 -07002690 optimizer::DexToDexCompilationLevel dex_to_dex_compilation_level =
Mathieu Chartier736b5602015-09-02 14:54:11 -07002691 GetDexToDexCompilationLevel(soa.Self(), *driver, jclass_loader, dex_file, class_def);
Andreas Gampe5eb0d382015-07-23 01:19:26 -07002692
Mathieu Chartier90443472015-07-16 20:32:27 -07002693 ClassDataItemIterator it(dex_file, class_data);
2694 // Skip fields
2695 while (it.HasNextStaticField()) {
2696 it.Next();
2697 }
2698 while (it.HasNextInstanceField()) {
2699 it.Next();
2700 }
2701
2702 bool compilation_enabled = driver->IsClassToCompile(
2703 dex_file.StringByTypeIdx(class_def.class_idx_));
2704
2705 // Compile direct methods
2706 int64_t previous_direct_method_idx = -1;
2707 while (it.HasNextDirectMethod()) {
2708 uint32_t method_idx = it.GetMemberIndex();
2709 if (method_idx == previous_direct_method_idx) {
2710 // smali can create dex files with two encoded_methods sharing the same method_idx
2711 // http://code.google.com/p/smali/issues/detail?id=119
2712 it.Next();
2713 continue;
2714 }
2715 previous_direct_method_idx = method_idx;
Mathieu Chartier736b5602015-09-02 14:54:11 -07002716 CompileMethod(soa.Self(), driver, it.GetMethodCodeItem(), it.GetMethodAccessFlags(),
Andreas Gampe5eb0d382015-07-23 01:19:26 -07002717 it.GetMethodInvokeType(class_def), class_def_index,
2718 method_idx, jclass_loader, dex_file, dex_to_dex_compilation_level,
Mathieu Chartier736b5602015-09-02 14:54:11 -07002719 compilation_enabled, dex_cache);
Mathieu Chartier90443472015-07-16 20:32:27 -07002720 it.Next();
2721 }
2722 // Compile virtual methods
2723 int64_t previous_virtual_method_idx = -1;
2724 while (it.HasNextVirtualMethod()) {
2725 uint32_t method_idx = it.GetMemberIndex();
2726 if (method_idx == previous_virtual_method_idx) {
2727 // smali can create dex files with two encoded_methods sharing the same method_idx
2728 // http://code.google.com/p/smali/issues/detail?id=119
2729 it.Next();
2730 continue;
2731 }
2732 previous_virtual_method_idx = method_idx;
Mathieu Chartier736b5602015-09-02 14:54:11 -07002733 CompileMethod(soa.Self(), driver, it.GetMethodCodeItem(), it.GetMethodAccessFlags(),
Andreas Gampe5eb0d382015-07-23 01:19:26 -07002734 it.GetMethodInvokeType(class_def), class_def_index,
2735 method_idx, jclass_loader, dex_file, dex_to_dex_compilation_level,
Mathieu Chartier736b5602015-09-02 14:54:11 -07002736 compilation_enabled, dex_cache);
Mathieu Chartier90443472015-07-16 20:32:27 -07002737 it.Next();
2738 }
2739 DCHECK(!it.HasNext());
Brian Carlstrom7940e442013-07-12 13:46:57 -07002740 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002741
2742 private:
2743 const ParallelCompilationManager* const manager_;
2744};
Brian Carlstrom7940e442013-07-12 13:46:57 -07002745
Andreas Gampeace0dc12016-01-20 13:33:13 -08002746void CompilerDriver::CompileDexFile(jobject class_loader,
2747 const DexFile& dex_file,
Andreas Gampede7b4362014-07-28 18:38:57 -07002748 const std::vector<const DexFile*>& dex_files,
Andreas Gampeace0dc12016-01-20 13:33:13 -08002749 ThreadPool* thread_pool,
2750 size_t thread_count,
2751 TimingLogger* timings) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07002752 TimingLogger::ScopedTiming t("Compile Dex File", timings);
Ian Rogersbe7149f2013-08-20 09:29:39 -07002753 ParallelCompilationManager context(Runtime::Current()->GetClassLinker(), class_loader, this,
Andreas Gampede7b4362014-07-28 18:38:57 -07002754 &dex_file, dex_files, thread_pool);
Mathieu Chartier90443472015-07-16 20:32:27 -07002755 CompileClassVisitor visitor(&context);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002756 context.ForAll(0, dex_file.NumClassDefs(), &visitor, thread_count);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002757}
2758
Andreas Gampe5eb0d382015-07-23 01:19:26 -07002759void CompilerDriver::AddCompiledMethod(const MethodReference& method_ref,
2760 CompiledMethod* const compiled_method,
2761 size_t non_relative_linker_patch_count) {
2762 DCHECK(GetCompiledMethod(method_ref) == nullptr)
2763 << PrettyMethod(method_ref.dex_method_index, *method_ref.dex_file);
2764 {
2765 MutexLock mu(Thread::Current(), compiled_methods_lock_);
2766 compiled_methods_.Put(method_ref, compiled_method);
2767 non_relative_linker_patch_count_ += non_relative_linker_patch_count;
Ian Rogersa4a3f402014-10-20 18:10:34 -07002768 }
Andreas Gampe5eb0d382015-07-23 01:19:26 -07002769 DCHECK(GetCompiledMethod(method_ref) != nullptr)
2770 << PrettyMethod(method_ref.dex_method_index, *method_ref.dex_file);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002771}
2772
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002773void CompilerDriver::RemoveCompiledMethod(const MethodReference& method_ref) {
2774 CompiledMethod* compiled_method = nullptr;
2775 {
2776 MutexLock mu(Thread::Current(), compiled_methods_lock_);
2777 auto it = compiled_methods_.find(method_ref);
2778 if (it != compiled_methods_.end()) {
2779 compiled_method = it->second;
2780 compiled_methods_.erase(it);
2781 }
2782 }
2783 if (compiled_method != nullptr) {
2784 CompiledMethod::ReleaseSwapAllocatedCompiledMethod(this, compiled_method);
2785 }
2786}
2787
Brian Carlstrom7940e442013-07-12 13:46:57 -07002788CompiledClass* CompilerDriver::GetCompiledClass(ClassReference ref) const {
2789 MutexLock mu(Thread::Current(), compiled_classes_lock_);
2790 ClassTable::const_iterator it = compiled_classes_.find(ref);
2791 if (it == compiled_classes_.end()) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002792 return nullptr;
Brian Carlstrom7940e442013-07-12 13:46:57 -07002793 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002794 CHECK(it->second != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002795 return it->second;
2796}
2797
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07002798void CompilerDriver::RecordClassStatus(ClassReference ref, mirror::Class::Status status) {
2799 MutexLock mu(Thread::Current(), compiled_classes_lock_);
2800 auto it = compiled_classes_.find(ref);
2801 if (it == compiled_classes_.end() || it->second->GetStatus() != status) {
2802 // An entry doesn't exist or the status is lower than the new status.
2803 if (it != compiled_classes_.end()) {
2804 CHECK_GT(status, it->second->GetStatus());
2805 delete it->second;
2806 }
2807 switch (status) {
2808 case mirror::Class::kStatusNotReady:
2809 case mirror::Class::kStatusError:
2810 case mirror::Class::kStatusRetryVerificationAtRuntime:
2811 case mirror::Class::kStatusVerified:
2812 case mirror::Class::kStatusInitialized:
Mathieu Chartiera8077802016-03-16 19:08:31 -07002813 case mirror::Class::kStatusResolved:
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07002814 break; // Expected states.
2815 default:
2816 LOG(FATAL) << "Unexpected class status for class "
2817 << PrettyDescriptor(ref.first->GetClassDescriptor(ref.first->GetClassDef(ref.second)))
2818 << " of " << status;
2819 }
2820 CompiledClass* compiled_class = new CompiledClass(status);
2821 compiled_classes_.Overwrite(ref, compiled_class);
2822 }
2823}
2824
Brian Carlstrom7940e442013-07-12 13:46:57 -07002825CompiledMethod* CompilerDriver::GetCompiledMethod(MethodReference ref) const {
2826 MutexLock mu(Thread::Current(), compiled_methods_lock_);
2827 MethodTable::const_iterator it = compiled_methods_.find(ref);
2828 if (it == compiled_methods_.end()) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002829 return nullptr;
Brian Carlstrom7940e442013-07-12 13:46:57 -07002830 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002831 CHECK(it->second != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002832 return it->second;
2833}
2834
Calin Juravlef1c6d9e2015-04-13 18:42:21 +01002835bool CompilerDriver::IsMethodVerifiedWithoutFailures(uint32_t method_idx,
2836 uint16_t class_def_idx,
2837 const DexFile& dex_file) const {
2838 const VerifiedMethod* verified_method = GetVerifiedMethod(&dex_file, method_idx);
2839 if (verified_method != nullptr) {
2840 return !verified_method->HasVerificationFailures();
2841 }
2842
2843 // If we can't find verification metadata, check if this is a system class (we trust that system
2844 // classes have their methods verified). If it's not, be conservative and assume the method
2845 // has not been verified successfully.
2846
2847 // TODO: When compiling the boot image it should be safe to assume that everything is verified,
2848 // even if methods are not found in the verification cache.
2849 const char* descriptor = dex_file.GetClassDescriptor(dex_file.GetClassDef(class_def_idx));
2850 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
2851 Thread* self = Thread::Current();
2852 ScopedObjectAccess soa(self);
2853 bool is_system_class = class_linker->FindSystemClass(self, descriptor) != nullptr;
2854 if (!is_system_class) {
2855 self->ClearException();
2856 }
2857 return is_system_class;
2858}
2859
Vladimir Markof4da6752014-08-01 19:04:18 +01002860size_t CompilerDriver::GetNonRelativeLinkerPatchCount() const {
2861 MutexLock mu(Thread::Current(), compiled_methods_lock_);
2862 return non_relative_linker_patch_count_;
2863}
2864
Mathieu Chartierc4ae9162016-04-07 13:19:19 -07002865void CompilerDriver::SetRequiresConstructorBarrier(Thread* self,
2866 const DexFile* dex_file,
2867 uint16_t class_def_index,
2868 bool requires) {
2869 WriterMutexLock mu(self, requires_constructor_barrier_lock_);
2870 requires_constructor_barrier_.emplace(ClassReference(dex_file, class_def_index), requires);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002871}
2872
Mathieu Chartier371bd832016-04-07 10:19:48 -07002873bool CompilerDriver::RequiresConstructorBarrier(Thread* self,
2874 const DexFile* dex_file,
Mathieu Chartierc4ae9162016-04-07 13:19:19 -07002875 uint16_t class_def_index) {
2876 ClassReference class_ref(dex_file, class_def_index);
2877 {
2878 ReaderMutexLock mu(self, requires_constructor_barrier_lock_);
2879 auto it = requires_constructor_barrier_.find(class_ref);
2880 if (it != requires_constructor_barrier_.end()) {
2881 return it->second;
2882 }
Mathieu Chartierb5d38612016-04-07 10:52:52 -07002883 }
Mathieu Chartierc4ae9162016-04-07 13:19:19 -07002884 WriterMutexLock mu(self, requires_constructor_barrier_lock_);
2885 const bool requires = RequiresConstructorBarrier(*dex_file, class_def_index);
2886 requires_constructor_barrier_.emplace(class_ref, requires);
2887 return requires;
Brian Carlstrom7940e442013-07-12 13:46:57 -07002888}
2889
Andreas Gampe8d295f82015-01-20 14:50:21 -08002890std::string CompilerDriver::GetMemoryUsageString(bool extended) const {
Mathieu Chartierab972ef2014-12-03 17:38:22 -08002891 std::ostringstream oss;
Calin Juravle69158982016-03-16 11:53:41 +00002892 const gc::Heap* const heap = Runtime::Current()->GetHeap();
Anton Kirilovdd9473b2016-01-28 15:08:01 +00002893 const size_t java_alloc = heap->GetBytesAllocated();
Calin Juravle69158982016-03-16 11:53:41 +00002894 oss << "arena alloc=" << PrettySize(max_arena_alloc_) << " (" << max_arena_alloc_ << "B)";
Anton Kirilovdd9473b2016-01-28 15:08:01 +00002895 oss << " java alloc=" << PrettySize(java_alloc) << " (" << java_alloc << "B)";
Elliott Hughes7bf5a262015-04-02 20:55:07 -07002896#if defined(__BIONIC__) || defined(__GLIBC__)
Anton Kirilovdd9473b2016-01-28 15:08:01 +00002897 const struct mallinfo info = mallinfo();
Mathieu Chartierab972ef2014-12-03 17:38:22 -08002898 const size_t allocated_space = static_cast<size_t>(info.uordblks);
2899 const size_t free_space = static_cast<size_t>(info.fordblks);
Anton Kirilovdd9473b2016-01-28 15:08:01 +00002900 oss << " native alloc=" << PrettySize(allocated_space) << " (" << allocated_space << "B)"
2901 << " free=" << PrettySize(free_space) << " (" << free_space << "B)";
Mathieu Chartierab972ef2014-12-03 17:38:22 -08002902#endif
Vladimir Marko35831e82015-09-11 11:59:18 +01002903 compiled_method_storage_.DumpMemoryUsage(oss, extended);
Mathieu Chartierab972ef2014-12-03 17:38:22 -08002904 return oss.str();
2905}
2906
Jeff Hao848f70a2014-01-15 13:49:50 -08002907bool CompilerDriver::IsStringTypeIndex(uint16_t type_index, const DexFile* dex_file) {
2908 const char* type = dex_file->GetTypeDescriptor(dex_file->GetTypeId(type_index));
2909 return strcmp(type, "Ljava/lang/String;") == 0;
2910}
2911
2912bool CompilerDriver::IsStringInit(uint32_t method_index, const DexFile* dex_file, int32_t* offset) {
2913 DexFileMethodInliner* inliner = GetMethodInlinerMap()->GetMethodInliner(dex_file);
Igor Murashkin9d4b6da2016-07-29 09:51:58 -07002914 const PointerSize pointer_size = InstructionSetPointerSize(GetInstructionSet());
Jeff Hao848f70a2014-01-15 13:49:50 -08002915 *offset = inliner->GetOffsetForStringInit(method_index, pointer_size);
2916 return inliner->IsStringInitMethodIndex(method_index);
2917}
2918
Jeff Haodcdc85b2015-12-04 14:06:18 -08002919bool CompilerDriver::MayInlineInternal(const DexFile* inlined_from,
2920 const DexFile* inlined_into) const {
2921 // We're not allowed to inline across dex files if we're the no-inline-from dex file.
2922 if (inlined_from != inlined_into &&
Vladimir Marko47496c22016-01-27 16:15:08 +00002923 compiler_options_->GetNoInlineFromDexFile() != nullptr &&
2924 ContainsElement(*compiler_options_->GetNoInlineFromDexFile(), inlined_from)) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002925 return false;
2926 }
2927
2928 return true;
2929}
2930
Andreas Gampeace0dc12016-01-20 13:33:13 -08002931void CompilerDriver::InitializeThreadPools() {
2932 size_t parallel_count = parallel_thread_count_ > 0 ? parallel_thread_count_ - 1 : 0;
2933 parallel_thread_pool_.reset(
2934 new ThreadPool("Compiler driver thread pool", parallel_count));
2935 single_thread_pool_.reset(new ThreadPool("Single-threaded Compiler driver thread pool", 0));
2936}
2937
2938void CompilerDriver::FreeThreadPools() {
2939 parallel_thread_pool_.reset();
2940 single_thread_pool_.reset();
2941}
2942
Brian Carlstrom7940e442013-07-12 13:46:57 -07002943} // namespace art