blob: 4f764209f2a2ddc4578d91a8795e9dd3c9a0d020 [file] [log] [blame]
Brian Carlstrom7940e442013-07-12 13:46:57 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "compiler_driver.h"
18
Andreas Gampeb0f370e2014-09-25 22:51:40 -070019#include <unordered_set>
Anwar Ghuloum67f99412013-08-12 14:19:48 -070020#include <vector>
Brian Carlstrom7940e442013-07-12 13:46:57 -070021#include <unistd.h>
22
Mathieu Chartierab972ef2014-12-03 17:38:22 -080023#ifndef __APPLE__
24#include <malloc.h> // For mallinfo
25#endif
26
Mathieu Chartierc7853442015-03-27 14:35:38 -070027#include "art_field-inl.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070028#include "art_method-inl.h"
David Brazdild9c90372016-09-14 16:53:55 +010029#include "base/array_ref.h"
Vladimir Marko492a7fa2016-06-01 18:38:43 +010030#include "base/bit_vector.h"
Andreas Gampe542451c2016-07-26 09:02:02 -070031#include "base/enums.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070032#include "base/stl_util.h"
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -080033#include "base/systrace.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010034#include "base/time_utils.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070035#include "base/timing_logger.h"
Vladimir Marko3481ba22015-04-13 12:22:36 +010036#include "class_linker-inl.h"
Mingyao Yang98d1cc82014-05-15 17:02:16 -070037#include "compiled_class.h"
Vladimir Marko20f85592015-03-19 10:07:02 +000038#include "compiled_method.h"
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +000039#include "compiler.h"
Vladimir Markobe0e5462014-02-26 11:24:15 +000040#include "compiler_driver-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070041#include "dex_compilation_unit.h"
42#include "dex_file-inl.h"
Andreas Gampeace0dc12016-01-20 13:33:13 -080043#include "dex_instruction-inl.h"
Andreas Gampe5eb0d382015-07-23 01:19:26 -070044#include "dex/dex_to_dex_compiler.h"
Vladimir Markoc7f83202014-01-24 17:55:18 +000045#include "dex/verification_results.h"
Vladimir Marko2730db02014-01-27 11:15:17 +000046#include "dex/verified_method.h"
Vladimir Marko2bc47802014-02-10 09:43:07 +000047#include "dex/quick/dex_file_method_inliner.h"
Jeff Hao848f70a2014-01-15 13:49:50 -080048#include "dex/quick/dex_file_to_method_inliner_map.h"
Mark Mendellae9fd932014-02-10 16:14:35 -080049#include "driver/compiler_options.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070050#include "jni_internal.h"
Ian Rogers22d5e732014-07-15 22:23:51 -070051#include "object_lock.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070052#include "runtime.h"
53#include "gc/accounting/card_table-inl.h"
54#include "gc/accounting/heap_bitmap.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070055#include "gc/space/image_space.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070056#include "gc/space/space.h"
57#include "mirror/class_loader.h"
58#include "mirror/class-inl.h"
59#include "mirror/dex_cache-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070060#include "mirror/object-inl.h"
61#include "mirror/object_array-inl.h"
62#include "mirror/throwable.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070063#include "scoped_thread_state_change-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070064#include "ScopedLocalRef.h"
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070065#include "handle_scope-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070066#include "thread.h"
Andreas Gampeb0f370e2014-09-25 22:51:40 -070067#include "thread_list.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070068#include "thread_pool.h"
Ian Rogers848871b2013-08-05 10:56:33 -070069#include "trampolines/trampoline_compiler.h"
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +010070#include "transaction.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(
Mathieu Chartier0795f232016-09-27 18:43:30 -0700538 hs.NewHandle(soa.Decode<mirror::ClassLoader>(jclass_loader)));
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700539 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) {
Igor Murashkin9aa9fa22016-09-26 10:10:17 -0700598 const InstructionSet instruction_set = driver->GetInstructionSet();
599 const bool use_generic_jni =
600 // Are we extracting only and have support for generic JNI down calls?
601 (!driver->GetCompilerOptions().IsJniCompilationEnabled() &&
602 InstructionSetHasGenericJniStub(instruction_set)) ||
603 // Always punt to generic JNI for MIPS because of no support for @CriticalNative. b/31743474
604 (instruction_set == kMips || instruction_set == kMips64);
605 if (use_generic_jni) {
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700606 // Leaving this empty will trigger the generic JNI version
607 } else {
Igor Murashkin9d4b6da2016-07-29 09:51:58 -0700608 // Look-up the ArtMethod associated with this code_item (if any)
609 // -- It is later used to lookup any [optimization] annotations for this method.
610 ScopedObjectAccess soa(self);
611 StackHandleScope<1> hs(soa.Self());
612 Handle<mirror::ClassLoader> class_loader_handle(hs.NewHandle(
Mathieu Chartier0795f232016-09-27 18:43:30 -0700613 soa.Decode<mirror::ClassLoader>(class_loader)));
Igor Murashkin9d4b6da2016-07-29 09:51:58 -0700614
615 // TODO: Lookup annotation from DexFile directly without resolving method.
616 ArtMethod* method =
617 Runtime::Current()->GetClassLinker()->ResolveMethod<ClassLinker::kNoICCECheckForCache>(
618 dex_file,
619 method_idx,
620 dex_cache,
621 class_loader_handle,
622 /* referrer */ nullptr,
623 invoke_type);
624
Igor Murashkin367f3dd2016-09-01 17:00:24 -0700625 // Query any JNI optimization annotations such as @FastNative or @CriticalNative.
626 Compiler::JniOptimizationFlags optimization_flags = Compiler::kNone;
627 if (UNLIKELY(method == nullptr)) {
Igor Murashkin9d4b6da2016-07-29 09:51:58 -0700628 // Failed method resolutions happen very rarely, e.g. ancestor class cannot be resolved.
629 DCHECK(self->IsExceptionPending());
630 self->ClearException();
Igor Murashkin367f3dd2016-09-01 17:00:24 -0700631 } else if (method->IsAnnotatedWithFastNative()) {
632 // TODO: Will no longer need this CHECK once we have verifier checking this.
633 CHECK(!method->IsAnnotatedWithCriticalNative());
634 optimization_flags = Compiler::kFastNative;
635 } else if (method->IsAnnotatedWithCriticalNative()) {
636 // TODO: Will no longer need this CHECK once we have verifier checking this.
637 CHECK(!method->IsAnnotatedWithFastNative());
638 optimization_flags = Compiler::kCriticalNative;
Igor Murashkin9d4b6da2016-07-29 09:51:58 -0700639 }
640
Igor Murashkin9d4b6da2016-07-29 09:51:58 -0700641 compiled_method = driver->GetCompiler()->JniCompile(access_flags,
642 method_idx,
643 dex_file,
644 optimization_flags);
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700645 CHECK(compiled_method != nullptr);
646 }
647 } else if ((access_flags & kAccAbstract) != 0) {
648 // Abstract methods don't have code.
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000649 } else {
Andreas Gampe0760a812015-08-26 17:12:51 -0700650 const VerifiedMethod* verified_method =
651 driver->GetVerificationResults()->GetVerifiedMethod(method_ref);
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700652 bool compile = compilation_enabled &&
653 // Basic checks, e.g., not <clinit>.
654 driver->GetVerificationResults()
655 ->IsCandidateForCompilation(method_ref, access_flags) &&
656 // Did not fail to create VerifiedMethod metadata.
Andreas Gampe0760a812015-08-26 17:12:51 -0700657 verified_method != nullptr &&
658 // Do not have failures that should punt to the interpreter.
659 !verified_method->HasRuntimeThrow() &&
660 (verified_method->GetEncounteredVerificationFailures() &
Andreas Gampea727e372015-08-25 09:22:37 -0700661 (verifier::VERIFY_ERROR_FORCE_INTERPRETER | verifier::VERIFY_ERROR_LOCKING)) == 0 &&
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700662 // Is eligable for compilation by methods-to-compile filter.
Calin Juravle226501b2015-12-11 14:41:31 +0000663 driver->IsMethodToCompile(method_ref) &&
664 driver->ShouldCompileBasedOnProfile(method_ref);
665
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700666 if (compile) {
667 // NOTE: if compiler declines to compile this method, it will return null.
668 compiled_method = driver->GetCompiler()->Compile(code_item, access_flags, invoke_type,
669 class_def_idx, method_idx, class_loader,
Mathieu Chartier736b5602015-09-02 14:54:11 -0700670 dex_file, dex_cache);
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700671 }
672 if (compiled_method == nullptr &&
673 dex_to_dex_compilation_level != optimizer::DexToDexCompilationLevel::kDontDexToDexCompile) {
Vladimir Marko492a7fa2016-06-01 18:38:43 +0100674 DCHECK(!Runtime::Current()->UseJitCompilation());
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700675 // TODO: add a command-line option to disable DEX-to-DEX compilation ?
Vladimir Marko492a7fa2016-06-01 18:38:43 +0100676 driver->MarkForDexToDexCompilation(self, method_ref);
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700677 }
678 }
679 if (kTimeCompileMethod) {
680 uint64_t duration_ns = NanoTime() - start_ns;
681 if (duration_ns > MsToNs(driver->GetCompiler()->GetMaximumCompilationTimeBeforeWarning())) {
682 LOG(WARNING) << "Compilation of " << PrettyMethod(method_idx, dex_file)
683 << " took " << PrettyDuration(duration_ns);
684 }
685 }
686
687 if (compiled_method != nullptr) {
688 // Count non-relative linker patches.
689 size_t non_relative_linker_patch_count = 0u;
690 for (const LinkerPatch& patch : compiled_method->GetPatches()) {
691 if (!patch.IsPcRelative()) {
692 ++non_relative_linker_patch_count;
693 }
694 }
695 bool compile_pic = driver->GetCompilerOptions().GetCompilePic(); // Off by default
696 // When compiling with PIC, there should be zero non-relative linker patches
697 CHECK(!compile_pic || non_relative_linker_patch_count == 0u);
698
699 driver->AddCompiledMethod(method_ref, compiled_method, non_relative_linker_patch_count);
700 }
701
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700702 if (self->IsExceptionPending()) {
703 ScopedObjectAccess soa(self);
704 LOG(FATAL) << "Unexpected exception compiling: " << PrettyMethod(method_idx, dex_file) << "\n"
705 << self->GetException()->Dump();
Sebastien Hertz75021222013-07-16 18:34:50 +0200706 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700707}
708
Mathieu Chartiere401d142015-04-22 13:56:20 -0700709void CompilerDriver::CompileOne(Thread* self, ArtMethod* method, TimingLogger* timings) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700710 DCHECK(!Runtime::Current()->IsStarted());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700711 jobject jclass_loader;
712 const DexFile* dex_file;
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700713 uint16_t class_def_idx;
Ian Rogersef7d42f2014-01-06 12:55:46 -0800714 uint32_t method_idx = method->GetDexMethodIndex();
715 uint32_t access_flags = method->GetAccessFlags();
716 InvokeType invoke_type = method->GetInvokeType();
Mathieu Chartier736b5602015-09-02 14:54:11 -0700717 StackHandleScope<1> hs(self);
718 Handle<mirror::DexCache> dex_cache(hs.NewHandle(method->GetDexCache()));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700719 {
720 ScopedObjectAccessUnchecked soa(self);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800721 ScopedLocalRef<jobject> local_class_loader(
722 soa.Env(), soa.AddLocalReference<jobject>(method->GetDeclaringClass()->GetClassLoader()));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700723 jclass_loader = soa.Env()->NewGlobalRef(local_class_loader.get());
724 // Find the dex_file
Mathieu Chartierbfd9a432014-05-21 17:43:44 -0700725 dex_file = method->GetDexFile();
726 class_def_idx = method->GetClassDefIndex();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700727 }
Ian Rogersef7d42f2014-01-06 12:55:46 -0800728 const DexFile::CodeItem* code_item = dex_file->GetCodeItem(method->GetCodeItemOffset());
Mathieu Chartier736b5602015-09-02 14:54:11 -0700729
730 // Go to native so that we don't block GC during compilation.
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700731 ScopedThreadSuspension sts(self, kNative);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700732
733 std::vector<const DexFile*> dex_files;
734 dex_files.push_back(dex_file);
735
Andreas Gampeace0dc12016-01-20 13:33:13 -0800736 InitializeThreadPools();
737
738 PreCompile(jclass_loader, dex_files, timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700739
Brian Carlstrom7940e442013-07-12 13:46:57 -0700740 // Can we run DEX-to-DEX compiler on this class ?
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700741 optimizer::DexToDexCompilationLevel dex_to_dex_compilation_level =
742 GetDexToDexCompilationLevel(self,
743 *this,
744 jclass_loader,
745 *dex_file,
746 dex_file->GetClassDef(class_def_idx));
747
Vladimir Marko492a7fa2016-06-01 18:38:43 +0100748 DCHECK(current_dex_to_dex_methods_ == nullptr);
Andreas Gampe5eb0d382015-07-23 01:19:26 -0700749 CompileMethod(self,
750 this,
751 code_item,
752 access_flags,
753 invoke_type,
754 class_def_idx,
755 method_idx,
756 jclass_loader,
757 *dex_file,
758 dex_to_dex_compilation_level,
Mathieu Chartier736b5602015-09-02 14:54:11 -0700759 true,
760 dex_cache);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700761
Vladimir Marko492a7fa2016-06-01 18:38:43 +0100762 ArrayRef<DexFileMethodSet> dex_to_dex_references;
763 {
764 // From this point on, we shall not modify dex_to_dex_references_, so
765 // just grab a reference to it that we use without holding the mutex.
766 MutexLock lock(Thread::Current(), dex_to_dex_references_lock_);
767 dex_to_dex_references = ArrayRef<DexFileMethodSet>(dex_to_dex_references_);
768 }
769 if (!dex_to_dex_references.empty()) {
770 DCHECK_EQ(dex_to_dex_references.size(), 1u);
771 DCHECK(&dex_to_dex_references[0].GetDexFile() == dex_file);
772 current_dex_to_dex_methods_ = &dex_to_dex_references.front().GetMethodIndexes();
773 DCHECK(current_dex_to_dex_methods_->IsBitSet(method_idx));
774 DCHECK_EQ(current_dex_to_dex_methods_->NumSetBits(), 1u);
775 CompileMethod(self,
776 this,
777 code_item,
778 access_flags,
779 invoke_type,
780 class_def_idx,
781 method_idx,
782 jclass_loader,
783 *dex_file,
784 dex_to_dex_compilation_level,
785 true,
786 dex_cache);
787 current_dex_to_dex_methods_ = nullptr;
788 }
789
Andreas Gampeace0dc12016-01-20 13:33:13 -0800790 FreeThreadPools();
791
Brian Carlstrom7940e442013-07-12 13:46:57 -0700792 self->GetJniEnv()->DeleteGlobalRef(jclass_loader);
Mathieu Chartier2535abe2015-02-17 10:38:49 -0800793}
794
Andreas Gampeace0dc12016-01-20 13:33:13 -0800795void CompilerDriver::Resolve(jobject class_loader,
796 const std::vector<const DexFile*>& dex_files,
797 TimingLogger* timings) {
798 // Resolution allocates classes and needs to run single-threaded to be deterministic.
799 bool force_determinism = GetCompilerOptions().IsForceDeterminism();
800 ThreadPool* resolve_thread_pool = force_determinism
801 ? single_thread_pool_.get()
802 : parallel_thread_pool_.get();
803 size_t resolve_thread_count = force_determinism ? 1U : parallel_thread_count_;
804
Brian Carlstrom7940e442013-07-12 13:46:57 -0700805 for (size_t i = 0; i != dex_files.size(); ++i) {
806 const DexFile* dex_file = dex_files[i];
Kenny Rootd5185342014-05-13 14:47:05 -0700807 CHECK(dex_file != nullptr);
Andreas Gampeace0dc12016-01-20 13:33:13 -0800808 ResolveDexFile(class_loader,
809 *dex_file,
810 dex_files,
811 resolve_thread_pool,
812 resolve_thread_count,
813 timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700814 }
815}
816
Andreas Gampeace0dc12016-01-20 13:33:13 -0800817// Resolve const-strings in the code. Done to have deterministic allocation behavior. Right now
818// this is single-threaded for simplicity.
819// TODO: Collect the relevant string indices in parallel, then allocate them sequentially in a
820// stable order.
821
822static void ResolveConstStrings(CompilerDriver* driver,
823 const DexFile& dex_file,
824 const DexFile::CodeItem* code_item) {
825 if (code_item == nullptr) {
826 // Abstract or native method.
827 return;
828 }
829
830 const uint16_t* code_ptr = code_item->insns_;
831 const uint16_t* code_end = code_item->insns_ + code_item->insns_size_in_code_units_;
832
833 while (code_ptr < code_end) {
834 const Instruction* inst = Instruction::At(code_ptr);
835 switch (inst->Opcode()) {
836 case Instruction::CONST_STRING: {
837 uint32_t string_index = inst->VRegB_21c();
838 driver->CanAssumeStringIsPresentInDexCache(dex_file, string_index);
839 break;
840 }
841 case Instruction::CONST_STRING_JUMBO: {
842 uint32_t string_index = inst->VRegB_31c();
843 driver->CanAssumeStringIsPresentInDexCache(dex_file, string_index);
844 break;
845 }
846
847 default:
848 break;
849 }
850
851 code_ptr += inst->SizeInCodeUnits();
852 }
853}
854
855static void ResolveConstStrings(CompilerDriver* driver,
856 const std::vector<const DexFile*>& dex_files,
857 TimingLogger* timings) {
858 for (const DexFile* dex_file : dex_files) {
859 TimingLogger::ScopedTiming t("Resolve const-string Strings", timings);
860
861 size_t class_def_count = dex_file->NumClassDefs();
862 for (size_t class_def_index = 0; class_def_index < class_def_count; ++class_def_index) {
863 const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_index);
864
865 const uint8_t* class_data = dex_file->GetClassData(class_def);
866 if (class_data == nullptr) {
867 // empty class, probably a marker interface
868 continue;
869 }
870
871 ClassDataItemIterator it(*dex_file, class_data);
872 // Skip fields
873 while (it.HasNextStaticField()) {
874 it.Next();
875 }
876 while (it.HasNextInstanceField()) {
877 it.Next();
878 }
879
880 bool compilation_enabled = driver->IsClassToCompile(
881 dex_file->StringByTypeIdx(class_def.class_idx_));
882 if (!compilation_enabled) {
883 // Compilation is skipped, do not resolve const-string in code of this class.
884 // TODO: Make sure that inlining honors this.
885 continue;
886 }
887
888 // Direct methods.
889 int64_t previous_direct_method_idx = -1;
890 while (it.HasNextDirectMethod()) {
891 uint32_t method_idx = it.GetMemberIndex();
892 if (method_idx == previous_direct_method_idx) {
893 // smali can create dex files with two encoded_methods sharing the same method_idx
894 // http://code.google.com/p/smali/issues/detail?id=119
895 it.Next();
896 continue;
897 }
898 previous_direct_method_idx = method_idx;
899 ResolveConstStrings(driver, *dex_file, it.GetMethodCodeItem());
900 it.Next();
901 }
902 // Virtual methods.
903 int64_t previous_virtual_method_idx = -1;
904 while (it.HasNextVirtualMethod()) {
905 uint32_t method_idx = it.GetMemberIndex();
906 if (method_idx == previous_virtual_method_idx) {
907 // smali can create dex files with two encoded_methods sharing the same method_idx
908 // http://code.google.com/p/smali/issues/detail?id=119
909 it.Next();
910 continue;
911 }
912 previous_virtual_method_idx = method_idx;
913 ResolveConstStrings(driver, *dex_file, it.GetMethodCodeItem());
914 it.Next();
915 }
916 DCHECK(!it.HasNext());
917 }
918 }
919}
920
921inline void CompilerDriver::CheckThreadPools() {
922 DCHECK(parallel_thread_pool_ != nullptr);
923 DCHECK(single_thread_pool_ != nullptr);
924}
925
926void CompilerDriver::PreCompile(jobject class_loader,
927 const std::vector<const DexFile*>& dex_files,
928 TimingLogger* timings) {
929 CheckThreadPools();
930
Brian Carlstrom7940e442013-07-12 13:46:57 -0700931 LoadImageClasses(timings);
Andreas Gampe8d295f82015-01-20 14:50:21 -0800932 VLOG(compiler) << "LoadImageClasses: " << GetMemoryUsageString(false);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700933
Mathieu Chartiere86deef2015-03-19 13:43:37 -0700934 const bool verification_enabled = compiler_options_->IsVerificationEnabled();
935 const bool never_verify = compiler_options_->NeverVerify();
Mathieu Chartiera8077802016-03-16 19:08:31 -0700936 const bool verify_only_profile = compiler_options_->VerifyOnlyProfile();
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700937
Mathieu Chartiere86deef2015-03-19 13:43:37 -0700938 // We need to resolve for never_verify since it needs to run dex to dex to add the
939 // RETURN_VOID_NO_BARRIER.
Mathieu Chartiera8077802016-03-16 19:08:31 -0700940 // Let the verifier resolve as needed for the verify_only_profile case.
941 if ((never_verify || verification_enabled) && !verify_only_profile) {
Andreas Gampeace0dc12016-01-20 13:33:13 -0800942 Resolve(class_loader, dex_files, timings);
Mathieu Chartiere86deef2015-03-19 13:43:37 -0700943 VLOG(compiler) << "Resolve: " << GetMemoryUsageString(false);
944 }
945
946 if (never_verify) {
Mathieu Chartierab972ef2014-12-03 17:38:22 -0800947 VLOG(compiler) << "Verify none mode specified, skipping verification.";
Andreas Gampeace0dc12016-01-20 13:33:13 -0800948 SetVerified(class_loader, dex_files, timings);
Mathieu Chartiere86deef2015-03-19 13:43:37 -0700949 }
950
951 if (!verification_enabled) {
Jeff Hao4a200f52014-04-01 14:58:49 -0700952 return;
953 }
954
Andreas Gampeace0dc12016-01-20 13:33:13 -0800955 if (GetCompilerOptions().IsForceDeterminism() && IsBootImage()) {
956 // Resolve strings from const-string. Do this now to have a deterministic image.
957 ResolveConstStrings(this, dex_files, timings);
958 VLOG(compiler) << "Resolve const-strings: " << GetMemoryUsageString(false);
959 }
960
961 Verify(class_loader, dex_files, timings);
Andreas Gampe8d295f82015-01-20 14:50:21 -0800962 VLOG(compiler) << "Verify: " << GetMemoryUsageString(false);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700963
Andreas Gampe6cf49e52015-03-05 13:08:45 -0800964 if (had_hard_verifier_failure_ && GetCompilerOptions().AbortOnHardVerifierFailure()) {
965 LOG(FATAL) << "Had a hard failure verifying all classes, and was asked to abort in such "
966 << "situations. Please check the log.";
967 }
968
Andreas Gampeace0dc12016-01-20 13:33:13 -0800969 InitializeClasses(class_loader, dex_files, timings);
Andreas Gampe8d295f82015-01-20 14:50:21 -0800970 VLOG(compiler) << "InitializeClasses: " << GetMemoryUsageString(false);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700971
972 UpdateImageClasses(timings);
Andreas Gampe8d295f82015-01-20 14:50:21 -0800973 VLOG(compiler) << "UpdateImageClasses: " << GetMemoryUsageString(false);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700974}
975
Ian Rogersdfb325e2013-10-30 01:00:44 -0700976bool CompilerDriver::IsImageClass(const char* descriptor) const {
Mathieu Chartierc5dd3192015-12-09 16:38:30 -0800977 if (image_classes_ != nullptr) {
978 // If we have a set of image classes, use those.
Ian Rogersdfb325e2013-10-30 01:00:44 -0700979 return image_classes_->find(descriptor) != image_classes_->end();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700980 }
Mathieu Chartierc5dd3192015-12-09 16:38:30 -0800981 // No set of image classes, assume we include all the classes.
982 // NOTE: Currently only reachable from InitImageMethodVisitor for the app image case.
983 return !IsBootImage();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700984}
985
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800986bool CompilerDriver::IsClassToCompile(const char* descriptor) const {
Andreas Gampeb1fcead2015-04-20 18:53:51 -0700987 if (classes_to_compile_ == nullptr) {
988 return true;
989 }
990 return classes_to_compile_->find(descriptor) != classes_to_compile_->end();
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800991}
992
Andreas Gampe70bef0d2015-04-15 02:37:28 -0700993bool CompilerDriver::IsMethodToCompile(const MethodReference& method_ref) const {
Andreas Gampe70bef0d2015-04-15 02:37:28 -0700994 if (methods_to_compile_ == nullptr) {
995 return true;
996 }
997
998 std::string tmp = PrettyMethod(method_ref.dex_method_index, *method_ref.dex_file, true);
999 return methods_to_compile_->find(tmp.c_str()) != methods_to_compile_->end();
1000}
1001
Calin Juravle226501b2015-12-11 14:41:31 +00001002bool CompilerDriver::ShouldCompileBasedOnProfile(const MethodReference& method_ref) const {
1003 if (profile_compilation_info_ == nullptr) {
1004 // If we miss profile information it means that we don't do a profile guided compilation.
1005 // Return true, and let the other filters decide if the method should be compiled.
1006 return true;
1007 }
1008 bool result = profile_compilation_info_->ContainsMethod(method_ref);
1009
1010 if (kDebugProfileGuidedCompilation) {
1011 LOG(INFO) << "[ProfileGuidedCompilation] "
1012 << (result ? "Compiled" : "Skipped") << " method:"
1013 << PrettyMethod(method_ref.dex_method_index, *method_ref.dex_file, true);
1014 }
1015 return result;
1016}
1017
Mathieu Chartiera8077802016-03-16 19:08:31 -07001018bool CompilerDriver::ShouldVerifyClassBasedOnProfile(const DexFile& dex_file,
1019 uint16_t class_idx) const {
1020 if (!compiler_options_->VerifyOnlyProfile()) {
1021 // No profile, verify everything.
1022 return true;
1023 }
1024 DCHECK(profile_compilation_info_ != nullptr);
1025 bool result = profile_compilation_info_->ContainsClass(dex_file, class_idx);
1026 if (kDebugProfileGuidedCompilation) {
1027 LOG(INFO) << "[ProfileGuidedCompilation] "
1028 << (result ? "Verified" : "Skipped") << " method:"
1029 << dex_file.GetClassDescriptor(dex_file.GetClassDef(class_idx));
1030 }
1031 return result;
1032}
1033
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001034class ResolveCatchBlockExceptionsClassVisitor : public ClassVisitor {
1035 public:
Chih-Hung Hsieh471118e2016-04-29 14:27:41 -07001036 explicit ResolveCatchBlockExceptionsClassVisitor(
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001037 std::set<std::pair<uint16_t, const DexFile*>>& exceptions_to_resolve)
1038 : exceptions_to_resolve_(exceptions_to_resolve) {}
1039
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001040 virtual bool operator()(mirror::Class* c) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere4275c02015-08-06 15:34:15 -07001041 const auto pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
Alex Lighte64300b2015-12-15 15:02:47 -08001042 for (auto& m : c->GetMethods(pointer_size)) {
Vladimir Marko05792b92015-08-03 11:56:49 +01001043 ResolveExceptionsForMethod(&m, pointer_size);
Mathieu Chartiere4275c02015-08-06 15:34:15 -07001044 }
1045 return true;
1046 }
1047
1048 private:
Andreas Gampe542451c2016-07-26 09:02:02 -07001049 void ResolveExceptionsForMethod(ArtMethod* method_handle, PointerSize pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001050 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001051 const DexFile::CodeItem* code_item = method_handle->GetCodeItem();
1052 if (code_item == nullptr) {
1053 return; // native or abstract method
Brian Carlstrom7940e442013-07-12 13:46:57 -07001054 }
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001055 if (code_item->tries_size_ == 0) {
1056 return; // nothing to process
1057 }
1058 const uint8_t* encoded_catch_handler_list = DexFile::GetCatchHandlerData(*code_item, 0);
1059 size_t num_encoded_catch_handlers = DecodeUnsignedLeb128(&encoded_catch_handler_list);
1060 for (size_t i = 0; i < num_encoded_catch_handlers; i++) {
1061 int32_t encoded_catch_handler_size = DecodeSignedLeb128(&encoded_catch_handler_list);
1062 bool has_catch_all = false;
1063 if (encoded_catch_handler_size <= 0) {
1064 encoded_catch_handler_size = -encoded_catch_handler_size;
1065 has_catch_all = true;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001066 }
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001067 for (int32_t j = 0; j < encoded_catch_handler_size; j++) {
1068 uint16_t encoded_catch_handler_handlers_type_idx =
1069 DecodeUnsignedLeb128(&encoded_catch_handler_list);
1070 // Add to set of types to resolve if not already in the dex cache resolved types
Vladimir Marko05792b92015-08-03 11:56:49 +01001071 if (!method_handle->IsResolvedTypeIdx(encoded_catch_handler_handlers_type_idx,
1072 pointer_size)) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001073 exceptions_to_resolve_.emplace(encoded_catch_handler_handlers_type_idx,
1074 method_handle->GetDexFile());
1075 }
1076 // ignore address associated with catch handler
1077 DecodeUnsignedLeb128(&encoded_catch_handler_list);
1078 }
1079 if (has_catch_all) {
1080 // ignore catch all address
1081 DecodeUnsignedLeb128(&encoded_catch_handler_list);
1082 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001083 }
1084 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001085
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001086 std::set<std::pair<uint16_t, const DexFile*>>& exceptions_to_resolve_;
1087};
1088
1089class RecordImageClassesVisitor : public ClassVisitor {
1090 public:
1091 explicit RecordImageClassesVisitor(std::unordered_set<std::string>* image_classes)
1092 : image_classes_(image_classes) {}
1093
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001094 bool operator()(mirror::Class* klass) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001095 std::string temp;
1096 image_classes_->insert(klass->GetDescriptor(&temp));
1097 return true;
1098 }
1099
1100 private:
1101 std::unordered_set<std::string>* const image_classes_;
1102};
Brian Carlstrom7940e442013-07-12 13:46:57 -07001103
1104// Make a list of descriptors for classes to include in the image
Mathieu Chartier90443472015-07-16 20:32:27 -07001105void CompilerDriver::LoadImageClasses(TimingLogger* timings) {
Kenny Rootd5185342014-05-13 14:47:05 -07001106 CHECK(timings != nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001107 if (!IsBootImage()) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001108 return;
1109 }
1110
Mathieu Chartierf5997b42014-06-20 10:37:54 -07001111 TimingLogger::ScopedTiming t("LoadImageClasses", timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001112 // Make a first class to load all classes explicitly listed in the file
1113 Thread* self = Thread::Current();
1114 ScopedObjectAccess soa(self);
1115 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Kenny Rootd5185342014-05-13 14:47:05 -07001116 CHECK(image_classes_.get() != nullptr);
Mathieu Chartier02e25112013-08-14 16:14:24 -07001117 for (auto it = image_classes_->begin(), end = image_classes_->end(); it != end;) {
Vladimir Markoe9c36b32013-11-21 15:49:16 +00001118 const std::string& descriptor(*it);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001119 StackHandleScope<1> hs(self);
1120 Handle<mirror::Class> klass(
1121 hs.NewHandle(class_linker->FindSystemClass(self, descriptor.c_str())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001122 if (klass.Get() == nullptr) {
Ian Rogerse6bb3b22013-08-19 21:51:45 -07001123 VLOG(compiler) << "Failed to find class " << descriptor;
Vladimir Markoe9c36b32013-11-21 15:49:16 +00001124 image_classes_->erase(it++);
Ian Rogersa436fde2013-08-27 23:34:06 -07001125 self->ClearException();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001126 } else {
1127 ++it;
1128 }
1129 }
1130
1131 // Resolve exception classes referenced by the loaded classes. The catch logic assumes
1132 // exceptions are resolved by the verifier when there is a catch block in an interested method.
1133 // Do this here so that exception classes appear to have been specified image classes.
Ian Rogers700a4022014-05-19 16:49:03 -07001134 std::set<std::pair<uint16_t, const DexFile*>> unresolved_exception_types;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001135 StackHandleScope<1> hs(self);
1136 Handle<mirror::Class> java_lang_Throwable(
1137 hs.NewHandle(class_linker->FindSystemClass(self, "Ljava/lang/Throwable;")));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001138 do {
1139 unresolved_exception_types.clear();
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001140 ResolveCatchBlockExceptionsClassVisitor visitor(unresolved_exception_types);
1141 class_linker->VisitClasses(&visitor);
Mathieu Chartier02e25112013-08-14 16:14:24 -07001142 for (const std::pair<uint16_t, const DexFile*>& exception_type : unresolved_exception_types) {
1143 uint16_t exception_type_idx = exception_type.first;
1144 const DexFile* dex_file = exception_type.second;
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001145 StackHandleScope<2> hs2(self);
Mathieu Chartierf284d442016-06-02 11:48:30 -07001146 Handle<mirror::DexCache> dex_cache(hs2.NewHandle(class_linker->RegisterDexFile(*dex_file,
1147 nullptr)));
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001148 Handle<mirror::Class> klass(hs2.NewHandle(
Mathieu Chartier9865bde2015-12-21 09:58:16 -08001149 class_linker->ResolveType(*dex_file,
1150 exception_type_idx,
1151 dex_cache,
1152 ScopedNullHandle<mirror::ClassLoader>())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001153 if (klass.Get() == nullptr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001154 const DexFile::TypeId& type_id = dex_file->GetTypeId(exception_type_idx);
1155 const char* descriptor = dex_file->GetTypeDescriptor(type_id);
1156 LOG(FATAL) << "Failed to resolve class " << descriptor;
1157 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001158 DCHECK(java_lang_Throwable->IsAssignableFrom(klass.Get()));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001159 }
1160 // Resolving exceptions may load classes that reference more exceptions, iterate until no
1161 // more are found
1162 } while (!unresolved_exception_types.empty());
1163
1164 // We walk the roots looking for classes so that we'll pick up the
1165 // above classes plus any classes them depend on such super
1166 // classes, interfaces, and the required ClassLinker roots.
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001167 RecordImageClassesVisitor visitor(image_classes_.get());
1168 class_linker->VisitClasses(&visitor);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001169
1170 CHECK_NE(image_classes_->size(), 0U);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001171}
1172
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001173static void MaybeAddToImageClasses(Handle<mirror::Class> c,
1174 std::unordered_set<std::string>* image_classes)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001175 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07001176 Thread* self = Thread::Current();
1177 StackHandleScope<1> hs(self);
1178 // Make a copy of the handle so that we don't clobber it doing Assign.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07001179 MutableHandle<mirror::Class> klass(hs.NewHandle(c.Get()));
Ian Rogers1ff3c982014-08-12 02:30:58 -07001180 std::string temp;
Andreas Gampe542451c2016-07-26 09:02:02 -07001181 const PointerSize pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001182 while (!klass->IsObjectClass()) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07001183 const char* descriptor = klass->GetDescriptor(&temp);
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001184 std::pair<std::unordered_set<std::string>::iterator, bool> result =
1185 image_classes->insert(descriptor);
Ian Rogers1ff3c982014-08-12 02:30:58 -07001186 if (!result.second) { // Previously inserted.
1187 break;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001188 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07001189 VLOG(compiler) << "Adding " << descriptor << " to image classes";
Mathieu Chartierf8322842014-05-16 10:59:25 -07001190 for (size_t i = 0; i < klass->NumDirectInterfaces(); ++i) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001191 StackHandleScope<1> hs2(self);
1192 MaybeAddToImageClasses(hs2.NewHandle(mirror::Class::GetDirectInterface(self, klass, i)),
Mathieu Chartierf8322842014-05-16 10:59:25 -07001193 image_classes);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001194 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001195 for (auto& m : c->GetVirtualMethods(pointer_size)) {
Alex Light36121492016-02-22 13:43:29 -08001196 StackHandleScope<1> hs2(self);
1197 MaybeAddToImageClasses(hs2.NewHandle(m.GetDeclaringClass()), image_classes);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001198 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001199 if (klass->IsArrayClass()) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001200 StackHandleScope<1> hs2(self);
1201 MaybeAddToImageClasses(hs2.NewHandle(klass->GetComponentType()), image_classes);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001202 }
Mathieu Chartierf8322842014-05-16 10:59:25 -07001203 klass.Assign(klass->GetSuperClass());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001204 }
1205}
1206
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001207// Keeps all the data for the update together. Also doubles as the reference visitor.
1208// Note: we can use object pointers because we suspend all threads.
1209class ClinitImageUpdate {
1210 public:
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001211 static ClinitImageUpdate* Create(std::unordered_set<std::string>* image_class_descriptors,
1212 Thread* self, ClassLinker* linker, std::string* error_msg) {
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001213 std::unique_ptr<ClinitImageUpdate> res(new ClinitImageUpdate(image_class_descriptors, self,
1214 linker));
Mathieu Chartiere401d142015-04-22 13:56:20 -07001215 if (res->dex_cache_class_ == nullptr) {
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001216 *error_msg = "Could not find DexCache class.";
1217 return nullptr;
1218 }
1219
1220 return res.release();
1221 }
1222
1223 ~ClinitImageUpdate() {
1224 // Allow others to suspend again.
1225 self_->EndAssertNoThreadSuspension(old_cause_);
1226 }
1227
1228 // Visitor for VisitReferences.
1229 void operator()(mirror::Object* object, MemberOffset field_offset, bool /* is_static */) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001230 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001231 mirror::Object* ref = object->GetFieldObject<mirror::Object>(field_offset);
1232 if (ref != nullptr) {
1233 VisitClinitClassesObject(ref);
1234 }
1235 }
1236
1237 // java.lang.Reference visitor for VisitReferences.
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001238 void operator()(mirror::Class* klass ATTRIBUTE_UNUSED, mirror::Reference* ref ATTRIBUTE_UNUSED)
1239 const {}
1240
1241 // Ignore class native roots.
1242 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED)
1243 const {}
1244 void VisitRoot(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED) const {}
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001245
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001246 void Walk() REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001247 // Use the initial classes as roots for a search.
1248 for (mirror::Class* klass_root : image_classes_) {
1249 VisitClinitClassesObject(klass_root);
1250 }
1251 }
1252
1253 private:
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001254 class FindImageClassesVisitor : public ClassVisitor {
1255 public:
1256 explicit FindImageClassesVisitor(ClinitImageUpdate* data) : data_(data) {}
1257
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001258 bool operator()(mirror::Class* klass) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001259 std::string temp;
1260 const char* name = klass->GetDescriptor(&temp);
1261 if (data_->image_class_descriptors_->find(name) != data_->image_class_descriptors_->end()) {
1262 data_->image_classes_.push_back(klass);
1263 } else {
1264 // Check whether it is initialized and has a clinit. They must be kept, too.
1265 if (klass->IsInitialized() && klass->FindClassInitializer(
1266 Runtime::Current()->GetClassLinker()->GetImagePointerSize()) != nullptr) {
1267 data_->image_classes_.push_back(klass);
1268 }
1269 }
1270 return true;
1271 }
1272
1273 private:
1274 ClinitImageUpdate* const data_;
1275 };
1276
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001277 ClinitImageUpdate(std::unordered_set<std::string>* image_class_descriptors, Thread* self,
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001278 ClassLinker* linker)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001279 REQUIRES_SHARED(Locks::mutator_lock_) :
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001280 image_class_descriptors_(image_class_descriptors), self_(self) {
1281 CHECK(linker != nullptr);
1282 CHECK(image_class_descriptors != nullptr);
1283
1284 // Make sure nobody interferes with us.
1285 old_cause_ = self->StartAssertNoThreadSuspension("Boot image closure");
1286
1287 // Find the interesting classes.
Andreas Gampedc8b63c2014-12-02 14:39:52 -08001288 dex_cache_class_ = linker->LookupClass(self, "Ljava/lang/DexCache;",
1289 ComputeModifiedUtf8Hash("Ljava/lang/DexCache;"), nullptr);
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001290
1291 // Find all the already-marked classes.
1292 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001293 FindImageClassesVisitor visitor(this);
1294 linker->VisitClasses(&visitor);
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001295 }
1296
1297 void VisitClinitClassesObject(mirror::Object* object) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001298 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001299 DCHECK(object != nullptr);
1300 if (marked_objects_.find(object) != marked_objects_.end()) {
1301 // Already processed.
1302 return;
1303 }
1304
1305 // Mark it.
1306 marked_objects_.insert(object);
1307
1308 if (object->IsClass()) {
1309 // If it is a class, add it.
1310 StackHandleScope<1> hs(self_);
1311 MaybeAddToImageClasses(hs.NewHandle(object->AsClass()), image_class_descriptors_);
1312 } else {
1313 // Else visit the object's class.
1314 VisitClinitClassesObject(object->GetClass());
1315 }
1316
Mathieu Chartiere401d142015-04-22 13:56:20 -07001317 // If it is not a DexCache, visit all references.
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001318 mirror::Class* klass = object->GetClass();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001319 if (klass != dex_cache_class_) {
Mathieu Chartier059ef3d2015-08-18 13:54:21 -07001320 object->VisitReferences(*this, *this);
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001321 }
1322 }
1323
1324 mutable std::unordered_set<mirror::Object*> marked_objects_;
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001325 std::unordered_set<std::string>* const image_class_descriptors_;
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001326 std::vector<mirror::Class*> image_classes_;
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001327 const mirror::Class* dex_cache_class_;
1328 Thread* const self_;
1329 const char* old_cause_;
1330
1331 DISALLOW_COPY_AND_ASSIGN(ClinitImageUpdate);
1332};
Brian Carlstrom7940e442013-07-12 13:46:57 -07001333
Ian Rogers3d504072014-03-01 09:16:49 -08001334void CompilerDriver::UpdateImageClasses(TimingLogger* timings) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001335 if (IsBootImage()) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07001336 TimingLogger::ScopedTiming t("UpdateImageClasses", timings);
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001337
Mathieu Chartier4f55e222015-09-04 13:26:21 -07001338 Runtime* runtime = Runtime::Current();
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001339
1340 // Suspend all threads.
Mathieu Chartier4f55e222015-09-04 13:26:21 -07001341 ScopedSuspendAll ssa(__FUNCTION__);
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001342
1343 std::string error_msg;
1344 std::unique_ptr<ClinitImageUpdate> update(ClinitImageUpdate::Create(image_classes_.get(),
1345 Thread::Current(),
Mathieu Chartier4f55e222015-09-04 13:26:21 -07001346 runtime->GetClassLinker(),
Andreas Gampeb0f370e2014-09-25 22:51:40 -07001347 &error_msg));
1348 CHECK(update.get() != nullptr) << error_msg; // TODO: Soft failure?
1349
1350 // Do the marking.
1351 update->Walk();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001352 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001353}
1354
Vladimir Marko07785bb2015-06-15 18:52:54 +01001355bool CompilerDriver::CanAssumeClassIsLoaded(mirror::Class* klass) {
1356 Runtime* runtime = Runtime::Current();
1357 if (!runtime->IsAotCompiler()) {
Calin Juravleffc87072016-04-20 14:22:09 +01001358 DCHECK(runtime->UseJitCompilation());
Vladimir Marko07785bb2015-06-15 18:52:54 +01001359 // Having the klass reference here implies that the klass is already loaded.
1360 return true;
1361 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001362 if (!IsBootImage()) {
Vladimir Marko07785bb2015-06-15 18:52:54 +01001363 // Assume loaded only if klass is in the boot image. App classes cannot be assumed
1364 // loaded because we don't even know what class loader will be used to load them.
1365 bool class_in_image = runtime->GetHeap()->FindSpaceFromObject(klass, false)->IsImageSpace();
1366 return class_in_image;
1367 }
1368 std::string temp;
1369 const char* descriptor = klass->GetDescriptor(&temp);
1370 return IsImageClass(descriptor);
1371}
1372
Vladimir Marko492a7fa2016-06-01 18:38:43 +01001373void CompilerDriver::MarkForDexToDexCompilation(Thread* self, const MethodReference& method_ref) {
1374 MutexLock lock(self, dex_to_dex_references_lock_);
1375 // Since we're compiling one dex file at a time, we need to look for the
1376 // current dex file entry only at the end of dex_to_dex_references_.
1377 if (dex_to_dex_references_.empty() ||
1378 &dex_to_dex_references_.back().GetDexFile() != method_ref.dex_file) {
1379 dex_to_dex_references_.emplace_back(*method_ref.dex_file);
1380 }
1381 dex_to_dex_references_.back().GetMethodIndexes().SetBit(method_ref.dex_method_index);
1382}
1383
Vladimir Marko3cd50df2016-04-13 19:29:26 +01001384bool CompilerDriver::CanAssumeTypeIsPresentInDexCache(Handle<mirror::DexCache> dex_cache,
1385 uint32_t type_idx) {
Nicolas Geoffray42e372e2015-11-24 15:48:56 +00001386 bool result = false;
1387 if ((IsBootImage() &&
Vladimir Marko3cd50df2016-04-13 19:29:26 +01001388 IsImageClass(dex_cache->GetDexFile()->StringDataByIdx(
1389 dex_cache->GetDexFile()->GetTypeId(type_idx).descriptor_idx_))) ||
Calin Juravleffc87072016-04-20 14:22:09 +01001390 Runtime::Current()->UseJitCompilation()) {
Nicolas Geoffray42e372e2015-11-24 15:48:56 +00001391 mirror::Class* resolved_class = dex_cache->GetResolvedType(type_idx);
1392 result = (resolved_class != nullptr);
1393 }
1394
1395 if (result) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001396 stats_->TypeInDexCache();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001397 } else {
1398 stats_->TypeNotInDexCache();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001399 }
Nicolas Geoffray42e372e2015-11-24 15:48:56 +00001400 return result;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001401}
1402
1403bool CompilerDriver::CanAssumeStringIsPresentInDexCache(const DexFile& dex_file,
1404 uint32_t string_idx) {
1405 // See also Compiler::ResolveDexFile
1406
1407 bool result = false;
Calin Juravleffc87072016-04-20 14:22:09 +01001408 if (IsBootImage() || Runtime::Current()->UseJitCompilation()) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001409 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001410 StackHandleScope<1> hs(soa.Self());
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001411 ClassLinker* const class_linker = Runtime::Current()->GetClassLinker();
1412 Handle<mirror::DexCache> dex_cache(hs.NewHandle(class_linker->FindDexCache(
1413 soa.Self(), dex_file, false)));
Nicolas Geoffray917d0162015-11-24 18:25:35 +00001414 if (IsBootImage()) {
1415 // We resolve all const-string strings when building for the image.
1416 class_linker->ResolveString(dex_file, string_idx, dex_cache);
1417 result = true;
1418 } else {
1419 // Just check whether the dex cache already has the string.
Calin Juravleffc87072016-04-20 14:22:09 +01001420 DCHECK(Runtime::Current()->UseJitCompilation());
Nicolas Geoffray917d0162015-11-24 18:25:35 +00001421 result = (dex_cache->GetResolvedString(string_idx) != nullptr);
1422 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001423 }
1424 if (result) {
1425 stats_->StringInDexCache();
1426 } else {
1427 stats_->StringNotInDexCache();
1428 }
1429 return result;
1430}
1431
Vladimir Marko3cd50df2016-04-13 19:29:26 +01001432bool CompilerDriver::CanAccessTypeWithoutChecks(uint32_t referrer_idx,
1433 Handle<mirror::DexCache> dex_cache,
1434 uint32_t type_idx) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001435 // Get type from dex cache assuming it was populated by the verifier
1436 mirror::Class* resolved_class = dex_cache->GetResolvedType(type_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001437 if (resolved_class == nullptr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001438 stats_->TypeNeedsAccessCheck();
1439 return false; // Unknown class needs access checks.
1440 }
Vladimir Marko3cd50df2016-04-13 19:29:26 +01001441 const DexFile::MethodId& method_id = dex_cache->GetDexFile()->GetMethodId(referrer_idx);
David Brazdil38f64d32016-01-18 17:13:41 +00001442 bool is_accessible = resolved_class->IsPublic(); // Public classes are always accessible.
1443 if (!is_accessible) {
1444 mirror::Class* referrer_class = dex_cache->GetResolvedType(method_id.class_idx_);
1445 if (referrer_class == nullptr) {
1446 stats_->TypeNeedsAccessCheck();
1447 return false; // Incomplete referrer knowledge needs access check.
1448 }
1449 // Perform access check, will return true if access is ok or false if we're going to have to
1450 // check this at runtime (for example for class loaders).
1451 is_accessible = referrer_class->CanAccess(resolved_class);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001452 }
David Brazdil38f64d32016-01-18 17:13:41 +00001453 if (is_accessible) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001454 stats_->TypeDoesntNeedAccessCheck();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001455 } else {
1456 stats_->TypeNeedsAccessCheck();
1457 }
David Brazdil38f64d32016-01-18 17:13:41 +00001458 return is_accessible;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001459}
1460
1461bool CompilerDriver::CanAccessInstantiableTypeWithoutChecks(uint32_t referrer_idx,
Vladimir Marko3cd50df2016-04-13 19:29:26 +01001462 Handle<mirror::DexCache> dex_cache,
Mingyao Yangfb8464a2015-11-02 10:56:59 -08001463 uint32_t type_idx,
1464 bool* finalizable) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001465 // Get type from dex cache assuming it was populated by the verifier.
1466 mirror::Class* resolved_class = dex_cache->GetResolvedType(type_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001467 if (resolved_class == nullptr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001468 stats_->TypeNeedsAccessCheck();
Mingyao Yangfb8464a2015-11-02 10:56:59 -08001469 // Be conservative.
1470 *finalizable = true;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001471 return false; // Unknown class needs access checks.
1472 }
Mingyao Yangfb8464a2015-11-02 10:56:59 -08001473 *finalizable = resolved_class->IsFinalizable();
Vladimir Marko3cd50df2016-04-13 19:29:26 +01001474 const DexFile::MethodId& method_id = dex_cache->GetDexFile()->GetMethodId(referrer_idx);
David Brazdil38f64d32016-01-18 17:13:41 +00001475 bool is_accessible = resolved_class->IsPublic(); // Public classes are always accessible.
1476 if (!is_accessible) {
1477 mirror::Class* referrer_class = dex_cache->GetResolvedType(method_id.class_idx_);
1478 if (referrer_class == nullptr) {
1479 stats_->TypeNeedsAccessCheck();
1480 return false; // Incomplete referrer knowledge needs access check.
1481 }
1482 // Perform access and instantiable checks, will return true if access is ok or false if we're
1483 // going to have to check this at runtime (for example for class loaders).
1484 is_accessible = referrer_class->CanAccess(resolved_class);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001485 }
David Brazdil38f64d32016-01-18 17:13:41 +00001486 bool result = is_accessible && resolved_class->IsInstantiable();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001487 if (result) {
1488 stats_->TypeDoesntNeedAccessCheck();
1489 } else {
1490 stats_->TypeNeedsAccessCheck();
1491 }
1492 return result;
1493}
1494
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001495bool CompilerDriver::CanEmbedTypeInCode(const DexFile& dex_file, uint32_t type_idx,
1496 bool* is_type_initialized, bool* use_direct_type_ptr,
Mathieu Chartier8668c3c2014-04-24 16:48:11 -07001497 uintptr_t* direct_type_ptr, bool* out_is_finalizable) {
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001498 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001499 Runtime* runtime = Runtime::Current();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001500 mirror::DexCache* dex_cache = runtime->GetClassLinker()->FindDexCache(
1501 soa.Self(), dex_file, false);
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001502 mirror::Class* resolved_class = dex_cache->GetResolvedType(type_idx);
1503 if (resolved_class == nullptr) {
1504 return false;
1505 }
Igor Murashkind6dee672014-10-16 18:36:16 -07001506 if (GetCompilerOptions().GetCompilePic()) {
1507 // Do not allow a direct class pointer to be used when compiling for position-independent
1508 return false;
1509 }
Mathieu Chartier8668c3c2014-04-24 16:48:11 -07001510 *out_is_finalizable = resolved_class->IsFinalizable();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001511 gc::Heap* heap = runtime->GetHeap();
1512 const bool compiling_boot = heap->IsCompilingBoot();
Alex Light6e183f22014-07-18 14:57:04 -07001513 const bool support_boot_image_fixup = GetSupportBootImageFixup();
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001514 if (compiling_boot) {
1515 // boot -> boot class pointers.
1516 // True if the class is in the image at boot compiling time.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001517 const bool is_image_class = IsBootImage() && IsImageClass(
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001518 dex_file.StringDataByIdx(dex_file.GetTypeId(type_idx).descriptor_idx_));
1519 // True if pc relative load works.
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001520 if (is_image_class && support_boot_image_fixup) {
1521 *is_type_initialized = resolved_class->IsInitialized();
1522 *use_direct_type_ptr = false;
1523 *direct_type_ptr = 0;
1524 return true;
1525 } else {
1526 return false;
1527 }
Calin Juravleffc87072016-04-20 14:22:09 +01001528 } else if (runtime->UseJitCompilation() && !heap->IsMovableObject(resolved_class)) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001529 *is_type_initialized = resolved_class->IsInitialized();
1530 // If the class may move around, then don't embed it as a direct pointer.
1531 *use_direct_type_ptr = true;
1532 *direct_type_ptr = reinterpret_cast<uintptr_t>(resolved_class);
1533 return true;
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001534 } else {
1535 // True if the class is in the image at app compiling time.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001536 const bool class_in_image = heap->FindSpaceFromObject(resolved_class, false)->IsImageSpace();
Alex Light6e183f22014-07-18 14:57:04 -07001537 if (class_in_image && support_boot_image_fixup) {
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001538 // boot -> app class pointers.
1539 *is_type_initialized = resolved_class->IsInitialized();
Alex Lighta59dd802014-07-02 16:28:08 -07001540 // TODO This is somewhat hacky. We should refactor all of this invoke codepath.
1541 *use_direct_type_ptr = !GetCompilerOptions().GetIncludePatchInformation();
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001542 *direct_type_ptr = reinterpret_cast<uintptr_t>(resolved_class);
1543 return true;
1544 } else {
1545 // app -> app class pointers.
1546 // Give up because app does not have an image and class
1547 // isn't created at compile time. TODO: implement this
1548 // if/when each app gets an image.
1549 return false;
1550 }
1551 }
1552}
1553
Fred Shihe7f82e22014-08-06 10:46:37 -07001554bool CompilerDriver::CanEmbedReferenceTypeInCode(ClassReference* ref,
1555 bool* use_direct_ptr,
1556 uintptr_t* direct_type_ptr) {
1557 CHECK(ref != nullptr);
1558 CHECK(use_direct_ptr != nullptr);
1559 CHECK(direct_type_ptr != nullptr);
1560
1561 ScopedObjectAccess soa(Thread::Current());
1562 mirror::Class* reference_class = mirror::Reference::GetJavaLangRefReference();
Andreas Gampe928f72b2014-09-09 19:53:48 -07001563 bool is_initialized = false;
Fred Shihe7f82e22014-08-06 10:46:37 -07001564 bool unused_finalizable;
1565 // Make sure we have a finished Reference class object before attempting to use it.
1566 if (!CanEmbedTypeInCode(*reference_class->GetDexCache()->GetDexFile(),
1567 reference_class->GetDexTypeIndex(), &is_initialized,
1568 use_direct_ptr, direct_type_ptr, &unused_finalizable) ||
1569 !is_initialized) {
1570 return false;
1571 }
1572 ref->first = &reference_class->GetDexFile();
1573 ref->second = reference_class->GetDexClassDefIndex();
1574 return true;
1575}
1576
1577uint32_t CompilerDriver::GetReferenceSlowFlagOffset() const {
1578 ScopedObjectAccess soa(Thread::Current());
1579 mirror::Class* klass = mirror::Reference::GetJavaLangRefReference();
1580 DCHECK(klass->IsInitialized());
1581 return klass->GetSlowPathFlagOffset().Uint32Value();
1582}
1583
1584uint32_t CompilerDriver::GetReferenceDisableFlagOffset() const {
1585 ScopedObjectAccess soa(Thread::Current());
1586 mirror::Class* klass = mirror::Reference::GetJavaLangRefReference();
1587 DCHECK(klass->IsInitialized());
1588 return klass->GetDisableIntrinsicFlagOffset().Uint32Value();
1589}
1590
Vladimir Marko20f85592015-03-19 10:07:02 +00001591DexCacheArraysLayout CompilerDriver::GetDexCacheArraysLayout(const DexFile* dex_file) {
Vladimir Markod1eaf0d2015-10-29 12:18:29 +00001592 return ContainsElement(GetDexFilesForOatFile(), dex_file)
Mathieu Chartierc7853442015-03-27 14:35:38 -07001593 ? DexCacheArraysLayout(GetInstructionSetPointerSize(instruction_set_), dex_file)
Vladimir Marko20f85592015-03-19 10:07:02 +00001594 : DexCacheArraysLayout();
1595}
1596
Vladimir Markobe0e5462014-02-26 11:24:15 +00001597void CompilerDriver::ProcessedInstanceField(bool resolved) {
1598 if (!resolved) {
1599 stats_->UnresolvedInstanceField();
1600 } else {
1601 stats_->ResolvedInstanceField();
1602 }
1603}
1604
1605void CompilerDriver::ProcessedStaticField(bool resolved, bool local) {
1606 if (!resolved) {
1607 stats_->UnresolvedStaticField();
1608 } else if (local) {
1609 stats_->ResolvedLocalStaticField();
1610 } else {
1611 stats_->ResolvedStaticField();
1612 }
1613}
1614
Vladimir Markof096aad2014-01-23 15:51:58 +00001615void CompilerDriver::ProcessedInvoke(InvokeType invoke_type, int flags) {
1616 stats_->ProcessedInvoke(invoke_type, flags);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001617}
1618
Mathieu Chartierc7853442015-03-27 14:35:38 -07001619ArtField* CompilerDriver::ComputeInstanceFieldInfo(uint32_t field_idx,
1620 const DexCompilationUnit* mUnit, bool is_put,
1621 const ScopedObjectAccess& soa) {
Vladimir Markobe0e5462014-02-26 11:24:15 +00001622 // Try to resolve the field and compiling method's class.
Mathieu Chartierc7853442015-03-27 14:35:38 -07001623 ArtField* resolved_field;
Vladimir Markobe0e5462014-02-26 11:24:15 +00001624 mirror::Class* referrer_class;
Mathieu Chartier736b5602015-09-02 14:54:11 -07001625 Handle<mirror::DexCache> dex_cache(mUnit->GetDexCache());
Vladimir Markobe0e5462014-02-26 11:24:15 +00001626 {
Mathieu Chartier736b5602015-09-02 14:54:11 -07001627 StackHandleScope<1> hs(soa.Self());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001628 Handle<mirror::ClassLoader> class_loader_handle(
Mathieu Chartier0795f232016-09-27 18:43:30 -07001629 hs.NewHandle(soa.Decode<mirror::ClassLoader>(mUnit->GetClassLoader())));
Mathieu Chartier736b5602015-09-02 14:54:11 -07001630 resolved_field = ResolveField(soa, dex_cache, class_loader_handle, mUnit, field_idx, false);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001631 referrer_class = resolved_field != nullptr
Mathieu Chartier736b5602015-09-02 14:54:11 -07001632 ? ResolveCompilingMethodsClass(soa, dex_cache, class_loader_handle, mUnit) : nullptr;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001633 }
Nicolas Geoffraye5038322014-07-04 09:41:32 +01001634 bool can_link = false;
Vladimir Markobe0e5462014-02-26 11:24:15 +00001635 if (resolved_field != nullptr && referrer_class != nullptr) {
Vladimir Markobe0e5462014-02-26 11:24:15 +00001636 std::pair<bool, bool> fast_path = IsFastInstanceField(
Mathieu Chartier736b5602015-09-02 14:54:11 -07001637 dex_cache.Get(), referrer_class, resolved_field, field_idx);
Nicolas Geoffraye5038322014-07-04 09:41:32 +01001638 can_link = is_put ? fast_path.second : fast_path.first;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001639 }
Nicolas Geoffraye5038322014-07-04 09:41:32 +01001640 ProcessedInstanceField(can_link);
1641 return can_link ? resolved_field : nullptr;
1642}
1643
1644bool CompilerDriver::ComputeInstanceFieldInfo(uint32_t field_idx, const DexCompilationUnit* mUnit,
1645 bool is_put, MemberOffset* field_offset,
1646 bool* is_volatile) {
1647 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartierc7853442015-03-27 14:35:38 -07001648 ArtField* resolved_field = ComputeInstanceFieldInfo(field_idx, mUnit, is_put, soa);
Nicolas Geoffraye5038322014-07-04 09:41:32 +01001649
Mathieu Chartierc7853442015-03-27 14:35:38 -07001650 if (resolved_field == nullptr) {
Vladimir Markobe0e5462014-02-26 11:24:15 +00001651 // Conservative defaults.
1652 *is_volatile = true;
1653 *field_offset = MemberOffset(static_cast<size_t>(-1));
Nicolas Geoffraye5038322014-07-04 09:41:32 +01001654 return false;
1655 } else {
1656 *is_volatile = resolved_field->IsVolatile();
1657 *field_offset = resolved_field->GetOffset();
1658 return true;
Vladimir Markobe0e5462014-02-26 11:24:15 +00001659 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001660}
1661
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +01001662void CompilerDriver::GetCodeAndMethodForDirectCall(const mirror::Class* referrer_class,
Mathieu Chartiere401d142015-04-22 13:56:20 -07001663 ArtMethod* method,
Ian Rogers65ec92c2013-09-06 10:49:58 -07001664 uintptr_t* direct_code,
1665 uintptr_t* direct_method) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001666 // For direct and static methods compute possible direct_code and direct_method values, ie
1667 // an address for the Method* being invoked and an address of the code for that Method*.
1668 // For interface calls compute a value for direct_method that is the interface method being
1669 // invoked, so this can be passed to the out-of-line runtime support code.
Ian Rogers65ec92c2013-09-06 10:49:58 -07001670 *direct_code = 0;
1671 *direct_method = 0;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001672 Runtime* const runtime = Runtime::Current();
1673 gc::Heap* const heap = runtime->GetHeap();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001674 auto* cl = runtime->GetClassLinker();
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 // TODO: support patching on all architectures.
1681 use_dex_cache = use_dex_cache || (force_relocations && !support_boot_image_fixup_);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001682 mirror::Class* declaring_class = method->GetDeclaringClass();
1683 bool method_code_in_boot = declaring_class->GetClassLoader() == nullptr;
Ian Rogers83883d72013-10-21 21:07:24 -07001684 if (!use_dex_cache) {
1685 if (!method_code_in_boot) {
1686 use_dex_cache = true;
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +01001687 } else if (method->IsStatic() &&
1688 declaring_class != referrer_class &&
1689 !declaring_class->IsInitialized()) {
1690 // Ensure we run the clinit trampoline unless we are invoking a static method in the same
1691 // class.
1692 use_dex_cache = true;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001693 }
Ian Rogers83883d72013-10-21 21:07:24 -07001694 }
Calin Juravleffc87072016-04-20 14:22:09 +01001695 if (runtime->UseJitCompilation()) {
Mathieu Chartier28a35882015-02-26 18:28:07 -08001696 // If we are the JIT, then don't allow a direct call to the interpreter bridge since this will
1697 // never be updated even after we compile the method.
Mathieu Chartiere401d142015-04-22 13:56:20 -07001698 if (cl->IsQuickToInterpreterBridge(
Mathieu Chartier28a35882015-02-26 18:28:07 -08001699 reinterpret_cast<const void*>(compiler_->GetEntryPointOf(method)))) {
1700 use_dex_cache = true;
1701 }
1702 }
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +01001703
Alex Lighta59dd802014-07-02 16:28:08 -07001704 if (!use_dex_cache && force_relocations) {
Jeff Haoa0acc2d2015-01-27 11:22:04 -08001705 bool is_in_image;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001706 if (IsBootImage()) {
Jeff Haoa0acc2d2015-01-27 11:22:04 -08001707 is_in_image = IsImageClass(method->GetDeclaringClassDescriptor());
1708 } else {
1709 is_in_image = instruction_set_ != kX86 && instruction_set_ != kX86_64 &&
Vladimir Markoc08ab292015-06-22 14:35:42 +01001710 heap->FindSpaceFromObject(method->GetDeclaringClass(), false)->IsImageSpace() &&
1711 !cl->IsQuickToInterpreterBridge(
1712 reinterpret_cast<const void*>(compiler_->GetEntryPointOf(method)));
Jeff Haoa0acc2d2015-01-27 11:22:04 -08001713 }
1714 if (!is_in_image) {
Ian Rogers83883d72013-10-21 21:07:24 -07001715 // We can only branch directly to Methods that are resolved in the DexCache.
1716 // Otherwise we won't invoke the resolution trampoline.
1717 use_dex_cache = true;
1718 }
1719 }
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +01001720
1721 if (!use_dex_cache) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001722 bool method_in_image = false;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001723 const std::vector<gc::space::ImageSpace*> image_spaces = heap->GetBootImageSpaces();
1724 for (gc::space::ImageSpace* image_space : image_spaces) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001725 const auto& method_section = image_space->GetImageHeader().GetMethodsSection();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001726 if (method_section.Contains(reinterpret_cast<uint8_t*>(method) - image_space->Begin())) {
1727 method_in_image = true;
1728 break;
1729 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001730 }
Calin Juravleffc87072016-04-20 14:22:09 +01001731 if (method_in_image || compiling_boot || runtime->UseJitCompilation()) {
Alex Lighta59dd802014-07-02 16:28:08 -07001732 // 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 -08001733 // In the case where we are the JIT, we can always use direct pointers since we know where
1734 // the method and its code are / will be. We don't sharpen to interpreter bridge since we
1735 // check IsQuickToInterpreterBridge above.
Vladimir Markoa51a0b02014-05-21 12:08:39 +01001736 CHECK(!method->IsAbstract());
Alex Lighta59dd802014-07-02 16:28:08 -07001737 *direct_method = force_relocations ? -1 : reinterpret_cast<uintptr_t>(method);
1738 *direct_code = force_relocations ? -1 : compiler_->GetEntryPointOf(method);
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +01001739 } else {
Vladimir Markoa51a0b02014-05-21 12:08:39 +01001740 // Set the code and rely on the dex cache for the method.
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +01001741 *direct_code = force_relocations ? -1 : compiler_->GetEntryPointOf(method);
Ian Rogers83883d72013-10-21 21:07:24 -07001742 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001743 }
1744}
1745
Vladimir Marko2730db02014-01-27 11:15:17 +00001746const VerifiedMethod* CompilerDriver::GetVerifiedMethod(const DexFile* dex_file,
1747 uint32_t method_idx) const {
1748 MethodReference ref(dex_file, method_idx);
1749 return verification_results_->GetVerifiedMethod(ref);
1750}
1751
1752bool CompilerDriver::IsSafeCast(const DexCompilationUnit* mUnit, uint32_t dex_pc) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001753 if (!compiler_options_->IsVerificationEnabled()) {
1754 // If we didn't verify, every cast has to be treated as non-safe.
1755 return false;
1756 }
Vladimir Marko2730db02014-01-27 11:15:17 +00001757 DCHECK(mUnit->GetVerifiedMethod() != nullptr);
1758 bool result = mUnit->GetVerifiedMethod()->IsSafeCast(dex_pc);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001759 if (result) {
1760 stats_->SafeCast();
1761 } else {
1762 stats_->NotASafeCast();
1763 }
1764 return result;
1765}
1766
Mathieu Chartier90443472015-07-16 20:32:27 -07001767class CompilationVisitor {
1768 public:
1769 virtual ~CompilationVisitor() {}
1770 virtual void Visit(size_t index) = 0;
1771};
1772
Brian Carlstrom7940e442013-07-12 13:46:57 -07001773class ParallelCompilationManager {
1774 public:
Brian Carlstrom7940e442013-07-12 13:46:57 -07001775 ParallelCompilationManager(ClassLinker* class_linker,
1776 jobject class_loader,
1777 CompilerDriver* compiler,
1778 const DexFile* dex_file,
Andreas Gampede7b4362014-07-28 18:38:57 -07001779 const std::vector<const DexFile*>& dex_files,
Ian Rogers3d504072014-03-01 09:16:49 -08001780 ThreadPool* thread_pool)
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001781 : index_(0),
1782 class_linker_(class_linker),
Brian Carlstrom7940e442013-07-12 13:46:57 -07001783 class_loader_(class_loader),
1784 compiler_(compiler),
1785 dex_file_(dex_file),
Andreas Gampede7b4362014-07-28 18:38:57 -07001786 dex_files_(dex_files),
Ian Rogers3d504072014-03-01 09:16:49 -08001787 thread_pool_(thread_pool) {}
Brian Carlstrom7940e442013-07-12 13:46:57 -07001788
1789 ClassLinker* GetClassLinker() const {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001790 CHECK(class_linker_ != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001791 return class_linker_;
1792 }
1793
1794 jobject GetClassLoader() const {
1795 return class_loader_;
1796 }
1797
1798 CompilerDriver* GetCompiler() const {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001799 CHECK(compiler_ != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001800 return compiler_;
1801 }
1802
1803 const DexFile* GetDexFile() const {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001804 CHECK(dex_file_ != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001805 return dex_file_;
1806 }
1807
Andreas Gampede7b4362014-07-28 18:38:57 -07001808 const std::vector<const DexFile*>& GetDexFiles() const {
1809 return dex_files_;
1810 }
1811
Mathieu Chartier90443472015-07-16 20:32:27 -07001812 void ForAll(size_t begin, size_t end, CompilationVisitor* visitor, size_t work_units)
1813 REQUIRES(!*Locks::mutator_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001814 Thread* self = Thread::Current();
1815 self->AssertNoPendingException();
1816 CHECK_GT(work_units, 0U);
1817
Ian Rogers3e5cf302014-05-20 16:40:37 -07001818 index_.StoreRelaxed(begin);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001819 for (size_t i = 0; i < work_units; ++i) {
Mathieu Chartier90443472015-07-16 20:32:27 -07001820 thread_pool_->AddTask(self, new ForAllClosure(this, end, visitor));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001821 }
1822 thread_pool_->StartWorkers(self);
1823
1824 // Ensure we're suspended while we're blocked waiting for the other threads to finish (worker
1825 // thread destructor's called below perform join).
1826 CHECK_NE(self->GetState(), kRunnable);
1827
1828 // Wait for all the worker threads to finish.
1829 thread_pool_->Wait(self, true, false);
Andreas Gampeace0dc12016-01-20 13:33:13 -08001830
1831 // And stop the workers accepting jobs.
1832 thread_pool_->StopWorkers(self);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001833 }
1834
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001835 size_t NextIndex() {
Ian Rogers3e5cf302014-05-20 16:40:37 -07001836 return index_.FetchAndAddSequentiallyConsistent(1);
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001837 }
1838
Brian Carlstrom7940e442013-07-12 13:46:57 -07001839 private:
Brian Carlstrom7940e442013-07-12 13:46:57 -07001840 class ForAllClosure : public Task {
1841 public:
Mathieu Chartier90443472015-07-16 20:32:27 -07001842 ForAllClosure(ParallelCompilationManager* manager, size_t end, CompilationVisitor* visitor)
Brian Carlstrom7940e442013-07-12 13:46:57 -07001843 : manager_(manager),
Brian Carlstrom7940e442013-07-12 13:46:57 -07001844 end_(end),
Mathieu Chartier90443472015-07-16 20:32:27 -07001845 visitor_(visitor) {}
Brian Carlstrom7940e442013-07-12 13:46:57 -07001846
1847 virtual void Run(Thread* self) {
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001848 while (true) {
1849 const size_t index = manager_->NextIndex();
1850 if (UNLIKELY(index >= end_)) {
1851 break;
1852 }
Mathieu Chartier90443472015-07-16 20:32:27 -07001853 visitor_->Visit(index);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001854 self->AssertNoPendingException();
1855 }
1856 }
1857
1858 virtual void Finalize() {
1859 delete this;
1860 }
Brian Carlstrom0cd7ec22013-07-17 23:40:20 -07001861
Brian Carlstrom7940e442013-07-12 13:46:57 -07001862 private:
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001863 ParallelCompilationManager* const manager_;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001864 const size_t end_;
Mathieu Chartier90443472015-07-16 20:32:27 -07001865 CompilationVisitor* const visitor_;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001866 };
1867
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001868 AtomicInteger index_;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001869 ClassLinker* const class_linker_;
1870 const jobject class_loader_;
1871 CompilerDriver* const compiler_;
1872 const DexFile* const dex_file_;
Andreas Gampede7b4362014-07-28 18:38:57 -07001873 const std::vector<const DexFile*>& dex_files_;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001874 ThreadPool* const thread_pool_;
Mathieu Chartier0b3eb392013-08-23 14:56:59 -07001875
1876 DISALLOW_COPY_AND_ASSIGN(ParallelCompilationManager);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001877};
1878
Jeff Hao0e49b422013-11-08 12:16:56 -08001879// A fast version of SkipClass above if the class pointer is available
1880// that avoids the expensive FindInClassPath search.
1881static bool SkipClass(jobject class_loader, const DexFile& dex_file, mirror::Class* klass)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001882 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001883 DCHECK(klass != nullptr);
Jeff Hao0e49b422013-11-08 12:16:56 -08001884 const DexFile& original_dex_file = *klass->GetDexCache()->GetDexFile();
1885 if (&dex_file != &original_dex_file) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001886 if (class_loader == nullptr) {
Jeff Hao0e49b422013-11-08 12:16:56 -08001887 LOG(WARNING) << "Skipping class " << PrettyDescriptor(klass) << " from "
1888 << dex_file.GetLocation() << " previously found in "
1889 << original_dex_file.GetLocation();
1890 }
1891 return true;
1892 }
1893 return false;
1894}
1895
Mathieu Chartier70b63482014-06-27 17:19:04 -07001896static void CheckAndClearResolveException(Thread* self)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001897 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier70b63482014-06-27 17:19:04 -07001898 CHECK(self->IsExceptionPending());
Nicolas Geoffray14691c52015-03-05 10:40:17 +00001899 mirror::Throwable* exception = self->GetException();
Ian Rogers1ff3c982014-08-12 02:30:58 -07001900 std::string temp;
1901 const char* descriptor = exception->GetClass()->GetDescriptor(&temp);
1902 const char* expected_exceptions[] = {
1903 "Ljava/lang/IllegalAccessError;",
1904 "Ljava/lang/IncompatibleClassChangeError;",
1905 "Ljava/lang/InstantiationError;",
Brian Carlstrom898fcb52014-08-25 23:07:30 -07001906 "Ljava/lang/LinkageError;",
Ian Rogers1ff3c982014-08-12 02:30:58 -07001907 "Ljava/lang/NoClassDefFoundError;",
1908 "Ljava/lang/NoSuchFieldError;",
1909 "Ljava/lang/NoSuchMethodError;"
1910 };
1911 bool found = false;
1912 for (size_t i = 0; (found == false) && (i < arraysize(expected_exceptions)); ++i) {
1913 if (strcmp(descriptor, expected_exceptions[i]) == 0) {
1914 found = true;
1915 }
1916 }
1917 if (!found) {
Brian Carlstrom898fcb52014-08-25 23:07:30 -07001918 LOG(FATAL) << "Unexpected exception " << exception->Dump();
Mathieu Chartier70b63482014-06-27 17:19:04 -07001919 }
1920 self->ClearException();
1921}
1922
Mathieu Chartierb5d38612016-04-07 10:52:52 -07001923bool CompilerDriver::RequiresConstructorBarrier(const DexFile& dex_file,
1924 uint16_t class_def_idx) const {
1925 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_idx);
1926 const uint8_t* class_data = dex_file.GetClassData(class_def);
1927 if (class_data == nullptr) {
1928 // Empty class such as a marker interface.
1929 return false;
1930 }
1931 ClassDataItemIterator it(dex_file, class_data);
1932 while (it.HasNextStaticField()) {
1933 it.Next();
1934 }
1935 // We require a constructor barrier if there are final instance fields.
1936 while (it.HasNextInstanceField()) {
1937 if (it.MemberIsFinal()) {
1938 return true;
1939 }
1940 it.Next();
1941 }
1942 return false;
1943}
1944
Mathieu Chartier90443472015-07-16 20:32:27 -07001945class ResolveClassFieldsAndMethodsVisitor : public CompilationVisitor {
1946 public:
1947 explicit ResolveClassFieldsAndMethodsVisitor(const ParallelCompilationManager* manager)
1948 : manager_(manager) {}
Brian Carlstrom7940e442013-07-12 13:46:57 -07001949
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07001950 void Visit(size_t class_def_index) OVERRIDE REQUIRES(!Locks::mutator_lock_) {
Mathieu Chartier90443472015-07-16 20:32:27 -07001951 ATRACE_CALL();
1952 Thread* const self = Thread::Current();
1953 jobject jclass_loader = manager_->GetClassLoader();
1954 const DexFile& dex_file = *manager_->GetDexFile();
1955 ClassLinker* class_linker = manager_->GetClassLinker();
Ian Rogerse6bb3b22013-08-19 21:51:45 -07001956
Mathieu Chartier90443472015-07-16 20:32:27 -07001957 // If an instance field is final then we need to have a barrier on the return, static final
1958 // fields are assigned within the lock held for class initialization. Conservatively assume
1959 // constructor barriers are always required.
1960 bool requires_constructor_barrier = true;
1961
1962 // Method and Field are the worst. We can't resolve without either
1963 // context from the code use (to disambiguate virtual vs direct
1964 // method and instance vs static field) or from class
1965 // definitions. While the compiler will resolve what it can as it
1966 // needs it, here we try to resolve fields and methods used in class
1967 // definitions, since many of them many never be referenced by
1968 // generated code.
1969 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
1970 ScopedObjectAccess soa(self);
1971 StackHandleScope<2> hs(soa.Self());
1972 Handle<mirror::ClassLoader> class_loader(
Mathieu Chartier0795f232016-09-27 18:43:30 -07001973 hs.NewHandle(soa.Decode<mirror::ClassLoader>(jclass_loader)));
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001974 Handle<mirror::DexCache> dex_cache(hs.NewHandle(class_linker->FindDexCache(
1975 soa.Self(), dex_file, false)));
Mathieu Chartier90443472015-07-16 20:32:27 -07001976 // Resolve the class.
1977 mirror::Class* klass = class_linker->ResolveType(dex_file, class_def.class_idx_, dex_cache,
1978 class_loader);
1979 bool resolve_fields_and_methods;
1980 if (klass == nullptr) {
1981 // Class couldn't be resolved, for example, super-class is in a different dex file. Don't
1982 // attempt to resolve methods and fields when there is no declaring class.
1983 CheckAndClearResolveException(soa.Self());
1984 resolve_fields_and_methods = false;
1985 } else {
1986 // We successfully resolved a class, should we skip it?
1987 if (SkipClass(jclass_loader, dex_file, klass)) {
1988 return;
Ian Rogerse6bb3b22013-08-19 21:51:45 -07001989 }
Mathieu Chartier90443472015-07-16 20:32:27 -07001990 // We want to resolve the methods and fields eagerly.
1991 resolve_fields_and_methods = true;
Ian Rogers68b56852014-08-29 20:19:11 -07001992 }
Mathieu Chartier90443472015-07-16 20:32:27 -07001993 // Note the class_data pointer advances through the headers,
1994 // static fields, instance fields, direct methods, and virtual
1995 // methods.
1996 const uint8_t* class_data = dex_file.GetClassData(class_def);
1997 if (class_data == nullptr) {
1998 // Empty class such as a marker interface.
1999 requires_constructor_barrier = false;
2000 } else {
2001 ClassDataItemIterator it(dex_file, class_data);
2002 while (it.HasNextStaticField()) {
2003 if (resolve_fields_and_methods) {
2004 ArtField* field = class_linker->ResolveField(dex_file, it.GetMemberIndex(),
2005 dex_cache, class_loader, true);
2006 if (field == nullptr) {
2007 CheckAndClearResolveException(soa.Self());
2008 }
Ian Rogers68b56852014-08-29 20:19:11 -07002009 }
2010 it.Next();
2011 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002012 // We require a constructor barrier if there are final instance fields.
2013 requires_constructor_barrier = false;
2014 while (it.HasNextInstanceField()) {
2015 if (it.MemberIsFinal()) {
2016 requires_constructor_barrier = true;
2017 }
2018 if (resolve_fields_and_methods) {
2019 ArtField* field = class_linker->ResolveField(dex_file, it.GetMemberIndex(),
2020 dex_cache, class_loader, false);
2021 if (field == nullptr) {
2022 CheckAndClearResolveException(soa.Self());
2023 }
Ian Rogers68b56852014-08-29 20:19:11 -07002024 }
2025 it.Next();
2026 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002027 if (resolve_fields_and_methods) {
2028 while (it.HasNextDirectMethod()) {
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08002029 ArtMethod* method = class_linker->ResolveMethod<ClassLinker::kNoICCECheckForCache>(
Mathieu Chartier90443472015-07-16 20:32:27 -07002030 dex_file, it.GetMemberIndex(), dex_cache, class_loader, nullptr,
2031 it.GetMethodInvokeType(class_def));
2032 if (method == nullptr) {
2033 CheckAndClearResolveException(soa.Self());
2034 }
2035 it.Next();
2036 }
2037 while (it.HasNextVirtualMethod()) {
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08002038 ArtMethod* method = class_linker->ResolveMethod<ClassLinker::kNoICCECheckForCache>(
Mathieu Chartier90443472015-07-16 20:32:27 -07002039 dex_file, it.GetMemberIndex(), dex_cache, class_loader, nullptr,
2040 it.GetMethodInvokeType(class_def));
2041 if (method == nullptr) {
2042 CheckAndClearResolveException(soa.Self());
2043 }
2044 it.Next();
2045 }
2046 DCHECK(!it.HasNext());
2047 }
2048 }
Mathieu Chartierc4ae9162016-04-07 13:19:19 -07002049 manager_->GetCompiler()->SetRequiresConstructorBarrier(self,
2050 &dex_file,
2051 class_def_index,
2052 requires_constructor_barrier);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002053 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002054
Mathieu Chartier90443472015-07-16 20:32:27 -07002055 private:
2056 const ParallelCompilationManager* const manager_;
2057};
2058
2059class ResolveTypeVisitor : public CompilationVisitor {
2060 public:
2061 explicit ResolveTypeVisitor(const ParallelCompilationManager* manager) : manager_(manager) {
2062 }
2063 virtual void Visit(size_t type_idx) OVERRIDE REQUIRES(!Locks::mutator_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07002064 // Class derived values are more complicated, they require the linker and loader.
Mathieu Chartier90443472015-07-16 20:32:27 -07002065 ScopedObjectAccess soa(Thread::Current());
2066 ClassLinker* class_linker = manager_->GetClassLinker();
2067 const DexFile& dex_file = *manager_->GetDexFile();
2068 StackHandleScope<2> hs(soa.Self());
Mathieu Chartier90443472015-07-16 20:32:27 -07002069 Handle<mirror::ClassLoader> class_loader(
Mathieu Chartier0795f232016-09-27 18:43:30 -07002070 hs.NewHandle(soa.Decode<mirror::ClassLoader>(manager_->GetClassLoader())));
Mathieu Chartierd57d4542015-10-14 10:55:30 -07002071 Handle<mirror::DexCache> dex_cache(hs.NewHandle(class_linker->RegisterDexFile(
2072 dex_file,
Mathieu Chartierf284d442016-06-02 11:48:30 -07002073 class_loader.Get())));
Mathieu Chartier90443472015-07-16 20:32:27 -07002074 mirror::Class* klass = class_linker->ResolveType(dex_file, type_idx, dex_cache, class_loader);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002075
Mathieu Chartier90443472015-07-16 20:32:27 -07002076 if (klass == nullptr) {
2077 soa.Self()->AssertPendingException();
2078 mirror::Throwable* exception = soa.Self()->GetException();
2079 VLOG(compiler) << "Exception during type resolution: " << exception->Dump();
2080 if (exception->GetClass()->DescriptorEquals("Ljava/lang/OutOfMemoryError;")) {
2081 // There's little point continuing compilation if the heap is exhausted.
2082 LOG(FATAL) << "Out of memory during type resolution for compilation";
2083 }
2084 soa.Self()->ClearException();
Ian Rogersa436fde2013-08-27 23:34:06 -07002085 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002086 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002087
2088 private:
2089 const ParallelCompilationManager* const manager_;
2090};
Brian Carlstrom7940e442013-07-12 13:46:57 -07002091
Andreas Gampeace0dc12016-01-20 13:33:13 -08002092void CompilerDriver::ResolveDexFile(jobject class_loader,
2093 const DexFile& dex_file,
Andreas Gampede7b4362014-07-28 18:38:57 -07002094 const std::vector<const DexFile*>& dex_files,
Andreas Gampeace0dc12016-01-20 13:33:13 -08002095 ThreadPool* thread_pool,
2096 size_t thread_count,
2097 TimingLogger* timings) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07002098 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
2099
2100 // TODO: we could resolve strings here, although the string table is largely filled with class
2101 // and method names.
2102
Andreas Gampede7b4362014-07-28 18:38:57 -07002103 ParallelCompilationManager context(class_linker, class_loader, this, &dex_file, dex_files,
2104 thread_pool);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002105 if (IsBootImage()) {
Ian Rogerse6bb3b22013-08-19 21:51:45 -07002106 // For images we resolve all types, such as array, whereas for applications just those with
2107 // classdefs are resolved by ResolveClassFieldsAndMethods.
Mathieu Chartierf5997b42014-06-20 10:37:54 -07002108 TimingLogger::ScopedTiming t("Resolve Types", timings);
Mathieu Chartier90443472015-07-16 20:32:27 -07002109 ResolveTypeVisitor visitor(&context);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002110 context.ForAll(0, dex_file.NumTypeIds(), &visitor, thread_count);
Ian Rogerse6bb3b22013-08-19 21:51:45 -07002111 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002112
Mathieu Chartierf5997b42014-06-20 10:37:54 -07002113 TimingLogger::ScopedTiming t("Resolve MethodsAndFields", timings);
Mathieu Chartier90443472015-07-16 20:32:27 -07002114 ResolveClassFieldsAndMethodsVisitor visitor(&context);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002115 context.ForAll(0, dex_file.NumClassDefs(), &visitor, thread_count);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002116}
2117
Andreas Gampeace0dc12016-01-20 13:33:13 -08002118void CompilerDriver::SetVerified(jobject class_loader,
2119 const std::vector<const DexFile*>& dex_files,
2120 TimingLogger* timings) {
2121 // This can be run in parallel.
Mathieu Chartier90443472015-07-16 20:32:27 -07002122 for (const DexFile* dex_file : dex_files) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002123 CHECK(dex_file != nullptr);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002124 SetVerifiedDexFile(class_loader,
2125 *dex_file,
2126 dex_files,
2127 parallel_thread_pool_.get(),
2128 parallel_thread_count_,
2129 timings);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002130 }
2131}
2132
Andreas Gampeace0dc12016-01-20 13:33:13 -08002133void CompilerDriver::Verify(jobject class_loader,
2134 const std::vector<const DexFile*>& dex_files,
2135 TimingLogger* timings) {
2136 // Note: verification should not be pulling in classes anymore when compiling the boot image,
2137 // as all should have been resolved before. As such, doing this in parallel should still
2138 // be deterministic.
Mathieu Chartier90443472015-07-16 20:32:27 -07002139 for (const DexFile* dex_file : dex_files) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002140 CHECK(dex_file != nullptr);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002141 VerifyDexFile(class_loader,
2142 *dex_file,
2143 dex_files,
2144 parallel_thread_pool_.get(),
2145 parallel_thread_count_,
2146 timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002147 }
2148}
2149
Mathieu Chartier90443472015-07-16 20:32:27 -07002150class VerifyClassVisitor : public CompilationVisitor {
2151 public:
Andreas Gampe5fd66d02016-09-12 20:22:19 -07002152 VerifyClassVisitor(const ParallelCompilationManager* manager, verifier::HardFailLogMode log_level)
Andreas Gampe7fe30232016-03-25 16:58:00 -07002153 : manager_(manager), log_level_(log_level) {}
Brian Carlstrom7940e442013-07-12 13:46:57 -07002154
Mathieu Chartier90443472015-07-16 20:32:27 -07002155 virtual void Visit(size_t class_def_index) REQUIRES(!Locks::mutator_lock_) OVERRIDE {
2156 ATRACE_CALL();
2157 ScopedObjectAccess soa(Thread::Current());
2158 const DexFile& dex_file = *manager_->GetDexFile();
Mathieu Chartiera8077802016-03-16 19:08:31 -07002159 if (!manager_->GetCompiler()->ShouldVerifyClassBasedOnProfile(dex_file, class_def_index)) {
2160 // Skip verification since the class is not in the profile.
2161 return;
2162 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002163 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
2164 const char* descriptor = dex_file.GetClassDescriptor(class_def);
2165 ClassLinker* class_linker = manager_->GetClassLinker();
2166 jobject jclass_loader = manager_->GetClassLoader();
2167 StackHandleScope<3> hs(soa.Self());
2168 Handle<mirror::ClassLoader> class_loader(
Mathieu Chartier0795f232016-09-27 18:43:30 -07002169 hs.NewHandle(soa.Decode<mirror::ClassLoader>(jclass_loader)));
Mathieu Chartier90443472015-07-16 20:32:27 -07002170 Handle<mirror::Class> klass(
2171 hs.NewHandle(class_linker->FindClass(soa.Self(), descriptor, class_loader)));
2172 if (klass.Get() == nullptr) {
Ian Rogerse6bb3b22013-08-19 21:51:45 -07002173 CHECK(soa.Self()->IsExceptionPending());
2174 soa.Self()->ClearException();
Mathieu Chartier90443472015-07-16 20:32:27 -07002175
2176 /*
2177 * At compile time, we can still structurally verify the class even if FindClass fails.
2178 * This is to ensure the class is structurally sound for compilation. An unsound class
2179 * will be rejected by the verifier and later skipped during compilation in the compiler.
2180 */
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002181 Handle<mirror::DexCache> dex_cache(hs.NewHandle(class_linker->FindDexCache(
2182 soa.Self(), dex_file, false)));
Mathieu Chartier90443472015-07-16 20:32:27 -07002183 std::string error_msg;
Andreas Gampeec6e6c12015-11-05 20:39:56 -08002184 if (verifier::MethodVerifier::VerifyClass(soa.Self(),
2185 &dex_file,
2186 dex_cache,
2187 class_loader,
David Brazdil15fc7292016-09-02 14:13:18 +01002188 class_def,
Andreas Gampe53e32d12015-12-09 21:03:23 -08002189 Runtime::Current()->GetCompilerCallbacks(),
Andreas Gampeec6e6c12015-11-05 20:39:56 -08002190 true /* allow soft failures */,
Andreas Gampe7fe30232016-03-25 16:58:00 -07002191 log_level_,
Andreas Gampeec6e6c12015-11-05 20:39:56 -08002192 &error_msg) ==
Mathieu Chartier90443472015-07-16 20:32:27 -07002193 verifier::MethodVerifier::kHardFailure) {
2194 LOG(ERROR) << "Verification failed on class " << PrettyDescriptor(descriptor)
2195 << " because: " << error_msg;
2196 manager_->GetCompiler()->SetHadHardVerifierFailure();
2197 }
2198 } else if (!SkipClass(jclass_loader, dex_file, klass.Get())) {
2199 CHECK(klass->IsResolved()) << PrettyClass(klass.Get());
Andreas Gampe7fe30232016-03-25 16:58:00 -07002200 class_linker->VerifyClass(soa.Self(), klass, log_level_);
Mathieu Chartier90443472015-07-16 20:32:27 -07002201
2202 if (klass->IsErroneous()) {
2203 // ClassLinker::VerifyClass throws, which isn't useful in the compiler.
2204 CHECK(soa.Self()->IsExceptionPending());
2205 soa.Self()->ClearException();
2206 manager_->GetCompiler()->SetHadHardVerifierFailure();
2207 }
2208
2209 CHECK(klass->IsCompileTimeVerified() || klass->IsErroneous())
2210 << PrettyDescriptor(klass.Get()) << ": state=" << klass->GetStatus();
2211
2212 // It is *very* problematic if there are verification errors in the boot classpath. For example,
2213 // we rely on things working OK without verification when the decryption dialog is brought up.
2214 // So abort in a debug build if we find this violated.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002215 DCHECK(!manager_->GetCompiler()->IsBootImage() || klass->IsVerified())
2216 << "Boot classpath class " << PrettyClass(klass.Get()) << " failed to fully verify.";
Ian Rogerse6bb3b22013-08-19 21:51:45 -07002217 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002218 soa.Self()->AssertNoPendingException();
Brian Carlstrom7940e442013-07-12 13:46:57 -07002219 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002220
2221 private:
2222 const ParallelCompilationManager* const manager_;
Andreas Gampe5fd66d02016-09-12 20:22:19 -07002223 const verifier::HardFailLogMode log_level_;
Mathieu Chartier90443472015-07-16 20:32:27 -07002224};
Brian Carlstrom7940e442013-07-12 13:46:57 -07002225
Andreas Gampeace0dc12016-01-20 13:33:13 -08002226void CompilerDriver::VerifyDexFile(jobject class_loader,
2227 const DexFile& dex_file,
Andreas Gampede7b4362014-07-28 18:38:57 -07002228 const std::vector<const DexFile*>& dex_files,
Andreas Gampeace0dc12016-01-20 13:33:13 -08002229 ThreadPool* thread_pool,
2230 size_t thread_count,
2231 TimingLogger* timings) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07002232 TimingLogger::ScopedTiming t("Verify Dex File", timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002233 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Andreas Gampede7b4362014-07-28 18:38:57 -07002234 ParallelCompilationManager context(class_linker, class_loader, this, &dex_file, dex_files,
2235 thread_pool);
Andreas Gampe5fd66d02016-09-12 20:22:19 -07002236 verifier::HardFailLogMode log_level = GetCompilerOptions().AbortOnHardVerifierFailure()
2237 ? verifier::HardFailLogMode::kLogInternalFatal
2238 : verifier::HardFailLogMode::kLogWarning;
Andreas Gampe7fe30232016-03-25 16:58:00 -07002239 VerifyClassVisitor visitor(&context, log_level);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002240 context.ForAll(0, dex_file.NumClassDefs(), &visitor, thread_count);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002241}
2242
Mathieu Chartier90443472015-07-16 20:32:27 -07002243class SetVerifiedClassVisitor : public CompilationVisitor {
2244 public:
2245 explicit SetVerifiedClassVisitor(const ParallelCompilationManager* manager) : manager_(manager) {}
2246
2247 virtual void Visit(size_t class_def_index) REQUIRES(!Locks::mutator_lock_) OVERRIDE {
2248 ATRACE_CALL();
2249 ScopedObjectAccess soa(Thread::Current());
2250 const DexFile& dex_file = *manager_->GetDexFile();
2251 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
2252 const char* descriptor = dex_file.GetClassDescriptor(class_def);
2253 ClassLinker* class_linker = manager_->GetClassLinker();
2254 jobject jclass_loader = manager_->GetClassLoader();
2255 StackHandleScope<3> hs(soa.Self());
2256 Handle<mirror::ClassLoader> class_loader(
Mathieu Chartier0795f232016-09-27 18:43:30 -07002257 hs.NewHandle(soa.Decode<mirror::ClassLoader>(jclass_loader)));
Mathieu Chartier90443472015-07-16 20:32:27 -07002258 Handle<mirror::Class> klass(
2259 hs.NewHandle(class_linker->FindClass(soa.Self(), descriptor, class_loader)));
2260 // Class might have failed resolution. Then don't set it to verified.
2261 if (klass.Get() != nullptr) {
2262 // Only do this if the class is resolved. If even resolution fails, quickening will go very,
2263 // very wrong.
2264 if (klass->IsResolved()) {
2265 if (klass->GetStatus() < mirror::Class::kStatusVerified) {
2266 ObjectLock<mirror::Class> lock(soa.Self(), klass);
2267 // Set class status to verified.
2268 mirror::Class::SetStatus(klass, mirror::Class::kStatusVerified, soa.Self());
2269 // Mark methods as pre-verified. If we don't do this, the interpreter will run with
2270 // access checks.
Igor Murashkindf707e42016-02-02 16:56:50 -08002271 klass->SetSkipAccessChecksFlagOnAllMethods(
Mathieu Chartier90443472015-07-16 20:32:27 -07002272 GetInstructionSetPointerSize(manager_->GetCompiler()->GetInstructionSet()));
Igor Murashkindf707e42016-02-02 16:56:50 -08002273 klass->SetVerificationAttempted();
Mathieu Chartier90443472015-07-16 20:32:27 -07002274 }
2275 // Record the final class status if necessary.
2276 ClassReference ref(manager_->GetDexFile(), class_def_index);
2277 manager_->GetCompiler()->RecordClassStatus(ref, klass->GetStatus());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002278 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002279 } else {
2280 Thread* self = soa.Self();
2281 DCHECK(self->IsExceptionPending());
2282 self->ClearException();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002283 }
2284 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002285
2286 private:
2287 const ParallelCompilationManager* const manager_;
2288};
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002289
Andreas Gampeace0dc12016-01-20 13:33:13 -08002290void CompilerDriver::SetVerifiedDexFile(jobject class_loader,
2291 const DexFile& dex_file,
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002292 const std::vector<const DexFile*>& dex_files,
Andreas Gampeace0dc12016-01-20 13:33:13 -08002293 ThreadPool* thread_pool,
2294 size_t thread_count,
2295 TimingLogger* timings) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002296 TimingLogger::ScopedTiming t("Verify Dex File", timings);
2297 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
2298 ParallelCompilationManager context(class_linker, class_loader, this, &dex_file, dex_files,
2299 thread_pool);
Mathieu Chartier90443472015-07-16 20:32:27 -07002300 SetVerifiedClassVisitor visitor(&context);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002301 context.ForAll(0, dex_file.NumClassDefs(), &visitor, thread_count);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002302}
2303
Mathieu Chartier90443472015-07-16 20:32:27 -07002304class InitializeClassVisitor : public CompilationVisitor {
2305 public:
2306 explicit InitializeClassVisitor(const ParallelCompilationManager* manager) : manager_(manager) {}
Ian Rogersfc0e94b2013-09-23 23:51:32 -07002307
Mathieu Chartier90443472015-07-16 20:32:27 -07002308 virtual void Visit(size_t class_def_index) REQUIRES(!Locks::mutator_lock_) OVERRIDE {
2309 ATRACE_CALL();
2310 jobject jclass_loader = manager_->GetClassLoader();
2311 const DexFile& dex_file = *manager_->GetDexFile();
2312 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
2313 const DexFile::TypeId& class_type_id = dex_file.GetTypeId(class_def.class_idx_);
2314 const char* descriptor = dex_file.StringDataByIdx(class_type_id.descriptor_idx_);
Jeff Hao0e49b422013-11-08 12:16:56 -08002315
Mathieu Chartier90443472015-07-16 20:32:27 -07002316 ScopedObjectAccess soa(Thread::Current());
2317 StackHandleScope<3> hs(soa.Self());
2318 Handle<mirror::ClassLoader> class_loader(
Mathieu Chartier0795f232016-09-27 18:43:30 -07002319 hs.NewHandle(soa.Decode<mirror::ClassLoader>(jclass_loader)));
Mathieu Chartier90443472015-07-16 20:32:27 -07002320 Handle<mirror::Class> klass(
2321 hs.NewHandle(manager_->GetClassLinker()->FindClass(soa.Self(), descriptor, class_loader)));
2322
2323 if (klass.Get() != nullptr && !SkipClass(jclass_loader, dex_file, klass.Get())) {
2324 // Only try to initialize classes that were successfully verified.
2325 if (klass->IsVerified()) {
2326 // Attempt to initialize the class but bail if we either need to initialize the super-class
2327 // or static fields.
2328 manager_->GetClassLinker()->EnsureInitialized(soa.Self(), klass, false, false);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07002329 if (!klass->IsInitialized()) {
Mathieu Chartier90443472015-07-16 20:32:27 -07002330 // We don't want non-trivial class initialization occurring on multiple threads due to
2331 // deadlock problems. For example, a parent class is initialized (holding its lock) that
2332 // refers to a sub-class in its static/class initializer causing it to try to acquire the
2333 // sub-class' lock. While on a second thread the sub-class is initialized (holding its lock)
2334 // after first initializing its parents, whose locks are acquired. This leads to a
2335 // parent-to-child and a child-to-parent lock ordering and consequent potential deadlock.
2336 // We need to use an ObjectLock due to potential suspension in the interpreting code. Rather
2337 // than use a special Object for the purpose we use the Class of java.lang.Class.
2338 Handle<mirror::Class> h_klass(hs.NewHandle(klass->GetClass()));
2339 ObjectLock<mirror::Class> lock(soa.Self(), h_klass);
2340 // Attempt to initialize allowing initialization of parent classes but still not static
2341 // fields.
2342 manager_->GetClassLinker()->EnsureInitialized(soa.Self(), klass, false, true);
2343 if (!klass->IsInitialized()) {
2344 // We need to initialize static fields, we only do this for image classes that aren't
2345 // marked with the $NoPreloadHolder (which implies this should not be initialized early).
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002346 bool can_init_static_fields = manager_->GetCompiler()->IsBootImage() &&
Mathieu Chartier90443472015-07-16 20:32:27 -07002347 manager_->GetCompiler()->IsImageClass(descriptor) &&
2348 !StringPiece(descriptor).ends_with("$NoPreloadHolder;");
2349 if (can_init_static_fields) {
2350 VLOG(compiler) << "Initializing: " << descriptor;
2351 // TODO multithreading support. We should ensure the current compilation thread has
2352 // exclusive access to the runtime and the transaction. To achieve this, we could use
2353 // a ReaderWriterMutex but we're holding the mutator lock so we fail mutex sanity
2354 // checks in Thread::AssertThreadSuspensionIsAllowable.
2355 Runtime* const runtime = Runtime::Current();
2356 Transaction transaction;
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002357
Mathieu Chartier90443472015-07-16 20:32:27 -07002358 // Run the class initializer in transaction mode.
2359 runtime->EnterTransactionMode(&transaction);
2360 const mirror::Class::Status old_status = klass->GetStatus();
2361 bool success = manager_->GetClassLinker()->EnsureInitialized(soa.Self(), klass, true,
2362 true);
2363 // TODO we detach transaction from runtime to indicate we quit the transactional
2364 // mode which prevents the GC from visiting objects modified during the transaction.
2365 // Ensure GC is not run so don't access freed objects when aborting transaction.
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07002366
Mathieu Chartier268764d2016-09-13 12:09:38 -07002367 ScopedAssertNoThreadSuspension ants("Transaction end");
Mathieu Chartier90443472015-07-16 20:32:27 -07002368 runtime->ExitTransactionMode();
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002369
Mathieu Chartier90443472015-07-16 20:32:27 -07002370 if (!success) {
2371 CHECK(soa.Self()->IsExceptionPending());
2372 mirror::Throwable* exception = soa.Self()->GetException();
2373 VLOG(compiler) << "Initialization of " << descriptor << " aborted because of "
2374 << exception->Dump();
2375 std::ostream* file_log = manager_->GetCompiler()->
2376 GetCompilerOptions().GetInitFailureOutput();
2377 if (file_log != nullptr) {
2378 *file_log << descriptor << "\n";
2379 *file_log << exception->Dump() << "\n";
2380 }
2381 soa.Self()->ClearException();
2382 transaction.Rollback();
2383 CHECK_EQ(old_status, klass->GetStatus()) << "Previous class status not restored";
Andreas Gampedbfe2542014-11-25 22:21:42 -08002384 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002385 }
2386 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002387 soa.Self()->AssertNoPendingException();
Brian Carlstrom7940e442013-07-12 13:46:57 -07002388 }
2389 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002390 // Record the final class status if necessary.
2391 ClassReference ref(manager_->GetDexFile(), class_def_index);
2392 manager_->GetCompiler()->RecordClassStatus(ref, klass->GetStatus());
Brian Carlstrom7940e442013-07-12 13:46:57 -07002393 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002394 // Clear any class not found or verification exceptions.
2395 soa.Self()->ClearException();
Brian Carlstrom7940e442013-07-12 13:46:57 -07002396 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002397
2398 private:
2399 const ParallelCompilationManager* const manager_;
2400};
Brian Carlstrom7940e442013-07-12 13:46:57 -07002401
Andreas Gampeace0dc12016-01-20 13:33:13 -08002402void CompilerDriver::InitializeClasses(jobject jni_class_loader,
2403 const DexFile& dex_file,
Andreas Gampede7b4362014-07-28 18:38:57 -07002404 const std::vector<const DexFile*>& dex_files,
Andreas Gampeace0dc12016-01-20 13:33:13 -08002405 TimingLogger* timings) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07002406 TimingLogger::ScopedTiming t("InitializeNoClinit", timings);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002407
2408 // Initialization allocates objects and needs to run single-threaded to be deterministic.
2409 bool force_determinism = GetCompilerOptions().IsForceDeterminism();
2410 ThreadPool* init_thread_pool = force_determinism
2411 ? single_thread_pool_.get()
2412 : parallel_thread_pool_.get();
2413 size_t init_thread_count = force_determinism ? 1U : parallel_thread_count_;
2414
Brian Carlstrom7940e442013-07-12 13:46:57 -07002415 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Andreas Gampede7b4362014-07-28 18:38:57 -07002416 ParallelCompilationManager context(class_linker, jni_class_loader, this, &dex_file, dex_files,
Andreas Gampeace0dc12016-01-20 13:33:13 -08002417 init_thread_pool);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002418 if (IsBootImage()) {
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002419 // TODO: remove this when transactional mode supports multithreading.
Andreas Gampeace0dc12016-01-20 13:33:13 -08002420 init_thread_count = 1U;
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002421 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002422 InitializeClassVisitor visitor(&context);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002423 context.ForAll(0, dex_file.NumClassDefs(), &visitor, init_thread_count);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002424}
2425
Mathieu Chartier91288d82016-04-28 09:44:54 -07002426class InitializeArrayClassesAndCreateConflictTablesVisitor : public ClassVisitor {
Mathieu Chartier085a0722016-04-01 17:33:31 -07002427 public:
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002428 virtual bool operator()(mirror::Class* klass) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier91288d82016-04-28 09:44:54 -07002429 if (Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(klass)) {
2430 return true;
2431 }
Mathieu Chartier085a0722016-04-01 17:33:31 -07002432 if (klass->IsArrayClass()) {
2433 StackHandleScope<1> hs(Thread::Current());
2434 Runtime::Current()->GetClassLinker()->EnsureInitialized(hs.Self(),
2435 hs.NewHandle(klass),
2436 true,
2437 true);
2438 }
Mathieu Chartier91288d82016-04-28 09:44:54 -07002439 // Create the conflict tables.
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00002440 FillIMTAndConflictTables(klass);
Nicolas Geoffray88f288e2016-06-29 08:17:52 +00002441 return true;
Nelli Kimbadee982016-05-13 13:08:53 +03002442 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00002443
2444 private:
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002445 void FillIMTAndConflictTables(mirror::Class* klass) REQUIRES_SHARED(Locks::mutator_lock_) {
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00002446 if (!klass->ShouldHaveImt()) {
2447 return;
2448 }
2449 if (visited_classes_.find(klass) != visited_classes_.end()) {
2450 return;
2451 }
2452 if (klass->HasSuperClass()) {
2453 FillIMTAndConflictTables(klass->GetSuperClass());
2454 }
2455 if (!klass->IsTemp()) {
2456 Runtime::Current()->GetClassLinker()->FillIMTAndConflictTables(klass);
2457 }
2458 visited_classes_.insert(klass);
2459 }
2460
2461 std::set<mirror::Class*> visited_classes_;
Mathieu Chartier085a0722016-04-01 17:33:31 -07002462};
2463
Brian Carlstrom7940e442013-07-12 13:46:57 -07002464void CompilerDriver::InitializeClasses(jobject class_loader,
2465 const std::vector<const DexFile*>& dex_files,
Andreas Gampeace0dc12016-01-20 13:33:13 -08002466 TimingLogger* timings) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07002467 for (size_t i = 0; i != dex_files.size(); ++i) {
2468 const DexFile* dex_file = dex_files[i];
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002469 CHECK(dex_file != nullptr);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002470 InitializeClasses(class_loader, *dex_file, dex_files, timings);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002471 }
Mathieu Chartier91288d82016-04-28 09:44:54 -07002472 if (boot_image_ || app_image_) {
Mathieu Chartier085a0722016-04-01 17:33:31 -07002473 // Make sure that we call EnsureIntiailized on all the array classes to call
2474 // SetVerificationAttempted so that the access flags are set. If we do not do this they get
2475 // changed at runtime resulting in more dirty image pages.
Mathieu Chartier91288d82016-04-28 09:44:54 -07002476 // Also create conflict tables.
2477 // Only useful if we are compiling an image (image_classes_ is not null).
Mathieu Chartier085a0722016-04-01 17:33:31 -07002478 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartier91288d82016-04-28 09:44:54 -07002479 InitializeArrayClassesAndCreateConflictTablesVisitor visitor;
2480 Runtime::Current()->GetClassLinker()->VisitClassesWithoutClassesLock(&visitor);
Mathieu Chartier085a0722016-04-01 17:33:31 -07002481 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002482 if (IsBootImage()) {
Mathieu Chartier093ef212014-08-11 13:52:12 -07002483 // Prune garbage objects created during aborted transactions.
2484 Runtime::Current()->GetHeap()->CollectGarbage(true);
2485 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002486}
2487
Andreas Gampeace0dc12016-01-20 13:33:13 -08002488void CompilerDriver::Compile(jobject class_loader,
2489 const std::vector<const DexFile*>& dex_files,
2490 TimingLogger* timings) {
Calin Juravle998c2162015-12-21 15:39:33 +02002491 if (kDebugProfileGuidedCompilation) {
2492 LOG(INFO) << "[ProfileGuidedCompilation] " <<
2493 ((profile_compilation_info_ == nullptr)
2494 ? "null"
2495 : profile_compilation_info_->DumpInfo(&dex_files));
Calin Juravle226501b2015-12-11 14:41:31 +00002496 }
Vladimir Marko492a7fa2016-06-01 18:38:43 +01002497
2498 DCHECK(current_dex_to_dex_methods_ == nullptr);
2499 for (const DexFile* dex_file : dex_files) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002500 CHECK(dex_file != nullptr);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002501 CompileDexFile(class_loader,
2502 *dex_file,
2503 dex_files,
2504 parallel_thread_pool_.get(),
2505 parallel_thread_count_,
2506 timings);
Calin Juravle69158982016-03-16 11:53:41 +00002507 const ArenaPool* const arena_pool = Runtime::Current()->GetArenaPool();
2508 const size_t arena_alloc = arena_pool->GetBytesAllocated();
2509 max_arena_alloc_ = std::max(arena_alloc, max_arena_alloc_);
Jean-Philippe Halimica76a1a2016-02-02 19:48:52 +01002510 Runtime::Current()->ReclaimArenaPoolMemory();
Brian Carlstrom7940e442013-07-12 13:46:57 -07002511 }
Vladimir Marko492a7fa2016-06-01 18:38:43 +01002512
2513 ArrayRef<DexFileMethodSet> dex_to_dex_references;
2514 {
2515 // From this point on, we shall not modify dex_to_dex_references_, so
2516 // just grab a reference to it that we use without holding the mutex.
2517 MutexLock lock(Thread::Current(), dex_to_dex_references_lock_);
2518 dex_to_dex_references = ArrayRef<DexFileMethodSet>(dex_to_dex_references_);
2519 }
2520 for (const auto& method_set : dex_to_dex_references) {
2521 current_dex_to_dex_methods_ = &method_set.GetMethodIndexes();
2522 CompileDexFile(class_loader,
2523 method_set.GetDexFile(),
2524 dex_files,
2525 parallel_thread_pool_.get(),
2526 parallel_thread_count_,
2527 timings);
2528 }
2529 current_dex_to_dex_methods_ = nullptr;
2530
Andreas Gampe8d295f82015-01-20 14:50:21 -08002531 VLOG(compiler) << "Compile: " << GetMemoryUsageString(false);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002532}
2533
Mathieu Chartier90443472015-07-16 20:32:27 -07002534class CompileClassVisitor : public CompilationVisitor {
2535 public:
2536 explicit CompileClassVisitor(const ParallelCompilationManager* manager) : manager_(manager) {}
2537
2538 virtual void Visit(size_t class_def_index) REQUIRES(!Locks::mutator_lock_) OVERRIDE {
2539 ATRACE_CALL();
2540 const DexFile& dex_file = *manager_->GetDexFile();
2541 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_index);
2542 ClassLinker* class_linker = manager_->GetClassLinker();
2543 jobject jclass_loader = manager_->GetClassLoader();
Mathieu Chartier90443472015-07-16 20:32:27 -07002544 ClassReference ref(&dex_file, class_def_index);
2545 // Skip compiling classes with generic verifier failures since they will still fail at runtime
2546 if (manager_->GetCompiler()->verification_results_->IsClassRejected(ref)) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07002547 return;
2548 }
Mathieu Chartier736b5602015-09-02 14:54:11 -07002549 // Use a scoped object access to perform to the quick SkipClass check.
2550 const char* descriptor = dex_file.GetClassDescriptor(class_def);
2551 ScopedObjectAccess soa(Thread::Current());
2552 StackHandleScope<3> hs(soa.Self());
2553 Handle<mirror::ClassLoader> class_loader(
Mathieu Chartier0795f232016-09-27 18:43:30 -07002554 hs.NewHandle(soa.Decode<mirror::ClassLoader>(jclass_loader)));
Mathieu Chartier736b5602015-09-02 14:54:11 -07002555 Handle<mirror::Class> klass(
2556 hs.NewHandle(class_linker->FindClass(soa.Self(), descriptor, class_loader)));
2557 Handle<mirror::DexCache> dex_cache;
2558 if (klass.Get() == nullptr) {
2559 soa.Self()->AssertPendingException();
2560 soa.Self()->ClearException();
2561 dex_cache = hs.NewHandle(class_linker->FindDexCache(soa.Self(), dex_file));
2562 } else if (SkipClass(jclass_loader, dex_file, klass.Get())) {
2563 return;
2564 } else {
2565 dex_cache = hs.NewHandle(klass->GetDexCache());
2566 }
2567
Mathieu Chartier90443472015-07-16 20:32:27 -07002568 const uint8_t* class_data = dex_file.GetClassData(class_def);
2569 if (class_data == nullptr) {
2570 // empty class, probably a marker interface
2571 return;
Brian Carlstrom7940e442013-07-12 13:46:57 -07002572 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002573
Mathieu Chartier736b5602015-09-02 14:54:11 -07002574 // Go to native so that we don't block GC during compilation.
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07002575 ScopedThreadSuspension sts(soa.Self(), kNative);
Mathieu Chartier736b5602015-09-02 14:54:11 -07002576
Mathieu Chartier90443472015-07-16 20:32:27 -07002577 CompilerDriver* const driver = manager_->GetCompiler();
2578
2579 // Can we run DEX-to-DEX compiler on this class ?
Andreas Gampe5eb0d382015-07-23 01:19:26 -07002580 optimizer::DexToDexCompilationLevel dex_to_dex_compilation_level =
Mathieu Chartier736b5602015-09-02 14:54:11 -07002581 GetDexToDexCompilationLevel(soa.Self(), *driver, jclass_loader, dex_file, class_def);
Andreas Gampe5eb0d382015-07-23 01:19:26 -07002582
Mathieu Chartier90443472015-07-16 20:32:27 -07002583 ClassDataItemIterator it(dex_file, class_data);
2584 // Skip fields
2585 while (it.HasNextStaticField()) {
2586 it.Next();
2587 }
2588 while (it.HasNextInstanceField()) {
2589 it.Next();
2590 }
2591
2592 bool compilation_enabled = driver->IsClassToCompile(
2593 dex_file.StringByTypeIdx(class_def.class_idx_));
2594
2595 // Compile direct methods
2596 int64_t previous_direct_method_idx = -1;
2597 while (it.HasNextDirectMethod()) {
2598 uint32_t method_idx = it.GetMemberIndex();
2599 if (method_idx == previous_direct_method_idx) {
2600 // smali can create dex files with two encoded_methods sharing the same method_idx
2601 // http://code.google.com/p/smali/issues/detail?id=119
2602 it.Next();
2603 continue;
2604 }
2605 previous_direct_method_idx = method_idx;
Mathieu Chartier736b5602015-09-02 14:54:11 -07002606 CompileMethod(soa.Self(), driver, it.GetMethodCodeItem(), it.GetMethodAccessFlags(),
Andreas Gampe5eb0d382015-07-23 01:19:26 -07002607 it.GetMethodInvokeType(class_def), class_def_index,
2608 method_idx, jclass_loader, dex_file, dex_to_dex_compilation_level,
Mathieu Chartier736b5602015-09-02 14:54:11 -07002609 compilation_enabled, dex_cache);
Mathieu Chartier90443472015-07-16 20:32:27 -07002610 it.Next();
2611 }
2612 // Compile virtual methods
2613 int64_t previous_virtual_method_idx = -1;
2614 while (it.HasNextVirtualMethod()) {
2615 uint32_t method_idx = it.GetMemberIndex();
2616 if (method_idx == previous_virtual_method_idx) {
2617 // smali can create dex files with two encoded_methods sharing the same method_idx
2618 // http://code.google.com/p/smali/issues/detail?id=119
2619 it.Next();
2620 continue;
2621 }
2622 previous_virtual_method_idx = method_idx;
Mathieu Chartier736b5602015-09-02 14:54:11 -07002623 CompileMethod(soa.Self(), driver, it.GetMethodCodeItem(), it.GetMethodAccessFlags(),
Andreas Gampe5eb0d382015-07-23 01:19:26 -07002624 it.GetMethodInvokeType(class_def), class_def_index,
2625 method_idx, jclass_loader, dex_file, dex_to_dex_compilation_level,
Mathieu Chartier736b5602015-09-02 14:54:11 -07002626 compilation_enabled, dex_cache);
Mathieu Chartier90443472015-07-16 20:32:27 -07002627 it.Next();
2628 }
2629 DCHECK(!it.HasNext());
Brian Carlstrom7940e442013-07-12 13:46:57 -07002630 }
Mathieu Chartier90443472015-07-16 20:32:27 -07002631
2632 private:
2633 const ParallelCompilationManager* const manager_;
2634};
Brian Carlstrom7940e442013-07-12 13:46:57 -07002635
Andreas Gampeace0dc12016-01-20 13:33:13 -08002636void CompilerDriver::CompileDexFile(jobject class_loader,
2637 const DexFile& dex_file,
Andreas Gampede7b4362014-07-28 18:38:57 -07002638 const std::vector<const DexFile*>& dex_files,
Andreas Gampeace0dc12016-01-20 13:33:13 -08002639 ThreadPool* thread_pool,
2640 size_t thread_count,
2641 TimingLogger* timings) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07002642 TimingLogger::ScopedTiming t("Compile Dex File", timings);
Ian Rogersbe7149f2013-08-20 09:29:39 -07002643 ParallelCompilationManager context(Runtime::Current()->GetClassLinker(), class_loader, this,
Andreas Gampede7b4362014-07-28 18:38:57 -07002644 &dex_file, dex_files, thread_pool);
Mathieu Chartier90443472015-07-16 20:32:27 -07002645 CompileClassVisitor visitor(&context);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002646 context.ForAll(0, dex_file.NumClassDefs(), &visitor, thread_count);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002647}
2648
Andreas Gampe5eb0d382015-07-23 01:19:26 -07002649void CompilerDriver::AddCompiledMethod(const MethodReference& method_ref,
2650 CompiledMethod* const compiled_method,
2651 size_t non_relative_linker_patch_count) {
2652 DCHECK(GetCompiledMethod(method_ref) == nullptr)
2653 << PrettyMethod(method_ref.dex_method_index, *method_ref.dex_file);
2654 {
2655 MutexLock mu(Thread::Current(), compiled_methods_lock_);
2656 compiled_methods_.Put(method_ref, compiled_method);
2657 non_relative_linker_patch_count_ += non_relative_linker_patch_count;
Ian Rogersa4a3f402014-10-20 18:10:34 -07002658 }
Andreas Gampe5eb0d382015-07-23 01:19:26 -07002659 DCHECK(GetCompiledMethod(method_ref) != nullptr)
2660 << PrettyMethod(method_ref.dex_method_index, *method_ref.dex_file);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002661}
2662
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002663void CompilerDriver::RemoveCompiledMethod(const MethodReference& method_ref) {
2664 CompiledMethod* compiled_method = nullptr;
2665 {
2666 MutexLock mu(Thread::Current(), compiled_methods_lock_);
2667 auto it = compiled_methods_.find(method_ref);
2668 if (it != compiled_methods_.end()) {
2669 compiled_method = it->second;
2670 compiled_methods_.erase(it);
2671 }
2672 }
2673 if (compiled_method != nullptr) {
2674 CompiledMethod::ReleaseSwapAllocatedCompiledMethod(this, compiled_method);
2675 }
2676}
2677
Brian Carlstrom7940e442013-07-12 13:46:57 -07002678CompiledClass* CompilerDriver::GetCompiledClass(ClassReference ref) const {
2679 MutexLock mu(Thread::Current(), compiled_classes_lock_);
2680 ClassTable::const_iterator it = compiled_classes_.find(ref);
2681 if (it == compiled_classes_.end()) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002682 return nullptr;
Brian Carlstrom7940e442013-07-12 13:46:57 -07002683 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002684 CHECK(it->second != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002685 return it->second;
2686}
2687
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07002688void CompilerDriver::RecordClassStatus(ClassReference ref, mirror::Class::Status status) {
2689 MutexLock mu(Thread::Current(), compiled_classes_lock_);
2690 auto it = compiled_classes_.find(ref);
2691 if (it == compiled_classes_.end() || it->second->GetStatus() != status) {
2692 // An entry doesn't exist or the status is lower than the new status.
2693 if (it != compiled_classes_.end()) {
2694 CHECK_GT(status, it->second->GetStatus());
2695 delete it->second;
2696 }
2697 switch (status) {
2698 case mirror::Class::kStatusNotReady:
2699 case mirror::Class::kStatusError:
2700 case mirror::Class::kStatusRetryVerificationAtRuntime:
2701 case mirror::Class::kStatusVerified:
2702 case mirror::Class::kStatusInitialized:
Mathieu Chartiera8077802016-03-16 19:08:31 -07002703 case mirror::Class::kStatusResolved:
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07002704 break; // Expected states.
2705 default:
2706 LOG(FATAL) << "Unexpected class status for class "
2707 << PrettyDescriptor(ref.first->GetClassDescriptor(ref.first->GetClassDef(ref.second)))
2708 << " of " << status;
2709 }
2710 CompiledClass* compiled_class = new CompiledClass(status);
2711 compiled_classes_.Overwrite(ref, compiled_class);
2712 }
2713}
2714
Brian Carlstrom7940e442013-07-12 13:46:57 -07002715CompiledMethod* CompilerDriver::GetCompiledMethod(MethodReference ref) const {
2716 MutexLock mu(Thread::Current(), compiled_methods_lock_);
2717 MethodTable::const_iterator it = compiled_methods_.find(ref);
2718 if (it == compiled_methods_.end()) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002719 return nullptr;
Brian Carlstrom7940e442013-07-12 13:46:57 -07002720 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002721 CHECK(it->second != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002722 return it->second;
2723}
2724
Calin Juravlef1c6d9e2015-04-13 18:42:21 +01002725bool CompilerDriver::IsMethodVerifiedWithoutFailures(uint32_t method_idx,
2726 uint16_t class_def_idx,
2727 const DexFile& dex_file) const {
2728 const VerifiedMethod* verified_method = GetVerifiedMethod(&dex_file, method_idx);
2729 if (verified_method != nullptr) {
2730 return !verified_method->HasVerificationFailures();
2731 }
2732
2733 // If we can't find verification metadata, check if this is a system class (we trust that system
2734 // classes have their methods verified). If it's not, be conservative and assume the method
2735 // has not been verified successfully.
2736
2737 // TODO: When compiling the boot image it should be safe to assume that everything is verified,
2738 // even if methods are not found in the verification cache.
2739 const char* descriptor = dex_file.GetClassDescriptor(dex_file.GetClassDef(class_def_idx));
2740 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
2741 Thread* self = Thread::Current();
2742 ScopedObjectAccess soa(self);
2743 bool is_system_class = class_linker->FindSystemClass(self, descriptor) != nullptr;
2744 if (!is_system_class) {
2745 self->ClearException();
2746 }
2747 return is_system_class;
2748}
2749
Vladimir Markof4da6752014-08-01 19:04:18 +01002750size_t CompilerDriver::GetNonRelativeLinkerPatchCount() const {
2751 MutexLock mu(Thread::Current(), compiled_methods_lock_);
2752 return non_relative_linker_patch_count_;
2753}
2754
Mathieu Chartierc4ae9162016-04-07 13:19:19 -07002755void CompilerDriver::SetRequiresConstructorBarrier(Thread* self,
2756 const DexFile* dex_file,
2757 uint16_t class_def_index,
2758 bool requires) {
2759 WriterMutexLock mu(self, requires_constructor_barrier_lock_);
2760 requires_constructor_barrier_.emplace(ClassReference(dex_file, class_def_index), requires);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002761}
2762
Mathieu Chartier371bd832016-04-07 10:19:48 -07002763bool CompilerDriver::RequiresConstructorBarrier(Thread* self,
2764 const DexFile* dex_file,
Mathieu Chartierc4ae9162016-04-07 13:19:19 -07002765 uint16_t class_def_index) {
2766 ClassReference class_ref(dex_file, class_def_index);
2767 {
2768 ReaderMutexLock mu(self, requires_constructor_barrier_lock_);
2769 auto it = requires_constructor_barrier_.find(class_ref);
2770 if (it != requires_constructor_barrier_.end()) {
2771 return it->second;
2772 }
Mathieu Chartierb5d38612016-04-07 10:52:52 -07002773 }
Mathieu Chartierc4ae9162016-04-07 13:19:19 -07002774 WriterMutexLock mu(self, requires_constructor_barrier_lock_);
2775 const bool requires = RequiresConstructorBarrier(*dex_file, class_def_index);
2776 requires_constructor_barrier_.emplace(class_ref, requires);
2777 return requires;
Brian Carlstrom7940e442013-07-12 13:46:57 -07002778}
2779
Andreas Gampe8d295f82015-01-20 14:50:21 -08002780std::string CompilerDriver::GetMemoryUsageString(bool extended) const {
Mathieu Chartierab972ef2014-12-03 17:38:22 -08002781 std::ostringstream oss;
Calin Juravle69158982016-03-16 11:53:41 +00002782 const gc::Heap* const heap = Runtime::Current()->GetHeap();
Anton Kirilovdd9473b2016-01-28 15:08:01 +00002783 const size_t java_alloc = heap->GetBytesAllocated();
Calin Juravle69158982016-03-16 11:53:41 +00002784 oss << "arena alloc=" << PrettySize(max_arena_alloc_) << " (" << max_arena_alloc_ << "B)";
Anton Kirilovdd9473b2016-01-28 15:08:01 +00002785 oss << " java alloc=" << PrettySize(java_alloc) << " (" << java_alloc << "B)";
Elliott Hughes7bf5a262015-04-02 20:55:07 -07002786#if defined(__BIONIC__) || defined(__GLIBC__)
Anton Kirilovdd9473b2016-01-28 15:08:01 +00002787 const struct mallinfo info = mallinfo();
Mathieu Chartierab972ef2014-12-03 17:38:22 -08002788 const size_t allocated_space = static_cast<size_t>(info.uordblks);
2789 const size_t free_space = static_cast<size_t>(info.fordblks);
Anton Kirilovdd9473b2016-01-28 15:08:01 +00002790 oss << " native alloc=" << PrettySize(allocated_space) << " (" << allocated_space << "B)"
2791 << " free=" << PrettySize(free_space) << " (" << free_space << "B)";
Mathieu Chartierab972ef2014-12-03 17:38:22 -08002792#endif
Vladimir Marko35831e82015-09-11 11:59:18 +01002793 compiled_method_storage_.DumpMemoryUsage(oss, extended);
Mathieu Chartierab972ef2014-12-03 17:38:22 -08002794 return oss.str();
2795}
2796
Jeff Haodcdc85b2015-12-04 14:06:18 -08002797bool CompilerDriver::MayInlineInternal(const DexFile* inlined_from,
2798 const DexFile* inlined_into) const {
2799 // We're not allowed to inline across dex files if we're the no-inline-from dex file.
2800 if (inlined_from != inlined_into &&
Vladimir Marko47496c22016-01-27 16:15:08 +00002801 compiler_options_->GetNoInlineFromDexFile() != nullptr &&
2802 ContainsElement(*compiler_options_->GetNoInlineFromDexFile(), inlined_from)) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002803 return false;
2804 }
2805
2806 return true;
2807}
2808
Andreas Gampeace0dc12016-01-20 13:33:13 -08002809void CompilerDriver::InitializeThreadPools() {
2810 size_t parallel_count = parallel_thread_count_ > 0 ? parallel_thread_count_ - 1 : 0;
2811 parallel_thread_pool_.reset(
2812 new ThreadPool("Compiler driver thread pool", parallel_count));
2813 single_thread_pool_.reset(new ThreadPool("Single-threaded Compiler driver thread pool", 0));
2814}
2815
2816void CompilerDriver::FreeThreadPools() {
2817 parallel_thread_pool_.reset();
2818 single_thread_pool_.reset();
2819}
2820
Brian Carlstrom7940e442013-07-12 13:46:57 -07002821} // namespace art